notifies the end of the procedure operations,def ProcedureEnd Event Procedure Example RLG finished Severity WARNING Finish Procedure finished return
"tests that when ordered = false , the schema columns are associated with data frame columns by name , not position . in this case , the schema 's column order is [ a , b ] , while the data frame 's order is [ b , a ] . there is an error in column b in the data frame ( leading whitespace ) , and a validation on column b in the schema .",def test_mixed_columns self df pd read_csv StringIO nb a n 1 1 n2 3 n3 3 n sep header 0 dtype str results self schema validate df self assertEqual len results 1 There should be 1 error self assertEqual results 0 row 0 self assertEqual results 0 column b The Schema object is not associating columns and column schemas by name
"copy a pair of little - endian doubles between files , truncating significands .",def approx_point_little src dest xy src read 2 8 dest write x00 x00 x00 dest write xy 13 8 dest write x00 x00 x00 dest write xy 5
"computes the edit distance between two different pq - grams . if the two pq - grams are the same then the distance is 1.0 , otherwise the distance is 0.0 . changing this will break the metrics of the algorithm .",def gram_edit_distance self gram1 gram2 distance 0 0 if gram1 gram2 distance 1 0 return distance
"convert a string to uppercase , removing any intonation : param s : the string to convert : return : the converted string",def upper_no_intonation s mapping xce x86 xce x88 xce x8a xce x89 xce x8e xce x8c xce x8f xce x91 xce x95 xce x99 xce x97 xce xa5 xce x9f xce xa9 s s upper s s translate str maketrans mapping 0 mapping 1 return s
build an xml mission string that uses the defaultworldgenerator .,def GetMissionXML return xml version 1 0 encoding UTF 8 Mission xmlns http ProjectMalmo microsoft com xmlns xsi http www w3 org 2001 XMLSchema instance About Summary Normal life Summary About ServerSection ServerHandlers DefaultWorldGenerator ServerHandlers ServerSection AgentSection mode Survival Name Rover Name AgentStart Inventory InventoryBlock slot 0 type glowstone quantity 63 Inventory AgentStart AgentHandlers ContinuousMovementCommands ObservationFromFullStats AgentHandlers AgentSection Mission
generates a dylib with an embedded python interpreter and runs launcher code when loaded into an application .,def generate_dylib self launcherCode arch hijacker import macholib MachO MH_DYLIB 6 if hijacker lower true if arch x86 f open self installPath data misc hijackers template dylib rb else f open self installPath data misc hijackers template64 dylib rb elif arch x86 f open self installPath data misc templateLauncher dylib rb else f open self installPath data misc templateLauncher64 dylib rb macho macholib MachO MachO f name if int macho headers 0 header filetype MH_DYLIB print helpers color Dylib template is not the correct filetype return cmds macho headers 0 commands for cmd in cmds count 0 if int cmd count cmd macholib MachO LC_SEGMENT_64 or int cmd count cmd macholib MachO LC_SEGMENT count 1 if cmd count segname strip x00 __TEXT and cmd count nsects 0 count 1 for section in cmd count if section sectname strip x00 __cstring offset int section offset placeHolderSz int section size 52 template f read f close if placeHolderSz and offset launcher launcherCode x00 placeHolderSz len launcherCode patchedDylib template offset launcher template offset len launcher return patchedDylib else print helpers color Unable to patch dylib
test the save button on the webeditor form .,def test03_test_save_button self new_post_text Here is the new post_text with self app app_context data title New Title tags New_Tag tldr New TLDR created_at 1985 11 29 updated_at 1985 11 29 author webeditor_test_user markdown new_post_text path self post_path rv self client post ajax editor save data json dumps data content_type application json headers user_header webeditor_test_user assert rv status 200 OK kp self repo post self post_path assert kp read headers False strip new_post_text
"returns true if the number is even , otherwise false .",def is_even func assertTrue func 2 assertFalse func 3 assertTrue func 4 assertTrue func 2 0 assertFalse func 3 0 assertTrue func 4 0 even True for i in xrange 100 100 assertEqual func i even even not even
in will be truncated at 8k,def vmo4_read___BII_I frame args ref args 1 offset args 2 length args 3 o frame vm heap ref 1 array o values c sys stdin read 1 if c frame stack append 1 array offset ord c if ord c 10 frame stack append 1 return i 1 while i length c sys stdin read 1 if c break array offset i ord c i 1 if ord c 10 break frame stack append i
returns package data as plain bytes,def res_plain resource return resource_string __name__ resource
displays a list of received messages for the current user . optional arguments : `` template_name `` : name of the template to use .,login_required def inbox request template_name django_messages inbox html message_list Message objects inbox_for request user return render request template_name message_list message_list
corresponds to n1 in the paper [ 1 ],def minmax_normalization self X_source X_target all_X X_source append X_target X_source_norm X_source copy X_target_norm X_target copy for feature_index in range all_X shape 1 min_ all_X iloc feature_index min max_ all_X iloc feature_index max range_ max_ min_ X_source_norm iloc feature_index X_source_norm iloc feature_index min_ range_ if range_ 0 else 0 X_target_norm iloc feature_index X_target_norm iloc feature_index min_ range_ if range_ 0 else 0 return X_source_norm X_target_norm
"initialize parser and internal query . if base query specified , copies as base to extend . after parsing , either destroy or call reset to parse a new object .",def __init__ self base None self reset base base
ensure that daemon and workers terminate when stdin is closed .,def test_termination_stdin self self do_termination_test lambda daemon daemon stdin close
test that the laus source can not be fetched,def test_laus_source self response self client get api source LAUS self assertEquals response status_code 400 required_keys message success for key in required_keys self assertIn key response json self assertFalse response json success expected_message Source LAUS is not allowed self assertEqual response json message expected_message
need to check that the ` remove_from_stored_directories ` arg is working . add the temp dir to the plugin directories first before setting the blacklisted dirs to be equal to ` temp_dir ` . check to see if ` blacklisted_directories ` contains ` temp_dir ` and then check to see that temp_dir is not in ` plugin_directories ` .,def test_set_blacklisted_directories self self directory_manager add_directories self temp_dir name self directory_manager set_blacklisted_directories self temp_dir name self assertIn self temp_dir name self directory_manager blacklisted_directories self assertNotIn self temp_dir name self directory_manager plugin_directories self directory_manager blacklisted_directories set self directory_manager add_directories self temp_dir name self directory_manager set_blacklisted_directories self temp_dir name False self assertIn self temp_dir name self directory_manager plugin_directories
"> > > get_qual_range(""dlxyxxrxwyytpmluuqwtxtrsxswmdmtrndnsmjfjffrmv "" ) ( 68 , 89 )",def get_qual_range qual_str vals ord c for c in qual_str return min vals max vals
pretty - print the report .,def print_report frame u if cli OUTPUT_FORMAT is None frame replace True u inplace True frame replace False u X inplace True dict_ frame to_dict orient u split del dict_ u index cli out tabulate tabulate dict_ u data dict_ u columns tablefmt u simple cli echo_green u nX designates the factor that prohibits scheduling the instance on the given server elif cli OUTPUT_FORMAT u yaml fmt plugin_manager load u treadmill formatters u yaml cli out fmt format frame to_dict orient u records elif cli OUTPUT_FORMAT u json cli out frame to_json orient u records elif cli OUTPUT_FORMAT u csv cli out frame to_csv index False else cli out tabulate tabulate frame frame columns tablefmt u simple
post and publish application event directly to zk .,def post_zk zkclient event u Post and publish application event directly to ZK n n Can be used if event directory is unknown i e master scheduler API n _LOGGER debug u post_zk r event _ts _src instanceid event_type event_data payload event to_data _publish_zk zkclient str time time instanceid event_type event_data payload
reads the data of cgroup parameter .,def get_data subsystem group pseudofile u fullpath makepath subsystem group pseudofile with io open fullpath u r as f return f read strip
add an interface to a bridge device .,def bridge_addif devname interface u Add an interface to a bridge device n n param str devname n The name of the network device n subproc check_call _BRCTL_EXE u addif devname interface
compute pearson 's correlation coefficient .,def cor y z return np corrcoef y z 0 1
": param bytes raw : a byte string containing isd id , as id . isd and as are respectively represented as 12 and 20 most significant bits .",def _parse_bytes self raw data Raw raw self NAME self LEN isd_as cast int struct unpack I data pop 0 self _parse_int isd_as
implements get_chunk_size as required by the base class,def get_chunk_size self return time 25 geographic 0 5
get a default point symbol .,def _point_symbol self return self _next_color o
check adherence to estimator api .,def test_check_estimator check_estimator MLPRegressorManyEpochs
"for an unknown arch , we should get back that with arch ' default ' .",def test_arch_package_mirror_info_unknown self arch_mirrors gapmi package_mirrors arch unknown self assertEqual unknown_arch_info arch_mirrors
execute action with specified options .,def execute_action self action_name options assert action_name in NG_ACTIONS wrong action 0 format action_name action NG_ACTIONS action_name self loop run_sync lambda action execute options timeout self timeout
get sid to use for this run,def __init__ self org sid if not sid or sid log try with open sid_log_file r encoding utf 8 as f_sid_log_file line f_sid_log_file readline self _sid_ int line except FileNotFoundError print sid_log_file not found starting SID from 5100000 return except PermissionError as err print err print Aborting quit 0 else self _sid_ sid Bl2ru2 _org_ org
represents / parses the multipart / report,def __init__ self headers None self headers headers if headers self parse_headers headers
adds a bit field to the set of bit fields .,def change_bit_field self field remove_val None for f in self __bit_fields if field self __bit_fields f remove_val f if remove_val is not None del self __bit_fields remove_val self __bit_fields field lsb field
"returns none , or the exchange rate as a decimal",def exchange_rate self rate self exchange quotes get self ccy if rate return Decimal rate
"recursively get text from subcomponents of a deserialized json . to enforce the same order on the documents , make sure to read keys of deserialized_json in a consistent ( alphabetical ) order .",def get_text self deserialized_json if isinstance deserialized_json dict result for key in sorted deserialized_json result self get_text deserialized_json key return result if isinstance deserialized_json list result for item in deserialized_json result self get_text item return result if isinstance deserialized_json six string_types return deserialized_json else return
"wrap immutable instance so a typecode can be set , making it self - describing ie . serializable .",def WrapImmutable pyobj what return _GetPyobjWrapper WrapImmutable pyobj what
dispatches to the first payment method or to the add payment method form if there is no payment method .,permission_required core manage_shop def manage_payment request try payment_method PaymentMethod objects all 0 except IndexError url reverse lfs_add_payment_method else url reverse lfs_manage_payment_method kwargs payment_method_id payment_method id return HttpResponseRedirect url
saves the criteria for the shipping method with given i d . the criteria are passed via request body .,permission_required core manage_shop def save_shipping_method_criteria request shipping_method_id shipping_method lfs_get_object_or_404 ShippingMethod pk shipping_method_id shipping_method save_criteria request html criteria shipping_method_criteria request shipping_method_id result json dumps html html message _ u Changes have been saved cls LazyEncoder return HttpResponse result content_type application json
returns a list of ` n ` paragraphs .,def paragraphs self n min 2 max 4 seed None lengths random randint min max for i in range n sentences self sentences sum lengths seed if not sentences return end list itertools accumulate lengths start 0 end return join sentences start i end i for i in range n
test that initial strategy cooperates .,def test_strategy self P1 axelrod Inverse P2 axelrod Player P2 history self assertEqual P1 strategy P2 C
"the decoding of the varint32 is copied from google.protobuf.internal.decoder and is only repeated here to avoid depending on the internal functions in the library . if the end of file is reached , return ( 0 , 0 ) .",def DecodeVarint in_file result 0 shift 0 pos 0 mask 4294967295 while 1 c in_file read 1 if len c 0 return 0 0 b struct unpack B c 0 result b 127 shift pos 1 if not b 128 if result 9223372036854775807 result 1 64 result mask else result mask return result pos shift 7 if shift 64 raise IOError Too many bytes when decoding varint
change auto2 mode to nav .,def set_nav_mode self if self auto2_index is not None msg PprzMessage ground DL_SETTING msg ac_id self ac_id msg index self auto2_index msg value 13 print Setting mode to NAV s msg self _interface send msg
"if file at file_path does not exist , create it and return the file object , otherwise return none",def create_file_if_does_not_exist file_path print_warning True if not os path exists file_path return open file_path w else if print_warning print File s exists file_path return None
initialize the local quartic object .,def __init__ self K 1 0 r0 0 0 cutoff infinity shift 0 0 if not pmi _PMIComm and pmi _PMIComm isActive or pmi _MPIcomm rank in pmi _PMIComm getMPIcpugroup if shift auto cxxinit self interaction_Quartic K r0 cutoff else cxxinit self interaction_Quartic K r0 cutoff shift
""" obsolete method : please use ' polar_coordinate ' .",def get_polar_coordiantes self raise DeprecationWarning get_polar_coordiantes is obsolete Please use the property polar_position
executes the code of the specified module .,def run self with utils ChangeDir self dirname sys path insert 0 self dirname sys argv 1 self args runpy run_module self not_suffixed self filename run_name __main__ alter_sys True
make sure a username exists .,def username_exists_validator value try User objects get username value except User DoesNotExist raise ValidationError _ Requested username does not exist
wait on pid and return an appropriate exit code . this may return unsuccessfully due to timeout if the daemon process does not appear to be alive .,def _run_writer self fifo_writer msg start_time time time fifo_writer start eof fifo_writer poll is not None while not eof fifo_writer _wait_loop timeout self _COMMUNICATE_RETRY_TIMEOUT_MS eof fifo_writer poll is not None if eof break elif self _daemon_is_alive self _timeout_retry_msg start_time msg else fifo_writer cancel self _no_daemon_msg fifo_writer wait return 2 return fifo_writer wait
print all values read from l{cin } to standard out or l{out}.,forever def Printer cin out sys stdout while True msg str cin read n out write msg yield
posts a form that contains validation errors .,def test_create_article_with_errors self view_url views create_update create article num_articles Article objects count response self client post view_url title My First Article self assertFormError response form slug u This field is required self assertTemplateUsed response views article_form html self assertEqual num_articles Article objects count Number of Articles should not have changed
returns a response with a template rendered with the given context .,def render_to_response self context response_kwargs return self response_class request self request template self get_template_names context context response_kwargs
# 13572 - querydict with a non - default encoding,def test_non_default_encoding self q QueryDict sbb one encoding rot_13 self assertEqual q encoding rot_13 self assertEqual q items u foo u bar self assertEqual q urlencode sbb one q q copy self assertEqual q encoding rot_13 self assertEqual q items u foo u bar self assertEqual q urlencode sbb one self assertEqual copy copy q encoding rot_13 self assertEqual copy deepcopy q encoding rot_13
get stats from within container .,def get_container_stats container_id stream False response do_get containers stats format container_id params stream stream return json loads response text
find all files under revision control,def walk_revctrl dirname for ep in pkg_resources iter_entry_points setuptools file_finders for item in ep load dirname yield item
@summary : write a renamed_fasta where the representative sequences id will be replaced by the id of the cluster . @param input_fasta : [ str ] path to the fasta to process . @param clusters_file : [ str ] path to the ' .clstr ' . @param renamed_fasta : [ str ] path to the fasta after process .,def filter_seq input_fasta clusters_file cluster_fasta cluster_representative dict cluster_idx 1 clusters_fh open clusters_file for line in clusters_fh line line strip representative_id line split 0 cluster_representative representative_id Cluster_ str cluster_idx cluster_idx 1 clusters_fh close FH_in FastaIO input_fasta FH_out FastaIO cluster_fasta w for record in FH_in if cluster_representative has_key record id record id cluster_representative record id FH_out write record
private method to check if an executable exists,def _which self program def is_exe fpath return os path isfile fpath and os access fpath os X_OK fpath fname os path split program if fpath if is_exe program return program else for path in os environ PATH split os pathsep path path strip exe_file os path join path program if is_exe exe_file return exe_file return None
"returns ( model , perm , ) for all models user can possibly see",def get_avail_models request items admin_site get_admin_site request request for model model_admin in admin_site _registry items perms model_admin get_model_perms request if True not in perms values continue items append model perms return items
make sure the value is correct,def test_candidatesubr_value self expected_value 348 374 rmoveto self assertEqual self cand_subr value expected_value
add a row to the table .,def add_row self title value label Gtk Label label title COLON halign Gtk Align END valign Gtk Align START label set_selectable True label show value Gtk Label label value halign Gtk Align START value set_selectable True value show self grid add label self grid attach_next_to value label Gtk PositionType RIGHT 1 1
get an option with the specified category and name .,def get_option self category name for oname option in self __options category if oname name return option return None
return list of non hidden registered reports : param gui : bool indicating if gui reports or cli reports must be returned,def get_reg_reports self gui True return plg for plg in self basemgr get_reg_reports gui if plg id not in self __hidden_plugins
on drag motion one wants the list to show as the database representation so it is clear how save will change the data,def tree_drag_motion self args if not self dbsort self columns 0 clicked
header format for remove dialogs .,def _message1_format self family return _ Delete s _ family s family gramps_id
extend to manually retry /users / pypy as /teams / pypy .,def api_get self path sess None kw u Extend to manually retry users pypy as teams pypy n n Bitbucket gives us a 404 where a 30x would be more helpful n n try return PlatformOAuth1 api_get self path sess kw except Response as response if response code 404 and u is a team account in response body assert path startswith u 2 0 users path u 2 0 teams path 11 return PlatformOAuth1 api_get self path sess kw else raise
"inner join . if columns are repeated , the left table has preference .",def full_outer_join table_left table_right column check_sorted True if column not in table_left keys raise ValueError not in left table format column if column not in table_right keys raise ValueError not in right table format column all_columns set chain table_left keys table_right keys joined_columns all_columns column common_left table_left get column common_right table_right get column if check_sorted if not np all common_left values np sort common_left values raise ValueError Trying to join with a non sorted column if not np all common_right values np sort common_right values raise ValueError Trying to join with a non sorted column common_rec union_sorted common_left values common_right values data_joined global_left global_right join_low_level common_left values common_left index common_right values common_right index common_rec data list index list keys list data append data_joined index append np ones len data_joined dtype np uint8 keys append column for i_column in joined_columns if i_column in table_left and i_column in table_right cl table_left get i_column cr table_right get i_column c_values c_index reindex_join_columns cl cr global_left global_right keys append i_column data append c_values index append c_index elif i_column in table_left c table_left get i_column c c reindex global_left keys append i_column data append c values index append c index elif i_column in table_right c table_right get i_column c c reindex global_right keys append i_column data append c values index append c index res Table res data data res index np vstack index res keys keys return res
generate a list of other versions in the hive .,def other_versions self u n Generate a list of other versions in the hive n return self get u versioning get u other_versions
register interest for a service or characteristic,csrf_exempt require_api_port require_POST transaction atomic def register_interest request remote_id uuid is_service True device_instance ConnectedDevice objects get gateway_instance__session_token __get_session_token request remote_id remote_id if not check_uuid uuid return HttpResponse status 400 uuid convert_uuid uuid if is_service try service Service objects get uuid uuid device_instance interested_services add service register_interest_service_evt delay device_instance id service uuid except Service DoesNotExist pass else try characteristic Characteristic objects get uuid uuid device_instance interested_characteristics add characteristic except Characteristic DoesNotExist pass device_instance save return HttpResponse
( obj ) - > dict,def get_global_attr_info nc_group global_attr_info OrderedDict if nc_group __dict__ for name val in nc_group __dict__ items value str val split n if n in str val else str val global_attr_info name value return global_attr_info
help [ command ] prints help for the specified command . ' h ' and ' ? ' are synonyms .,def do_help self argv if argv 1 for arg in argv 1 if self _do_one_help arg break else doc self _doc_to_help self __class__ if doc sys stdout write doc n sys stdout flush
process profile picture to be the correct size and shape and to have a circular mask .,def process_profile_picture img_data size 100 100 im Image open img_data im thumbnail size Image ANTIALIAS bigsize im size 0 3 im size 1 3 mask Image new L bigsize 0 draw ImageDraw Draw mask draw ellipse 0 0 bigsize fill 255 mask mask resize size Image ANTIALIAS output ImageOps fit im size centering 0 5 0 5 output putalpha mask return output
creates an face . methodimplementation for the given behavior .,def unary_stream_inline behavior return _MethodImplementation cardinality Cardinality UNARY_STREAM style Service INLINE None behavior None None None None None None
test if a number is prime .,def test_probable_prime candidate randfunc None if randfunc is None randfunc Random new read if not isinstance candidate Integer candidate Integer candidate try map candidate fail_if_divisible_by _sieve_base except ValueError return False mr_ranges 220 30 280 20 390 15 512 10 620 7 740 6 890 5 1200 4 1700 3 3700 2 bit_size candidate size_in_bits try mr_iterations list filter lambda x bit_size x 0 mr_ranges 0 1 except IndexError mr_iterations 1 if miller_rabin_test candidate mr_iterations randfunc randfunc COMPOSITE return COMPOSITE if lucas_test candidate COMPOSITE return COMPOSITE return PROBABLY_PRIME
setup any state tied to the execution of the given method in a class . setup_method is invoked for every test method of a class .,def setup_method self method sparkConf create_spark_conf setMaster local 1 setAppName test model self sc get_spark_context sparkConf init_engine resource_path os path join os path split __file__ 0 resources self image_path os path join resource_path pascal 000025 jpg
the number of parameters in the `` global_transform ``,property def n_global_parameters self return self global_transform n_parameters
return the sum of cross - validation residuals for the input data,def cv_error self cv True skip_endpoints True resids self cv_residuals cv if skip_endpoints resids resids 1 1 return np mean abs resids
"for the polynomials in the list of strings * pols * and the solutions in * sols * for the values in the list * start * , a sweep through the parameter space will be performed in double double precision to the target values of the parameters in the list * target*. the number of variables in the polynomials and the solutions must be the same and be equal to the value of * nvar*. the list of symbols in * pars * contains the names of the variables in the polynomials * pols * that serve as parameters . the size of the lists * pars * , * start * , and * target * must be same .",def dobldobl_complex_sweep pols sols nvar pars start target from phcpy interface import store_dobldobl_solutions as storesols from phcpy interface import store_dobldobl_system as storesys storesys pols nbvar nvar storesols nvar sols from phcpy interface import load_dobldobl_solutions as loadsols from phcpy phcpy2c3 import py2c_sweep_define_parameters_symbolically as define from phcpy phcpy2c3 import py2c_sweep_set_dobldobl_start as set_start from phcpy phcpy2c3 import py2c_sweep_set_dobldobl_target as set_target from phcpy phcpy2c3 import py2c_sweep_dobldobl_complex_run as run nbq nbp len pols len pars parnames join pars nbc len parnames define nbq nvar nbp nbc parnames print setting the start and the target set_start nbp str start set_target nbp str target print calling run in double double precision run 0 0 0 0 0 result loadsols return result
parse the headers in a stomp response,def parse_headers lines offset 0 headers for header_line in lines offset header_match HEADER_LINE_RE match header_line if header_match key header_match group key key re sub _unescape_header key if key not in headers value header_match group value value re sub _unescape_header value headers key value return headers
return the log - pdf value of the measurement,def measure self particles y t logyprob numpy empty len particles dtype float for k in range len particles logyprob k kalman lognormpdf particles k reshape 1 1 y self R return logyprob
"raise a runtime error , unless implemented by sub - classes .",def _run self args kwargs raise RuntimeError Must be implemented by a sub class
update the kobo display to show the email atom feed atom .,def updateDisplay print Creating Image white 255 255 255 black 0 0 0 gray 125 125 125 pygame display init pygame font init pygame mouse set_visible False display pygame display set_mode 800 600 pygame FULLSCREEN screen pygame Surface 600 800 screen fill white font pygame font Font fonts Forum Regular otf 40 large_font pygame font Font fonts Forum Regular otf 70 huge_font pygame font Font fonts Forum Regular otf 250 atom_all getGmailData atom_filtered getGmailData True configData getConfigSectionMap configFname gmailAccount if atom_all None txt font render configData title True black white txt_rect txt get_rect txt_rect topleft 0 45 screen blit txt txt_rect str You have txt large_font render str True black white txt_rect txt get_rect txt_rect topleft 0 80 screen blit txt txt_rect str 2d len atom_all entries txt huge_font render str True black white txt_rect txt get_rect txt_rect topleft 600 txt_rect width 50 screen blit txt txt_rect str new Emails txt large_font render str True black white txt_rect txt get_rect txt_rect topleft 0 200 screen blit txt txt_rect str Including d important ones len atom_filtered entries txt font render str True black white txt_rect txt get_rect txt_rect topleft 0 300 screen blit txt txt_rect maxList 10 ybase 350 ystep 40 if len atom_all entries maxList maxList len atom_all entries for i in range maxList y ybase ystep i txtStr s s atom_all entries i author split 0 atom_all entries i title txt font render txtStr True black white txt_rect txt get_rect txt_rect topleft 0 y screen blit txt txt_rect else str Error Accessing Gmail txt large_font render str True black white txt_rect txt get_rect txt_rect topleft 0 400 screen blit txt txt_rect wifiImg getWirelessIcon screen blit wifiImg 0 5 batImg getBatteryIcon screen blit batImg 40 5 txtStr time strftime d m Y H M txt font render txtStr True black white txt_rect txt get_rect txt_rect topleft 600 5 txt_rect width 0 screen blit txt txt_rect graphic pygame transform rotate screen 90 display blit graphic 0 0 pygame display update call full_update
called when the connection is lost or closed .,def connection_lost self exc
updates the repository to a given commit .,def apply_commit self commit self executor cd s git checkout s self dirname commit
: return : the table name relative to the fact table,property def name self return self nested_path 0
checks projects for correct settings .,def run self filt fix False boskos False def check project fix self results report_project project for prop_class in ProjectProperty __subclasses__ prop prop_class self rl_exec self results _log info Checking project s for s project prop name prop check_and_maybe_update self config project fix boskos_path None if boskos boskos_path s boskos resources yaml os path dirname __file__ projects self load_projects s jobs config json os path dirname __file__ boskos_path filt _log info Checking d projects len projects run_threads_to_completion threading Thread target check args project fix for project in sorted projects self log_summary
create a rolerequest with the optional parameters below .,def __init__ self xid None role None generation_id None super __init__ xid role generation_id self header message_type Type OFPT_ROLE_REQUEST
an inverse function to : py : func:`encode ` .,def decode str_ escape_char special_map None charset utf 8 errors strict tok re compile escape_char 0 9A Fa f 2 re DOTALL output barr bytearray for match in tok finditer str_ enc_couple char match groups if enc_couple barr append int enc_couple 16 else if len barr 0 output barr decode charset errors barr bytearray if special_map is not None and char in special_map output special_map char else output char if len barr 0 output barr decode charset errors return output
read wave files ( .wav ) .,def read_wav sourcefiles gulp_nframe args kwargs return WavSourceBlock sourcefiles gulp_nframe args kwargs
validates email domain by blacklist .,def validate_email_domain email try domain email split 1 1 lower strip except IndexError return if domain in dju_settings DJU_EMAIL_DOMAIN_BLACK_LIST raise ValidationError _ u Email with domain domain s is disallowed code banned_domain params domain domain
"query the smart contract for its token information ( name , symbol , decimals ) .",def Query self if self name is not None return sb ScriptBuilder sb EmitAppCallWithOperation self ScriptHash name sb EmitAppCallWithOperation self ScriptHash symbol sb EmitAppCallWithOperation self ScriptHash decimals engine ApplicationEngine Run sb ToArray results engine EvaluationStack Items try self name results 0 GetString self symbol results 1 GetString self decimals results 2 GetBigInteger if len self name 1 and self name Stack Item and len self symbol 1 and self symbol Stack Item and self decimals 10 return True except Exception as e logger info could not query token s e return False
backwards compatibility with geopy 0.93 tuples .,def __getitem__ self index return self name self point index
run a given module as if it was the system entry point .,def run_module_as_main module argv where os path dirname module __file__ filename os path basename module __file__ filename os path splitext filename 0 py with patch sys argv new argv imp load_source __main__ os path join where filename
starts all pyro_workers defined in pyro_settings.pyro_workers,def main for computer in pyro_settings worker_servers cmd pyro_settings ssh_start_cmd_tpl format computer print Executing command 0 format cmd return_code subprocess call cmd shell True time sleep 0 1
determines the end of the sep event by analysing the prediccs data .,def all_clear self print nall clear triggered count 0 for i in self db prediccs find sort _id 1 limit 1 last_entry i for i in last_entry data if count self stack append i if float i 2 self Al_3_threshold self stack2 append i 0 if len self stack2 self clear_limit print all clear self SEP 0 print stack self stack2 self stack self stack2 self last_data i 0 return 1 break else self stack2 if i 0 self stack 1 0 count 1
add a python virtual environment and twin master,def add_venv_master self executable None twinterpreter_id None kernel None requirements None _interpreter interpreter Interpreter executable or twinterpreter_id _twinterpreter_id twinterpreter_id or os path basename _interpreter executable assert _twinterpreter_id not in self twin_masters Collision in twinterpreter ids print creating virtualenv _interpreter requires requirements file sys stderr venv_dir self _get_venv_dir _twinterpreter_id subprocess check_call virtualenv no site packages p _interpreter executable venv_dir pip_requirements os path dirname os path dirname os path abspath cpy2py __file__ coverage unittest2 if isinstance requirements stringabc pip_requirements append requirements elif requirements is not None pip_requirements extend requirements for requirement in pip_requirements subprocess check_call os path join venv_dir bin pip install requirement upgrade self twin_masters _twinterpreter_id master TwinMaster executable os path join venv_dir bin python twinterpreter_id _twinterpreter_id kernel kernel atexit register self twin_masters _twinterpreter_id stop if self autostart self twin_masters _twinterpreter_id start return self twin_masters _twinterpreter_id
get values from gui objects and apply to gui_support variables,def _update_data self self axis_z dir self DirZComboHandle get_selection_index self axis_y dir self DirYComboHandle get_selection_index self axis_x dir self DirXComboHandle get_selection_index self axis_z step int self StepNumZ get_text self axis_y step int self StepNumY get_text self axis_x step int self StepNumX get_text self axis_z pulse_width_high int self pulsewidth_z_h get_text self axis_z pulse_width_low int self pulsewidth_z_l get_text self axis_y pulse_width_high int self pulsewidth_y_h get_text self axis_y pulse_width_low int self pulsewidth_y_l get_text self axis_x pulse_width_high int self pulsewidth_x_h get_text self axis_x pulse_width_low int self pulsewidth_x_l get_text
ensures string 's length is a multple of 16,def _is_multiple_16 s if not len s 16 0 raise Exception Ciphertext was not a multiple of 16 in length
"http://www.imagingshop.com/articles/automatic-cropping-non-rectangular-images this is a very slow , genearal purpose , enumerative approach : param mask : image mask : return : largest inscribed rectangle within mask",def maximumInscribedRectangle self mask def getSize ww hh return ww hh height width mask size squares numpy zeros height width dtype int row height 1 for col in range 0 width if mask getpixel row col squares row col 1 col width 1 for row in range 0 height if mask getpixel row col squares row col 1 for row in range height 2 1 1 for col in range width 2 1 1 if mask getpixel row col a squares row col 1 b squares row 1 col c squares row 1 col 1 squares row col min min a b c 1 sizes numpy zeros height width dtype int maxSquare 0 for row in range 0 height for col in range 0 width square squares row col sizes row col getSize square square if square maxSquare maxSquare square height2width None maxSquare 1 widths numpy zeros height width dtype int heights numpy zeros height width dtype int for row in range 0 height for s in range 0 maxSquare 1 height2width s 0 for col in range width 1 1 1 square squares row col if square 0 maxSize sizes row col for rectHeight in range square 0 1 rectWidth height2width rectHeight rectWidth max rectWidth 1 square height2width rectHeight rectWidth size getSize rectWidth rectHeight if size maxSize maxSize size widths row col rectWidth heights row col rectHeight sizes row col maxSize for s in range square 1 maxSquare 1 height2width s 0 width2height None maxSquare 1 for col in range 0 width for s in range 0 maxSquare 1 width2height s 0 for row in range height 1 1 1 square squares row col if square 0 maxSize sizes row col for rectWidth in range square rectWidth 1 rectHeight width2height rectWidth rectHeight max rectHeight 1 square width2height rectWidth rectHeight size getSize rectWidth rectHeight if size maxSize maxSize size widths row col rectWidth heights row col rectHeight sizes row col maxSize for s in range square 1 maxSquare 1 width2height s 0 maxSize 0 rectWidth 0 rectHeight 0 rectRow 0 rectCol 0 for row in range 0 height for col in range 0 width size sizes row col if size maxSize maxSize size rectRow row rectCol col rectWidth widths row col rectHeight heights row col return rectCol rectRow rectCol rectWidth rectRow rectHeight
returns a description of the interface provided by this function .,def getSignature self return self _signature
test for nastiness - removal in the transfield 's locale,def test_locale_html_xss testfield Mock testfield locale script alert 1 script s jinja_helpers locale_html testfield assert script not in s assert lt script gt alert 1 lt script gt in s
test a valid dtd file by passing in a data stream .,def test_passing_stream path tests resources l10n dtd valid dtd parser dtd DTDParser open path _inspect_file_results parser
"tests that generators inside simple ` function`s ( opposed to ` function * ` ) are not raising syntax errors . we use ` version(180 ) ` in ` testcases.javascript.jsshell.jsshell ` so we do n't use the latest "" version "" ( 185 at the time of this writing ) when running spidermonkey . see https://developer.mozilla.org/en-us/docs/mozilla/projects/spidermonkey/jsapi_reference/jsversion ) # noqa which deprecates generators with ' function ' ( see https://developer.mozilla.org/en-us/docs/web/javascript/reference/statements/legacy_generator_function ) # noqa if we get to the point where we want to drop support for generators as ` function`s , then we 'll need to remove ` version(180 ) ` and modify this test .",pytest mark parametrize test_input function foo s yield 1 function foo yield s var foo function s yield 1 function foo s yield 1 function foo yield s var foo function s yield 1 def test_generators test_input ID javascript dangerous_global eval EVIL eval evilStuff err _do_test_raw test_input EVIL assert err message_count 1 Missing expected failure for block s test_input assert err warnings 0 id ID
test that spaces in filenames are errors .,def test_spaces_in_names package MockXPI foo bar foo bar None foo bar foo bar None err ErrorBundle packagelayout test_blacklisted_files err package assert err failed assert len err errors 2
handle a successful login . use this to perform complex redirects post - login . returns ajax in case of an ajax validation call,def login_success self result super AjaxVerify self login_success if self request is_ajax response status okay email self user email return HttpResponse json dumps response mimetype application json return result
execute the plugin on the internal test suite .,def _execPlugin self from nose config import Config from nose core import TestProgram from nose plugins manager import PluginManager suite None stream Buffer conf Config env self env stream stream plugins PluginManager plugins self plugins if self ignoreFiles is not None conf ignoreFiles self ignoreFiles if not self suitepath suite self makeSuite self nose TestProgram argv self argv config conf suite suite exit False self output AccessDecorator stream
create and fit lumped model from pre - existing msm .,classmethod def from_msm cls msm n_macrostates filter 1 1 save_all_maps True n_proc 1 chunk_size 100 params msm get_params lumper cls n_macrostates filter save_all_maps n_proc chunk_size params lumper transmat_ msm transmat_ lumper populations_ msm populations_ lumper mapping_ msm mapping_ lumper countsmat_ msm countsmat_ lumper n_states_ msm n_states_ if n_macrostates is not None lumper _do_lumping return lumper
test multi - source replication for missing privileges .,def test_rplms_missing_privileges self cmd logfile comment if self debug print comment print COMMAND 0 format cmd proc f_out self start_process cmd if self debug print Waiting for process to start i 1 time sleep 1 while proc poll is not None time sleep 1 i 1 if i _TIMEOUT if self debug print Timeout process to start break if self debug print Waiting for logfile to be created for i in range _TIMEOUT if os path exists logfile break else time sleep 1 else raise MUTLibError 0 failed timeout waiting for logfile 1 to be created format comment logfile stop_phrase_found False try self find_stop_phrase logfile comment _RPLMS_MISSING_PRIV_PHRASE stop_phrase_found True except MUTLibError pass try if not stop_phrase_found self kill_process proc f_out comment os unlink logfile except OSError pass return stop_phrase_found
shortcut to add a daily cron task .,def add_daily name user command environment None add_task name daily user command environment
"compute the cost function given a set of features / values , and the values for our thetas .",def compute_cost features values theta m len values sum_of_square_errors np square np dot features theta values sum cost sum_of_square_errors 2 m return cost
"populate a license_policy mapping with four attributes : license_key , label , icon , and color_code at the file resource level .",def process_codebase self codebase license_policy kwargs u n Populate a license_policy mapping with four attributes license_key label n icon and color_code at the File Resource level n if not self is_enabled license_policy return if has_policy_duplicates license_policy codebase errors append u ERROR License Policy file contains duplicate entries n return policies load_license_policy license_policy get u license_policies for resource in codebase walk topdown True if not resource is_file continue try resource_license_keys set entry get u key for entry in resource licenses except AttributeError resource license_policy codebase save_resource resource continue for key in resource_license_keys for policy in policies if key policy get u license_key resource license_policy policy codebase save_resource resource
"return a checksum computed from a file tree using the file paths , size and last modified time stamps . the purpose is to detect is there has been any modification to source code or data files and use this as a proxy to verify the cache consistency .",def tree_checksum tree_base_dir scancode_src_dir _ignored _ignored_from_hash resources resource_iter tree_base_dir ignored _ignored with_dirs False hashable pth str getmtime pth str getsize pth for pth in resources return md5 join sorted hashable hexdigest
"return q(s , a ) for given state and action",def forward self obs_var actions_var v_var self forward_v obs_var mu_var self forward_mu obs_var l_var self forward_l obs_var size len obs_var zero_matrices Variable torch zeros size self action_dim self action_dim l_matrices_var zero_matrices masked_scatter_ self formation_mask l_var l_matrices_var l_matrices_var self strict_lower_tri_mask torch exp l_matrices_var self diag_mask p_var torch bmm l_matrices_var l_matrices_var transpose 2 1 u_minus_mu actions_var mu_var unsqueeze 2 a_var 0 5 torch bmm torch bmm u_minus_mu transpose 2 1 p_var u_minus_mu 0 q_var v_var a_var return q_var
"override to create the dialog 's body ; you must return the containing widget and the focus widget , or just the containing widget",def body self master label ttk Label master text Override Dialog body return label
"mock a game for each test individually . mockworld ( ) will set up a : avatar manager , game state , turn manager and a map generator .",def setUp self self game MockWorld self game game_state add_avatar 1 None Location 0 0 self cell self game game_state world_map get_cell Location 1 0 self initial_health self game avatar_manager get_avatar 1 health
unpack a ymlpath to a pydict and merge it the current dict . returns the fully merged dict .,def unpack_yml configyml key_for_ymlpaths ymlpath def update_dict yml D _yml yml copy _yml pop key_for_ymlpaths None D update _yml def recursive_parse yml D if isinstance yml dict if yml has_key key_for_ymlpaths if not isinstance yml key_for_ymlpaths str list raise YmlFormatError key_for_ymlpaths for p in assert_iterable_return_iterable yml key_for_ymlpaths if not os path isfile p raise IOError Cannot find format p recursive_parse p D update_dict yml D return next_yml YmlLoader load_from_path yml recursive_parse next_yml D D onlynewkeysdict recursive_parse configyml D return D
"the validationreport should contain an id of the root node that was validated in the graph . for example , if the input was the url of an assertion , that url ( the assertion['id ' ] would appear .",def test_validation_subject_reducer self node_id http example com assertion store create_store main_reducer INITIAL_STATE store dispatch set_validation_subject node_id state store get_state self assertEqual state report validationSubject node_id
can view a shortcut for an author object that has a get_absolute_url method,def test_shortcut_with_absolute_url self u for obj in Author objects all short_url u views shortcut s s ContentType objects get_for_model Author id obj pk response self client get short_url self assertRedirects response u http testserver s obj get_absolute_url status_code 302 target_status_code 404
"signature(value , salt= ... ) should work",def test_signature_with_salt self u signer signing Signer u predictable secret salt u extra salt self assertEqual signer signature u hello signing base64_hmac u extra salt u signer u hello u predictable secret decode self assertNotEqual signing Signer u predictable secret salt u one signature u hello signing Signer u predictable secret salt u two signature u hello
parse the http - equiv refrsh parameter from the given response,def get_meta_refresh response if response not in _metaref_cache text response body_as_unicode 0 4096 text _noscript_re sub u text text _script_re sub u text _metaref_cache response html get_meta_refresh text response url response encoding return _metaref_cache response
initialize this l{twisted.web.distrib . request } based on the copied state so that it closely resembles a l{twisted.web.server . request}.,def setCopyableState self state for k in host client tup state k addrdesc INET TCP UNIX UNIX tup 0 addr TCP lambda address IPv4Address addrdesc tup 1 tup 2 UNIX lambda address UNIXAddress tup 1 addrdesc state k addr state requestHeaders Headers dict state requestHeaders pb RemoteCopy setCopyableState self state self content cStringIO StringIO self content_data self finish self remote remoteMethod finish self setHeader self remote remoteMethod setHeader self addCookie self remote remoteMethod addCookie self setETag self remote remoteMethod setETag self setResponseCode self remote remoteMethod setResponseCode self setLastModified self remote remoteMethod setLastModified self _write self remote remoteMethod write
"create and bind my socket , and begin listening on it .",def startListening self self _bindSocket self _connectToProtocol
test that the number of bytes l{fdesc.writetofd } reports as written with its return value are seen by l{fdesc.readfromfd}.,def test_writeAndRead self n self write hello self failUnless n 0 s self read self assertEquals len s n self assertEquals hello n s
implementation of resource . resource 's render method .,def render self request resrc self _getResourceForRequest request return resrc render request
dynamically add in an upload handler .,def file_upload_quota request u n Dynamically add in an upload handler n request upload_handlers insert 0 QuotaUploadHandler return file_upload_echo request
select and setup authentication mechanism .,def setMechanism self jid self xmlstream authenticator jid password self xmlstream authenticator password mechanisms get_mechanisms self xmlstream if jid user is not None if DIGEST MD5 in mechanisms self mechanism sasl_mechanisms DigestMD5 xmpp jid host None jid user password elif PLAIN in mechanisms self mechanism sasl_mechanisms Plain None jid user password else raise SASLNoAcceptableMechanism elif ANONYMOUS in mechanisms self mechanism sasl_mechanisms Anonymous else raise SASLNoAcceptableMechanism
"when a generator reraises a different exception , l{failure._findfailure } inside the generator should find the reraised exception rather than original one .",def test_ambiguousFailureInGenerator self def generator try try yield except 1 except self assertIsInstance Failure value IndexError g generator g next f getDivisionFailure self _throwIntoGenerator f g
"returns the number of "" on "" bits in the bit array .",def count self if self bcount is None self bcount sum BYTE_COUNTS b 255 for b in self bits return self bcount
calculates a checksum with the provided algorithm .,def has_valid_checksum self number u n Calculates a checksum with the provided algorithm n weights 8 9 2 3 4 5 6 7 1 2 4 8 5 0 9 7 3 6 1 2 4 8 1 8 9 2 3 4 5 6 7 1 0 0 0 0 0 weights table for table in weights if len table len number for table in weights checksum sum int n w for n w in zip number table if checksum 11 10 return False return bool weights
create a new group with the given name .,def createGroup name
find the root of a set of symbolic links .,def readLink path
"adds registered models to the current revision , if any .",def post_save_receiver self instance sender kwargs if self is_active self add instance
handles any resource urls specified in an environment .,def resolve_environment_urls resource_registry files env_base_url is_object False object_request None if resource_registry is None return rr resource_registry base_url rr get base_url env_base_url def ignore_if key value if key base_url return True if isinstance value dict return True if in value return True if key in hooks restricted_actions return True get_file_contents rr files base_url ignore_if is_object is_object object_request object_request for res_name res_dict in rr get resources items res_base_url res_dict get base_url base_url get_file_contents res_dict files res_base_url ignore_if is_object is_object object_request object_request
construct an interface name based on the prefix and name .,def get_interface_name name prefix max_len constants DEVICE_NAME_MAX_LEN requested_name prefix name if len requested_name max_len return requested_name if len prefix INTERFACE_HASH_LEN max_len raise ValueError _ Too long prefix provided New name would exceed given length for an interface name namelen max_len len prefix INTERFACE_HASH_LEN hashed_name hashlib sha1 encodeutils to_utf8 name new_name prefix s truncated s hash s prefix prefix truncated name 0 namelen hash hashed_name hexdigest 0 INTERFACE_HASH_LEN LOG info The requested interface name requested_name s exceeds the limit d character limitation It was shortened to new_name s to fit requested_name requested_name limit max_len new_name new_name return new_name
scrape the url of the photo used on the legislator profile page,def get_photo_url legislator_profile_page photo_url legislator_profile_page xpath div contains class legislator profile picture descendant or self img src return photo_url
publish network status ( collection of endpoint data ),def publish_status self status_data None endp None self mqtt_client publish_status status_data endp
convert named group to format tags .,def test_make_format self r re compile os path join P SM A Z0 9 P SM _ P ID2 0 9 _ P ID1 0 9 m re findall P w sep format sep os sep r pattern fmt re sub _ sep _ format sep os sep os sep _ join x 1 if x 1 else x 2 for x in m self assertEqual fmt SM SM _ ID2 _ ID1
show and image and save on file : param fig : matplotlib figure object : param file : filename to save the picture : param flag : if true the image will be saved : param lgd : legend,def show_and_save_image fig file flag lgd None if flag plt show if lgd is not None fig savefig file additional_artists lgd bbox_inches tight else fig savefig file plt close fig
choose a slave to replace and launch it,def launch_a_slave_replacement replica_set zk host_utils MysqlZookeeper instance zk get_mysql_instance_from_replica_set replica_set host_utils REPLICA_ROLE_DR_SLAVE if not instance instance zk get_mysql_instance_from_replica_set replica_set host_utils REPLICA_ROLE_SLAVE launch_replacement_db_host launch_replacement_db_host instance reason restore age replace_again True
read an image from a dm3 file into a numpy array,def read_dm3 image_path get_parms True image_file open image_path rb dmtag parse_dm_header image_file img_index 1 image imagedatadict_to_ndarray dmtag ImageList img_index ImageData image_parms dmtag ImageList img_index ImageTags if get_parms image_parms unnest_parm_dicts image_parms else image_parms dict return image image_parms
return a list of checkpoints for a given file,outside_root_to_404 def list_checkpoints self path u with self engine begin as db return list_remote_checkpoints db self user_id path
writes a command to the instrument,def write self command self connection write command
return true if ` value ` can be converted to a float .,def isnumeric value try float value return True except ValueError TypeError return False
execute a command and return the output .,def execute command env None split_lines False ignore_errors False extra_ignore_errors translate_newlines True with_errors True none_on_ignored_error False u Execute a command and return the output n n Args n command list of unicode n The command to run n n env dict optional n The environment variables to use when running the process n n split_lines bool optional n Whether to return the output as a list split on newlines or a n single string n n ignore_errors bool optional n Whether to ignore non zero return codes from the command n n extra_ignore_errors tuple of int optional n Process return codes to ignore n n translate_newlines bool optional n Whether to convert platform specific newlines such as r n to n the regular newline n character n n with_errors bool optional n Whether the stderr output should be merged in with the stdout n output or just ignored n n none_on_ignored_error bool optional n Whether to return None if there was an ignored error instead n of the process output n n Returns n unicode or list of unicode n Either the output of the process or a list of lines in the output n depending on the value of split_lines n if isinstance command list logging debug subprocess list2cmdline command else logging debug command if env env update os environ else env os environ copy env u LC_ALL u en_US UTF 8 env u LANGUAGE u en_US UTF 8 if with_errors errors_output subprocess STDOUT else errors_output subprocess PIPE if sys platform startswith u win p subprocess Popen command stdin subprocess PIPE stdout subprocess PIPE stderr errors_output shell False universal_newlines translate_newlines env env else p subprocess Popen command stdin subprocess PIPE stdout subprocess PIPE stderr errors_output shell False close_fds True universal_newlines translate_newlines env env if split_lines data p stdout readlines else data p stdout read rc p wait if rc and not ignore_errors and rc not in extra_ignore_errors raise Exception u Failed to execute command s n s command data if rc and none_on_ignored_error return None return data
see tools / android / loading / cloud / frontend / readme.md for a specification of the parameters .,def __init__ self action action_params backend_params self _action action self _action_params action_params or self _backend_params backend_params or if not self _backend_params get tag self _backend_params update tag str uuid uuid1
send a message to the child http server process and wait for it to finish .,def Shutdown self self conn send False self process join
gets the message name from the url .,def _GetName self request match re match self _REGEX request path if not match return None return match group name
turns stack frames ' absolute addresses into mmap relative addresses .,def RelativizeStackFrames self mmap assert isinstance mmap memory_map Map for abs_addr stack_frame in self stack_frames iteritems assert abs_addr stack_frame address map_entry mmap Lookup abs_addr if not map_entry continue stack_frame SetExecFileInfo map_entry mapped_file map_entry GetRelativeFileOffset abs_addr
register a new shared library or executable .,def AddBinaryAt self binary load_address self _load_addresses binary load_address
"on the last tab , cycle through each tab that was opened and then record a single histogram for the tab switching metric .",def ValidateAndMeasurePage self page tab results browser tab browser if len browser tabs len page story_set stories return if browser tabs 2 raise Exception Should have at least two tabs for tab switching util WaitFor tab HasReachedQuiescence 60 if browser platform CanMonitorPower self _power_metric Start page tab time sleep TabSwitching SAMPLE_TIME self _power_metric Stop page tab self _power_metric AddResults tab results histogram_name MPArch RWH_TabSwitchPaintDuration histogram_type histogram_util BROWSER_HISTOGRAM display_name MPArch_RWH_TabSwitchPaintDuration first_histogram histogram_util GetHistogram histogram_type histogram_name tab prev_histogram first_histogram for tab_to_switch in browser tabs tab_to_switch Activate def _IsDone cur_histogram histogram_util GetHistogram histogram_type histogram_name tab_to_switch diff_histogram histogram_util SubtractHistogram cur_histogram prev_histogram diff_histogram_count json loads diff_histogram get count 0 return diff_histogram_count 0 util WaitFor _IsDone 30 prev_histogram histogram_util GetHistogram histogram_type histogram_name tab_to_switch last_histogram prev_histogram total_diff_histogram histogram_util SubtractHistogram last_histogram first_histogram results AddSummaryValue histogram HistogramValue None display_name ms raw_value_json total_diff_histogram important False keychain_metric KeychainMetric AddResults tab results
compares a series of scrapes using a series of operators .,def Compare base compare ops root_path None out_path None if root_path is None root_path os path join os path split __file__ 0 Scrapes if out_path is None out_path os path join os path split __file__ 0 Compares if type base in types StringTypes base base None if type compare in types StringTypes compare compare None if type ops in types StringTypes ops ops base_dir os path join root_path base 0 compare_dir os path join root_path compare 0 if base 1 is None base base 0 max os listdir base_dir if compare 1 is None compare compare 0 min os listdir compare_dir out_path os path join out_path base 0 base 1 compare 0 compare 1 drivers windowing PreparePath out_path out_file open os path join out_path log txt w description_string Comparing s s to s s base 0 base 1 compare 0 compare 1 out_file write description_string print description_string base_dir os path join base_dir base 1 compare_dir os path join compare_dir compare 1 for filename in os listdir base_dir out_file write s filename if not os path isfile os path join compare_dir filename out_file write Does not exist in target directory n print File s does not exist in target directory filename continue base_filename os path join base_dir filename compare_filename os path join compare_dir filename for op in ops if type op in types StringTypes op op None module operators GetOperator op 0 ret module Compare base_filename compare_filename if ret is None print s OK filename out_file write OK n else print s s filename ret 0 out_file write s n ret 0 ret 1 save os path join out_path filename out_file close
build a command line argument 's parser .,def _ArgumentParser sandwich_setup_parser argparse ArgumentParser add_help False sandwich_setup_parser add_argument android default None type str dest android_device_serial help Android device s serial to use sandwich_setup_parser add_argument c corpus required True help Path to a JSON file with a corpus such as in s _CORPUS_DIR sandwich_setup_parser add_argument m measure default nargs choices _SPEED_INDEX_MEASUREMENT _MEMORY_MEASUREMENT _TTFMP_MEASUREMENT dest optional_measures help Enable optional measurements sandwich_setup_parser add_argument o output type str required True help Path of the output directory to setup sandwich_setup_parser add_argument r url repeat default 1 type int help How many times to repeat the urls plumbing_parser OPTIONS GetParentParser plumbing options parser argparse ArgumentParser parents plumbing_parser fromfile_prefix_chars task_manager FROMFILE_PREFIX_CHARS subparsers parser add_subparsers dest subcommand help subcommand line subparsers add_parser setup prefetch parents sandwich_setup_parser help Setup all NoState Prefetch benchmarks swr_setup_parser subparsers add_parser setup swr parents sandwich_setup_parser help Setup all Stale While Revalidate benchmarks swr_setup_parser add_argument d domains csv type argparse FileType r required True help Path of the CSV containing the pattern of domains in a domain patterns column and a usage column in percent in how likely they are in a page load subparsers add_parser run parents task_manager CommandLineParser help Run benchmarks steps using the task manager infrastructure collect_csv_parser subparsers add_parser collect csv help Collects all CSVs from Sandwich output directory into a single CSV collect_csv_parser add_argument output_dir type str help Path to the run output directory collect_csv_parser add_argument output_csv type argparse FileType w help Path to the output CSV return parser
copies mobile provisioning profile info to |installation_path| .,def Install self installation_path shutil copy2 self path installation_path
regression - tests sorting even after a goog.settestonly statement .,def testFixRequires_withTestOnly self self fixRequiresTest_withTestOnly position 0 self fixRequiresTest_withTestOnly position 1 self fixRequiresTest_withTestOnly position 2 self fixRequiresTest_withTestOnly position 4
returns the category this node belongs to .,def _GetCategory self if self _lookup_path 2 in GetNodeCategories return self _lookup_path 2 if self _lookup_path 1 callback return events if self _lookup_path 2 parameters return properties if self _lookup_path 1 endswith Type and self _lookup_path 1 len Type self _lookup_path 2 or self _lookup_path 1 len ReturnType self _lookup_path 2 return properties if self _lookup_path 0 events return properties raise AssertionError Could not classify node s self
adds or deletes a class and qdisc attached to the root .,def _ConfigureClass option config class_id 1 x config port if bandwidth not in config keys or not config bandwidth bandwidth _DEFAULT_MAX_BANDWIDTH_KBIT else bandwidth config bandwidth bandwidth dkbit bandwidth command sudo tc class option dev config interface parent 1 classid class_id htb rate bandwidth ceil bandwidth _Exec command msg Error configuring class ID s using s command class_id option
build an architecture specific version for the chrome installer .,def BuildArchForInstaller version_quad arch lib_overrides target_dir PnaclDirs OutputDir StepBanner BUILD INSTALLER Packaging for arch s in s arch target_dir CopyFlattenDirsAndPrefix PnaclDirs SandboxedCompilerDir arch arch target_dir CopyFlattenDirsAndPrefix PnaclDirs LibDir arch arch target_dir if arch in lib_overrides for override_lib desired_name in lib_overrides arch target_name UseWhitelistedChars desired_name arch shutil copy override_lib J target_dir target_name
sets up the android build environment .,def SetupAndroidBuildEnvironment opts path_to_src None env_vars os environ copy for k _ in env_vars iteritems del os environ k for k v in ORIGINAL_ENV iteritems os environ k v envsetup_path os path join build android envsetup sh proc subprocess Popen bash c source s env envsetup_path stdout subprocess PIPE stderr subprocess PIPE cwd path_to_src out _ proc communicate for line in out splitlines k _ v line partition os environ k v if GYP_DEFINES not in os environ os environ GYP_DEFINES OS android else os environ GYP_DEFINES OS android if opts use_goma os environ GYP_DEFINES use_goma 1 return not proc returncode
will add the fixtures for the new modul to the fixture files .,def add_fixtures package name session path os path join get_app_location package package fixtures modul_fixture get_modul_fixture name package session modul_file _get_fixture_file path _modules json with open modul_file r as mf print Adding data to fixture s modul_file modul_json json load mf modul_json append modul_fixture mf seek 0 mf write json dumps modul_json indent 4 print Ok modul_id modul_fixture id action_fixtures get_action_fixtures session modul_id action_file _get_fixture_file path _actions json with open action_file r as af print Adding data to fixture s action_file action_json json load af action_json extend action_fixtures af seek 0 af write json dumps action_json indent 4 print Ok
"implements the "" reverse - mode "" gradient [ 1 ] _ for the cholesky factorization of a positive - definite matrix .",def perform self node inputs outputs x inputs 0 L inputs 1 dz inputs 2 dx outputs 0 N x shape 0 if self lower F numpy tril dz for k in xrange N 1 1 1 for j in xrange k 1 N for i in xrange j N F i k F i j L j k F j k F i j L i k for j in xrange k 1 N F j k L k k F k k L j k F j k F k k 2 L k k else F numpy triu dz for k in xrange N 1 1 1 for j in xrange k 1 N for i in xrange j N F k i F j i L k j F k j F j i L k i for j in xrange k 1 N F k j L k k F k k L k j F k j F k k 2 L k k dx 0 F
compute the weight vector via ` a^{-1 } b ` .,property def theta self _theta np dot np linalg pinv self A self b return _theta
calculates the angle between two reciprocal vectors,def recAngle self h1 k1 l1 h2 k2 l2 degrees False q1 np matrix h1 k1 l1 q2 np matrix h2 k2 l2 q1 self Gstar q1 E q1 T q2 sum angle np arccos E self dstar h1 k1 l1 self dstar h2 k2 l2 if degrees return np degrees angle else return angle
return a new unique key .,def _getkey self self _keys 1 return self _keys
yields ` k ` cross - validation splits of ` data ` .,def cv_splits data k 10 assert k 2 Folds value k too small s Should be at least 3 k d copy deepcopy data prop float k 1 float k for _ in range k trd ted weighed_split d proportion prop d1 copy deepcopy trd d2 copy deepcopy ted set_sequence_start_idx d1 idx len d2 d np concatenate d2 d1 yield trd ted
the actual data underlying this dataset .,property def data self return self _data
"pickle a dictionary of "" var name "" : values for debugging .",def pickleDict objDict fname with open fname wb as FH pk dump objDict FH
load the inference ops library and return the loaded module .,def Load with _ops_lock global _inference_ops if not _inference_ops ops_path resource_loader get_path_to_datafile INFERENCE_OPS_FILE logging info data path s ops_path _inference_ops load_library load_op_library ops_path assert _inference_ops Could not load inference_ops so return _inference_ops
sets up a queue for a reader .,def _SetUpQueue reader queue data_flow_ops FIFOQueue 8 types_pb2 DT_STRING shapes key value reader read queue queue enqueue_many reader partitions run queue close run return key value
compute the matrix of predictions versus labels,def confusionMatrix labels_test labels_predicted if len labels_test len labels_predicted return 0 TP 0 FP 0 TN 0 FN 0 for i in range 0 len labels_test if labels_test i 0 or labels_predicted i 0 return 0 if labels_test i 0 if labels_predicted i 0 TP 1 else FN 1 elif labels_predicted i 0 FP 1 else TN 1 return TP TN FP FN
proccesses a block of 320 pcm audio samples streamed from rover . audio is sampled at 8192 hz and quantized to + /- 2 ^ 15 . default method is a no - op ; subclass and override to do something interesting .,def processAudio self pcmsamples timestamp_10msec pass
return a dict of key value carfted from appveyor environment variables .,def appveyor_vars from os import environ appveyor_url environ get APPVEYOR_URL message_extended environ get APPVEYOR_REPO_COMMIT_MESSAGE_EXTENDED configuration_name environ get CONFIGURATION branch environ get APPVEYOR_REPO_BRANCH author environ get APPVEYOR_REPO_COMMIT_AUTHOR author_email environ get APPVEYOR_REPO_COMMIT_AUTHOR_EMAIL timestamp environ get APPVEYOR_REPO_COMMIT_TIMESTAMP repo_provider environ get APPVEYOR_REPO_PROVIDER lower project_name environ get APPVEYOR_PROJECT_NAME project_slug environ get APPVEYOR_PROJECT_SLUG pull_request_title environ get APPVEYOR_PULL_REQUEST_TITLE build_version environ get APPVEYOR_BUILD_VERSION commit environ get APPVEYOR_REPO_COMMIT message environ get APPVEYOR_REPO_COMMIT_MESSAGE account_name environ get APPVEYOR_ACCOUNT_NAME pull_request_number environ get APPVEYOR_PULL_REQUEST_NUMBER repo_name environ get APPVEYOR_REPO_NAME short_commit commit 7 build_url appveyor_url project account_name project_slug build build_version format locals commit_url https repo_provider com repo_name commit commit format locals vars dict appveyor_url appveyor_url account_name account_name project_name project_name project_slug project_slug build_version build_version build_url build_url repo_provider repo_provider repo_name repo_name branch branch configuration_name configuration_name author author author_email author_email timestamp timestamp commit commit short_commit short_commit message message message_extended message_extended pull_request_title pull_request_title pull_request_number pull_request_number commit_url commit_url color_green x033 color_red x034 bold x02 underline x1f plain x0f return vars
"return a token that can be used to upload archives throug the api . after hash is calculated , we concat the project i d in order to simplify the token check , otherwise we would have to go through all the objects in the database .",def make_token self project project_b36 int_to_base36 project pk digest salted_hmac self key_salt self _make_hash_value project secret self secret hexdigest return project digest format project project_b36 digest digest
"brute force regex based html tag parser . this is a rough - and - ready searcher to find html tags when standards compliance is not required . will find tags that are commented out , or inside script tag etc . : param html : html page : param tag : tag name to find : return : generator with tags",def itertags html tag for match in tag_re finditer html if match group tag tag attrs dict a group key lower a group value for a in attr_re finditer match group attr yield Tag match group tag attrs match group inner
finds the closest rightbound message to the trigger,def get_rightbound message_type msg_tow trigger_tow msgout numofmsg itt 0 rightbound msg_tow numofmsg 1 while itt numofmsg if msg_tow itt trigger_tow and msg_tow itt rightbound and message_type itt msgout rightbound msg_tow itt itt 1 return rightbound
helper method to write images from single batch into datastore .,def _write_single_batch_images_internal self batch_id client_batch client self _datastore_client batch_key client key self _entity_kind_batches batch_id for img_id img in iteritems self _data batch_id images img_entity client entity client key self _entity_kind_images img_id parent batch_key for k v in iteritems img img_entity k v client_batch put img_entity
adds tf options to numpy scan ops .,def handle_options func x axis exclusive reverse length len x shape if axis 0 axis length axis if reverse x numpy_reverse x axis if exclusive ix_head slice 0 1 if i axis else slice None for i in range length ix_init slice 0 1 if i axis else slice None for i in range length if func np cumsum init np zeros_like x ix_head elif func np cumprod init np ones_like x ix_head else raise ValueError Unknown scan function x np concatenate init func x ix_init axis axis axis else x func x axis axis if reverse x numpy_reverse x axis return x
"construct sinharcsinh distribution on ` ( -inf , inf ) ` .",deprecation deprecated 2018 10 01 The TensorFlow Distributions library has moved to TensorFlow Probability https github com tensorflow probability You should update all references to use tfp distributions instead of tf contrib distributions warn_once True def __init__ self loc scale skewness None tailweight None distribution None validate_args False allow_nan_stats True name SinhArcsinh parameters dict locals with ops name_scope name values loc scale skewness tailweight as name loc ops convert_to_tensor loc name loc dtype loc dtype scale ops convert_to_tensor scale name scale dtype dtype tailweight 1 0 if tailweight is None else tailweight has_default_skewness skewness is None skewness 0 0 if skewness is None else skewness tailweight ops convert_to_tensor tailweight name tailweight dtype dtype skewness ops convert_to_tensor skewness name skewness dtype dtype batch_shape distribution_util get_broadcast_shape loc scale tailweight skewness if distribution is None distribution normal Normal loc array_ops zeros dtype dtype scale array_ops ones dtype dtype allow_nan_stats allow_nan_stats else asserts distribution_util maybe_check_scalar_distribution distribution dtype validate_args if asserts loc control_flow_ops with_dependencies asserts loc f bijectors SinhArcsinh skewness skewness tailweight tailweight if has_default_skewness f_noskew f else f_noskew bijectors SinhArcsinh skewness skewness dtype as_numpy_dtype 0 0 tailweight tailweight c 2 scale f_noskew forward ops convert_to_tensor 2 dtype dtype affine bijectors AffineScalar shift loc scale c validate_args validate_args bijector bijectors Chain affine f super SinhArcsinh self __init__ distribution distribution bijector bijector batch_shape batch_shape validate_args validate_args name name self _parameters parameters self _loc loc self _scale scale self _tailweight tailweight self _skewness skewness
tests the reduce sum of float16 does n't lose too much precision .,def testReduceSumF16 self if np float16 not in self all_types return f16_max np finfo np float16 max self _testReduceSum f16_max np float16 itertools permutations f16_max f16_max f16_max 1 0 3
hold a message for moderator approval .,def hold_message mlist msg msgdata None reason None u Hold a message for moderator approval n n The message is added to the mailing list s request database n n param mlist The mailing list to hold the message on n param msg The message to hold n param msgdata Optional message metadata to hold If not given a new n metadata dictionary is created and held with the message n param reason Optional string reason why the message is being held If n not given the empty string is used n return An id used to handle the held message later n if msgdata is None msgdata else msgdata msgdata copy if reason is None reason u message_id msg get u message id if message_id is None msg u Message ID message_id unicode make_msgid assert isinstance message_id unicode u Message ID is not a unicode s message_id getUtility IMessageStore add msg msgdata u _mod_message_id message_id msgdata u _mod_fqdn_listname mlist fqdn_listname msgdata u _mod_sender msg sender msgdata u _mod_subject msg get u subject _ u no subject msgdata u _mod_reason reason msgdata u _mod_hold_date now isoformat requestsdb IListRequests mlist request_id requestsdb hold_request RequestType held_message message_id msgdata return request_id
calculates accuracy and the speed up of lshforest .,def calc_accuracy X queries n_queries n_neighbors exact_neighbors average_time_exact lshf_params print Building LSHForest for d samples in d dimensions X shape 0 X shape 1 lshf LSHForest lshf_params t0 time lshf fit X lshf_build_time time t0 print Done in 0 3fs lshf_build_time accuracy 0 t0 time approx_neighbors lshf kneighbors queries n_neighbors n_neighbors return_distance False average_time_approx time t0 n_queries for i in range len queries accuracy np in1d approx_neighbors i exact_neighbors i mean accuracy n_queries speed_up average_time_exact average_time_approx print Average time for lshf neighbor queries 0 3fs average_time_approx print Average time for exact neighbor queries 0 3fs average_time_exact print Average Accuracy 0 2f accuracy print Speed up 0 1fx speed_up return speed_up accuracy
returns the static or dynamic batch size .,def _static_or_dynamic_batch_size tensor batch_axis batch_size array_ops shape tensor batch_axis static_batch_size tensor_util constant_value batch_size return static_batch_size or batch_size
initialize a ` linearoperatorfullmatrix ` .,def __init__ self matrix is_non_singular None is_self_adjoint None is_positive_definite None is_square None name LinearOperatorFullMatrix Initialize a LinearOperatorFullMatrix Args matrix Shape B1 Bb M N with b 0 M N 0 Allowed dtypes float32 float64 complex64 complex128 is_non_singular Expect that this operator is non singular is_self_adjoint Expect that this operator is equal to its hermitian transpose is_positive_definite Expect that this operator is positive definite meaning the quadratic form x H A x has positive real part for all nonzero x Note that we do not require the operator to be self adjoint to be positive definite See https en wikipedia org wiki Positive definite_matrix Extension_for_non_symmetric_matrices is_square Expect that this operator acts like square batch matrices name A name for this LinearOperator Raises TypeError If diag dtype is not an allowed type with ops name_scope name values matrix self _matrix ops convert_to_tensor matrix name matrix self _check_matrix self _matrix super LinearOperatorFullMatrix self __init__ dtype self _matrix dtype graph_parents self _matrix is_non_singular is_non_singular is_self_adjoint is_self_adjoint is_positive_definite is_positive_definite is_square is_square name name
assignment of index positions and scalars .,def testParseValuesWithIndexAssigment4 self parse_dict hparam parse_values x 10 arr 1 20 y 30 x int y int arr int self assertEqual len parse_dict 3 self assertTrue isinstance parse_dict arr dict self assertDictEqual parse_dict arr 1 20 self assertEqual parse_dict x 10 self assertEqual parse_dict y 30
processes and send the beta form data submitted by beta testers,login_required def send_beta_feedback_email request post request POST url post get betaFormUrl app get_active_app url url if app is None or not hasattr app feedback_emails json success False error App not found or feedback_emails not defined in app py return JsonResponse json subject User Feedback for 0 format app name encode utf 8 message User 0 User Local Time 1 UTC Offset in Hours 2 App URL 3 User Agent 4 Vendor 5 Comments 6 format post get betaUser post get betaSubmitLocalTime post get betaSubmitUTCOffset post get betaFormUrl post get betaFormUserAgent post get betaFormVendor post get betaUserComments try send_mail subject message from_email None recipient_list app feedback_emails except Exception as e json success False error Failed to send email e message return JsonResponse json json success True result Emails sent to specified developers return JsonResponse json
test that the node tree correctly produces condensed html,def test_condensedOutput output TREE toHTML assert output html head head body br div id myDiv div body html
"set the default settings , execute title & settings filename .",def __init__ self skeinforge_profile addListsSetCraftProfileArchive getCraftSequence ABS self skeinforge_tools profile_plugins extrusion html
parse a gcode line and add it to the commented gcode .,def parseLine self line splitLine gcodec getSplitLineBeforeBracketSemicolon line if len splitLine 1 return firstWord splitLine 0 if firstWord G1 self linearMove splitLine elif firstWord G2 self setHelicalMoveEndpoint splitLine self addComment Helical clockwise move to str self oldLocation elif firstWord G3 self setHelicalMoveEndpoint splitLine self addComment Helical counterclockwise move to str self oldLocation elif firstWord G21 self addComment Set units to mm elif firstWord G28 self addComment Start at home elif firstWord G90 self addComment Set positioning to absolute elif firstWord M101 self addComment Extruder on forward elif firstWord M102 self addComment Extruder on reverse elif firstWord M103 self addComment Extruder off elif firstWord M104 self addComment Set temperature to str gcodec getDoubleAfterFirstLetter splitLine 1 C elif firstWord M105 self addComment Custom code for temperature reading elif firstWord M106 self addComment Turn fan on elif firstWord M107 self addComment Turn fan off elif firstWord M108 self addComment Set extruder speed to str gcodec getDoubleAfterFirstLetter splitLine 1 self output write line n
list method of api viewset . lists should not contain geojson : param request : : return :,def list self request queryset Boundary objects only country level serializer self get_serializer queryset many True return Response serializer data
the arm ror ( rotate right ) operation .,def ROR value amount width if amount 0 return value result _ ROR_C value amount width return result
indicates whether the record enabled for using the calendar service .,def calendarsEnabled
test render_post when results button is clicked and token is wrong,def test_resourcePOST_Results_BadToken self loadsim WebAdminTests FakeLoadSim resource LoadSimAdminResource loadsim self assertTrue loadsim reactor running response resource render_POST WebAdminTests FakeRequest token xyz results None self assertTrue response startswith html self assertTrue response find resource token 1 self assertTrue response find FakeReporter 1 self assertTrue loadsim running
binds all functions in the given module ( as defined by that module 's c{__all _ _ } attribute ) which start with any of the given prefixes as methods of the given class . @param module : the module in which to search for functions . @param clazz : the class to bind found functions to as methods . @param prefixes : a sequence of prefixes to match found functions against .,def bindMethods module clazz prefixes preconditions_ http_ report_ for submodule_name in module __all__ try __import__ module __name__ submodule_name except ImportError log error Unable to import module s module __name__ submodule_name Failure raiseException submodule getattr module submodule_name for method_name in submodule __all__ for prefix in prefixes if method_name startswith prefix method getattr submodule method_name setattr clazz method_name method break
"extend the path component of the given url . relative paths extend the existing path , absolute paths replace it . special path elements like ' . ' and ' .. ' are not treated any differently than any other path element .",def url_path_join url extra_path scheme netloc path params query fragment urlparse urlparse url joined_path os path join path extra_path return urlparse urlunparse scheme netloc joined_path params query fragment
response after client credentials access request .,fixture def client_credentials_response u mock_response Mock status_code http STATUS_OK response_json u access_token ACCESS_TOKEN u expires_in EXPIRES_IN_SECONDS u scope CLIENT_CREDENTIALS_SCOPES_STRING mock_response json Mock return_value response_json return mock_response
the string below is prepared so that ctags with the bug does not start a new triple string . for a clean precondition for the next test . '',def f3 print f3
retrieve volume usage info for the given path .,def getVolInfo paths path os path join paths path os path expanduser path st os statvfs path free st f_bavail st f_frsize total st f_blocks st f_frsize return free free used total free total total
decorator for use with ondem to add key callback methods .,def keymeth name def keyfunc f f _keycache_name name return f return keyfunc
correct attenuation on reflectivity using py - art tool .,def correct_attenuation_zh_pyart radar refl_field DBZ ncp_field NCP rhv_field RHOHV_CORR phidp_field PHIDP_BRINGI atten_meta zh_corr pyart correct calculate_attenuation radar 0 rhv_min 0 3 refl_field refl_field ncp_field rhv_field rhv_field rhv_field phidp_field phidp_field dbz radar fields refl_field data copy att atten_meta data r radar range data dr r 1 r 0 int_att np cumsum att axis 1 dr 1000 0 dbz_corr dbz int_att zh_corr data dbz_corr return atten_meta zh_corr
"converts a 4-dimensional array to blob proto . if diff is given , also convert the diff . you need to make sure that arr and diff have the same shape , and this function does not do sanity check .",def array_to_blobproto arr diff None if arr ndim 4 raise ValueError Incorrect array shape blob caffe_pb2 BlobProto blob num blob channels blob height blob width arr shape blob data extend arr astype float flat if diff is not None blob diff extend diff astype float flat return blob
class decorator for subclasses of `` unittest . testcase `` .,def ddt cls def feed_data func args kwargs This internal method decorator feeds the test data item to the test wraps func def wrapper self return func self args kwargs return wrapper for name f in cls __dict__ items if hasattr f MAGIC i 0 for v in getattr f MAGIC test_name getattr v __name__ u 0 _ 1 format name v formatted_test_name re sub test_name setattr cls formatted_test_name feed_data f v i i 1 delattr cls name return cls def process_file_data name func file_attr Process the parameter in the file_data decorator cls_path os path abspath inspect getsourcefile cls data_file_path os path join os path dirname cls_path file_attr def _raise_ve args raise ValueError u 0 does not exist format file_attr if os path exists data_file_path is False test_name u 0 _ 1 format name error setattr cls test_name feed_data _raise_ve None else data json loads open data_file_path read for elem in data if isinstance data dict key value elem data elem test_name u 0 _ 1 format name key elif isinstance data list value elem test_name u 0 _ 1 format name value setattr cls test_name feed_data func value for name func in list cls __dict__ items if hasattr func DATA_ATTR for v in getattr func DATA_ATTR test_name getattr v __name__ u 0 _ 1 format name v setattr cls test_name feed_data func v delattr cls name elif hasattr func FILE_ATTR file_attr getattr func FILE_ATTR process_file_data name func file_attr delattr cls name return cls
reads a signed 16-bit value from the i2c device,def readS16 self reg try result self bus read_word_data self address reg if self debug print I2C Device 0x 02X returned 0x 04X from reg 0x 02X self address result 65535 reg return result except IOError as err return self errMsg
try all values for jokers in all 5-card selections .,def best_wild_hand hand hands set best_hand h for h in itertools product map replacements hand return max hands key hand_rank
check the revision options before checkout to compensate that tags and branches may need origin/ as a prefix . returns the sha1 of the branch or tag if found .,def check_rev_options self rev dest rev_options revisions self get_refs dest origin_rev origin s rev if origin_rev in revisions return revisions origin_rev elif rev in revisions return revisions rev else logger warn Could not find a tag or branch s assuming commit rev return rev_options
warn if self.object_list is unordered ( typically a queryset ) .,def _check_object_list_is_ordered self ordered getattr self object_list ordered None if ordered is not None and not ordered obj_list_repr format self object_list model self object_list __class__ __name__ if hasattr self object_list model else r format self object_list warnings warn Pagination may yield inconsistent results with an unordered object_list format obj_list_repr UnorderedObjectListWarning stacklevel 3
"resolve and call the view , then apply view , exception , and template_response middleware . this method is everything that happens inside the request / response middleware .",def _get_response self request u n Resolve and call the view then apply view exception and n template_response middleware This method is everything that happens n inside the request response middleware n response None if hasattr request u urlconf urlconf request urlconf set_urlconf urlconf resolver get_resolver urlconf else resolver get_resolver resolver_match resolver resolve request path_info callback callback_args callback_kwargs resolver_match request resolver_match resolver_match for middleware_method in self _view_middleware response middleware_method request callback callback_args callback_kwargs if response break if response is None wrapped_callback self make_view_atomic callback try response wrapped_callback request callback_args callback_kwargs except Exception as e response self process_exception_by_middleware e request if response is None if isinstance callback types FunctionType view_name callback __name__ else view_name callback __class__ __name__ u __call__ raise ValueError u The view s s didn t return an HttpResponse object It returned None instead callback __module__ view_name elif hasattr response u render and callable response render for middleware_method in self _template_response_middleware response middleware_method request response if response is None raise ValueError u s process_template_response didn t return an HttpResponse object It returned None instead middleware_method __self__ __class__ __name__ try response response render except Exception as e response self process_exception_by_middleware e request return response
parses the request content into ` self.data ` .,def _load_data_and_files self u n Parses the request content into self data n if not _hasattr self u _data self _data self _files self _parse if self _files self _full_data self _data copy self _full_data update self _files else self _full_data self _data
"helper function to convert a slice argument to an integer , and raise typeerror with a suitable message on failure .",def evaluate_slice_index arg if hasattr arg __index__ return operator index arg else raise TypeError slice indices must be integers or None or have an __index__ method
called once before any tests are executed .,def startTestRun self
handle date segments in help.html .,def handle_data self data if self show and not self hdrlink d data if self pre else data replace n if self tags h1 self hprefix d 0 d index if self tags in h1 h2 h3 and self hprefix if d 0 len self hprefix self hprefix d d len self hprefix strip self header d self text insert end d self tags self chartags
install an exception handler that formats tracebacks as html .,def enable display 1 logdir None context 5 format html sys excepthook Hook display display logdir logdir context context format format
get metadata for single item .,def _get_item_data_for_itemid self itemid index 0 total 0 if total 0 percent float index float total 100 0 else percent 0 0 data name None itemid itemid url self _create_item_url itemid self debug open 06d 06d 6 2f s index total percent url soup self soup url try data update name self _regex_name match soup title text group 1 except AttributeError data update name None for tag in soup find_all span number format try key tag parent find_previous_sibling text lower data key int float tag text except AttributeError ValueError pass for tag in soup find_all span sales rate try data rate float tag text except AttributeError ValueError pass data self _fix_stack_price_key data return data
"reload all configuration data from the config file . if the file can not be loaded , the configuration data is cleared . this is automatically called by module initialization , and should not need to be called directly .",def reload self try json_data open self filename r self data json load json_data except self data pass
closes all duplicate ' active ' incidents .,def close_duplicate_incidents event element logger logging getLogger poller_logger try incidents Incident objects filter event event element__iexact element status Active for i in incidents logger warning closing duplicate incident s i id i status Cleared i save except Exception logger error Could not close multiple incidents on event s element s event id element return
main method that prints netconf capabilities of remote device .,def main serial_number System xmlns http cisco com ns yang cisco nx os device serial System for device in DEVICES with manager connect host device port PORT username USER password PASS hostkey_verify False device_params name nexus look_for_keys False allow_agent False as m netconf_response m get subtree serial_number xml_data netconf_response data_ele serial xml_data find http cisco com ns yang cisco nx os device serial text print The serial number for is format DEVICE_NAMES device device serial
"create a course with a section , subsection , and unit to which to add the component .",def setUp self is_staff True super AdvancedProblemComponentTest self setUp is_staff is_staff
"get a valid token , assings the token to the agol object .",def getToken self url https arcgis com sharing rest generateToken data username self username password self password referer https www arcgis com f json return requests post url data json token
call an opc - ua method . methodid is browse name of child method or the nodeid of method as a nodeid object arguments are variants or python object convertible to variants . which may be of different types returns a list of values or a single value depending on the output of the method,def call_method parent methodid args result call_method_full parent methodid args if len result OutputArguments 0 return None elif len result OutputArguments 1 return result OutputArguments 0 else return result OutputArguments
returns an iterator over the results from executing this query .,def results_iter self self check_query fields self get_fields low_mark self query low_mark high_mark self query high_mark for entity in self build_query fields fetch low_mark high_mark yield self _make_result entity fields
"get the global meta data , which will be stored in a tree structure",property def global_meta_data self with switch_db MetaDataModel hyperstream return sorted map lambda x x to_dict MetaDataModel objects key lambda x len x identifier split reverse True
@api { get } /enc/<node - name > get node informations ( enc ) @apiname get_enc @apigroup enc @apipermission user @apiversion 1.0.0 @apiparam { string } node_name ( uri parameter ) the node 's name @apiparam { string } [ output = yaml ] ( query parameter ) output result . avaiable methods : yaml / json @apisuccess { string } name the hostgroup 's name . @apisuccess { datetime } insert_date the hostgroup 's inserted date @apisuccess { datetime } update_date the hostgroup 's updated date @apisuccess { datetime } delete_date the hostgroup 's deleted date @apiexample { curl } example usage : curl -i http://127.0.0.1:5000/api / v1/enc/:node_name @apisuccessexample { yaml } success - response : http/1.0 200 ok classes : - role::webserver environment : stable parameters : hostgroup : my_hostgroup puppenc_node_id : 2740 puppetmaster : '',auth login_required def get self page 1 node_name None output str request args get output yaml if not node_name return success False message No node provided 304 else node Node query filter_by name node_name first if not node app logger warning ENC Cannot find s by s node_name g user return success False message Node not found 404 if node hostgroup_id is None or node environment_id is None app logger warning ENC Please set a hostgroup and an environment return success False message Please set a hostgroup and an environment 404 else data Node query join Hostgroup Node hostgroup_id Hostgroup id join Class Hostgroup class_id Class id join Environment Node environment_id Environment id add_columns Node id label node_id Class name label class_name Hostgroup name label hostgroup_name Environment name label environment_name filter Node name node_name first if not data app logger warning No class for the node s node_name class_name data Node query join Hostgroup Node hostgroup_id Hostgroup id join Environment Node environment_id Environment id add_columns Node id label node_id Hostgroup name label hostgroup_name Environment name label environment_name filter Node name node_name first else class_name data class_name hostgroup_name data hostgroup_name environment_name data environment_name node_id data node_id params params parameters params parameters puppetmaster params parameters hostgroup hostgroup_name params parameters puppenc_node_id node_id for p in node nodes_var if p content true content True elif p content false content False elif p content 0 try content json loads p content except app logger info unable to format json content p content else content p content params parameters p name content app logger info Get ENC on s by s node_name g user base environment environment_name if class_name classes_result classes class_name else classes_result classes base update classes_result res base copy res update params app logger info res Node query filter_by id node_id update last_used db func current_timestamp synchronize_session False db session commit if output json return jsonify res 200 else return output_yaml res 200
returns true if this lava test strategy can be used on the given device and details of an image in the parameters .,classmethod def accepts cls device parameters return NotImplementedError accepts s cls
returns the result of the last calculation if finished otherwise returns none,def getCurrentCalculationResult self if self _currentResult is not None result self _currentResult self _currentResult None return result else return None
num2char(int ) - > char num2char(tuple / * of int * / ) - > str convert numbers to corresponding chinese characters .,def num2char sth if isinstance sth int return charList sth else return join map lambda x charList x sth
"apply the list of settings values given to the provided view , in the order the setting names were given to the constructor .",def apply self view values if len values len self key_list raise IndexError Expected d settings len self key_list for setting in zip self key_list values view settings set setting
store books from a file in json format .,def _handle_json self jsonpath jsonfile open jsonpath data_list json loads jsonfile read status_published Status objects get status Published stats dict total 0 errors 0 skipped 0 imported 0 for d in data_list stats total 1 logger debug read item s json dumps d if book_path not in d stats skipped 1 continue if not os path exists d book_path stats skipped 1 continue f open d book_path rb d book_file File f del d book_path if cover_path in d f_cover open d cover_path rb d cover_img File f_cover del d cover_path if a_status in d d a_status Status objects get status d a_status else d a_status status_published a_author None if a_author in d d a_author Author objects get_or_create a_author d a_author 0 tags d get tags if tags in d del d tags book Book d try book validate_unique with transaction atomic book save book tags add tag for tag in tags if tag book save stats imported 1 except ValidationError as e stats skipped 1 logger info Book already imported skipping title s book a_title except Exception as e stats errors 1 logger warn Error adding book title s s book a_title e logger info addbooks complete total total d imported imported d skipped skipped d errors errors d stats
initializes the required arguments for managedsystempcmpreferences,def __init__ self ip managedsystem_id x_api_session self service pcm self root ManagedSystem self ip ip self x_api_session x_api_session self managedsystem_id managedsystem_id
return list of predefined options .,def get_options self view options self options if options if callable options options options return options return None
a vectorized function that returns the value of the look ahead estimate at the values in the array y.,def __call__ self y k len y v self p self X y reshape 1 k psi_vals np mean v axis 0 return psi_vals flatten
: param num_features_lr : size of left or right features vectors : param num_features_c : size of central features vectors : param num_pitches : size of output : param num_units_lstm : list of lstm layer sizes : param num_dense : : return :,def deepbach_skip_connections num_features_lr num_features_c num_features_meta num_pitches num_units_lstm 200 num_dense 200 timesteps 16 left_features Input shape timesteps num_features_lr name left_features right_features Input shape timesteps num_features_lr name right_features central_features Input shape num_features_c name central_features left_metas Input shape timesteps num_features_meta name left_metas right_metas Input shape timesteps num_features_meta name right_metas central_metas Input shape num_features_meta name central_metas embedding_left Dense input_dim num_features_lr num_features_meta units num_dense name embedding_left embedding_right Dense input_dim num_features_lr num_features_meta units num_dense name embedding_right predictions_left concatenate left_features left_metas predictions_right concatenate right_features right_metas predictions_center concatenate central_features central_metas predictions_left Dropout 0 2 predictions_left predictions_right Dropout 0 2 predictions_right predictions_center Dropout 0 2 predictions_center predictions_left TimeDistributed embedding_left predictions_left predictions_right TimeDistributed embedding_right predictions_right predictions_center Dense num_dense activation relu predictions_center predictions_center Dense num_dense activation relu predictions_center return_sequences True for k stack_index in enumerate range len num_units_lstm if k len num_units_lstm 1 return_sequences False if k 0 predictions_left_tmp add Activation relu predictions_left predictions_left_old predictions_right_tmp add Activation relu predictions_right predictions_right_old else predictions_left_tmp predictions_left predictions_right_tmp predictions_right predictions_left_old predictions_left predictions_right_old predictions_right predictions_left predictions_left_tmp predictions_right predictions_right_tmp predictions_left LSTM num_units_lstm stack_index return_sequences return_sequences name lstm_left_ str stack_index predictions_left predictions_right LSTM num_units_lstm stack_index return_sequences return_sequences name lstm_right_ str stack_index predictions_right predictions_left_old Lambda lambda t t 1 output_shape lambda input_shape input_shape 0 input_shape 1 predictions_left_old predictions_right_old Lambda lambda t t 1 output_shape lambda input_shape input_shape 0 input_shape 1 predictions_right_old predictions_left concatenate Activation relu predictions_left predictions_left_old predictions_right concatenate Activation relu predictions_right predictions_right_old predictions concatenate predictions_left predictions_center predictions_right predictions Dense num_dense activation relu predictions pitch_prediction Dense num_pitches activation softmax name pitch_prediction predictions model Model inputs left_features central_features right_features left_metas right_metas central_metas outputs pitch_prediction model compile optimizer adam loss pitch_prediction categorical_crossentropy metrics accuracy model summary return model
set the form value to appear like it was submitted,def set_form_value self name value if not name return self request params name value
insert new entry in database .,def db_insert db_in table dict_in connection db_in connection cursor keys values for key value in dict_in items keys append key if isinstance value str values append value replace else values append str value for key in keys try connection execute ALTER TABLE s ADD COLUMN s table name key except sqlite3 OperationalError pass connection execute INSERT INTO s s VALUES s table name join keys join values return_entry Entry connection lastrowid db_in table dict_in db_in connection commit return return_entry
constructor for amazon alexa requests . : param event : < dict > json : param user : < baseuser > user object,def __init__ self event user None super AlexaSkill self __init__ event user None self skill_type Alexa self event event if user self user user intent self event request get intent session self event get session self parameters self slots_to_dict intent get slots self attributes session get attributes self _contexts self attributes get self DEFAULT_CONTEXT self user_id self event session user userId self intent_name intent get name self request_type self event request get type
initiate an instance of the cachehandler,def __init__ self cacheObject None logger None CacheBase __init__ self logger self __Log Init cache handler decorator self __Log cacheObject __class__ if cacheObject is None self __cacheObject dict else self __cacheObject cacheObject return
wrapper around elementtree.fromstring with some extras .,def parse_xml data name XML ignore_ns False exception PluginError schema None if is_py2 and isinstance data unicode data data encode utf8 if ignore_ns data re sub xmlns data try tree ET fromstring data except Exception as err snippet repr data if len snippet 35 snippet snippet 35 raise exception Unable to parse 0 1 2 format name err snippet if schema tree schema validate tree name name exception exception return tree
returns the list of resolvers of this : class:`hostedmediafile ` .,def get_resolvers self validated False if validated self valid_url return self __resolvers
generates an a - instruction from a specified address_value . : param address_value : value of address in decimal . : return : a - instruction in binary ( string ) .,def gen_a_instruction self address_value return 0 self _bits address_value zfill 15
ensure authentication fails when su = false and user i d is valid,def test_authenticate_dont_do_it self self assertEqual self backend authenticate su False user_id self user pk None
loads the development environment set online . : return :,def loadEnvironment development shed development for variable in development os environ HFX ENV unquote variable development variable envVars devVars for var in os environ if var startswith HFX ENV envVars append ENV VAR s s var os environ var elif var startswith HFX devVars append DEV VAR s s var os environ var else pass tools TOOLS_LOGGER info nEnvironment n t s n n t join devVars envVars
return the name attribute from the user profile object,def get_name self user profile UserProfile objects get user user return profile name
gets the user preference value for a given key .,classmethod def get_value cls user preference_key try user_preference cls objects get user user key preference_key return user_preference value except cls DoesNotExist return None
this will replace a link to another piece of courseware to a ' jump_to ' url that will redirect to the right place in the courseware,def replace_jump_to_id_urls text course_id jump_to_id_base_url def replace_jump_to_id_url match quote match group quote rest match group rest return join quote jump_to_id_base_url rest quote return re sub _url_replace_regex jump_to_id replace_jump_to_id_url text
verifies that get_bookmark raises error as expected .,def test_get_bookmark_raises_error self with self assertNumQueries 1 with self assertRaises ObjectDoesNotExist api get_bookmark user self other_user usage_key self vertical_1 location
convert a list of instances into a header list and datarows list .,def format_instances instances features header features datarows getattr x f for f in features for x in instances return header datarows
"call the view for the implementing test class , constructing a request from the parameters .",def call_view self mock_request commentable_id user group_id pass_group_id True pass
return a test course fixture containing a discussion component .,def populate_course_fixture self course_fixture course_fixture add_children XBlockFixtureDesc chapter Test Section add_children XBlockFixtureDesc sequential Test Subsection add_children XBlockFixtureDesc vertical Test Unit add_children XBlockFixtureDesc discussion Test Discussion
"calls safesessionmiddleware.process_response and verifies the response , while expecting the cookie to be deleted if expect_delete_called is true .",def assert_response_with_delete_cookie self expect_delete_called True set_request_user False set_session_cookie False with patch django http HttpResponse set_cookie as mock_delete_cookie self assert_response set_request_user set_request_user set_session_cookie set_session_cookie self assertEquals mock_delete_cookie called expect_delete_called
return dictionary prepared with module content and type for indexing .,def index_dictionary self xblock_body super CapaDescriptor self index_dictionary capa_content re sub re compile solution solution script script style style a z hint a z hint re DOTALL re VERBOSE self data capa_content escape_html_characters capa_content capa_body capa_content capa_content display_name self display_name if content in xblock_body xblock_body content update capa_body else xblock_body content capa_body xblock_body content_type self INDEX_CONTENT_TYPE xblock_body problem_types list self problem_types return xblock_body
the default for an inheritable name is found on a parent .,def default self block name if name in self inheritable_names field block fields name ancestor block get_parent while ancestor is not None if field is_set_on ancestor return field read_json ancestor else ancestor ancestor get_parent return super InheritingFieldData self default block name
sets the config for the service to bootstrap a specific db . : param db_connect_str : : return :,classmethod def setup_engine_config cls db_connect_str from anchore_engine configuration import localconfig localconfig load_defaults localconfig localconfig credentials database db_connect db_connect_str return localconfig localconfig
creates the inception v4 model .,def create_net num_classes 1001 sample_shape 3 299 299 is_training True dropout_keep_prob 0 8 final_endpoint InceptionV4 Mixed_7d aux_endpoint InceptionV4 Mixed_6e end_points name InceptionV4 net end_points inception_v4_base sample_shape final_endpoint final_endpoint aux_endpoint aux_endpoint if aux_endpoint is not None aux_logits end_points aux_endpoint aux blk name AuxLogits net add AvgPooling2D s AvgPool_1a_5x5 blk 5 stride 3 border_mode VALID aux_logits t conv2d net s Conv2d_1b_1x1 blk 128 1 conv2d net s Conv2d_2a blk 768 t get_output_sample_shape 1 3 border_mode VALID net add Flatten s flat blk end_points blk net add Dense s Aux_logits blk num_classes blk name Logits last_layer end_points final_endpoint net add AvgPooling2D s AvgPool_1a blk last_layer get_output_sample_shape 1 3 border_mode VALID last_layer net add Dropout s Dropout_1b blk 1 dropout_keep_prob net add Flatten s PreLogitsFlatten blk end_points blk net add Dense s Logits blk num_classes return net end_points
get pysimplelog pypi 's link .,def get_pypi return __pypi__
compute a score for the given scoringproject .,def score_and_explain self project if project details weekly_applications_estimate project_pb2 LESS_THAN_2 or project details job_search_length_months 2 return scoring_base ExplainedScore 3 project translate_string vous nous avez dit que vous en xc3 xaates au d xc3 xa9but de vos candidatures return scoring_base NULL_EXPLAINED_SCORE
initializes an error with the given message .,def __init__ self msg RuntimeError __init__ self msg
"return the list of all files in bepasty , including metadata in the form :",def get self if not may LIST return Missing Permissions 403 ret for name in current_app storage item current_app storage open name ret name uri url_for bepasty_apis items_detail name name file meta dict item meta return jsonify ret
prepare a named resolver for a given injection point .,def _prime self ip try provider_resolver self _resolvers ip name except KeyError err InjectError No provider for injection point r ip name if not ip implicit raise err def fail_if_injected raise err return fail_if_injected provider self call_inject provider_resolver ip config return self wrap provider
returns the number of forms that are required in this formset .,def initial_form_count self if not self data or self files apps Application objects filter user self user parent self parent app_definition self app_def return apps count return super FormunculousBaseFormSet self initial_form_count
parse pindel options . add region to cmd . : param items : ( dict ) information from yaml : param config : ( dict ) information from yaml ( items[0]['config ' ] ) : param region : ( str or tupple ) region to analyze : param tmp_path : ( str ) temporal folder : returns : ( list ) options for pindel,def _pindel_options items config out_file region tmp_path variant_regions utils get_in config algorithm variant_regions target subset_variant_regions variant_regions region out_file items opts if target if isinstance target basestring and os path isfile target target_bed target else target_bed os path join tmp_path tmp bed with file_transaction config target_bed as tx_tmp_bed if not isinstance region list tuple message Region must be a tuple something odd just happened raise ValueError message chrom start end region with open tx_tmp_bed w as out_handle print s t s t s chrom start end file out_handle opts j remove_lcr_regions target_bed items return opts
run manta analysis inside prepared workflow directory .,def _run_workflow items paired workflow_file work_dir utils remove_safe os path join work_dir workspace data paired tumor_data if paired else items 0 cmd sys executable workflow_file m local j dd get_num_cores data do run cmd Run manta SV analysis utils remove_safe os path join work_dir workspace
generate recalibration tables as inputs to bqsr .,def bqsr_table data in_file dd get_align_bam data out_file s recal table txt utils splitext_plus in_file 0 if not utils file_uptodate out_file in_file with file_transaction data out_file as tx_out_file assoc_files dd get_variation_resources data known k s assoc_files get dbsnp if dbsnp in assoc_files else license license_export data cores dd get_num_cores data ref_file dd get_ref_file data cmd license sentieon driver t cores r ref_file i in_file algo QualCal known tx_out_file do run cmd format locals Sentieon QualCal generate table return out_file
adds gpg keys from all repositories,def _add_apt_gpg_keys env logger info Update GPG keys for repositories standalone http archive cloudera com debian archive key http download virtualbox org virtualbox debian oracle_vbox asc https www postgresql org media keys ACCC4CF8 asc keyserver keyserver ubuntu com 7F0CEB10 keyserver ubuntu com E084DAB9 keyserver ubuntu com D018A4CE keyserver ubuntu com D67FC6EAE2A11821 standalone keyserver env flavor rewrite_apt_keys standalone keyserver for key in standalone with settings warn_only True env safe_sudo wget q O s apt key add key for url key in keyserver with settings warn_only True env safe_sudo apt key adv keyserver s recv s url key with settings warn_only True env safe_sudo apt get update env safe_sudo sudo apt get install y force yes bio linux keyring
fetches the updated ring from redis and updates the current ranges .,def update self ring self _fetch n_replicas len ring replica_set set r 1 for r in self replicas self ranges for n start replica in enumerate ring if replica in replica_set end ring n 1 n_replicas 0 RING_SIZE if start end self ranges append start end elif end start self ranges append start RING_SIZE self ranges append 0 end else self ranges append 0 RING_SIZE
tests to see if a particular folder exists,def assert_folder_exists target_dir sub_dir assert os path exists os path join target_dir sub_dir
construct a typical queryset for retrieving all relevant assertions from conceptnet :,def conceptnet_queryset lang None cutoff DEFAULT_CUTOFF queryset Assertion useful filter score__gt 0 if lang is not None queryset queryset filter language lang if cutoff queryset queryset filter concept1__num_assertions__gte cutoff concept2__num_assertions__gte cutoff return queryset
parameters ---------- mols : obj list of rdkit molecule objects verbose : bool how much logging log_every_n : how often to log returns ------- obj numpy array of features,def featurize self smiles verbose True log_every_n 1000 if self charset is None self charset self _create_charset smiles return np array self one_hot_encoded smile for smile in smiles
reproduces the failure described in python-893,def test_creation_warning_on_long_column_list self if not NAMEDTUPLE_CREATION_BUG named_tuple_factory self long_colnames self long_rows return with warnings catch_warnings record True as w rows named_tuple_factory self long_colnames self long_rows self assertEqual len w 1 warning w 0 self assertIn pseudo_namedtuple_factory str warning self assertIn 3 7 str warning for r in rows self assertEqual r col0 self long_rows 0 0
cloud - specific method of pulling keys,def _pull_key self key path no_progress_bar False pass
tests that no xml file is generated if the default xml listener is shut down before run_all_tests is invoked .,def testSuppressedXmlOutput self xml_path os path join gtest_test_utils GetTempDir GTEST_PROGRAM_NAME out xml if os path isfile xml_path os remove xml_path command GTEST_PROGRAM_PATH s xml s GTEST_OUTPUT_FLAG xml_path shut_down_xml p gtest_test_utils Subprocess command if p terminated_by_signal self assertFalse p terminated_by_signal s was killed by signal d GTEST_PROGRAM_NAME p signal else self assert_ p exited self assertEquals 1 p exit_code s exited with code s which doesn t match the expected exit code s command p exit_code 1 self assert_ not os path isfile xml_path
get all tags where the user is registered as : class:`~.devilry.apps.core.models.relateduser . relatedstudent ` .,def filter_tags_for_related_student_user self user u n Get all tags where the user is registered as n class devilry apps core models relateduser RelatedStudent n n Args n user class devilry account models User instance n n Returns n QuerySet QuerySet of class PeriodTag n return self filter relatedstudents__user user
"roidb are list , concat them together",def merge_roidb roidbs roidb roidbs 0 for r in roidbs 1 roidb extend r return roidb
this function calculates the ' --help ' text for ' --download ' .,def help return Select which packages may be auto downloaded valid values are none all s default is s join download_types download_default
converts a refine project i d to a source_id for opencontext,def convert_refine_to_source_id self refine_project if refine_project is not False source_id ref str refine_project else source_id False return source_id
parses a trinomial into its parts . this will need modification + exceptions to handle trinomials for other states . see : http://en.wikipedia.org/wiki/smithsonian_trinomial,def parse_trinomial self trinomial non_zero_found False tri_len len trinomial act_part state parts state county site i 0 while i tri_len act_char trinomial i if act_part state if not act_char isdigit act_part county if act_part county if act_char isdigit act_part site parts act_part act_char i 1 if self remove_prepended_zeros int_site False try int_site int float parts site except int_site False if int_site is not False parts site int_site return parts
"parses a solr_value string into slug , solr - data - type , uri , and label parts",def parse_solr_value_parts self solr_value output False if ___ in solr_value solr_ex solr_value split ___ if len solr_ex 4 output output slug solr_ex 0 output data_type solr_ex 1 output uri solr_ex 2 output label solr_ex 3 output uuid None if in output uri uri_ex output uri split if len uri_ex 0 output uuid uri_ex 1 output href self make_url_from_val_string output uri return output
bool : whether the session is using marionette .,def ismarionette session return getattr session driver _marionette False
"get a list of keywords and phrases from the keyword input field , using : meth:`eulcommon.searchutil.search_terms ` . assumes that the form has already been validated and cleaned_data is available .",def search_terms self keywords self cleaned_data keyword keywords re sub http ark 1 keywords return re sub http ark 1 term for term in search_terms keywords
print attributes of an rds instance .,def print_rds_instance dbinstance full False indentspaces 0 indent indentspaces print indent id id format indent indent id dbinstance id indent indentspaces 3 if full attrnames sorted dbinstance __dict__ keys else attrnames status endpoint DBName master_username instance_class availability_zone for attrname in attrnames if attrname startswith _ continue value dbinstance __dict__ attrname if not isinstance value str unicode bool int value pformat value print indent attrname value format vars
injects ` has_delete_permission ` field which indicates the user is authorized to remove comment or not .,def dehydrate self bundle if bundle request is not None and bundle request user is_authenticated bundle data has_delete_permission bundle request user pk bundle data get user_id return bundle
"after successful login , user should get 403 on secret page .",def test_default_login_forbidden active_user authable_app authable_app get secret status 302 forbidden authable_app get secret xhr True status 403 assert forbidden json status is False authenticate authable_app authable_app get secret status 403 forbidden authable_app get secret xhr True status 403 assert forbidden json status is False assert login_url not in forbidden json
utility function to obtain a graph from a tree in a single line,def parseGraph t pg GraphRepresentation t return pg gr
"f_locals is not guaranteed to have .get ( ) , but it will always support _ _ getitem__. even if it does n't , we return `` default `` .",def _getitem_from_frame f_locals key default None try return f_locals key except Exception return default
return a copy of the correlation matrix after having dropped whatever columns . : returns : pd dataframe,def sub_correlation_matrix self return self _sub_correlation_matrix copy
sanitizes a hostname for consistent search functionality .,classmethod def NormalizeHostname cls hostname strip_fqdn False if strip_fqdn hostname hostname partition 0 return hostname lower
get a resource as a string ; see _ call .,def GetResource name return _Call pkg_resources resource_string name
finds connected device matching device_name .,def get_scanner_device self devices evdev InputDevice x for x in evdev list_devices for dev in devices if str dev name self _device_name return dev raise NoMatchingDevice self _device_name d name for d in devices check permissions
convert the provided metrics headers to a string .,def stringify metrics_headers metrics_headers collections OrderedDict metrics_headers return join s s k v for k v in metrics_headers items
blocking call to retrieve n coordinate pairs through mouse clicks .,def __call__ self n 1 timeout 30 show_clicks True u n Blocking call to retrieve n coordinate pairs through mouse n clicks n self show_clicks show_clicks self clicks self marks BlockingInput __call__ self n n timeout timeout return self clicks
"parse probe result : ' [ prb:99.000,99.000,-1.959:1 ] '",def probe_grbl ln match grbl_probe_re match ln if match is None raise ParseError Unable to parse probe response format ln x y z success match groups return float x float y float z bool success
"the function scales the parameters from -1 and 1 to the given interval ( min , max ) for each actor .",def denormalize self actors assert len self actor_limits len actors result for l a in zip self actor_limits actors if not l result append a else r a 1 0 2 l 1 l 0 l 0 if self clipping r clip r l 0 l 1 result append r return result
"trains the network on the stored dataset . if convergence is > 0 , check after that many epoch increments whether test error is going down again , and stop training accordingly .",def runTraining self convergence 0 kwargs assert isinstance self Trainer Trainer if self Graph is not None self Graph setLabels x epoch y classification error self Graph setLegend training test loc lower right epoch 0 inc self epoinc best_error 100 0 best_epoch 0 learncurve_x 0 learncurve_y 0 0 valcurve_y 0 0 converged False convtest 0 if convergence 0 logging info Convergence criterion d batches of d epochs w o improvement convergence inc while epoch self maxepochs and not converged self Trainer trainEpochs inc epoch inc learncurve_x append epoch if isinstance self DS SequentialDataSet r_trn 100 0 1 0 testOnSequenceData self Trainer module self DS else out trueclass self Trainer testOnClassData return_targets True r_trn 100 0 1 0 Validator classificationPerformance out trueclass learncurve_y append r_trn if self TDS is None logging info epoch 6d err_trn 5 2f epoch r_trn else if isinstance self DS SequentialDataSet r_tst 100 0 1 0 testOnSequenceData self Trainer module self TDS else out trueclass self Trainer testOnClassData return_targets True dataset self TDS r_tst 100 0 1 0 Validator classificationPerformance out trueclass valcurve_y append r_tst if r_tst best_error best_epoch epoch best_error r_tst bestweights self Trainer module params copy convtest 0 else convtest 1 logging info epoch 6d err_trn 5 2f err_tst 5 2f best_tst 5 2f epoch r_trn r_tst best_error if self Graph is not None self Graph addData 1 epoch r_tst if convtest convergence converged True if self Graph is not None self Graph addData 0 epoch r_trn self Graph update logging info Best epoch 6d with error 5 2f best_epoch best_error if self VDS is not None self Trainer module params bestweights copy if isinstance self DS SequentialDataSet r_val 100 0 1 0 testOnSequenceData self Trainer module self VDS else out trueclass self Trainer testOnClassData return_targets True dataset self VDS r_val 100 0 1 0 Validator classificationPerformance out trueclass logging info Result on evaluation data 5 2f r_val self trainCurve learncurve_x learncurve_y valcurve_y
prints out ( to stdout ) a representation intended to help with debugging,def DebugFormat self print FormatAsBits self output self out_boff for i in xrange self idx_byte 8 self idx_boff 1 if not i 8 sys stdout write sys stdout write print
returns the pretty - print string for tree with indentation given by the string tab .,def __str__ self return n join compose_lines self n
remove the keystroke interceptor and resume normal behavior .,def remove_any_key_handler self raise NotImplemented
"find the latest build for the given commit and return it , or none if no build for the commit yet .",def commit_latest_build_status self commit build self _latest_travis_build commit if build is None return None logger info Found latest build for commit s s s commit build number build id return build
verify that flush will force a write .,def test_5_flush self f LoopbackFile r 512 f write Not nquite n512 bytes n self assertEqual f read 1 f flush self assertEqual f read 5 Not nq self assertEqual f read 10 uite n512 b self assertEqual f read 9 ytes n self assertEqual f read 3 f close
"displays each of the input images in order , pausing for "" delay "" seconds after each image .",def animate self images delay 0 25 for image in images self set_image image self write_display time sleep delay
register available commands method and return the list of commands name,def _register_commands self u register available commands method and return the list of n commands name n self commands self _command_help commands attr 3 for attr in dir self if attr 3 u do_ for command in commands topic self CMD_MAP command help_method getattr self u help_do_ s command self _topics setdefault topic append help_method self commands self CMD_PREFIX command command self _command_help command help_method return list self commands keys
called to publish the package to pypi .,def run self if self bump major new 0 1 2 format VER 0 1 0 0 elif self bump minor new 0 1 2 format VER 0 VER 1 1 0 elif self bump micro new 0 1 2 format VER 0 VER 1 VER 2 1 else raise Exception bump must be major minor or micro user self github_user encode utf 8 token self github_token encode utf 8 encode base64 b64encode user token call git pull sha call git rev parse HEAD strip name call git log format an n 1 0 format sha strip email call git log format ae n 1 0 format sha strip tagdata tag new message Publishing version new object sha type commit tagger name name email email date datetime datetime utcnow isoformat Z request url Request https api github com repos 0 git tags format self github_slug request add_header Authorization Basic encode request add_header Content Type application json response url urlopen request json dumps tagdata encode utf 8 print response refdata ref refs tags new sha sha request url Request https api github com repos 0 git refs format self github_slug request add_header Authorization Basic encode request add_header Content Type application json response url urlopen request json dumps refdata encode utf 8 call git pull call python setup py sdist call python setup py bdist_wheel if not os path exists os path expanduser pypirc config configparser RawConfigParser config add_section distutils config set distutils index servers pypi config add_section pypi config set pypi repository https pypi python org pypi config set pypi username self pypi_user config set pypi password self pypi_pass with open os path expanduser pypirc w as pypirc_file config write pypirc_file call twine upload dist
"purpose : calculates the norm difference between two joints over m timesteps : ||jointxyz1_i - jointxyz2_i|| , i = 0:m-1",def getJointDifference jointxyz1 jointxyz2 jointdiff np linalg norm jointxyz1 jointxyz2 axis 1 return jointdiff
construct the dataset based on the data in the files .,def __init__ self filenames filename_to_examples relative_path True shuffle True self _examples if isinstance filenames basestring filenames filenames for filename in filenames if relative_path filename os path join DataDirectory root filename self _examples extend filename_to_examples filename if shuffle with random_seed 42 random shuffle self _examples logging info Read examples from format len self _examples shuffled if shuffle else not shuffled filenames
"produces standard normally distributed random numbers with shape ( n , n )",def rand_numbers wb Workbook Book1 n int Range Sheet1 B1 value rand_num np random randn n n Range Sheet1 C3 value rand_num
set the user mirror setting .,def setMirrorEnabled self value logger info Set mirror enabled s value self settings mirrorEnabled value self mirrorChanged emit bool value
set up the test case by initiating the class .,def setUp self class RadTest object ab RadianceNumber ab ambinent bounces valid_range None accepted_inputs None num_type int check_positive True default_value None ad RadianceNumber ad ambinent divisions valid_range 1 128 accepted_inputs None num_type None check_positive True default_value None d RadianceBoolFlag d sun mtx only default_value None is_dual_sign False i RadianceBoolFlag I illuminance default_value None is_dual_sign True c RadianceTuple C color default_value None num_type int valid_range 0 255 o RadianceValue o output format default_value None accepted_inputs f d isJoined True weaFile RadiancePath weaFile Weather File Path relativePath None checkExists False extension wea def __init__ self pass def to_rad_string self _radString join self ab to_rad_string self ad to_rad_string self d to_rad_string self i to_rad_string self c to_rad_string self o to_rad_string self wea_file to_rad_string return _radString strip class RadTestWithDefaults RadTest ab RadianceNumber ab ambinent bounces valid_range None accepted_inputs None num_type int check_positive True default_value 2 ad RadianceNumber ad ambinent divisions valid_range 1 128 accepted_inputs None num_type None check_positive True default_value 5 d RadianceBoolFlag d sun mtx only default_value False is_dual_sign False i RadianceBoolFlag I illuminance default_value False is_dual_sign True c RadianceTuple C color default_value 250 250 250 num_type int valid_range 0 255 o RadianceValue o output format default_value f accepted_inputs f d isJoined True def __init__ self self wea_file c ladybug test wea self rad RadTest self rad_with_def RadTestWithDefaults
"specify 0 for visible radiation , 1 for total solar radiation .",property def sky_type self return self _sky_type
dispatches events to python user qemu monitor event callbacks,def _dispatchQemuMonitorEventCallback conn dom event seconds micros details cbData cb cbData cb opaque cbData opaque cb conn libvirt virDomain conn _obj dom event seconds micros details opaque return 0
"convert python object(s ) into lua object(s ) , as at times python object(s ) are not compatible with lua functions",staticmethod def _python_to_lua pval import lua if pval is None return lua eval if isinstance pval list tuple set lua_list lua eval lua_table lua eval table for item in pval lua_table insert lua_list Script _python_to_lua item return lua_list elif isinstance pval dict lua_dict lua eval lua_table lua eval table for k v in pval iteritems lua_table insert lua_dict Script _python_to_lua k lua_table insert lua_dict Script _python_to_lua v return lua_dict elif isinstance pval str return pval elif isinstance pval bool return lua eval str pval lower elif isinstance pval int long float lua_globals lua globals return lua_globals tonumber str pval raise RuntimeError Invalid Python type str type pval
whether the buffer should be flushed .,def is_ready self return self _size self size_limit
""" build vocabulary , the lookup table and transform the text",def build_vocabulary sim_data non_sim_data train_texts for data in sim_data train_texts append data sentence_1 train_texts append data sentence_2 for data in non_sim_data train_texts append data sentence_1 train_texts append data sentence_2 max_document_length max len x split for x in train_texts print The max document length is format max_document_length vocab_processor learn preprocessing VocabularyProcessor max_document_length vocab_processor vocab_processor fit train_texts print Vocabulary Size d format len vocab_processor vocabulary_ return vocab_processor max_document_length
int : the number of strong references int : the number of weak references,property def count self return len self 0
l is a list on integers,def swapSort L print Original L L for i in range len L for j in range i 1 len L if L j L i L j L i L i L j print i j L print Final L L
produce help output related to command synopsis,def showInvLines rh if rh subfunction rh printLn N Usage rh printLn N python rh cmdName CmdVM userid cmd cmdToSend rh printLn N python rh cmdName CmdVM help rh printLn N python rh cmdName CmdVM version return
generate a group of [ nstars ] stars with initial positions and velocities normally distributed with appropriate means and stdevs . generated stars will have negligible but non - zero position and velocitie uncertainties,def generate_stars nstars pos_mu pos_sig vel_mu vel_sig init_pos_mu np random normal pos_mu pos_sig nstars init_vel_mu np random normal vel_mu 1 nstars init_pos_sig np zeros nstars 0 01 init_vel_sig np zeros nstars 0 01 gen_stars np vstack init_pos_mu init_pos_sig init_vel_mu init_vel_sig T return gen_stars
fulfill ' name ' field for objects under ' # /definitions ' and with ' properties ',Disp register Schema def _schema self path obj app if path startswith definitions last_token jp_split path 1 if app version 1 2 obj update_field name scope_split last_token 1 else obj update_field name last_token
return the successor of the binary tree node n.,def successor n if n right is not None return leftmost n right while n parent is not None and n parent right n n n parent return n parent
update the interest sets of one receiver based on the latest tracking and rate report data .,profile trackcpu def update_interest self receiver if receiver last_rate_report is None new_sync ac for ac in receiver tracking if len ac tracking 1 new_mlat ac for ac in receiver tracking if ac allow_mlat receiver update_interest_sets new_sync new_mlat asyncio get_event_loop call_later 15 0 receiver refresh_traffic_requests return ac_to_ratepair_map ratepair_list for icao rate in receiver last_rate_report items if rate 0 2 continue ac self aircraft get icao if not ac continue ac_to_ratepair_map ac l for r1 in ac tracking if receiver is r1 continue if r1 last_rate_report is None rate1 1 0 else rate1 r1 last_rate_report get icao 0 0 rp rate rate1 4 0 if rp 0 1 continue ratepair rp r1 ac l append ratepair ratepair_list append ratepair ratepair_list sort ntotal new_sync_set set for rp r1 ac in ratepair_list if ac in new_sync_set continue if ntotal get r1 0 0 1 0 new_sync_set add ac for rp2 r2 ac2 in ac_to_ratepair_map ac ntotal r2 ntotal get r2 0 0 rp2 new_mlat_set set for ac in receiver tracking if ac icao not in receiver last_rate_report and ac allow_mlat new_mlat_set add ac receiver update_interest_sets new_sync_set new_mlat_set asyncio get_event_loop call_later 15 0 receiver refresh_traffic_requests
is the timestamp that is part of the specified nonce string within the allowed clock - skew of the current time ?,def checkTimestamp nonce_string allowed_skew SKEW now None try stamp _ split nonce_string except ValueError return False else if now is None now time past now allowed_skew future now allowed_skew return past stamp future
return the parameters used to configure this exporter .,def parameters self raise Exception Abstract method must be overridden in subclass
"prepares a given environment , by adding library dependencies .",def UseLibraries env libs arch None if not arch and env ARCH host or arch and env ARCH arch return for lib in libs env Append CPPPATH lib lib env Append LIBPATH env BUILDROOT lib lib env Append LIBS lib
return an instance of the model we will use .,def instantiateModel args kValues keywords 21 args networkConfig getNetworkConfig args networkConfigPath args k kValues get args modelName 1 model createModel vars args return model
"write dictionary to a csv , where keys are row numbers and values are a list .",def writeFromDict dataDict headers csvFile with open csvFile wb as f writer csv writer f delimiter writer writerow headers for row in sorted dataDict keys writer writerow dataDict row
sets the state of a sax2 feature .,def setFeature self name state raise SAXNotRecognizedException Feature s not recognized name
"run custom site specific code , if available .",def execsitecustomize try import sitecustomize except ImportError pass
each vendors will have some plugins to do some operations .,def process_data self oper SCAN kwargs raise NotImplementedError
pop an instance uuid off the set of instances to update .,lockutils synchronized LOCK_NVRAM_UPDT_SET def _pop_from_set self uuid None try if uuid is None return self _update_set pop else self _update_set remove uuid return uuid except KeyError return None
"if failed is true , returns a human - readable description of the error .",def ErrorText self u raise NotImplementedError
creates and returns a new entry for the cache .,def _new_entry self site using return self db_manager using create site site
assert no errors occur during scatter visualizer integration,def test_scatter self X_two_cols self X 2 features temperature relative_humidity visualizer ScatterViz features features visualizer fit_transform X_two_cols self y
"the fit method is the primary drawing input for the tsne projection since the visualization requires both x and an optional y value . the fit method expects an array of numeric vectors , so text documents must be vectorized before passing them to this method .",def fit self X y None kwargs if y is not None self classes_ np unique y elif y is None and self labels is not None self classes_ np array self labels 0 else self classes_ np array self NULL_CLASS vecs self transformer_ fit_transform X self n_instances_ vecs shape 0 self draw vecs y kwargs return self
"tries to deserialize a message , might fail if data is missing",classmethod def read cls data protocol None fallback_protocol TBinaryProtocol finagle_thrift False max_fields MAX_FIELDS max_list_size MAX_LIST_SIZE max_map_size MAX_MAP_SIZE max_set_size MAX_SET_SIZE read_values False if len data cls MIN_MESSAGE_SIZE raise ValueError not enough data if protocol is None protocol cls detect_protocol data fallback_protocol trans TTransport TMemoryBuffer data proto protocol trans header None if finagle_thrift try header ThriftStruct read proto max_fields max_list_size max_map_size max_set_size read_values except trans TTransport TMemoryBuffer data proto protocol trans method mtype seqid proto readMessageBegin mtype cls message_type_to_str mtype if len method 0 or method isspace or method startswith raise ValueError no method name if len method cls MAX_METHOD_LENGTH raise ValueError method name too long valid range 33 127 if any ord char not in valid for char in method raise ValueError invalid method name method args ThriftStruct read proto max_fields max_list_size max_map_size max_set_size read_values proto readMessageEnd msglen trans _buffer tell return cls method mtype seqid args header msglen msglen
past -- paste one image into another,def chunk_PAST self offset bytes if self count 0 raise SyntaxError misplaced PAST chunk if self repair is not None self images self id self images self repair copy self repair None s self fp read bytes im self images i16 s x y i32 s 2 6 i32 s 6 10 bbox x y im size 0 x im size 1 y if im mode in RGBA self images self id paste im bbox im else self images self id paste im bbox self action PAST self __store return s
ahvrr colormap used by noaa coastwatch .,def avhrr_cm m 256 x np arange 0 0 m m 1 xr 0 0 0 2 0 4 0 5 0 6 0 8 1 0 rr 0 5 1 0 1 0 0 5 0 5 0 0 0 5 xg 0 0 0 4 0 6 1 0 gg 0 0 1 0 1 0 0 0 xb 0 0 0 2 0 4 0 5 0 6 0 8 1 0 bb 0 0 0 0 0 5 0 5 1 0 1 0 0 5 r np interp x xr rr g np interp x xg gg b np interp x xb bb return np flipud np c_ r g b
test depolarizing on a simple qubit state,def test_depolarizing self test_density_matrix depolarizing_channel self cat_matrix 0 1 self assertAlmostEquals norm self cat_matrix test_density_matrix 0 0 test_density_matrix depolarizing_channel self cat_matrix 0 1 transpose True self assertAlmostEquals norm self cat_matrix test_density_matrix 0 0 correct_density_matrix array 0 27777778 0 0 0 0 0 05555556 0 0 0 22222222 0 0 0 0 0 0 0 0 0 22222222 0 0 0 05555556 0 0 0 0 0 27777778 test_density_matrix depolarizing_channel self cat_matrix 1 0 test_density_matrix depolarizing_channel test_density_matrix 1 1 self assertAlmostEquals norm correct_density_matrix test_density_matrix 0 0 places 6 test_density_matrix depolarizing_channel self cat_matrix 1 0 transpose True test_density_matrix depolarizing_channel test_density_matrix 1 1 transpose True self assertAlmostEquals norm correct_density_matrix test_density_matrix 0 0 places 6 correct_density_matrix eye 4 4 0 test_density_matrix depolarizing_channel self cat_matrix 1 All self assertAlmostEquals norm correct_density_matrix test_density_matrix 0 0 places 6
should be able to cap the number of rows,def test_max_rows self self render_config_template mysql_ports 3306 mysql_max_row_length 79 mysql_max_rows 5 mysql_send_response True self run_packetbeat pcap mysql_long_result pcap debug_selectors mysqldetailed objs self read_output assert len objs 1 res objs 0 assert res mysql num_rows 15 lines res response strip split n assert len lines 6 for line in lines 3 assert len line 81
returns the authorization password of the account .,def get_authorization_password self return self authorization_password or self password
event executed after each command when it fails . get the output of the command and create a failure jobstate and a file associated .,def v2_runner_on_failed self result ignore_errors False if not self _job_id return super CallbackModule self v2_runner_on_failed result ignore_errors try output Formatter format result except Exception as e output An error while parsing the output occured please reach to distributed ci redhat com s e if ignore_errors self post_message result output return if self _current_status in new pre run status error else status failure self create_jobstate status status comment self task_name result self post_message result output
estimate a quantum process from single shot histograms obtained by preparing specific input states and measuring bitstrings in the z - eigenbasis after application of given channel operators .,staticmethod def estimate_from_ssr histograms readout_povm pre_channel_ops post_channel_ops settings nqc len pre_channel_ops 0 dims 0 pauli_basis grove tomography operator_utils PAULI_BASIS nqc pi_basis readout_povm pi_basis if not histograms shape 1 pi_basis dim raise ValueError Currently tomography is only implemented for two level systems rho0 grove tomography operator_utils n_qubit_ground_state nqc n_lkj np asarray histograms b_jkl_mn _prepare_b_jkl_mn readout_povm pauli_basis pre_channel_ops post_channel_ops rho0 r_mn cvxpy Variable pauli_basis dim 2 p_jkl b_jkl_mn real r_mn obj np matrix n_lkj ravel cvxpy log p_jkl p_jkl_mat cvxpy reshape p_jkl pi_basis dim len pre_channel_ops len post_channel_ops constraints p_jkl 0 np matrix np ones 1 pi_basis dim p_jkl_mat 1 r_mn_mat cvxpy reshape r_mn pauli_basis dim pauli_basis dim super_pauli_basis pauli_basis super_basis choi_real_imag sum r_mn_mat jj kk o_ut to_realimag super_pauli_basis ops jj kk pauli_basis dim for jj in range pauli_basis dim for kk in range pauli_basis dim 0 if COMPLETELY_POSITIVE in settings constraints if tomography _SDP_SOLVER is_functional constraints append choi_real_imag 0 else _log warning No convex solver capable of semi definite problems installed Dropping the complete positivity constraint on the process if TRACE_PRESERVING in settings constraints constraints append r_mn_mat 0 0 1 constraints append r_mn_mat 0 1 0 prob cvxpy Problem cvxpy Minimize obj constraints _ prob solve solver tomography SOLVER settings solver_kwargs r_mn_est r_mn value reshape pauli_basis dim pauli_basis dim transpose return ProcessTomography r_mn_est pauli_basis settings
update the status of a support case,def do_update self args case_fields args split if len case_fields 2 return self do_help args input_data status case_fields 1 url s s self baseurl case_fields 0 case_info api_call url data input_data calltype put print case_info
"get the environment variable var_name , or raise an exception .",def env_var var_name try return os environ var_name except KeyError msg You need to set the environment variable format var_name raise ImproperlyConfigured msg
testing sort behavior by sorting any kind of data type together and compare the result with mongodb,def test_sort_behavior collection dirname os path dirname __file__ source os path join dirname dataset_sample mixed_type json dataset with open source as data_file for line in data_file dataset append json loads line for i d in enumerate dataset d _id i 1 collection mongo delete_many collection mongo insert_many dataset collection tiny delete_many collection tiny insert_many dataset sort_by item 1 amount 1 mongo_find collection mongo find sort sort_by tiny_find collection tiny find sort sort_by assert mongo_find count tiny_find count no_difference True for i m_data in enumerate mongo_find if not m_data tiny_find i no_difference False assert no_difference
check the table is not missing rows or columns we should have at least one entry in every row and one entry in every colum of each dma table,def check_full_table table stream_mask 0 0 channel_mask 0 0 for k in table for v in table k engine stream channel v if engine 2 or engine 1 error Bad entry for s s k v stream_mask engine 1 1 stream channel_mask engine 1 1 channel for i in range 2 for c in range 8 if not 1 c channel_mask i error Missing channel u for dma table u c i if not 1 c stream_mask i error Missing stream u for dma table u c i
look for workitems in ` work_db ` that should not be mutated due to spor metadata .,def intercept work_db for item in work_db work_items try anchors tuple find_anchors item filename except ValueError log info No spor repository for s item filename continue for anchor in anchors metadata anchor metadata if item line_number anchor line_number and not metadata get mutate True item worker_outcome WorkerOutcome SKIPPED log info skipping s item work_db update_work_item item
: param observations : vector of x vectors : return : theta ( estimated using maximum likelihood estimation ),def mle self observations theta_start self theta0 func self _get_nll_func observations theta_min fmin func theta_start return theta_min
start the cherrypy app server in ' serverless ' mode ( for modpython / wsgi ) .,def startup_modpython req None if cherrypy engine state cherrypy _cpengine STOPPED if req if nullreq in req get_options cherrypy engine request_class NullRequest cherrypy engine response_class NullResponse ab_opt req get_options get ab if ab_opt global AB_PATH AB_PATH ab_opt cherrypy engine start if cherrypy engine state cherrypy _cpengine STARTING cherrypy engine wait return 0
"this function just mimics the function with the same name from the c client . we do n't really care which file descriptor the server tells us to write to - stdout and stderr are the same on vim side ( see eclim.bat , "" 2>&1 "" at the end of command ) .",def recvToFD self destFD buf lenPayload received self recvBlocked lenPayload return received
load the data from a file .,def load self encoding u utf8 encoding_errors u ignore u Load the data from a file n n param str encoding The character encoding of the file n param str encoding_errors How to handle encoding errors n rtype io StringIO n if isinstance self codec codec NoCodec and self fs load_text FileSystem load_text stream self fs load_text encoding encoding_errors else stream self fs load stream self codec decompress stream stream TextIOWrapper stream encoding encoding_errors return stream
opens stock tensorboard web assets collection .,def get_assets_zip_provider path os path join tf resource_loader get_data_files_path webfiles zip if not os path exists path logger warning webfiles zip static assets not found s path return None return lambda open path rb
remove any previous test profiles1 .,def tearDown self try profile1 models Profile objects get name TEST_PROFILE for rsrc in models Resource objects filter profile profile1 rsrc delete profile1 delete except models Profile DoesNotExist pass try hv1 models HV objects get connection CONNECTION product PRODUCT hv1 delete except models HV DoesNotExist pass
yields the changelog notes for a given version .,def get_release_notes self with open ChangeLog as f found_version False for line in f if line startswith self version_name found_version True yield This is Please v s self version elif line startswith continue elif found_version if line startswith Version return elif line startswith line line 3 yield line raise Exception Couldn t find release notes for self version_name
turns string representation of timestamp into an aware datetime object .,def timestamp_converter timestamp dt_naive datetime strptime timestamp Y m d H M S mountain pytz timezone America Dawson_Creek dt_aware mountain localize dt_naive return dt_aware
statement : run newline | list newline | new newline,def p_statement_interactive p p 0 0 p 1 0
in the case you do n't even have wget ...,download_tool urllib2 def urllib2_download client download_url filename resuming False assert not resuming print Downloading download_url to filename request urllib2 Request download_url headers Cookie gdriveid client get_gdriveid response urllib2 urlopen request import shutil with open filename wb as output shutil copyfileobj response output
"openpty ( ) - > ( master_fd , slave_fd ) open a pty master / slave pair , using os.openpty ( ) if possible .",def openpty try return os openpty except AttributeError OSError pass master_fd slave_name _open_terminal slave_fd slave_open slave_name return master_fd slave_fd
yield a doctest - safe sequence of object reprs .,def consts t for elt in t r repr elt if r startswith code object yield code object s elt co_name else yield r
shortcuts for generating request headers .,def make_headers keep_alive None accept_encoding None user_agent None basic_auth None headers if accept_encoding if isinstance accept_encoding str pass elif isinstance accept_encoding list accept_encoding join accept_encoding else accept_encoding gzip deflate headers accept encoding accept_encoding if user_agent headers user agent user_agent if keep_alive headers connection keep alive if basic_auth headers authorization Basic b64encode six b basic_auth decode utf 8 return headers
get the query to obtain properties stored in mongodb . : return mapping : the query to obtain properties stored in mongodb .,property def query self return self _query
return the status of the board,def hardware_status u pipeline redis pipeline for light in range LIGHTS pipeline get u hardware lights format light pipeline get u hardware microcontroller programming pipeline get u hardware microcontroller state results pipeline execute lights_data for pos light_state in enumerate results 0 LIGHTS lights_data u light format pos 1 light_state u on programming state results LIGHTS if programming is not None microcontroller gettext u Programming step s step programming elif state u empty microcontroller gettext u Empty memory elif state u failed microcontroller gettext u Programming failed elif state u programmed microcontroller gettext u Programming worked else microcontroller gettext u Invalid state state s state state task_id weblab_user data get u programming_task if task_id task weblab get_task task_id if task print u Current programming task status s error s result s task status task error task result return dict lights lights_data microcontroller microcontroller time_left weblab_user time_left
search first the vendor package then as a natural package .,property def search_path self yield self vendor_pkg yield
moves a file from one location to another in the safest way possible .,def file_move_safe old_file_name new_file_name chunk_size 1024 64 allow_overwrite False if _samefile old_file_name new_file_name return try if not allow_overwrite and os access new_file_name os F_OK raise IOError Destination file s exists and allow_overwrite is False new_file_name os rename old_file_name new_file_name return except OSError pass with open old_file_name rb as old_file fd os open new_file_name os O_WRONLY os O_CREAT getattr os O_BINARY 0 os O_EXCL if not allow_overwrite else 0 try locks lock fd locks LOCK_EX current_chunk None while current_chunk current_chunk old_file read chunk_size os write fd current_chunk finally locks unlock fd os close fd copystat old_file_name new_file_name try os remove old_file_name except OSError as e if getattr e winerror 0 32 and getattr e errno 0 13 raise
"this is called once every server restart , so we want to add the ( memory - resident ) cmdset to the object here . is_valid is automatically checked so we do n't need to worry about adding the script to an open lid .",def at_start self self obj cmdset add cmdsetexamples LidClosedCmdSet
returns the value of the name property .,def __str__ self return self name
called when mssp is not requested . this is the normal operation .,def no_mssp self option self protocol handshake_done
define l{headers } instances as being equal to each other if they have the same raw headers .,def __cmp__ self other if isinstance other Headers return cmp sorted self _rawHeaders items sorted other _rawHeaders items return NotImplemented
returns the number of points in this linestring .,def __len__ self return len self _cs
tell if a key exists in the mapping ; equivalent to _ _ contains _ _,def has_key key
the xml stream has been initialized .,def connectionInitialized
any child of the i{twisted } package has a privacy according to the general rules defined in pydoctor .,def test_privacyClassPublicCode self sut TwistedSystem twistedPackage model Package system sut name twisted docstring ignored parent None twistedSubProjectPackage model Package system sut name subproject docstring ignored parent twistedPackage twistedSubProjectModule model Module system sut name other_child docstring ignored parent twistedSubProjectPackage twistedPrivateModule model Module system sut name _private_child docstring ignored parent twistedSubProjectPackage result sut privacyClass twistedSubProjectPackage self assertIs result model PrivacyClass VISIBLE result sut privacyClass twistedSubProjectModule self assertIs result model PrivacyClass VISIBLE result sut privacyClass twistedPrivateModule self assertIs result model PrivacyClass PRIVATE
return a value similar to that returned by c{os.path.splitext}.,def splitext self return os path splitext self path
"send text data . this will pre - process the text for color - replacement , conversion to html etc .",def send_text self args kwargs if args args list args text args 0 if text is None return else return flags self protocol_flags text to_str text force_string True options kwargs pop options raw options get raw flags get RAW False nocolor options get nocolor flags get NOCOLOR False screenreader options get screenreader flags get SCREENREADER False prompt options get send_prompt False if screenreader text parse_ansi text strip_ansi True xterm256 False mxp False text _RE_SCREENREADER_REGEX sub text cmd prompt if prompt else text if raw args 0 text else args 0 parse_html text strip_ansi nocolor self sendLine json dumps cmd args kwargs
this is called by render_post when the client is replying to the keepalive .,def mode_keepalive self request csessid request args get csessid 0 self last_alive csessid time time False return
"set a bunch of values in the cache at once from a dict of key / value pairs . for certain backends ( memcached ) , this is much more efficient than calling set ( ) multiple times .",def set_many self data timeout DEFAULT_TIMEOUT version None u n Set a bunch of values in the cache at once from a dict of key value n pairs For certain backends memcached this is much more efficient n than calling set multiple times n n If timeout is given that timeout will be used for the key otherwise n the default cache timeout will be used n for key value in data items self set key value timeout timeout version version
"pickle and b64encode the object , optionally compressing it .",def get_db_prep_value self value connection None prepared False if value is not None and not isinstance value PickledObject value force_text dbsafe_encode value self compress self protocol return value
render the function name this frame references as a child of c{tag}.,renderer def function self request tag return tag self frame 0
"get all of the parent classes of c{c } , not including c{c } itself , which are strict subclasses of l{versioned}.",def _aybabtu c l c Versioned for b in inspect getmro c if b not in l and issubclass b Versioned l append b return l 2
"when used as a context manager , a l{nonepidfile } does n't raise , despite not existing .",def test_contextManager self pidFile NonePIDFile with pidFile pass
is this instance fully loaded / e.g. all data available ?,property def is_fully_loaded self return self full and votes in self
enables specifying a custom gradient .,def custom_gradient fx gx x axis fx_gx_manually_stopped False name None with ops name_scope name custom_gradient fx gx x fx ops convert_to_tensor fx name fx with ops control_dependencies fx gx ops convert_to_tensor gx dtype fx dtype name gx gx array_ops identity gx name gx sum_x math_ops reduce_sum x axis axis name sum_x if not fx_gx_manually_stopped fx array_ops stop_gradient fx gx array_ops stop_gradient gx return sum_x array_ops stop_gradient sum_x gx fx
returns word 's i d in the vocabulary .,def get self category if category not in self _mapping if self _freeze return 0 self _mapping category len self _mapping if self _support_reverse self _reverse_mapping append category return self _mapping category
build a serving_input_receiver_fn expecting fed tf . examples .,def build_parsing_serving_input_receiver_fn feature_spec default_batch_size None def serving_input_receiver_fn An input_fn that expects a serialized tf Example serialized_tf_example array_ops placeholder dtype dtypes string shape default_batch_size name input_example_tensor receiver_tensors examples serialized_tf_example features parsing_ops parse_example serialized_tf_example feature_spec return ServingInputReceiver features receiver_tensors return serving_input_receiver_fn
readahead files not implemented ; simply returns given path .,def readahead_file_path path readahead 128M return path
"undoes all smartset ( ) & set ( ) calls , restoring original definitions .",def CleanUp self self SmartUnsetAll self UnsetAll
insert the dims in ` axis ` back as singletons after being removed .,def _insert_back_keep_dims x axis for i in sorted axis x array_ops expand_dims x axis i return x
"created a list of all the normalized string contained in all the queries passed in the queries list . if after the normalization , the list contains a single string , the result is dropped , and an empty list is returned .",def _normalize_queries queries normalized_queries set for query in queries normalized_query set _normalize_query query if not normalized_queries normalized_queries update normalized_query else normalized_queries intersection_update normalized_query if len normalized_queries 1 logger debug normalized_queries contains only single string dropping s normalized_queries return return list normalized_queries
sets the given session as active for the given site .,def set_active_session self site session apikey return six next six itervalues self zap _request self zap base httpSessions action setActiveSession site site session session apikey apikey
return a list of disk that are not used by storage pool or has a different type as the one required for this cluster,def find_disks self disk_type available_disks for disk in self disks list if disk type name disk_type continue if len disk filesystems 0 continue if len disk partitions 0 available_disks setdefault self name append disk return available_disks
test for the oled pmod .,pytest mark run order 25 pytest mark skipif not flag reason need OLED attached in order to run def test_write_string global oled oled Pmod_OLED oled_id oled draw_line 0 0 255 0 oled draw_line 0 2 255 2 oled write Welcome to PYNQ 0 1 oled draw_line 0 20 255 20 oled draw_line 0 22 255 22 assert user_answer_yes nWelcome message shown on the OLED oled clear assert user_answer_yes OLED screen clear now del oled
computes the likelihood of the data under the hypothesis .,def Likelihood self data hypo std 30 meanx meany hypo x y data like thinkbayes2 EvalNormalPdf x meanx std like thinkbayes2 EvalNormalPdf y meany std return like
get the load balancer notifications for a specific rule within a specifying window time frame : type startdate : datetime : type enddate : datetime : type loadbalancerid : int : type loadbalancerruleid : int : param startdate : from date : param enddate : to date : param loadbalancerid : id of the laod balancer : param loadbalancerruleid : id of the load balancer rule,def get_notifications self startDate endDate loadBalancerID loadBalancerRuleID return self _call GetLoadBalancerNotifications startDate startDate endDate endDate loadBalancerID loadBalancerID loadBalancerRuleID loadBalancerRuleID
"function to return a list with status of tcp connections at linux systems to get pid of all network process running on system , you must run this script as superuser",def netstat typ tcp with open proc net typ r encoding utf8 as f content f readlines content pop 0 result for line in content line_array _remove_empty line split tcp_id line_array 0 l_addr _convert_ip_port line_array 1 r_addr _convert_ip_port line_array 2 state line_array 3 inode int line_array 9 nline tcp_id l_addr r_addr state inode result append nline return result
test otsu of two distributions with no points in between is between the two distributions,def test_02_TwoDistributions self np random seed 0 x0 np random uniform 0 1 0 4 size 1000 x1 np random uniform 0 6 1 0 size 1000 x np append x0 x1 np random shuffle x threshold otsu x self assertTrue threshold 0 4 self assertTrue threshold 0 6
parse a dataframe with ensembl exon information,def parse_ensembl_exon_request result keys chrom gene transcript exon_id exon_chrom_start exon_chrom_end 5_utr_start 5_utr_end 3_utr_start 3_utr_end strand rank for res in zip result Chromosome scaffold name result Gene stable ID result Transcript stable ID result Exon stable ID result Exon region start bp result Exon region end bp result 5 UTR start result 5 UTR end result 3 UTR start result 3 UTR end result Strand result Exon rank in transcript ensembl_info dict zip keys res if ensembl_info strand 1 start max ensembl_info exon_chrom_start ensembl_info 5_utr_end or 1 end min ensembl_info exon_chrom_end ensembl_info 3_utr_start or float inf elif ensembl_info strand 1 start max ensembl_info exon_chrom_start ensembl_info 3_utr_end or 1 end min ensembl_info exon_chrom_end ensembl_info 5_utr_start or float inf ensembl_info start start ensembl_info end end yield ensembl_info
override in subclasses to provide alternate translations factory .,def _get_translations self return None
instantiate a new user with default values .,def __init__ self id self id id
tests that post request with invalid data to endpoint returns expected error .,def test_post_invalid_data_account_error self self create_user self create_account self data account self account id email jackson flores78 example com response self client post self url self data format json expected_response error account Account does not allow signup with email address self assertEqual response status_code status HTTP_400_BAD_REQUEST self assertEqual response data expected_response
test len of random utils string .,def test_len_random_utils self u self assertEqual len random_alphanum 15 15
"run method , which starts the generator",def run self self parametersCheck self parametersPrint self engineStartsInfo self __engine self engineStopsInfo return self __dict__
: type root : treenode : type key : int : rtype : treenode,def deleteNode self root key if not root return if key root val root left self deleteNode root left key elif key root val root right self deleteNode root right key elif not root left return root right elif not root right return root left else root val self getMin root right root right self deleteNode root right root val return root
sorts rows of matrix based on columns,def sortRows matrix columns None if columns None columns numpy core multiarray arange matrix shape 1 columns columns 1 lexsortable tuple matrix columns transpose indices numpy core multiarray lexsort lexsortable return matrix indices indices
store formula image metrics and image ids in the database,def store_ion_metrics self ion_metrics_df ion_img_ids db logger info Storing iso image metrics rows list self _metrics_table_row_gen self job_id self sf_db_id ion_metrics_df reset_index ion_img_ids db insert METRICS_INS rows
"parameters : filepath : filename without extension . ftype : file type , e.g. vtkimagedata , etc .",def __init__ self filepath ftype self ftype ftype self filename filepath self xml XmlWriter self filename self offset 0 self appendedDataIsOpen False self xml openElement VTKFile addAttributes type ftype name version 0 1 byte_order _get_byte_order
the rule says that the destination file should be same after replacing the language code : mi0064_en.htm====>mi0064_it.htm or it should have the structure of type = en,def rule1 url lang components normalize url fileS components 1 if isHTML fileS regex A Za z lang htm l m re search regex fileS if m return 1 elif hasLangParameter lang fileS return 1 return 0
a generalized contraction between tensors of arbitrary dimension .,def einsum axes inputs match re match a z a z axes assert match Indices have incorrect format s axes inputs list inputs idx_in match group 1 split idx_out match group 2 idx_all set join idx_in assert len idx_in len inputs Expected d inputs but only got d len idx_in len inputs for i input_ axes_ in enumerate zip inputs idx_in assert input_ get_shape ndims len axes_ Input d with axes s has incorrect number of dimensions expected d got d i axes_ len axes_ input_ get_shape ndims sorted_idx sorted axes_ if list axes_ sorted_idx permuted axes_ find ax for ax in sorted_idx inputs i array_ops transpose input_ permuted idx_in i sorted_idx missing_idx set idx_out difference idx_all assert not missing_idx Unknown ouput axes s missing_idx reduction_idx shapes dim if dim else 1 for dim in tensor get_shape as_list for tensor in inputs for j ax in enumerate sorted idx_all dims for i idx in enumerate idx_in if ax not in idx shapes i insert j 1 else dim shapes i j if isinstance dim int and dim 1 dims append dim assert len set dims 1 Dimension mismatch on axis s ax if ax not in idx_out reduction_idx append j expanded_inputs array_ops reshape input_ shape for input_ shape in zip inputs shapes expanded_output 1 for input_ in expanded_inputs expanded_output input_ return math_ops reduce_sum expanded_output reduction_idx
provide a transactional scope around a series of operations . this method could be used by test code or db scripts to run queries as transactions .,contextmanager def session_scope self session self session try try yield session session commit except session rollback raise finally session close
"returns the items that have changed if there are no changes in dependencies , otherwise returns all slurped items for reauditing",def get_items_to_audit self watcher auditor watchers_with_changes watcher full_audit_list None if auditor support_watcher_indexes for support_watcher_index in auditor support_watcher_indexes if support_watcher_index in watchers_with_changes app logger debug Upstream watcher changed reauditing format support_watcher_index watcher index watcher full_audit_list auditor read_previous_items if auditor support_auditor_indexes for support_auditor_index in auditor support_auditor_indexes if support_auditor_index in watchers_with_changes app logger debug Upstream auditor changed reauditing format support_auditor_index watcher index watcher full_audit_list auditor read_previous_items if watcher full_audit_list return watcher full_audit_list return item for item in watcher created_items watcher changed_items
computes the median . median is the middle value in a sorted list of values .,staticmethod def median lst lst __class__ sort lst length __class__ length lst mid int length 2 if length 2 0 return lst mid lst mid 1 2 return lst mid
"add a unit set containing a new element to the collection , and return the identifier of the new element .",def add self nid len self p self p append nid return nid
initialize the object with the right database configuration,def _initialize self provideUtility global_zstorm IZStorm zstorm getUtility IZStorm zstorm _reset if self engine ENGINE NATIVE if self backend sqlite and sqlite_version_info 3 6 19 uri foreign_keys 1 format config Database uri else uri config Database uri elif self engine ENGINE INMEMORY if sqlite_version_info 3 6 19 uri sqlite foreign_keys 1 else uri sqlite else tmpfile tempfile NamedTemporaryFile delete False self tmp_file tmpfile name if sqlite_version_info 3 6 19 uri sqlite foreign_keys 1 format tmpfile name else uri sqlite format tmpfile name tmpfile close zstorm set_default_uri mamba uri self started True
apply specified markup to matched term(s ) within the returned field(s ),def highlight self fields None tags None args HIGHLIGHT fields self _mk_field_list fields if fields args FIELDS str len fields fields if tags args TAGS list tags self _highlight_fields args return self
test the string cast of the object,def test_str_cast self room114 str Room objects get roomNr 114 room113 str Room objects get roomNr 113 self assertEqual Room 114 Benne str room114 self assertEqual Room 113 Preben Mogensen str room113
update xml from lists of old and new namespaces .,def update_from_lists tree from_ns to_ns ns_mapping dict zip from_ns to_ns new_root update_namespaces tree getroot ns_mapping if new_root is not tree getroot tree _setroot new_root update_schemalocations tree ns_mapping
output : returns response that contains the list of table files in data,def _listTableFiles file_list ut stripFileExtension ff for ff in os listdir settings SCISHEETS_USER_TBLDIR if ut getFileExtension ff settings SCISHEETS_EXT and ff 0 _ file_list sort return _makeAjaxResponse file_list True
create a standard synapse transaction ( default or scheduled ) .,def create_transaction kwargs args amount kwargs amount to_id kwargs savings_node_id to_type SYNAPSE US currency USD ip 127 0 0 1 if kwargs get process_in args process_in kwargs process_in transaction Transaction create kwargs debit_node args return Transaction created n transaction_summary transaction
enable and disable the family filter . : return : nothing,def testC_SetFamilyFilter self xxx_filter self xmlrpc settings get_family_filter assert self xmlrpc settings set_family_filter False xxx_filter self xmlrpc settings get_family_filter assert xxx_filter is False assert self xmlrpc settings set_family_filter True xxx_filter self xmlrpc settings get_family_filter assert xxx_filter is True
"a capsule network on mnist . : param input_shape : data shape , 3d , [ width , height , channels ] : param n_class : number of classes : param routings : number of routing iterations : return : two keras models , the first one used for training , and the second one for evaluation . ` eval_model ` can also be used for training .",def CapsNet input_shape n_class routings x layers Input shape input_shape conv1 layers Conv2D filters 256 kernel_size 9 strides 1 padding valid activation relu name conv1 x primarycaps PrimaryCap conv1 dim_capsule 8 n_channels 32 kernel_size 9 strides 2 padding valid digitcaps CapsuleLayer num_capsule n_class dim_capsule 16 routings routings name digitcaps primarycaps out_caps Length name capsnet digitcaps y layers Input shape n_class masked_by_y Mask digitcaps y masked Mask digitcaps decoder models Sequential name decoder decoder add layers Dense 512 activation relu input_dim 16 n_class decoder add layers Dense 1024 activation relu decoder add layers Dense np prod input_shape activation sigmoid decoder add layers Reshape target_shape input_shape name out_recon train_model models Model x y out_caps decoder masked_by_y eval_model models Model x out_caps decoder masked noise layers Input shape n_class 16 noised_digitcaps layers Add digitcaps noise masked_noised_y Mask noised_digitcaps y manipulate_model models Model x y noise decoder masked_noised_y return train_model eval_model manipulate_model
"divide lst of ( numbers , symbols ) using entropy .",def ediv lst lvl 0 tiny The tree min dull The math brink cohen num lambda x x 0 sym lambda x x 1 def divide this lvl def ke z return z k z ent lhs rhs Sym Sym sym x for x in this n0 k0 e0 ke0 1 0 rhs n rhs k rhs ent ke rhs cut least None e0 last num this 0 for j x in enumerate this rhs sym x lhs sym x now num x if now last if lhs n tiny and rhs n tiny maybe lhs n n0 lhs ent rhs n n0 rhs ent if maybe least gain e0 maybe delta log2 float 3 k0 2 ke0 ke rhs ke lhs if gain log2 n0 1 delta n0 cut least j maybe last now return cut least def recurse this cuts lvl cut e divide this lvl if cut recurse this cut cuts lvl 1 recurse this cut cuts lvl 1 else lo num this 0 hi num this 1 cuts Thing at lo e e _has this range lo hi return cuts return recurse sorted lst key num 0
create a new model linked to the given model .,step STEP_PREFIX u A Z a z0 9_ with a z u has an A Z a z0 9_ in the database def _create_models_for_relation_step self rel_model_name rel_key rel_value model u n Create a new model linked to the given model n n Syntax n n And model with field value has new model in the database n n Example n n code block gherkin n n And project with name Ball Project has goals in the database n description n To have fun playing with balls of twine n model get_model model lookup rel_key rel_value rel_model get_model rel_model_name objects get lookup data guess_types self hashes for hash_ in data hash_ u s rel_model_name rel_model try func _WRITE_MODEL model except KeyError func partial write_models model func data None
executes a sysv service check command that adheres to lsb - compliant return codes . the return codes are interpreted as defined by the lsb .,def service_check cmd user label Logger info Performing service check cmd 0 user 1 label 2 format cmd user label rc out err get_user_call_output cmd user is_checked_call False if rc in 1 2 3 Logger info 0 is not running format label raise ComponentIsNotRunning elif rc 0 Logger info 0 is running format label else err_msg 0 service check failed cmd 1 returned 2 format label cmd rc Logger error err_msg raise ExecutionFailed err_msg rc out err
signal function for adding any cookies needed for email marketing,receiver CREATE_LOGON_COOKIE def add_email_marketing_cookies sender response None user None kwargs email_config EmailMarketingConfiguration current if not email_config enabled return response post_parms id user email fields keys 1 vars last_login_date datetime datetime now strftime Y m d request crum get_current_request if request sailthru_content request COOKIES get anonymous_interest if sailthru_content post_parms cookies anonymous_interest sailthru_content time_before_call datetime datetime now sailthru_response get_email_cookies_via_sailthru delay user email post_parms try sailthru_response get timeout email_config user_registration_cookie_timeout_delay propagate True cookie sailthru_response result _log_sailthru_api_call_time time_before_call except TimeoutError as exc log error Timeout error while attempting to obtain cookie from Sailthru s text_type exc return response except SailthruClientError as exc log error Exception attempting to obtain cookie from Sailthru s text_type exc return response except Exception log error Exception Connecting to celery task for s user email return response if not cookie log error No cookie returned attempting to obtain cookie from Sailthru for s user email return response else response set_cookie sailthru_hid cookie max_age 365 24 60 60 domain settings SESSION_COOKIE_DOMAIN path log info sailthru_hid cookie s successfully retrieved for user s cookie user email return response
simulate having a course which has closed enrollments that has a pre - req course,patch dict settings FEATURES ENABLE_PREREQUISITE_COURSES True def test_course_with_prereq self pre_requisite_course CourseFactory create org edX course 900 display_name pre requisite course emit_signals True pre_requisite_courses unicode pre_requisite_course id course CourseFactory create org edX course 1000 display_name course that has pre requisite enrollment_start datetime datetime 2013 1 1 enrollment_end datetime datetime 2014 1 1 start datetime datetime 2013 1 1 end datetime datetime 2030 1 1 pre_requisite_courses pre_requisite_courses emit_signals True set_prerequisite_courses course id pre_requisite_courses resp self client get self assertEqual resp status_code 200 self assertIn pre requisite course resp content self assertIn course that has pre requisite resp content
recompute the related team 's team_size after deleting a membership,def delete self args kwargs super CourseTeamMembership self delete args kwargs self team reset_team_size
returns a broken line structure . there are two cases,def breakLines self width if not isSeq width maxWidths width else maxWidths width lines lineno 0 maxWidth maxWidths lineno style self style fFontSize float style fontSize requiredWidth 0 _handleBulletWidth self bulletText style maxWidths self height 0 autoLeading getattr self autoLeading getattr style autoLeading calcBounds autoLeading not in off frags self frags nFrags len frags if nFrags 1 f frags 0 if hasattr f text fontSize f fontSize fontName f fontName ascent descent getAscentDescent fontName fontSize kind 0 L f text split n for l in L currentWidth stringWidth l fontName fontSize requiredWidth max currentWidth requiredWidth extraSpace maxWidth currentWidth lines append extraSpace l split currentWidth lineno lineno 1 maxWidth lineno len maxWidths and maxWidths lineno or maxWidths 1 blPara f clone kind kind lines lines ascent ascent descent descent fontSize fontSize else kind f kind lines f lines for L in lines if kind 0 currentWidth L 2 else currentWidth L currentWidth requiredWidth max currentWidth requiredWidth blPara f clone kind kind lines lines self width max self width requiredWidth return blPara elif nFrags 0 return ParaLines kind 0 fontSize style fontSize fontName style fontName textColor style textColor ascent style fontSize descent 0 2 style fontSize lines else for L in _getFragLines frags currentWidth n w _getFragWord L maxWidth f w 0 0 maxSize f fontSize maxAscent minDescent getAscentDescent f fontName maxSize words f clone words 1 text w 0 1 for i in w 1 f i 0 clone f text i 1 words append f fontSize f fontSize fontName f fontName if calcBounds cbDefn getattr f cbDefn None if getattr cbDefn width 0 descent ascent imgVRange imgNormV cbDefn height fontSize cbDefn valign fontSize else ascent descent getAscentDescent fontName fontSize else ascent descent getAscentDescent fontName fontSize maxSize max maxSize fontSize maxAscent max maxAscent ascent minDescent min minDescent descent lineno 1 maxWidth lineno len maxWidths and maxWidths lineno or maxWidths 1 requiredWidth max currentWidth requiredWidth extraSpace maxWidth currentWidth lines append ParaLines extraSpace extraSpace wordCount n words words fontSize maxSize ascent maxAscent descent minDescent currentWidth currentWidth self width max self width requiredWidth return ParaLines kind 1 lines lines return lines
theano function returns total loss and accuracy,def val_fn input_var target_var test_loss test_acc return theano function input_var target_var test_loss test_acc allow_input_downcast True
trims string s of unicode text,def trimUnicode s return re sub x00 x7F s
sets the predicate used to check whether a push response suggests the node that a pull should be performed . default value is a constant `` false `` procedure .,def set_pull_suggestion_criterion predicate assert inspect isroutine predicate criterion must be a function pushmodule suggests_pull predicate return predicate
return the equation as basis to calculate the segetal flora .,def get_equation culture_type fallow climate_type 2 LOGGER debug equation for s s culture_type climate_type climate_type str climate_type if culture_type fallow if climate_type 1 equation sffallow1 exp 46 4619 15 4355 s 273 15 0 7070 power s 273 15 2 tas tas elif climate_type 2 equation sffallow2 66 463 exp 0 1315 s 273 15 tas elif climate_type 3 equation sffallow3 exp 1 837 0 2856 s 273 15 0 0156 power s 273 15 2 tas tas elif climate_type 4 equation sffallow4 0 0685 power s 273 15 3 2 9184 power s 273 15 2 38 864 s 273 15 80 046 tas tas tas elif climate_type 5 equation sffallow5 1 68 exp 0 735 exp 0 1134 s 273 15 tas elif climate_type 6 equation sffallow6 0 0088 power s 273 15 3 0 3457 power s 273 15 2 3 6656 s 273 15 5 3486 tas tas tas elif climate_type 7 equation sffallow7 3 4655 exp 0 1303 s 273 15 tas elif climate_type all equation sffallowall 0 2787 power s 273 15 3 7 5658 power s 273 15 2 72 4143 s 273 15 76 29 tas tas tas else equation None LOGGER debug No equations determinated for s s culture_type climate_type elif culture_type extensive if climate_type 1 equation sfextensive1 exp 46 0518 15 4597 s 273 15 0 7143 power s 273 15 2 tas tas elif climate_type 2 equation sfextensive2 45 6589 exp 0 0987 s 273 15 tas elif climate_type 3 equation sfextensive3 exp 1 4383 0 33 s 273 15 0 0176 power s 273 15 2 tas tas elif climate_type 4 equation sfextensive4 0 7587 power s 273 15 2 17 8515 s 273 15 32 8794 tas tas elif climate_type 5 equation sfextensive5 0 0817 exp 0 4597 s 273 15 tas elif climate_type 6 equation sfextensive6 0 0263 power s 273 15 3 0 7119 power s 273 15 2 4 878 s 273 15 11 154 tas tas tas elif climate_type 7 equation sfextensive7 1 1653 exp 0 1711 s 273 15 tas elif climate_type all equation sfextensiveall 0 2386 power s 273 15 3 6 5351 power s 273 15 2 62 475 s 273 15 73 9023 tas tas tas else equation None LOGGER debug No equations determinated for s 273 15 s 273 15 culture_type climate_type elif culture_type intensive if climate_type 1 equation sfintensive1 exp 46 0518 15 4597 s 273 15 0 7143 power s 273 15 2 tas tas elif climate_type 2 equation sfintensive2 31 3493 exp 0 1108 s 273 15 tas elif climate_type 3 equation sfintensive3 exp 1 0791 0 3449 s 273 15 0 0189 power s 273 15 2 tas tas elif climate_type 4 equation sfintensive4 0 0919 power s 273 15 3 2 3824 power s 273 15 2 14 29 s 273 15 38 93 tas tas tas elif climate_type 5 equation sfintensive5 exp 0 1663 0 0457 s 273 15 0 0128 power s 273 15 2 tas tas elif climate_type 6 equation sfintensive6 14 1641 exp 0 0363 s 273 15 tas elif climate_type 7 equation sfintensive7 1 704 exp 0 0982 s 273 15 tas elif climate_type all equation sfintensiveall 43 2846 exp 0 071 s 273 15 tas else equation None LOGGER debug No equations determinated for s s culture_type climate_type else equation None LOGGER debug No equations determinated for s s culture_type climate_type return equation
prints a shallow dict to console .,def print_dict d show_missing True for k v in sorted d items if not v and show_missing print format k elif isinstance v list print k for item in v print format item elif isinstance v dict print k for kk vv in sorted v items print 20 format kk vv
create a ` content ` object from a file on disk .,def content_from_file path content_type None chunk_size DEFAULT_CHUNK_SIZE buffer_now False if content_type is None content_type UTF8_TEXT def reader stream open path rb for chunk in _iter_chunks stream chunk_size yield chunk stream close return content_from_reader reader content_type buffer_now
list should return all current contracts .,def test_non_current_contracts self factories ProjectContract projects self projects status ProjectContract STATUS_COMPLETE factories ProjectContract projects self projects status ProjectContract STATUS_UPCOMING response self _get self assertEqual response status_code 200 contracts response context contracts self assertEqual len contracts 0
"custom on_delete handler which sets _ cascade_deletion_origin on the _ state of the all relating objects that will deleted . we use this handler on modeldefinitionattribute.model_def , so when we delete a modeldefinition we can skip field_definition_post_delete and base_definition_post_delete and avoid an incremental columns deletion before the entire table is dropped .",def CASCADE_MARK_ORIGIN collector field sub_objs using u n Custom on_delete handler which sets _cascade_deletion_origin on the _state n of the all relating objects that will deleted n We use this handler on ModelDefinitionAttribute model_def so when we delete n a ModelDefinition we can skip field_definition_post_delete and n base_definition_post_delete and avoid an incremental columns deletion before n the entire table is dropped n CASCADE collector field sub_objs using if sub_objs for obj in sub_objs obj _state _cascade_deletion_origin field name
get all rules so we ensure they 're dynamic and always updated .,def get_rulesmap bad static index return r endpoint for r in app url_map _rules if r endpoint not in bad
make sure the nth item is returned,def test_basic self l range 10 for i v in enumerate l eq_ nth l i v
"should read from the stream into buffer and return number of bytes read , or 0 on eof or raise error , or timeout",def read self buffer timeout 1 0 pass
create redcap tables via the remote host,def create_redcap_tables resource_path Resources sql print Creating redcap tables redcap_sql_root_dir os path join env backup_pre_path env remote_project_name with settings user env deploy_user redcap_name run ls s grep redcap_v 0 9 1 2 0 9 1 2 0 9 1 2 sort n tail n 1 redcap_sql_root_dir redcap_sql_dir os path join redcap_sql_root_dir redcap_name resource_path match re search redcap_v d d d redcap_name version match group 1 with settings user env deploy_user run mysql s install sql redcap_sql_dir run mysql s install_data sql redcap_sql_dir run mysql e UPDATE s redcap_config SET value s WHERE field_name redcap_version env database_name version files run ls v1 s create_demo_db sql redcap_sql_dir for file in files splitlines print Executing sql file s file run mysql s file
this function checks for the admin_pw and the secret in config.py in the flask request context 's cookies .,def check_login_cookie session_cookie session get pwhash if not session_cookie return False else pwhash _xor_decrypt session_cookie SECRET_KEY return pwhash ADMIN_PW
"walk tree of x , making optimizations / fixes , and signaling syntaxerror .",def expand x toplevel False require x x if not isa x list return x elif x 0 is _quote require x len x 2 return x elif x 0 is _if if len x 3 x x None require x len x 4 return map expand x elif x 0 is _set require x len x 3 var x 1 require x isa var Symbol can set only a symbol return _set var expand x 2 elif x 0 is _define or x 0 is _definemacro require x len x 3 _def v body x 0 x 1 x 2 if isa v list and v f args v 0 v 1 return expand _def f _lambda args body else require x len x 3 require x isa v Symbol can define only a symbol exp expand x 2 if _def is _definemacro require x toplevel define macro only allowed at top level proc eval exp require x callable proc macro must be a procedure macro_table v proc return None return _define v exp elif x 0 is _begin if len x 1 return None else return expand xi toplevel for xi in x elif x 0 is _lambda require x len x 3 vars body x 1 x 2 require x isa vars list and all isa v Symbol for v in vars or isa vars Symbol illegal lambda argument list exp body 0 if len body 1 else _begin body return _lambda vars expand exp elif x 0 is _quasiquote require x len x 2 return expand_quasiquote x 1 elif isa x 0 Symbol and x 0 in macro_table return expand macro_table x 0 x 1 toplevel else return map expand x
"write out format foo . the dpi , facecolor and edgecolor are restored to their original values after this call , so you do n't need to save and restore them .",def print_foo self filename args kwargs u n Write out format foo The dpi facecolor and edgecolor are restored n to their original values after this call so you don t need to n save and restore them n pass
register a plugin class . this function will call back your plugin 's constructor .,def register PluginClass if PluginClass in _cache raise Exception Plugin class already registered plugin PluginClass _cache PluginClass plugin settings_form getattr PluginClass settings_form None if settings_form if isinstance settings_form str klassname settings_form split 1 modulename join settings_form split 1 form_module import_module modulename settings_form getattr form_module klassname _settings_forms append settings_form if getattr PluginClass article_tab None _article_tabs append plugin if getattr PluginClass sidebar None _sidebar append plugin _markdown_extensions extend getattr PluginClass markdown_extensions _html_whitelist extend getattr PluginClass html_whitelist _html_attributes update getattr PluginClass html_attributes dict
compute the cross entropy loss in tensorflow .,def cross_entropy_loss y yhat print y print yhat out tf reduce_sum tf to_float y tf log yhat return out
returns a list of apicall .,def get_api_calls api_functions api_functions ignore_unfound False functions n f for n f in api_functions if getattr f is_api False functions sorted functions key lambda n f n ret for function in functions try ret append APICall function except NoReverseMatch if not ignore_unfound raise return ret
"given a symbol price and the amount of shares purchased , this method will return the fees incurred for the trade .",def get_fee self price shares return self fee
serve static files below a given point in the directory structure or from locations inferred from the static files finders .,def serve request path document_root None show_indexes False insecure False if not settings DEBUG and not insecure raise ImproperlyConfigured The view to serve static files can only be used if the DEBUG setting is True or the insecure option of runserver is used if not document_root absolute_path finders find path if not absolute_path raise Http404 s could not be found path document_root path os path split absolute_path path posixpath normpath urllib unquote path path path lstrip newpath for part in path split if not part continue drive part os path splitdrive part head part os path split part if part in os curdir os pardir continue newpath os path join newpath part replace if newpath and path newpath return HttpResponseRedirect newpath fullpath os path join document_root newpath if os path isdir fullpath if show_indexes return directory_index newpath fullpath raise Http404 Directory indexes are not allowed here if not os path exists fullpath raise Http404 s does not exist fullpath statobj os stat fullpath mimetype encoding mimetypes guess_type fullpath mimetype mimetype or application octet stream if not was_modified_since request META get HTTP_IF_MODIFIED_SINCE statobj stat ST_MTIME statobj stat ST_SIZE return HttpResponseNotModified mimetype mimetype contents open fullpath rb read response HttpResponse contents mimetype mimetype response Last Modified http_date statobj stat ST_MTIME response Content Length len contents if encoding response Content Encoding encoding return response
marks a view function as being exempt from the csrf checks and post processing .,def csrf_exempt view_func return csrf_response_exempt csrf_view_exempt view_func
return a weak - reference - like instance for a bound method,def __init__ self target onDelete None def remove weak self self Set self isDead to true when method or instance is destroyed methods self deletionMethods del self deletionMethods try del self __class__ _allInstances self key except KeyError pass for function in methods try if callable function function self except Exception as e try traceback print_exc except AttributeError as err print Exception during saferef s cleanup function s s self function e self deletionMethods onDelete self key self calculateKey target self weakSelf weakref ref target im_self remove self weakFunc weakref ref target im_func remove self selfName str target im_self self funcName str target im_func __name__
returns the wkb representation of the given geometry .,def write self geom return buffer wkb_writer_write self ptr geom ptr byref c_size_t
generates a signal that resembles a shock excitation as a gaussian followed by a smaller gaussian of opposite sign .,def shocklikeGaussian time t0 m0 sigma noise 0 0 x m0 time t0 sigma np exp 0 5 np exp time t0 2 2 sigma 2 if noise 0 x np random randn len time noise return x
set the value for a given cell,def __setitem__ self column_name value if not column_name in self table default_columns raise KeyError s isn t a column in this table column_name index self table default_columns index column_name self cells index value
the relative weight is used to determine how much we want to see the data of this vm .,def update_relative_weight self self relative_weight 1 for i in self cpu_datapoints self relative_weight i self relative_weight self heartbeat_status 10
a dictionary can satisfy the protocol,def test_protocol self f type Feature id 1 geometry type Point coordinates 53 4 properties title Dict 1 json geojson dumps f sort_keys True self assertEqual json geometry coordinates 53 4 type Point id 1 properties title Dict 1 type Feature o geojson loads json output geojson dumps o sort_keys True self assertEqual output geometry coordinates 53 4 type Point id 1 properties title Dict 1 type Feature
write out 8 shards and their bounds .,task def shards from binascii import hexlify from os import urandom limits sorted hexlify urandom 32 for _ in range 7 limits 0 64 limits f 64 shards for i b0 b1 in enumerate zip limits 1 limits 1 name n s i bounds b0 b1 shards append name bounds from json import dumps file shards json w write dumps shards
set members based on inventory .,def _configure self SpatialDBObj _configure self ModuleUserFunctionDB coordsys self self inventory cs for name fn units in self functions ModuleUserFunctionDB addValue self name fn units return
"returns the next value , and changes state , called in each iteration",def __next__ self if self _current 0 value self _current self _current 1 return value else raise StopIteration
returns the proxied equivalent of subprocess . popen .,ClientOnly def _ProxyPopen self args kwargs args args kwargs kwargs copy test_path os path abspath __file__ client_path os path join os path dirname test_path lab_device_proxy_client py assert os path exists client_path Missing s client_path cmd os path basename args 0 server_file os path join self _server_temp cmd with open server_file w as f f write bin sh nexec s mock s s s n test_path self __class__ __name__ self _test_name cmd os chmod server_file 493 args client_path url self _server_url args kwargs setdefault env PATH self _python_path kwargs setdefault cwd self _server_temp kwargs setdefault close_fds True return subprocess Popen args kwargs
predict using an model in a local or gcs directory .,staticmethod def predict model_dir image_files resize show_image from import _predictor images _util load_images image_files resize resize labels_and_scores _predictor predict model_dir images results zip image_files images labels_and_scores ret _util process_prediction_results results show_image return ret
run batch prediction using the cloudml engine prediction service .,def _run_batch_prediction self job_name test_mltoolbox_batchprediction_ s uuid uuid4 hex cmd gcloud ml engine jobs submit prediction job_name data format TEXT input paths self _csv_predict_filename output path self _prediction_output model dir os path join self _train_output model runtime version 1 0 region us central1 self _logger debug Running subprocess s n n join cmd subprocess check_call join cmd shell True subprocess check_call gcloud ml engine jobs stream logs job_name shell True error_files file_io get_matching_files os path join self _prediction_output prediction errors_stats self assertEqual 1 len error_files error_str file_io read_file_to_string error_files 0 self assertEqual error_str
"returns the handler function given xy = ' x ' or ' y ' ind = 1 or for the quandrature sq wave res= 1,2,4 for resolutions",def getAlgo xy ind res print xy str ind str res return eval xy str ind str res
make a mock of mocks subprocess.check_output ( ) for r cmd batch commands,def make_r_side_effect recognized True def side_effect args kwargs This side effect mocks the behaviour of a subprocess check_output call on a machine with R set up for command line use command args 0 if re search R command flags re I and not recognized raise subprocess CalledProcessError 1 command match helpers command_match command R executable match group executable log match group log append match group append if log is None source match group source log s log re sub R source if executable Rscript and log and append 2 1 with open log replace strip wb as log_file log_file write Test log n with open test_output txt wb as target target write Test target return side_effect
add edges at random so that the probability is p that there is an edge between any two nodes .,def add_random_edges self p for i v in enumerate self vs for j w in enumerate self vs if j i continue if random random p continue self add_edge Edge w v
return a value that does n't exist .,def _raises_exception model return model does_not_exist
function to to make multiple runs of yambo to converge calculation parameters input : a dictionary conv that has all the variables to be optimized a list fo the name of the variables in the dicitonary that are to be optimized a function run that takes as input the name of the inputfile ( used to run yambo ) a boolean ref_run that can disable the submitting of the reference run ( see scripts / analyse_gw.py ) .. code - block : : python def run(filename ) : os.system('yambo -f % s'%filename ),def optimize self conv variables all run lambda x None ref_run True name_files if all in variables variables conv keys backup for var in variables backup var self var for key value in conv items if type value 1 str and type value 0 list conv key value reference for key value in conv items values unit value reference key values 0 unit self key values 0 unit if ref_run True self write s reference in self folder run reference in else print Reference run disabled for key in var for var in conv keys if var in variables values unit conv key for var in variables self var reference var if type values 0 str for string in values 1 filename s_ s key string self key string self write self folder filename run filename in continue if type values 0 float for val in values 1 filename s_ 12 8lf key val self key val unit self write s s in self folder filename run filename in continue if type values 0 int for val in values 1 filename s_ 05d key val self key val unit self write s s in self folder filename run filename in continue if type values 0 list for array in values 1 filename s_ s key _ join map str array self key array unit self write s s in self folder filename run filename in continue if type values 0 complex for value in values 1 filename s_ lf_ lf key value real value imag self key value unit self write s s in self folder filename run filename in continue raise ValueError unknown type for variable key for var in variables self var backup var return name_files
insert a freecad fem mechanical result object in the activedocument,def import_z88_disp filename analysis None result_name_prefix None import importToolsFem import ObjectsFem if result_name_prefix is None result_name_prefix m read_z88_disp filename if len m Nodes 0 if analysis is None analysis_name os path splitext os path basename filename 0 analysis_object ObjectsFem makeAnalysis Analysis analysis_object Label analysis_name else analysis_object analysis for result_set in m Results results_name result_name_prefix results results ObjectsFem makeResultMechanical results_name for m in analysis_object Member if m isDerivedFrom Fem FemMeshObject results Mesh m break results importToolsFem fill_femresult_mechanical results result_set 0 analysis_object Member analysis_object Member results if FreeCAD GuiUp import FemGui FemGui setActiveAnalysis analysis_object
returns true if the url points to a valid local netcdf file,def is_netcdf url if url startswith http return False if url endswith nc return True with open url rb as f magic_number f read 4 if len magic_number 4 return False if is_classic_netcdf magic_number return True elif is_hdf5 magic_number return True return False
test _ _ init _ _ ( ),def test_init self cls _S3Service 21 43 assert cls service_name S3 assert cls api_name s3 assert cls conn is None assert cls warning_threshold 21 assert cls critical_threshold 43
check if a given service identifier is allowed to proxy requests .,def proxy_allowed service return _is_allowed proxy_allowed service
"clear the : class:`~flask_restless . apimanager ` objects known by the global helper functions : data:`model_for ` , : data:`url_for ` , etc .",def tearDown self super ManagerTestBase self tearDown for func in GLOBAL_FUNCS func created_managers clear
recursively yields all regular files ' names in a sub - directory of the storage backend .,def list_tree self subdir assert subdir Subdir must be specified base_path self base_path if not base_path endswith os sep base_path os sep tree_base os path join base_path subdir for root dirs filenames in os walk tree_base topdown False for filename in filenames root_relative_path root len base_path replace os sep relative_path join root_relative_path filename yield relative_path
write data into a .yml file,def yaml_write_data yaml_data filename u Write data into a yml file n with open filename u w as fd yaml dump yaml_data fd default_flow_style False return True return False
read vm tests from fixtures fixtures / vmtests/ *,pytest fixture scope module def vm_tests_fixtures filenames os listdir os path join testutils fixture_path VMTests files os path join testutils fixture_path VMTests f for f in filenames vm_fixtures try for f fn in zip files filenames if f 5 json vm_fixtures fn 5 json load open f r except IOError as e raise IOError Could not read vmtests json from fixtures Make sure you did git submodule init return vm_fixtures
reports that the call statement ending at ` position ` in ` filename ` is missing a from clause .,def report_missing target filename position missing filename append position target
returns a printable string informing the user which tags are allowed,def xtags self self permitted_tags sort tg for x in self permitted_tags tg x if x in self allowed_attributes for y in self allowed_attributes x tg s y tg return xssescape tg strip
"read data in all gather_training_%d.hdf5 files , and store in gather_training_all.hdf5",def merge_rank_data self if os path exists self hdf5_fn_final print Already exists s self hdf5_fn_final else fns glob os path join self data_dir training_gathered_ hdf5 assert len fns 0 all_data for cnt fn in enumerate fns fobj h5py File fn r for obj in list fobj keys assert obj in elg lrg star qso back data for obj in list fobj keys data obj fobj s obj if cnt 0 all_data obj data obj else all_data obj np concatenate all_data obj data obj axis 0 print extracted d d cnt 1 len fns f h5py File self hdf5_fn_final w for obj in all_data keys dset f create_dataset obj data all_data obj chunks True print Wrote s self hdf5_fn_final
add local time to our counters,def add_local self delta self code_info add_local delta
returns and removes the stack 's most recent ( right - most ) item,def pop self if not self __items raise EmptyStackError return self __items pop
minimize a loss function with respect to some symbolic parameters .,def minimize loss train valid None params None inputs None algo rmsprop updates monitors monitor_gradients False batch_size 32 train_batches None valid_batches None kwargs if not isinstance train Dataset train Dataset train name train batch_size batch_size iteration_size train_batches if valid is not None and not isinstance valid Dataset valid Dataset valid name valid batch_size batch_size iteration_size valid_batches return build algo loss loss params params inputs inputs updates updates monitors monitors monitor_gradients monitor_gradients minimize train valid kwargs
fill the provided tensor with random values drawn from a gaussian distribution .,def fill self param param self be rng normal self loc self scale param shape
"attempts to dedent the lines to the edge . looks at no . of leading spaces in line 2 , and removes up to that number of blanks from other lines .",def dedent comment commentLines string split comment n if len commentLines 2 cleaned map string lstrip commentLines else spc 0 for char in commentLines 1 if char in string whitespace spc spc 1 else break cleaned for line in commentLines for i in range min len line spc if line 0 in string whitespace line line 1 cleaned append line return string join cleaned n
get table data from a silo . first get the data url from the silo details then get data and return it : param url : url to silo meta detail info : return : json dump of table data,def get_table url data None token TolaSites objects get site_id 1 if token tola_tables_token headers content type application json Authorization Token token tola_tables_token else headers content type application json print Token Not Found response requests get url headers headers verify True if data data json loads response content data else data json loads response content return data
encrypt the given data with the given key .,def encrypt_sym key data f Fernet key return f encrypt data
tests that user names are updated correctly,pytest mark django_db pytest mark parametrize first_name last_name Keihanaikukauakahihuliheekahaunaele van der Graaf Jane Joe FakeName10 16 def test_update_full_name first_name last_name user UserFactory create update_full_name user join first_name last_name assert user first_name first_name 30 assert user last_name last_name 30
register method to handle given pattern .,def register_pattern self method pattern self patterns append method compile_pattern pattern
: returns : the dataset file name : rtype : str,staticmethod def get_dataset dataset DataParser get_config dataset if dataset citeulike a and dataset citeulike t raise NameError citeulike a and citeulike t are the only valid datasets return dataset
generate list of choices from a song list .,def generate_songlist_display song False zeromsg None if g browse_mode ytpl return generate_playlist_display max_results getxy max_results if not g model g message zeromsg or Enter search term to search or h elp return logo c g n n g rprompt page_msg g current_page have_meta all x ytid in g meta for x in g model user_columns _get_user_columns if have_meta else maxlength max x length for x in g model lengthsize 8 if maxlength 35999 else 7 lengthsize 6 if maxlength 6000 else lengthsize reserved 9 lengthsize len user_columns cw getxy width cw 1 title_size cw sum 1 x size for x in user_columns reserved before name idx size 3 heading Num name title size title_size heading Title after name length size lengthsize heading Length columns before user_columns after for n column in enumerate columns column idx n column sign if not column name length else fmt s format x sign x size for x in columns fmtrow fmt 0 1 s fmt 2 fmt fmtrow join fmt strip join fmtrow strip titles tuple x heading x size for x in columns hrow c ul fmt titles c w out n hrow n for n x in enumerate g model max_results col c r if n 2 0 else c p if not song else c b details title x title length fmt_time x length details copy copy g meta x ytid if have_meta else details otitle details title details idx 2d n 1 details title uea_pad columns 1 size otitle cat details get category or details category pafy get_categoryname cat details ytid x ytid data for z in columns fieldsize field z size z name if len details field fieldsize details field details field fieldsize data append details field line fmtrow tuple data col col if not song or song g model n else c p line col line c w out line n return out n 5 len g model if not song else out
get number of values each pruned layer is supposed to have .,def get_dtype self layer_name if conv in layer_name return self dtype self conv elif fc in layer_name or ip in layer_name return self dtype self fc elif bias in layer_name return np float32 elif nz in layer_name return self dtype self nz elif ind in layer_name return self dtype self ind else print WARNING layer_name dtype is not implemented return np uint16
"take n amount of cards from top of playingdeck instance , that is from the right side of the deck_container",def pass_n_cards self num_to_deal holder deque for num in range num_to_deal holder append self deck_container pop return holder
show error message and die if doex > 0,def error doex fmt args sfmt s s Z fmt if args sfmt sfmt args if not sfmt endswith n sfmt n sys stdout flush sys stderr write sfmt sys stderr flush if doex 0 sys exit doex
returns an image object corresponding to the page,def __get_img self with self fs open self __img_path rb as fd img PIL Image open fd img load return img
gets the set of rotational speed of the hdd drives,property def drive_rotational_speed_rpm self if self _drive_rotational_speed_rpm is None self _drive_rotational_speed_rpm set for member in self get_members if member rotational_speed_rpm is not None self _drive_rotational_speed_rpm add member rotational_speed_rpm return self _drive_rotational_speed_rpm
dispatch s3 upload depending on local path,def upload_file_or_folder s3_path local_path bucket key path_to_bucket_and_key s3_path if op isfile local_path s3 upload_file local_path bucket key ExtraArgs ServerSideEncryption AES256 elif op isdir local_path local_path local_path if local_path endswith else local_path s3_path s3_path if s3_path endswith else s3_path cmd aws s3 sync sse AES256 format local_path s3_path check_output cmd shell True
spawns gevent / pool threads that will run the execute method on each hibp object .,def send self hibp_obj if self pool is not None return self pool spawn hibp_obj execute return gevent spawn hibp_obj execute
returns a queryset of public photos posted on a specific date .,register simple_tag def day_photos date nsid None time post_time if time not in post_time taken_time raise ValueError time must be either post_time or taken_time not s time start datetime datetime combine date datetime time min replace tzinfo pytz utc end datetime datetime combine date datetime time max replace tzinfo pytz utc photos Photo public_photo_objects if time taken_time photos photos filter taken_time__range start end else photos photos filter post_time__range start end if nsid is not None photos photos filter user__nsid nsid photos photos prefetch_related user return photos
turn automatic balancing on or off /setbalance < on|off >,command setbalance admin_only True def set_balance connection value should_balance get_truthy value if should_balance is None raise CommandError protocol connection protocol protocol balanced_teams should_balance if should_balance protocol send_chat now balancing teams connection protocol irc_say s turned on balanced teams connection name else protocol send_chat now no longer balancing teams connection protocol irc_say s turned off balanced teams connection name
run a command within the named namespace . : param command : the command to run . : param shell : whether this is a shell command . : param timeout : command timeout in seconds .,def check_output self command command self _get_nets_command command _log debug Run command s command return check_output command timeout IP_CMD_TIMEOUT
load schema from project ` project `,def load project os environ PROJECTROOT abspath os path join project database schema yaml return lucidity Schema from_yaml abspath
create a list with tree nodes for which the < filter > function returned true in a pre order fashion,def test_known_values_pre_order_list2 self def filter node if node id child_2_2 return 0 return 1 L root child_1_1 child_2_1 child_1_2 child_2_3 l n id for n in pre_order_list self o filter self assertEqual l L l
constructs the extra replay memory .,def setup_components_and_tf_funcs self custom_getter None custom_getter super QDemoModel self setup_components_and_tf_funcs custom_getter self demo_memory Replay states self states_spec internals self internals_spec actions self actions_spec include_next_states True capacity self demo_memory_capacity scope demo replay summary_labels self summary_labels self fn_import_demo_experience tf make_template name_ import demo experience func_ self tf_import_demo_experience custom_getter_ custom_getter self fn_demo_loss tf make_template name_ demo loss func_ self tf_demo_loss custom_getter_ custom_getter self fn_combined_loss tf make_template name_ combined loss func_ self tf_combined_loss custom_getter_ custom_getter self fn_demo_optimization tf make_template name_ demo optimization func_ self tf_demo_optimization custom_getter_ custom_getter return custom_getter
return whether or not the current request is for an embedded datagrid .,def _is_datagrid_gridonly request u Return whether or not the current request is for an embedded datagrid n n This method allows us to disable consent checks in n py func reviewboard accounts decorators valid_prefs_required when a n datagrid is requesting updated data so that we do not return a redirect n and embed the result of that redirect in the datagrid instead n n Args n request django http HttpRequest n The HTTP request from the client n n Returns n bool n Whether or not this request is for an embedded datagrid n return u gridonly in request GET
testing the get < url > api with text_type = markdown and ? force - text - type = markdown,webapi_test_template def test_get_with_markdown_and_force_text_type_markdown self u Testing the GET URL API with text_type markdown and n force text type markdown n self _test_get_with_force_text_type text u This is a test rich_text True force_text_type u markdown expected_text u This is a test
marks up any extra whitespace in the specified text .,register filter def showextrawhitespace value u n Marks up any extra whitespace in the specified text n n Any trailing whitespace or tabs following one or more spaces are n marked up by inserted span class ew span tags n value extraWhitespace sub u span class ew 1 span value return value replace u t u span class tb t span
testing rawfilediffdata migration accessing filediff.diff with associated shared legacyfilediffdata,def test_migration_by_shared_legacy_diff_hash self u Testing RawFileDiffData migration accessing FileDiff diff n with associated shared LegacyFileDiffData n legacy LegacyFileDiffData objects create binary_hash u abc123 binary Base64DecodedValue self DEFAULT_GIT_FILEDIFF_DATA self filediff legacy_diff_hash legacy self filediff save diffset DiffSet objects create name u test revision 1 repository self repository FileDiff objects create source_file u README dest_file u README diffset diffset diff64 u parent_diff64 u legacy_diff_hash legacy diff self filediff diff self assertIsNotNone self filediff diff_hash self assertIsNone self filediff parent_diff_hash self assertIsNone self filediff legacy_diff_hash self assertEqual LegacyFileDiffData objects count 1 self assertEqual diff self DEFAULT_GIT_FILEDIFF_DATA self assertEqual self filediff diff64 u self assertEqual self filediff diff_hash content self DEFAULT_GIT_FILEDIFF_DATA self assertEqual self filediff diff diff self assertIsNone self filediff parent_diff self assertIsNone self filediff parent_diff_hash
testing checklocalsiteaccessviewmixin.dispatch with localsite and anonymous user,add_fixtures u test_site def test_dispatch_with_local_site_and_anonymous self u Testing CheckLocalSiteAccessViewMixin dispatch with LocalSite and n anonymous user n class MyView CheckLocalSiteAccessViewMixin View def get view args kwargs self assertIsNotNone view local_site self assertEqual view local_site name u local site 1 return HttpResponse u success view MyView as_view request RequestFactory request request resolver_match ResolverMatch view request local_site LocalSite objects get name u local site 1 request user AnonymousUser response view request local_site_name u local site 1 self assertIsInstance response HttpResponseRedirect
take the mean of all the duplicates . this is where we could do a bit more checking .,staticmethod def squash_duplicates data def squash d if not isinstance d dict return np nan else return k np mean v for k v in d items return data applymap squash
simple putget test with internode ssl enabled without internode compression @jira_ticket cassandra-9884,def putget_with_internode_ssl_without_compression_test self self __putget_with_internode_ssl_test none
function to iterate through an array,def print_array array tab 0 indexes array keys indexes sort for i in indexes if type array i is dict print s s t tab i print_array array i tab tab 1 else print s s s t tab i array i
starts the simulated serial port for the unit tests . assumes that ` socat ` has been initialized already to setup the virtual com ports .,pytest fixture scope session autouse True def simulated_serial request from os import name from liveserial simulator import ComSimulatorThread if name nt simulator ComSimulatorThread COM1 else simulator ComSimulatorThread lscom w simulator start def cleanup_simulator simulator join 1 request addfinalizer cleanup_simulator
synchronises the domain definition sections between namelist.wps and namelist.input,def sync_namelists namelist_wps namelist_input wps nl read_namelist namelist_wps inp nl read_namelist namelist_input for setting in max_dom e_we e_sn i_parent_start j_parent_start parent_grid_ratio val wps settings setting inp update setting val inp to_file namelist_input
reports the progress of a scan,def report_scan_progress self num_sweeps valid_scan_index output_json_message type update status scan msg Scan in Progress duration num_sweeps self settings get_motor_speed remaining num_sweeps valid_scan_index self settings get_motor_speed
returns bool if callback will respond to a particular signal,def responds_to callback signal return callback in receivers signal
"initialize the component with the parameters from the given model , the vector of symbolic variables , vars , and the offset into that vector , offset .",def __init__ self model self nlin lambda x T log 1 0 T exp x self log_p T constant 0 0 self f_nlin lambda x np log 1 0 np exp x
retrieves all the books published by the artist : return : list . books published by the artist,def get_books self return itunespy lookup id self artist_id entity itunespy entities ebook 1
"/v1/server / start post - account start a virtual machine . if the machine is already running , it will be restarted .",def start self subid params None params update_params params SUBID subid return self request v1 server start params POST
does a get request to the server .,def get_content self path parameters None return self _do_request GET path parameters parameters
create a namespace manager for use with a database table via sqlalchemy .,def __init__ self namespace bind table data_dir None lock_dir None kwargs OpenResourceNamespaceManager __init__ self namespace if lock_dir self lock_dir lock_dir elif data_dir self lock_dir data_dir container_db_lock if self lock_dir verify_directory self lock_dir self bind self __class__ binds get str bind url lambda bind self table self __class__ tables get s s bind url table name lambda table self hash self _is_new False self loaded False
"tries to make the specified dir , but in case it fails it does nothing",def try_makedir dirname debug_out Creating directory dirname try makedirs dirname except pass
opens the settings window and brings it into focus,def open_settings self self settingswindow show_settings
"print unicode text in utf-8 , so it can be output without errors",def uniprint text if type text is unicode print text encode utf 8 else print text
initialize a new permissions object .,def __init__ self username None rights None super AdminPermissions self __init__ self username username if rights is not None self SetRights rights
gathers pre - mutation information : 1 . queries for existing followers and viewpoint . 2 . checkpoints list of followers that need to be revived . 3 . checkpoints list of contacts that need to be made prospective users . 4 . checkpoints list of contacts that are already following the viewpoint .,gen coroutine def _Check self self _viewpoint self _follower yield gen Task Viewpoint QueryWithFollower self _client self _user_id self _viewpoint_id if self _follower is None or not self _follower CanContribute raise PermissionError User d does not have permission to add followers to viewpoint s self _user_id self _viewpoint_id if self _op checkpoint is None self _existing_followers _ yield gen Task Viewpoint QueryFollowers self _client self _viewpoint_id limit Viewpoint MAX_FOLLOWERS self _revive_follower_ids self _GetRevivableFollowers self _existing_followers self _contact_ids yield self _ResolveContactIds self _contact_dicts checkpoint existing follower user_id for follower in self _existing_followers revive self _revive_follower_ids contacts self _contact_ids yield self _op SetCheckpoint self _client checkpoint else follower_keys DBKey follower_id self _viewpoint_id for follower_id in self _op checkpoint existing self _existing_followers yield gen Task Follower BatchQuery self _client follower_keys None self _revive_follower_ids self _op checkpoint revive self _contact_ids self _op checkpoint contacts self _contact_user_ids user_id for user_exists user_id webapp_dev_id in self _contact_ids if len self _existing_followers len self _contact_dicts Viewpoint MAX_FOLLOWERS raise LimitExceededError User d attempted to exceed follower limit on viewpoint s by adding d followers self _user_id self _viewpoint_id len self _contact_dicts
try to remove some contacts that do n't exist and expect a no - op .,def testRemoveNonExistingContacts self remove_contacts ip lkjasdlfkjasdf m lkjasdlfkj self _tester RemoveContacts self _cookie remove_contacts
"share photo from originator to user2 , non - owner removes viewpoint , then owner unshares .",def testRemoveViewpointByNonOwnerAndUnshare self self _tester RemoveViewpoint self _cookie2 self _new_vp_id self _tester Unshare self _cookie self _new_vp_id self _new_ep_id self _photo_ids 1
return the blurb for the names page .,def getBlurb cpp_names py_names cpp_in_py_names py_in_cpp_names cpp2py compare ARGS cpp_names num_py len py_in_cpp_names num_total len cpp_names percent float num_py num_total 100 result 1f of the Wild Magic C API is covered by the mod wm5 module s classes of s total percent num_py num_total result The table below matches C classes with their Python counterparts return result
send channels to subscribe : param self : a roguehostapdinfo object . : type self : roguehostapdinfo : return : empty list : rtype : list .. note : we do n't need to send frames in this extension,def send_channels self return self _data target_ap_channel
finds the maximum radius and npnp in the force field .,def find_max_rad_npnp self max_rad 0 max_npnp 0 for res atoms in self items if res KEY for atom ff_params in self res items if max_rad ff_params 1 max_rad ff_params 1 if max_npnp ff_params 4 max_npnp ff_params 4 return max_rad max_npnp
given a dataset name and a split_name returns a dataset .,def get_dataset name split_name dataset_dir file_pattern None reader None if name not in datasets_map raise ValueError Name of dataset unknown s name return datasets_map name get_split split_name dataset_dir file_pattern reader
apply filter functions to an endpoint until one of them returns non - none .,def applyFilters self endpoint for filter_function in self filter_functions e filter_function endpoint if e is not None return e return None
return a dummary context dict for a content block .,def get_context content return fill_leaf_values expand_list extract_vars content
returns column indices that are ignored ( neither matched nor unmatched ) .,def ignored_column_indices self return self _reshape_and_cast tf where self ignored_column_indicator
this function will break up words for us .,def break_words stuff words stuff split return words
: param multihash : : return : string stored in redis,classmethod def get cls multihash verbose False return cls hash_get multihash cls redisfield verbose
base `` hal `` document . if no arguments are provided a minimal viable `` hal `` document is created .,def __init__ self data None links None embedded None self data data self embedded embedded or self links links or Collection
! @brief determine if the input variable is a basic 3d variable @param var_id < str > : the id ( short name ) of the variable @return < bool > : true if the variable is one of the basic variables,def is_basic_3d_variable var_ID return var_ID in basic_3D_vars_IDs
filter out any permissions that do not have a description or with a name that ends with private then sort permissions features by name into a list .,def _ListifyPermissions permissions def filter_permissions perm return description in perm and not perm name endswith Private return sorted ifilter filter_permissions permissions values key itemgetter name
parses a raw test list as provided by --gtest_list_tests .,staticmethod def _ParseGTestListTests raw_list ret current for test in raw_list if not test continue if test 0 and not test endswith continue if test 0 and test endswith current test continue if YOU HAVE in test break test_name test 2 ret current test_name return ret
override to expose command - line options for this test .,def AddCommandLineOptions self parser pass
"convert a single physical information object , or a list of such objects , into a json - encoded text file .",def dump pif fp kwargs return json dump pif fp cls PifEncoder kwargs
this is a more complex record example,def prov_api_record_example doc ProvDocument doc add_namespace ex http example com doc add_namespace custom http custom com attributes attributes_dict_example del attributes ex dict value del attributes ex list value attributes update ex Qualified name doc valid_qualified_name custom qualified name attributes update ex Qualified name 2 ex unqualified_name attributes update ex Literal Literal test literal langtag en attributes update ex Literal 2 Literal test literal with datatype langtag en datatype PROV InternationalizedString attributes update ex identifier type Identifier http example com test expected_attributes dict for key value in attributes items new_key doc valid_qualified_name key expected_attributes update new_key value namespaces dict namespaces update ex http example com namespaces update custom http custom com namespaces update prov http www w3 org ns prov type_map dict type_map update ex date value type xsd dateTime type_map update ex double value type xsd double type_map update ex int value type xsd int type_map update ex Qualified name type prov QUALIFIED_NAME type_map update ex Literal lang en type_map update ex Literal 2 lang en type_map update ex identifier type type xsd anyURI metadata dict metadata update METADATA_KEY_PROV_TYPE PROV_RECORD_IDS_MAP activity metadata update METADATA_KEY_IDENTIFIER doc valid_qualified_name ex record metadata update METADATA_KEY_NAMESPACES namespaces metadata update METADATA_KEY_TYPE_MAP type_map record ProvActivity doc ex record attributes Example namedtuple prov_api_metadata_record_example metadata attributes prov_record expected_attributes return Example metadata attributes record expected_attributes
"poll until a file can be opened , or a timeout occurs .",def wait_until_open_succeeds fn for i in xrange 100 fh attempt_to_open_file fn if fh return fh time sleep 0 1 raise Exception File could not be opened
"given a sequence of sequences , return a flat numpy array .",def as_flat_array iterables arr for x in iterables arr extend x return np array arr
"validate an application property . returns : valid ( bool ) , message(dict ) : ( true , empty ) on success , ( false , error message dict ) otherwise .",inlineCallbacks def valid self messages if self port 1 or self port 223 messages port Invalid port number if self type not in self TYPES messages type Unknown data type valid not any messages returnValue valid messages yield
close the database connections and stop any receiving thread .,def teardown self for cb in self _stop_callbacks cb for cnn in self _conns cnn close if self _slot_created self drop_slot
retrieve the remote syslog forwarding severity names,def get isamAppliance check_mode False force False return isamAppliance invoke_get Retrieve the remote syslog forwarding severity names uri requires_modules requires_modules requires_version requires_version
check if the last created snapshot has the exact same comment or i d exists,def _check isamAppliance comment id None ret_obj get isamAppliance if id None for snaps in ret_obj data if snaps id id return True else for snaps in ret_obj data if snaps comment comment return True return False
compare cluster configuration between two appliances,def compare isamAppliance1 isamAppliance2 ret_obj1 get isamAppliance1 ret_obj2 get isamAppliance2 return ibmsecurity utilities tools json_compare ret_obj1 ret_obj2 deleted_keys
generate word vector matrix for a set of tokenized sentences by creating a feature matrix of word vectors .,def generate_embedding_matrix sentences_tokenized word_vectors word_to_index max_length min_words_mapped 0 replace_disease_gene_tokens True n_samples len sentences_tokenized vector_dim len word_vectors 0 embedding_matrix np zeros n_samples max_length vector_dim for i sentence in enumerate sentences_tokenized words_mapped 0 for j word in enumerate sentence if j max_length break if word not in word_to_index and replace_disease_gene_tokens and word DISEASE_PLACEHOLDER lower embedding_matrix i j word_vectors word_to_index disease elif word not in word_to_index and replace_disease_gene_tokens and word GENE_PLACEHOLDER lower embedding_matrix i j word_vectors word_to_index gene elif word in word_to_index words_mapped 1 embedding_matrix i j word_vectors word_to_index word if words_mapped min_words_mapped embedding_matrix i np full max_length vector_dim np nan return embedding_matrix
was_published_recently ( ) should return false for questions whose pub_date is older than 1 day,def test_was_published_recently_with_old_question self time timezone now timedelta days 30 old_question Question create_date time self assertEqual old_question was_published_recently False
send the packet to the driver .,def _send_packet self
converts a provided datetime to amount of seconds that have passed,def timesince_in_seconds value current_datetime timezone now difference current_datetime value return difference total_seconds
calculates the sha256 hash of the file .,def _sha256sum path u sha256 hashlib sha256 with io open path u rb as f for block in iter lambda f read sha256 block_size sha256 update block return sha256 hexdigest
send flush request to the rrd cache daemon .,def flush self rrdfile oneway False u self command u FLUSH rrdfile oneway
test behaviour and output of the ' explain ' subverb .,mock patch u treadmill restclient get mock Mock return_value mock MagicMock requests Response mock patch u treadmill context Context cell_api mock Mock return_value u http example com def test_explain self u restclient get return_value json return_value u columns u partition u traits u affinity u state u lifetime u memory u cpu u disk u name u data u True u True u True u False u True u False u True u False u host_1 ms com u True u True u True u True u True u False u True u False u host_2 ms com result self runner invoke self scheduler u cell u TEST u explain u proid app 123 self assertEqual result exit_code 0 restclient get assert_called_with u http example com u scheduler explain proid app 23123 self assertIn u host_1 ms com result output self assertIn u host_2 ms com result output self assertIn u X result output explain_mod plugin_manager load u treadmill cli scheduler u explain auto_handled_excepts ex 0 for ex in explain_mod _EXCEPTIONS self assertNotIn restclient AlreadyExistsError auto_handled_excepts
"test a tuple for required values , extracting the tuple beforehand . : param content : content string containing the tuple attribute ( e.g. django settings ) : param tuple_key : attribute name of the tuple : param required_values : list or tuple of values for testing the tuple : return : none ( asserts in case of failure )",def probe_values_in_tuple content tuple_key required_values delimiter try start_pos content find key delim n format key tuple_key delim delimiter assert start_pos 1 Tuple not found s tuple_key stop_pos 1 content find n n start_pos assert stop_pos start_pos End of tuple not found s tuple_key tuple content start_pos stop_pos for val in required_values val_line s n val assert val_line in tuple Not found in tuple s s tuple_key val return True except AssertionError as ae print ae message return False
"method used as target of the created threads : retrieve a task to run from the threadpool , run it , and proceed to the next task until threadpool is stopped .",def _worker self ct self currentThread o self q get while o is not WorkerStop with self _workerState self working ct ctx function args kwargs onResult o del o try result context call ctx function args kwargs success True except success False if onResult is None context call ctx log err result None else result failure Failure del function args kwargs if onResult is not None try context call ctx onResult success result except context call ctx log err del ctx onResult result with self _workerState self waiters ct o self q get self threads remove ct
"todo : this self - test was written to build the module , but should now be moved to a unit test .",def _selftest import csv print CSV file self test tmp_path tempfile mktemp with open tmp_path w as csv_file csv_writer csv writer csv_file for line in gen_json2csv visitor_site_id 1 apikey qz com ts_action 2016 11 26 08 30 57 action pageview extra_data present True url http qz com 1234 csv_writer writerow line for i line in enumerate open tmp_path readlines print line 80 os remove tmp_path print Done
"resets our "" fake "" port list . : return :",def _clear_fake_ports self self fake_port_list
sorts an array of items by multiple properties ;,def sort_by_v2 a criteria criteria reverse for k in criteria prop order k def fn o v o get prop if isinstance v str v unidecode unidecode v return v a sort key fn reverse desc in order return a
adds piece to part . note : if piece is already in it wo n't be added,def add_piece self piece if piece get_index in self __pieces return False self __pieces piece get_index piece return True
set uv layer to mask texture in shader .,staticmethod def set_mask_uv node_tree uv_layer if uv_layer is None or uv_layer uv_layer _MESH_consts none_uv node_tree nodes Lamp SEC_GEOM_NODE uv_layer uv_layer
parser from terminal with $ python2 bruker2nifti_scan -h $ python2 bruker2nifti_scan -i input_file_path -o output_file_path,def main_scan parser argparse ArgumentParser parser add_argument i input_scan_folder dest pfo_input type str required True help Bruker scan folder parser add_argument o output_scan_folder dest pfo_output type str required True help Output folder where the study will be saved parser add_argument fin_output dest fin_output type str default None parser add_argument nifti_version dest nifti_version type int default 1 help Filename of the nifti output parser add_argument qform_code dest qform_code type int default 2 parser add_argument sform_code dest sform_code type int default 1 parser add_argument do_not_save_human_readable dest do_not_save_human_readable action store_true parser add_argument correct_slope dest correct_slope action store_true parser add_argument verbose v dest verbose type int default 1 args parser parse_args bruconv Bruker2Nifti os path dirname args pfo_input args pfo_output bruconv nifti_version args nifti_version bruconv qform_code args qform_code bruconv sform_code args sform_code bruconv save_human_readable not args do_not_save_human_readable bruconv correct_slope args correct_slope bruconv verbose args verbose if parser add_argument 0 print nConverter parameters print print Study Folder format os path dirname args pfo_input print Scan to convert format os path basename args pfo_input print List of scans format bruconv scans_list print Output NifTi version format bruconv nifti_version print Output NifTi q form format bruconv qform_code print Output NifTi s form format bruconv sform_code print Save human readable format bruconv save_human_readable print Correct the slope format bruconv correct_slope print bruconv convert_scan args pfo_input args pfo_output nifti_file_name args fin_output create_output_folder_if_not_exists True
compute similarity between two sets using jaccard similarity .,def jaccard_sim features1 features2 set1 set features1 set2 set features2 try return len set1 intersection set2 float max len set1 len set2 except ZeroDivisionError return 0
get tolerated absolute pressure for the compartment .,def get_max_amb self gf return self pp_he self pp_n2 self a_he_n2 gf gf self b_he_n2 gf 1 0
bounds query with regex child match .,def test_011_child_regex self q BoundsQuery self p child test11_child child_regex True qbounds sorted q results self assertEqual 2 len qbounds b qbounds 0 self assertEqual BoundsRuletype typebounds b ruletype self assertEqual test11_parent1 b parent self assertEqual test11_child2 b child b qbounds 1 self assertEqual BoundsRuletype typebounds b ruletype self assertEqual test11_parent2 b parent self assertEqual test11_child1 b child
user query with range proper subset match ( equal ),def test_044_range_proper_subset2 self q UserQuery self p range_ s4 c5 s4 c1 c3 c5 range_subset True range_proper True users sorted str u for u in q results self assertListEqual users
relative path from the base of the repository to the actual plugin,property def path self return core BNPluginGetPath self handle
return yubihsm response status code as string .,def status2str num known 128 YSM_STATUS_OK 129 YSM_KEY_HANDLE_INVALID 130 YSM_AEAD_INVALID 131 YSM_OTP_INVALID 132 YSM_OTP_REPLAY 133 YSM_ID_DUPLICATE 134 YSM_ID_NOT_FOUND 135 YSM_DB_FULL 136 YSM_MEMORY_ERROR 137 YSM_FUNCTION_DISABLED 138 YSM_KEY_STORAGE_LOCKED 139 YSM_MISMATCH 140 YSM_INVALID_PARAMETER if num in known return known num return 0x 02x num
"updates tree node edge indicators which will by affected by the deletion of the given model instance and any descendants it may have , to ensure the integrity of the tree structure is maintained .",def pre_delete instance opts instance _meta tree_width getattr instance opts right_attr getattr instance opts left_attr 1 target_right getattr instance opts right_attr tree_id getattr instance opts tree_id_attr instance _tree_manager _close_gap tree_width target_right tree_id
returns the max coins with an optimal popping strategy .,def maxCoins self balloons n len balloons if n 0 return 0 elif n 1 return balloons 0 dp 1 for _ in xrange n for _ in xrange n return self maxCoinsHelper balloons 0 n 1 dp 1 1
"returns true if the file should be copied , otherwise false .",def should_copy_file remote_storage path prefixed_path source_storage if has_matching_etag remote_storage source_storage path prefixed_path logger info s Skipping based on matching file hashes path return False destroy_etag path logger info s Hashes did not match path return True
adds an element to the set .,def add self element _check_element element self _adds add element
convert pem key to openssh key : param key : : return :,def pem_to_openssh key eb long_to_bytes key e nb long_to_bytes key n if bord eb 0 128 eb bchr 0 eb if bord nb 0 128 nb bchr 0 nb keyparts ssh rsa eb nb keystring join struct pack I len kp kp for kp in keyparts return ssh rsa binascii b2a_base64 keystring 1
"uyum verileri ve tahminleri iceren dataframe'leri birlestir . geriye dondurulen df icinde takim isimleri , tahminler , ve ( eger mevcut ise ) puan olarak sonuc .",def extract_predictions data predictions probs _team_test_prob predictions teams0 teams1 points for game in xrange len data 2 if data matchid iloc game 2 data matchid iloc game 2 1 raise Exception Unexpeted match id d vs d data matchid iloc game 2 data matchid iloc game 2 1 team0 data team_name iloc game 2 team1 data op_team_name iloc game 2 if points in data columns points append data points iloc game 2 teams0 append team0 teams1 append team1 results pd DataFrame team_name pd Series teams0 op_team_name pd Series teams1 predicted pd Series probs mul 100 columns team_name op_team_name predicted expected_winner for game in xrange len results row results iloc game col team_name if row predicted 50 else op_team_name expected_winner append row col results expected pd Series expected_winner if len points 0 winners for game in xrange len results row results iloc game point points game if point 1 1 winners append row team_name elif point 0 9 winners append row op_team_name elif point 0 1 winners append draw else winners append NA results winner pd Series winners results points pd Series points return results
get the file contents and encode then in base64 : param file : filename + path : return : none or base64 string,def get_base64_contents self file try with open file rb as f return f read encode base64 except return None
set this connection 's underlying socket blocking _ mode_.,def setblocking self mode self __ssl_conn setblocking mode
"returns a mapping indicating the permission levels of users , anonymous users any authenticated users that have specific permissions assigned to them .",def get_all_level_info_by_email self my_ct ContentType objects get_for_model self user_levels user_names for rm in UserObjectRoleMapping objects filter object_id self id object_ct my_ct all user_levels rm user email rm role codename user_names rm user email rm user username levels for rm in GenericObjectRoleMapping objects filter object_id self id object_ct my_ct all levels rm subject rm role codename levels users user_levels levels names user_names return levels
test pop on an empty list .,def test_pop_empty empty_heap with pytest raises IndexError empty_heap pop
return the function under test .,pytest fixture def converter from agile_analytics fetchers import convert_jira_issue return convert_jira_issue
use select.select ( ) to implement telnet.expect ( ) .,def test_expect_with_select self want x 10 match y 10 telnet test_telnet want use_poll False if self old_poll select poll lambda _ self fail unexpected poll call _ _ data telnet expect match self assertEqual data join want 1
returns 1/2 the l2 norm squared .,def norm2 arr return np sum arr 2 2
run after the fixer ' run ' method .,def postRun self ctx return
export a pandas . dataframe to a vega - lite data json .,def df_to_vega_lite df path None chart altair Chart data df data chart to_dict data values if path is None return json dumps data json_dump_kwargs with open path w as write_file json dump data write_file json_dump_kwargs
delete a metadata tag key .,def __delitem__ self key if self tags is None raise KeyError key else del self tags key
"returns a template loader object for the given app name in the given subdir . for example , get_template_loader('homepage ' , ' styles ' ) will return a loader for the styles/ directory in the homepage app .",def get_template_loader self app subdir templates create False if app is None raise TemplateDoesNotExist Cannot locate loader when app is None if not isinstance app AppConfig app apps get_app_config app path os path join app path subdir if not create dmp apps get_app_config django_mako_plus if not dmp is_registered_app app raise ValueError is not registered with DMP hint check urls py for include django_mako_plus urls format app return self get_template_loader_for_path path use_cache True
"condition : expression ( "" < "" | "" > "" | "" < = "" | "" > = "" | "" = "" | "" ! = "" ) expression",def simpleCondition self node None self expression node if self found GE node or self found LE node or self found LT node or self found GT node or self found EQ node or self found NE node self expression node elif self token type RIGHT_PARAN print condition error wrong token self error self token else pass
"create the directory for storing the hashes , if it does n't exist already .",def create_prereqs_cache_dir try os makedirs PREREQS_STATE_DIR except OSError if not os path isdir PREREQS_STATE_DIR raise
"retrieve information about xpack , including build number / timestamp and license status ` < https://www.elastic.co/guide/en/elasticsearch/reference/current/info-api.html > ` _",query_params categories human def info self params None return self transport perform_request GET _xpack params params
"embellishment in the form of a dsl . entry(1 , 2 , 3 ) / 4 / 5 = = entry(1 , 2 , 3 , 4 , 5 )",def __div__ self other args self path other return self __class__ args
"flatten a tree , removing all hierarchical information , making a list out of all the nodes .",def flatten_tree node_list node for c in node children flatten_tree node_list c no_kids copy deepcopy node no_kids children node_list append no_kids
start a bitcoind and return rpc connection to it,def start_node i dirname extra_args None rpchost None datadir os path join dirname node str i args os getenv BITCOIND bitcoind datadir datadir keypool 1 discover 0 rest if extra_args is not None args extend extra_args bitcoind_processes i subprocess Popen args devnull open dev null w subprocess check_call os getenv BITCOINCLI bitcoin cli datadir datadir _rpchost_to_args rpchost rpcwait getblockcount stdout devnull devnull close url http rt rt s d rpchost or 127 0 0 1 rpc_port i proxy AuthServiceProxy url proxy url url return proxy
: type n : int : rtype : bool,def isHappy self n visited while n 1 if n in visited return False visited append n n sum int i 2 for i in str n return True
removes a pair given the first key,def _remove_by_first self first second self _first_to_second first del self _second_to_first second del self _first_to_second first
upload the layers of the given image .,def upload self image self _top image top for layer in reversed image ancestry self _top self _upload_one image layer
run video - level validation on the charades test set,def validate_video self loader model epoch args batch_time AverageMeter outputs gts ids model eval end time time for i input target meta in enumerate loader target target long cuda async True assert target 0 eq target 1 all val_video not synced input_var torch autograd Variable input cuda volatile True output model input_var output torch nn Softmax dim 1 output output_video output mean dim 0 outputs append output_video data cpu numpy gts append target 0 ids append meta id 0 batch_time update time time end end time time if i args print_freq 0 print Test2 0 1 tTime batch_time val 3f batch_time avg 3f format i len loader batch_time batch_time mAP _ ap map charades_map np vstack outputs np vstack gts print ap print mAP 3f format mAP submission_file ids outputs epoch_ 03d txt format args cache epoch 1 return mAP
"get remote filename , saving it to local_path",def get self remote_filename local_path remote_path os path join urllib unquote self parsed_url path remote_filename rstrip commandline lftp c source s get s o s self tempname remote_path lstrip local_path name self run_command_persist commandline local_path setdata
"set up database , e.g. migrate : return :",tasks register_helper def prepare_db u n Set up database e g migrate n return n tasks manage u migrate u noinput
get a list of test methods with no known annotations .,def _GetTestsMissingAnnotation self tests_missing_annotations for test_method in self GetTestMethods annotations_ frozenset self GetTestAnnotations test_method if annotations_ isdisjoint self _ANNOTATIONS and not self IsHostDrivenTest test_method tests_missing_annotations append test_method return sorted tests_missing_annotations
find the next class in ` cls.mro ( ) ` after ` current ` .,def next_mro_class cls current mro cls mro return mro mro index current 1
the zip method joins list elements pairwise like a zip fastener,def zip_iterables from sys import version_info as python_version a_list 0 1 2 3 b_list a b c d zipper zip a_list b_list if python_version 3 zipper list zipper assert zipper 0 a 1 b 2 c 3 d
expects a list of dictionaries with `` k `` and `` v `` set to the keys and values that will be unwrapped into the output python dictionary should have,def validate_unwrap self value if not isinstance value list self _fail_validation_type value list for value_dict in value if not isinstance value_dict dict cause BadValueException value_dict Values in a KVField list must be dicts self _fail_validation value Values in a KVField list must be dicts cause cause k value_dict get k v value_dict get v if k is None self _fail_validation value Value had None for a key try self key_type validate_unwrap k except BadValueException as bve self _fail_validation value Bad value for KVField key s k cause bve try self value_type validate_unwrap v except BadValueException as bve self _fail_validation value Bad value for KFVield value s k cause bve return True
disconnect signals for the model .,def _disconnect_signals self model u n Disconnect signals for the model n for signal receiver in self _signals items signal disconnect sender model dispatch_uid self _dispatch_uid signal model
get the matrix representation of the learned metric,def get_A self return self A
return the drop table and restraint dropping statements for a single model .,def sql_destroy_model self model references_to_delete style if not model _meta managed or model _meta proxy or model _meta swapped return qn self connection ops quote_name output s s style SQL_KEYWORD DROP TABLE style SQL_TABLE qn model _meta db_table if model _meta has_auto_field ds self connection ops drop_sequence_sql model _meta db_table if ds output append ds return output
tool to estimate the central wavelength of an averaged collapsed val .,def central_wav wav central_wav 10 0 5 np log10 wav 0 wav 1 return central_wav
return access_token stored in extra_data or none,property def tokens self backend self get_backend if backend return backend AUTH_BACKEND tokens self else return
create data to use for testing .,def setUp self self close_data SampleData get_sample_close_data self high_data SampleData get_sample_high_data self low_data SampleData get_sample_low_data self volume SampleData get_sample_volume self cmf_period_6_expected np nan np nan np nan np nan np nan 0 003312520909302368 0 004861355060509591 0 007636828834298363 0 00652872237456285 0 010712462475030939 0 016573767174777168 0 022118018755417572 0 029221567084304925 0 0334847571835854 0 04173529363575846 0 04284315406589872 0 020876675876256596 0 02441587065869279 0 026707069318664234 0 08003092546713404 0 05714776905364929 0 06560480887728143 0 06593914113115479 0 04624372252245244 0 039084580765582945 0 023732518823802458 0 014371385759892283 0 005384131073542457 0 007356643108053271 0 023993372933344703 0 02996042824540523 0 020848896421251553 0 03322184506971148 0 023632410244811587 0 009705008823045832 0 018370449199058135 0 010361413074362698 0 02995516308307368 0 0356690137517131 0 04222574523198988 0 016262549780505727 0 0013941588013852452 0 012306879131758812 0 003570242667534922 0 01685594061104065 0 017195749786707487 0 03514249564569789 0 08192838697487738 0 07463930382933483 0 059587959294833265 0 025673521303580357 0 005801702165825746 0 01764998796148713 0 03774368045632273 0 030009726186828133 0 035697538763242824 0 03764415988386345 0 004892840446688841 0 0009010251192627237 0 0035648800422953685 0 015052762227444404 0 014071386096076447 0 03508329543861937 0 012371868491255654 0 02142494952229579 0 020558640966843865 0 06444840359402675 0 05217658658494619 0 019569995625100225 0 028186526955462123 0 031094787908345023 0 03246050402493244 0 05819815000228063 0 04350319079769754 0 0009559410977857809 0 010813889014902886 0 011190581326110635 0 00786771202826834 0 037517542650319986 0 044658480463605946 0 055190082593348115 0 07189735710445547 0 0739150565863593 0 07101148964635963 0 05984985684244601 0 05909421093693829 0 03287724077897463 0 044715034918426266 0 04519212736579133 0 0337951508223283 0 07534702288930027 0 060429544725187107 0 08184095142643666 0 03772196331257113 0 03263979423784871 0 022413515752428483 0 005025819884799211 0 010372825841295268 0 0008344957710629373 0 008566990223150443 0 027089129950182974 0 03956141033382661 0 044011605196096544 0 03889133222563874 0 027574878189471158 0 046321405729603714 0 041172145145542835 0 034642007487542176 0 014260177160802688 0 008298806520820485 0 017126773507882866 0 01474150391403774 0 016010639972291973 0 02532611236298593 0 0346296488753863 0 014997042039988612 0 01069599087866673 0 011127907594170367 0 00801688662935928 0 013671648032558471 0 026946141394489087 0 021756121749873004 0 032467558230566636 0 041891312663086974 0 03582260481412334 0 03121264843950771 0 040638532850568315 self cmf_period_8_expected np nan np nan np nan np nan np nan np nan np nan 0 0081185024674913 0 0025371802819565883 0 0010644977834666388 0 005672830131270103 0 004169495227618881 0 027797521862243494 0 014603048497697219 0 019669640273245477 0 043772436549748425 0 03224625156955247 0 03548560101181097 0 03849757979962801 0 05610456280382046 0 04059266391741898 0 06878156913062386 0 05186803798243697 0 03907657188927923 0 05073123988977297 0 05322955172813692 0 030648158861072514 0 012411553304442827 0 013827755337462506 0 008789433783271234 0 02372021526121806 0 03411519622662579 0 02588762902283894 0 012678892347838255 0 010229402522448557 0 0183800152209006 0 009120096215610472 0 007988239029429347 0 025256686134179286 0 03664652628853453 0 022578841768494146 0 00037994399427053205 0 009405676037352368 0 015170928752505568 0 024780406255827572 0 02398510443090455 0 025206632383119276 0 027437965711461888 0 040771722434282294 0 057773298969144654 0 04288845336214161 0 03411895353870836 0 008619555706187202 0 0053082066228187265 0 007327694741039293 0 04033995498086043 0 04402496033694127 0 008372116834863547 0 010894944701009993 0 002069543889197569 0 007073247880315286 0 0027650689324161004 0 003099300977691961 0 028980930474517174 0 032897879595979874 0 011512894812962913 0 037606534276955164 0 03161087470746074 0 0014348407984348796 0 007620812878550823 0 02255891656436438 0 024463692779761438 0 03139903804062639 0 025163213707663782 0 029551186437460762 0 03645993477631073 0 015706223008120388 0 0015586402908818618 0 019379406270457197 0 03361748616441026 0 056610182531136054 0 051801585060995865 0 043696289983268924 0 06433950255772614 0 07349901037305931 0 06998928567815062 0 055791870559251916 0 05309804091164417 0 03330390300209949 0 03441482599303197 0 07466876462239005 0 06129901630246664 0 07508174790517361 0 03748022647701813 0 03288992518672232 0 020106235192252808 0 028204580027412218 0 034341643352812236 0 0218875275188007 0 0071316698495589425 0 005275083820965108 0 015188886014108748 0 03606129424285989 0 050278602384032256 0 04313053297104245 0 03456326466891572 0 026040168606977436 0 034587936909265836 0 02876909144339216 0 03469067860193259 0 024532129642417532 0 014883586477139587 0 016726987370967537 0 012188281555131105 0 016841358495234233 0 020078868602802388 0 02524487617720117 0 017970496234460627 0 0030203029703223822 0 009665000477511228 0 016473215917856138 0 015549623508933264 0 022702905873274063 0 02471095578339294 0 038703957202912316 0 04145277672649277 0 04115774295848392 self cmf_period_10_expected np nan np nan np nan np nan np nan np nan np nan np nan np nan 0 0009700544284587938 0 00641992684734979 0 00981630771032585 0 01539385491408015 0 0019407376530060584 0 021201955642506994 0 025200322249567 0 016200232414935737 0 03781153110822709 0 04402675896520553 0 05853407702833407 0 046548203377963476 0 05198320162628678 0 039512066195189634 0 046003067307706036 0 04213240707248592 0 046334449727507415 0 04133207922271704 0 03901864789164138 0 02733492269520747 0 013686335276416654 0 02580417159608526 0 01994459508591013 0 021723804450678588 0 024950741592236047 0 009228098432937539 0 010856808489330882 0 009634993834405657 0 002917532283971009 0 00824283962304065 0 019496326105300225 0 017285768031592645 0 001954688027274251 0 014596209539885734 0 012571839892109608 0 020738139163870514 0 030856858152494813 0 03049958536258458 0 03164822168427241 0 0303665403083119 0 01776324429095813 0 025830127055555277 0 04041148592198683 0 026592245316573945 0 027352531826117733 0 011207243951777237 0 01571672073472607 0 024814013216715024 0 01690975716740387 0 02070347263173442 0 007465740993427714 0 014086706455012497 0 0029493218051483677 0 006586361206931457 0 010589147609965469 0 00587481429105602 0 025036458880156737 0 042389180311841836 0 021170442660274864 0 00465179736632976 0 01147883354933807 0 006355345189282063 0 009652131359682927 0 024853981082800104 0 019947952803719058 0 012644857452069816 0 02282098981637035 0 035389803360523206 0 022302450718866752 0 009660622909779728 0 023530102149541612 0 03957530631848888 0 041663203623864616 0 046846269401670804 0 04914780476010481 0 04653270383244754 0 06453228108336988 0 06788443541346015 0 06343290236372225 0 0517389246620805 0 04350246923029494 0 058961336245194944 0 057160593743307196 0 07467173950117462 0 04045293665095788 0 03375822977374965 0 022087082552981425 0 028947816115888845 0 03095295438416122 0 038982492918535165 0 028150926559148217 0 014865469834815303 0 01170230670122519 0 008399550919717384 0 03090710173350411 0 03689932839643731 0 04492090321100161 0 03966145783171248 0 026671091384831067 0 018272102875036875 0 034633486248171697 0 033332625706768454 0 03455433662312155 0 02330355950897256 0 012915875614998074 0 01725568578495628 0 010453027043024619 0 013367439404347276 0 021473243280857524 0 01291678949782856 0 0011786722377113861 0 010994206543604062 0 012037897092003943 0 015417115757289098 0 01932122426096974 0 0294759442510717 0 027951042217520154 0 04254339389609021
method to select the model to be used for classification,def model_selector args embedding_matrix if args model_name lower self return _predefined_model args embedding_matrix
run each test case with the corresponding arguments and add log object into the dictionary of arguments,def generator self envlog log EnvLog self logfile self loglevel env_logger envlog env_log casenumber len self case_name_list start_time time strftime Y m d H M S env_logger info Checking Testing Environment envck env_inspect EnvInspect self env env_logger if envck env_checking 1 sys exit 1 else env_logger info nStart Testing env_logger info Case Count s casenumber env_logger info Log File s n self logfile caselog log CaseLog self logfile self loglevel case_logger caselog case_log retflag 0 0 0 case_retlist for i in range casenumber clean_flag False mod_case_func self case_name_list i if mod_case_func endswith clean mod_case_func mod_case_func 6 clean_flag True mod_case mod_case_func rsplit 1 0 self fmt print_start mod_case env_logger case_params self case_params_list i case_params logger case_logger if mod_case_func in self cases_checkfunc_ref_dict if self cases_checkfunc_ref_dict mod_case_func case_params case_logger info Failed to meet testing requirement self fmt print_end mod_case 2 env_logger retflag 2 1 continue case_start_time time strftime Y m d H M S ret 1 try try if mod_case_func sleep sleepsecs case_params get sleep 0 case_logger info sleep s seconds sleepsecs time sleep int sleepsecs ret 0 else xml_file_to_str self proxy_obj mod_case case_params ret self cases_func_ref_dict mod_case_func case_params if ret 0 ret 1 if clean_flag clean_func mod_case_func _clean self fmt print_string 12 Cleaning env_logger clean_ret self cases_func_ref_dict clean_func case_params if clean_ret and clean_ret 1 self fmt print_string 21 Fail env_logger continue self fmt print_string 21 Done env_logger except Exception as e case_logger error traceback format_exc continue finally case_end_time time strftime Y m d H M S if ret 0 retflag 0 1 elif ret 1 retflag 1 1 elif ret 2 retflag 2 1 self fmt print_end mod_case ret env_logger case_retlist append ret envck close_hypervisor_connection end_time time strftime Y m d H M S env_logger info nSummary env_logger info Total s Pass s Fail s Skip s casenumber retflag 0 retflag 1 retflag 2 result retflag 1 and FAIL or PASS fcntl lockf self lockfile fileno fcntl LOCK_EX self log_xml_parser add_test_summary self testrunid self testid result case_retlist start_time end_time self logfile fcntl lockf self lockfile fileno fcntl LOCK_UN return retflag 1
expose only the containers and the images that match the rules set - skip_image : exclude all images matching the regex - match_image : keep all images matching the regex - skip_container : exclude all containers matching the regex - match_container : keep all containers matching the regex,def filter self containers filtered for c in containers if c attrs Config Image startswith logmatic logmatic docker continue if self args skip_image and re search self args skip_image c attrs Config Image continue if self args skip_name and re search self args skip_name c name continue if self args match_image and not re search self args match_image c attrs Config Image continue if self args match_name and not re search self args match_name c name continue self local_cache c id self _build_context c filtered append c logger debug Filter Keeping containers format filtered return filtered
blocks until any of the specified events are triggered . returns the index of the event that was triggerd or raises a timeouterror param timeout : a timeout in seconds,def wait_any timeout None events or_event threading Event subscriptions for event in events subscriptions append event event subscribe lambda or_event set or_event wait timeout timeout for event sub in subscriptions event unsubscribe sub for i in range len events if events i is_set return i raise TimeoutError
create a comp model from the given model paths .,def create_merged_doc model_paths merged_id merged sbmlns libsbml SBMLNamespaces 3 1 sbmlns addPackageNamespace comp 1 doc libsbml SBMLDocument sbmlns doc setPackageRequired comp True model doc createModel model setId merged_id comp_doc doc getPlugin comp comp_model model getPlugin comp for emd_id path in model_paths items emd comp create_ExternalModelDefinition comp_doc emd_id source path comp add_submodel_from_emd comp_model submodel_id emd_id emd emd return doc
calculate : math:`\vec{m}(t+\delta t ) ` for a given timestep .,def step self state dt Calculate math vec m t Delta t for a given timestep Arguments state class State The simulation state dt class float The time step size with Timer LLG Step v self calculate_v state dt state m vector axpy dt v vector state m normalize
redirect parameters for oauth 1.0 provider .,def test_oauth_1_redirect_parameters self u self provider request_token_url self get_random_url self provider save with patch u allaccess clients OAuthClient get_request_token as request_token request_token return_value u oauth_token token oauth_token_secret secret response self client get self url url response u Location scheme netloc path params query fragment urlparse url query parse_qs query self assertEqual query u oauth_token 0 u token callback reverse u allaccess callback kwargs u provider self provider name self assertEqual query u oauth_callback 0 u http testserver callback
parses a line of log output from the child process and passes it to mozlog to update the overall status of the run . re - emits the logged line in human - readable format .,def parse_single_line self line level INFO tbpl_level TBPL_SUCCESS data None try candidate_data json loads line if isinstance candidate_data dict and action in candidate_data and candidate_data action in self log_actions data candidate_data except ValueError pass if data is None self _handle_unstructured_output line return self handler data action data action if action log level getattr log data level upper self log self formatter data level level self update_levels tbpl_level level
remove and return an item from the queue .,def get self block True timeout None self not_empty acquire try if not block if self _empty raise Empty elif timeout is None while self _empty self not_empty wait else if timeout 0 raise ValueError timeout must be a positive number endtime _time timeout while self _empty remaining endtime _time if remaining 0 0 raise Empty self not_empty wait remaining item self _get self not_full notify return item finally self not_empty release
test if the substitute function works,def testSubstitute self self assertTrue substitute distro_codename updates nacked updates self assertTrue substitute distro_id MyDistroID
return flag as list of its parts .,def as_list self if self __prefix return self __prefix self __body return self __body
should include ember full js stack libraries without jquery,override_settings DEBUG True def test_ember_full_js_without_jquery self t Template load ember ember_full_js jquery false rendered t render Context self assertNotIn script type text javascript src sjs libs jquery settings STATIC_URL rendered self assertIn script type text javascript src sjs libs handlebars js settings STATIC_URL rendered self assertIn script type text javascript src sjs libs ember js settings STATIC_URL rendered
get a jittered loop path .,def getJitteredLoop jitterDistance jitterLoop loopLength euclidean getLoopLength jitterLoop lastLength 0 0 pointIndex 0 totalLength 0 0 jitterPosition jitterDistance 256 0 loopLength loopLength while totalLength jitterPosition and pointIndex len jitterLoop firstPoint jitterLoop pointIndex secondPoint jitterLoop pointIndex 1 len jitterLoop pointIndex 1 lastLength totalLength totalLength abs firstPoint secondPoint remainingLength jitterPosition lastLength pointIndex pointIndex len jitterLoop ultimateJitteredPoint jitterLoop pointIndex penultimateJitteredPointIndex pointIndex len jitterLoop 1 len jitterLoop penultimateJitteredPoint jitterLoop penultimateJitteredPointIndex segment ultimateJitteredPoint penultimateJitteredPoint segmentLength abs segment originalOffsetLoop euclidean getAroundLoop pointIndex pointIndex jitterLoop if segmentLength 0 0 return originalOffsetLoop newUltimatePoint penultimateJitteredPoint segment remainingLength segmentLength return newUltimatePoint originalOffsetLoop
parse gcode text and store the feed gcode .,def getCraftedGcode self gcodeText repository self repository repository self feedRatePerSecond repository feedRatePerSecond value self travelFeedRateMinute 60 0 self repository travelFeedRatePerSecond value self lines archive getTextLines gcodeText self parseInitialization for line in self lines self lineIndex self parseLine line return self distanceFeedRate output getvalue
parse gcode text and store the gcode .,def getCraftedGcode self gcodeText binary16ByteRepository self binary16ByteRepository binary16ByteRepository lines archive getTextLines gcodeText for line in lines self parseLine line return self output getvalue
a wrapper method that calls validate_authorization_request on ` server_class ` instance .,def validate_authorization_request self request u n A wrapper method that calls validate_authorization_request on server_class instance n n param request The current django http HttpRequest object n try uri http_method body headers self _extract_params request scopes credentials self server validate_authorization_request uri http_method http_method body body headers headers return scopes credentials except oauth2 FatalClientError as error raise FatalClientError error error except oauth2 OAuth2Error as error raise OAuthToolkitError error error
the maxwritebatchsize reported by the server .,property def max_write_batch_size self return self master max_write_batch_size
return the number of hops left in message the trasport .,property def hopsLeft self return self _hopsLeft
returns the formated tabs attribute .,def get_formatted_tabs self request obj None if self tabs self parse_fieldsets_inlines_from_tabs request obj return self formatted_tabs
"test topics_to_bytes basic usage , without specifying a uuid .",def test_topics_to_bytes_without_uuid handlers topic_one handler topic_two handler curated topics_to_bytes handlers assert isinstance curated dict for k v in curated items assert isinstance k bytes assert k startswith topic_ assert v handler
: param consumer : an instance of ` simpleconsumer `,def __init__ self consumer self consumer consumer self initial_offsets None self high_water_mark None self logger getLogger kafka context
perform a http put on the url,def put self url json_body return self _rest_call url PUT json_body
one - dimensional gaussian quadrature rule .,def g1d N quadtype if N 1 if quadtype Hermite ab r_hermite N elif quadtype Legendre ab r_jacobi N 1 1 0 0 else raise ValueError quadtype must be Legendre or Hermite J jacobi_matrix ab e V np linalg eig J ind np argsort e x e ind reshape N 1 x np fabs x 1e 12 0 0 w V 0 ind V 0 ind reshape N 1 else x w np array 0 0 np array 1 0 return x w
should be called at some point after : meth:`start()<cursesmenu . cursesmenu.start > ` to block until the menu exits . : param number timeout : how long to wait before timing out,def join self timeout None self _main_thread join timeout timeout
print the diff to the last time the state of objects was measured .,def print_diff self ignore ignore append inspect currentframe diff self get_diff ignore print Added objects summary print_ summary summarize diff print Removed objects summary print_ summary summarize diff del ignore
returns the hash digest of the package data .,def get_hash self return hash_contents self get_contents
create an oauth client application that is confidential .,def create_confidential_client self name user redirect_uri client_id None return models Client objects create name name user user client_id client_id redirect_uri redirect_uri client_type constants CONFIDENTIAL
this method is deprecated . please use : func:`request_cache.get_cache ` .,classmethod def get_request_cache cls name None if name is None return REQUEST_CACHE else return REQUEST_CACHE data setdefault name
"when importing an xblock from xml , this method will parse the license information out of the xml and attach it to the block . it is defined here so that classes that use this mixin can simply refer to this method , rather than reimplementing it in their xml import functions .",classmethod def parse_license_from_xml cls definition node license node get license default None if license definition license license return definition
test that credit eligibility requirements are present in response if the feature flag ' enable_credit_eligibility ' is enabled .,mock patch dict django conf settings FEATURES ENABLE_CREDIT_ELIGIBILITY True def test_course_details_with_enabled_setting self response self client get_html self course_details_url self assertEqual response status_code 200 self assertNotContains response Course Credit Requirements self assertNotContains response Steps required to earn course credit credit_course CreditCourse course_key unicode self course id enabled True credit_course save self assertEqual len get_credit_requirements self course id 0 on_course_publish self course id self assertEqual len get_credit_requirements self course id 1 response self client get_html self course_details_url self assertEqual response status_code 200 self assertContains response Course Credit Requirements self assertContains response Steps required to earn course credit
get the video branding configuration .,classmethod def get_config cls info cls current return json loads info configuration if info enabled else
whether responses from the ecommerce api will be cached .,property def is_cache_enabled self return self cache_ttl 0
"given an email context , replaces all % % -encoded words in the given string ` context ` is a dictionary that should include ` user_id ` and ` course_title ` keys",def substitute_keywords_with_data string context user_id context get user_id course_title context get course_title if user_id is None or course_title is None return string return substitute_keywords string user_id context
"click one of the "" add new component "" buttons .",def add_component page item_type specific_type is_advanced_problem False btn page q css add xblock component add xblock component button data type format item_type multiple_templates btn filter lambda el multiple templates in el get_attribute class present btn click if multiple_templates sub_template_menu_div_selector new component format item_type page wait_for_element_visibility sub_template_menu_div_selector Wait for the templates sub menu to appear page wait_for_element_invisibility add xblock component new component Wait for the add component menu to disappear if is_advanced_problem advanced_tab page q css problem type tabs a filter text Advanced first advanced_tab click css problem type tabs li ui tabs active a page wait_for lambda len page q css css filter text Advanced execute 0 Waiting for the Advanced problem tab to be active all_options page q css new component ul new component template li button span format item_type chosen_option all_options filter text specific_type first chosen_option click sync_on_notification page page wait_for_ajax
"parses version into major , minor and patch versions before saving",def save self args kwargs self major_version self minor_version self patch_version utils parsed_version self version super AppVersionConfig self save args kwargs
record visiting the pub101 course outline page,with_cache def test_visit_outline self self record_visit_outline
check that course overview is cached after course published signal is sent,def test_course_overview_cached self course_key CCXLocator from_course_locator self course id self ccx id overview CourseOverview objects filter id course_key self assertEqual len overview 0 with mock_signal_receiver SignalHandler course_published as receiver self call_fut self course id self assertEqual receiver call_count 3 overview CourseOverview objects filter id course_key self assertEqual len overview 1
extract information from the request and add it to the tracking context .,def enter_request_context self request context session self get_session_key request user_id self get_user_primary_key request username self get_username request ip self get_request_ip_address request for header_name context_key in META_KEY_TO_CONTEXT_KEY iteritems context context_key request META get header_name decode latin1 google_analytics_cookie request COOKIES get _ga if google_analytics_cookie is None context client_id request META get HTTP_X_EDX_GA_CLIENT_ID else context client_id join google_analytics_cookie split 2 context update contexts course_context_from_url request build_absolute_uri tracker get_tracker enter_context CONTEXT_NAME context
the caller requests adding the given users to the role . checks that the caller has sufficient authority .,def add_users caller role users _check_caller_authority caller role role add_users users
get list from sailthru and return if list_name exists else create a new one and return list data for all lists . : param sailthru_client : param list_name : return sailthru list,def _get_or_create_user_list sailthru_client list_name sailthru_list_cache cache get SAILTHRU_LIST_CACHE_KEY is_cache_updated False if not sailthru_list_cache sailthru_list_cache _get_list_from_email_marketing_provider sailthru_client is_cache_updated True sailthru_list sailthru_list_cache get list_name if not sailthru_list is_created _create_user_list sailthru_client list_name if is_created sailthru_list_cache _get_list_from_email_marketing_provider sailthru_client is_cache_updated True sailthru_list sailthru_list_cache get list_name if is_cache_updated cache set SAILTHRU_LIST_CACHE_KEY sailthru_list_cache return sailthru_list
"ensures that staff can always access all blocks in the course , regardless of gating or proctoring .",def test_staff_access self expected_blocks self ALL_BLOCKS self setup_gated_section self blocks H self blocks A self get_blocks_and_check_against_expected self staff expected_blocks
"returns a list of ( pattern , response ) tuples , where ` pattern ` is a pattern to match in the xqueue body , and ` response ` is a dictionary to return as the response from the grader .",property def queue_responses self return key value for key value in self config iteritems if key not in self NON_QUEUE_CONFIG_KEYS items
click the studio help link in the page footer .,def click_studio_help page help_link_selector cta show sock EmptyPromise lambda page q css help_link_selector visible Help link visible fulfill page q css help_link_selector click EmptyPromise lambda page q css support list actions a results 0 text Support section opened fulfill
return allocation for the group .,property def allocation self css group allocation return self find_css css first text 0
return the text to output for a result .,def _dump_results self result result _ansible_verbose_always True save for key in stdout stdout_lines stderr stderr_lines msg if key in result save key result pop key output CallbackModule_default _dump_results self result for key in stdout stderr msg if key in save and save key output n n s n n s n key upper save key for key value in save items result key value return output
dummy init method . use the other initialization before using the class,def __init__ self
get the minimum value of the property associated with the given use_as value for every node 's layer i.,def getPropertyMinVal self use_as layer_i return self layers layer_i use_as 2
the constructor for initializing the backup image .,def __init__ self uri self __uri uri if self __uri is not None parsed urlparse self __uri self __scheme parsed scheme self __netloc parsed netloc self __path parsed path self __params parsed params self __query parsed query self __fragment parsed fragment self __username parsed username self __password parsed password self __hostname parsed hostname self __port parsed port
return an int representing a category .,staticmethod def idx_category info_category return MySQLHandler CATEGORIES index info_category
the default footer specified by this mailsettings .,property def footer_settings self return self _footer_settings
initializes the user at the database level .,default user def _user_default self user_name self command_line_config user user User name user_name user account self db get_user user_name user_name return user
make a directory to store all caches : return : cache path,property def cache_path self cache_path os path join self root_path cache if not os path exists cache_path os mkdir cache_path return cache_path
"load the given filepath if it exists , otherwise ignore .",def loadif self filepath if path isfile filepath self load filepath return self
create a single pool with 1 device ! : return : none,def test_simple_udev_add self self _single_pool 1 1
return the contents of the file at the given path as a unicode string .,def read_text_file self path with codecs open path r utf8 as f return f read
test when it 's all good .,def test_happy_status f_httpretty webapp monkeypatch dataclip_url http dnstwister report not_the_url json monkeypatch setenv MONITORING_DATACLIP dataclip_url payload json dumps fields DNS resolution Atom feed delta generation Atom feed publishing Email subscription processing values True True True True f_httpretty register_uri f_httpretty GET dataclip_url body payload resp webapp get status assert All systems operating normally in resp body
read the values of the velocity field from a foamfile - format file .,def read_structured_velocity_foamfile baseReadPath surfaceName nPointsZ yInd zInd addValBot float nan float nan float nan addValTop float nan float nan float nan excludeBot 0 excludeTop 0 interpValBot False interpValTop False def read time A function that will actually perform the reading Parameters time float or string The value of the time will be converted to a string Returns List of 2d arrays The list contains three items corresponding to the three components of the velocity field the order of the components in the list is x y and the z readUPath os path join baseReadPath str time surfaceName vectorField U with open readUPath as UFile u line rstrip n for line in UFile u line lstrip for line in u u u 3 1 u np genfromtxt u u 0 u yInd 0 u 1 u yInd 1 u 2 u yInd 2 uX np copy np reshape u 0 1 nPointsZ uY np copy np reshape u 1 1 nPointsZ uZ np copy np reshape u 2 1 nPointsZ for i in range uX shape 0 uX i uX i zInd i uY i uY i zInd i uZ i uZ i zInd i if not np isnan addValBot 0 uX np append addValBot 0 np ones 1 nPointsZ uX axis 0 uY np append addValBot 1 np ones 1 nPointsZ uY axis 0 uZ np append addValBot 2 np ones 1 nPointsZ uZ axis 0 if not np isnan addValTop 0 uX np append uX addValTop 0 np ones 1 nPointsZ axis 0 uY np append uY addValTop 1 np ones 1 nPointsZ axis 0 uZ np append uZ addValTop 2 np ones 1 nPointsZ axis 0 nPointsY uX shape 0 topmostPoint nPointsY excludeTop if interpValTop and excludeTop uX topmostPoint 1 0 5 uX topmostPoint 1 uX topmostPoint uY topmostPoint 1 0 5 uY topmostPoint 1 uY topmostPoint uZ topmostPoint 1 0 5 uZ topmostPoint 1 uZ topmostPoint if interpValBot and excludeBot uX excludeBot 0 5 uX excludeBot 1 uX excludeBot uY excludeBot 0 5 uY excludeBot 1 uY excludeBot uZ excludeBot 0 5 uZ excludeBot 1 uZ excludeBot if excludeTop uX uX topmostPoint uY uY topmostPoint uZ uZ topmostPoint if excludeBot uX uX excludeBot uY uY excludeBot uZ uZ excludeBot return uX uY uZ read reader foamFile return read
update django models by pk and return old values as one atomic action .,rpc task name utils GETSET_TASK_NAME bind True base _base_model_change_task shared False def getset self model data fields None nocache False manager objects database None args kwargs from celery_rpc base import DRF3 db_for_write router db_for_write self model with atomic_commit_on_success using db_for_write instance many self get_instance data using db_for_write if DRF3 kwargs else kwargs allow_add_remove False s self serializer_class instance instance data data many many partial True kwargs if not DRF3 old_values s data elif s is_valid old_values s data del s _data else errors unproxy s errors raise RestFrameworkError Serializer errors happened errors if s is_valid s save force_update True if many return old_values else return old_values else errors unproxy s errors raise RestFrameworkError Serializer errors happened errors
"if the aperture exists in the gat , modify the ap.code field to reflect the global code and return the code . otherwise , create a new aperture in the gat and return the new code for it .",def findOrAddAperture AP code findInApertureTable AP if code AP code code return code else return addToApertureTable AP
return the name of the selected genotypes scenario,def get_current_scenario self option self select genotypes filter input input checked return option get_attribute value
build an absolute path from * parts * and and return the contents of the resulting file . assume utf-8 encoding .,def read parts with codecs open os path join HERE parts rb utf 8 as f return f read
"set up and return image , label , and width tensors",def _get_single_input image width label length text filename mjsynth threaded_input_pipeline deps get records str split FLAGS filename_pattern batch_size 1 num_threads FLAGS num_input_threads num_epochs 1 batch_device FLAGS input_device preprocess_device FLAGS input_device return image width label length text filename
create a data object from a single pycmds output file .,def from_PyCMDS filepath name None parent None verbose True headers tidy_headers read filepath if name is None data_name headers data name else data_name name if data_name data_name headers data origin kwargs name data_name kind PyCMDS source filepath created headers file created if parent is not None data parent create_data kwargs else data Data kwargs arr np genfromtxt filepath T axes for name identity units in zip headers axis names headers axis identities headers axis units points np array headers name points if name centers in headers keys centers headers name centers else centers None axis points points units units name name identity identity centers centers axes append axis shape tuple a points size for a in axes for i ax in enumerate axes sh 1 len shape sh i len ax points data create_variable name ax name _points values np array ax points reshape sh if ax centers is not None sh 1 len shape sh i 1 len axes i 1 points data create_variable name ax name _centers values np array ax centers reshape sh for index kind name in zip range len arr headers kind headers name values np full np prod shape np nan values len arr index arr index values shape shape if name time data create_variable name labtime values values if kind hardware units headers units index label headers label index if w in name and name startswith tuple data variable_names inherited_shape data name split _ 0 shape for i s in enumerate inherited_shape if s 1 values np mean values axis i values np expand_dims values i else tolerance headers tolerance index for i in range len shape if tolerance is None break if d in name tolerance 3 0 if zero in name tolerance 1e 10 try assert i headers axis names index name tolerance 0 except ValueError AssertionError if name in headers axis names and s_centers name not in data variable_names tolerance np inf mean np nanmean values axis i mean np expand_dims mean i values meanexp wt_kit share_nans values mean if np allclose meanexp values atol tolerance equal_nan True values mean if name in headers axis names points np array headers name points pointsshape 1 len values shape for i ax in enumerate axes if ax name name pointsshape i len points break points shape pointsshape for i in range points ndim if points shape i 1 points np repeat points values shape i axis i values np isnan values points np isnan values data create_variable name values values units units label label if kind channel data create_channel name name values values shape values shape for a in axes expression a identity if expression startswith D expression expression 1 expression replace D a expression expression data transform a expression for a in axes if verbose print data created at 0 format data fullpath print axes 0 format data axis_names print shape 0 format data shape return data
add the truth - in - a - model value to each semantic representation for each syntactic parse of each input sentences .,def evaluate_sents inputs grammar model assignment trace 0 u n Add the truth in a model value to each semantic representation n for each syntactic parse of each input sentences n n param inputs a list of sentences n type inputs list str n param grammar FeatureGrammar or name of feature based grammar n type grammar nltk grammar FeatureGrammar n return a mapping from sentences to lists of triples parse tree semantic representations evaluation in model n rtype list list tuple nltk tree Tree nltk sem logic ConstantExpression bool or dict str bool n return syn sem model evaluate u s sem assignment trace trace for syn sem in interpretations for interpretations in interpret_sents inputs grammar
update main spectrum data ( and possibly apply smoothing ),def update_data self data if self smooth data y self smooth_data data y self y data y self data_updated emit self self start_task self update_average data self start_task self update_peak_hold_max data self start_task self update_peak_hold_min data
"gaussian kernel for continuous variables parameters ---------- h : 1-d ndarray , shape ( k , ) the bandwidths used to estimate the value of the kernel function . xi : 1-d ndarray , shape ( k , ) the value of the training set . x : 1-d ndarray , shape ( k , ) the value at which the kernel density is being estimated .",def gaussian h Xi x return 1 0 np sqrt 2 np pi np exp Xi x 2 h 2 2 0
return the django - filters ` filterset ` used to filter the queryset .,def get_filter_class self view queryset None filter_class getattr view filter_class None filter_fields getattr view filter_fields None if filter_class or filter_fields return super AllDjangoFilterBackend self get_filter_class self view queryset class AutoFilterSet self default_filter_set class Meta model queryset model fields for f in model _meta get_fields if not f many_to_many and not isinstance f ManyToOneRel fields append f name return AutoFilterSet
test passing an int as a string validation,def test_validate_available_choice_2 self self assertIsNone validate_available_choice BeerStyle s BeerStyle LAGER
"for every transition ( from , to , c ) adds every transition ( from , to , s ' ) where s ' represents c plus every other symbol",def our_completion_DFA states alphabet transitions initialState finalStates table powerset_table alphabet new_alphabet alphabet union str i for i in range len table new_transitions for from_s to_s c in transitions for i pairs in enumerate table if c in pairs and from_s to_s str i not in new_transitions new_transitions append from_s to_s str i return states new_alphabet transitions new_transitions initialState finalStates
"object name , desc , presence,[0 or 1 for global ]",def do_object self args elements args strip split if len elements 3 self db object elements 0 elements 1 elements 2 elif len elements 4 self db object elements 0 elements 1 elements 2 int elements 3 else print Argument error
http request handler function to handle actions on collections,def request_handler request if not request user is_authenticated return HttpResponse Response error None User must be logged in mode request GET get mode reply_xml None logger info request_handler Received Request s mode if mode get collection list reply_xml Collection list elif mode load collection metadata request GET get metadata reply_xml Collection load request user username metadata if reply_xml is None return HttpResponse Response error mode Failed if isinstance reply_xml str return HttpResponse Response success mode reply_xml elif mode add collection metadata request GET get metadata payload request GET get payload logger debug metadata metadata logger debug payload payload if not Collection add metadata payload return HttpResponse Response error mode Failed reply_xml Collection list mode get collection list elif mode delete collection metadata request GET get metadata if not Collection remove metadata return HttpResponse Response error mode Failed reply_xml Collection list mode get collection list elif mode rpc req request GET get payload reply_xml Adapter gen_rpc request user username req if isinstance reply_xml str return HttpResponse Response success mode reply_xml elif mode gen script req request GET get payload target request GET get target ncclient reply_xml Adapter gen_script request user username req target if isinstance reply_xml str return HttpResponse Response success mode reply_xml elif mode in get cap run rpc run edit commit run commit payload request GET get payload logger debug run payload reply_xml Adapter run_request request user username payload if isinstance reply_xml str return HttpResponse Response success mode reply_xml return HttpResponse Response success mode ok reply_xml
restituisce il numero di giudizi positivi o negativi associati all'oggetto .,def _giudizi self positivo return self giudizi filter positivo positivo count
basic test for gitlab integration .,def test_check aggregator gitlab GitlabCheck gitlab CONFIG init_config gitlab check CONFIG instances 0 for service_check in GitlabCheck ALLOWED_SERVICE_CHECKS aggregator assert_service_check gitlab format service_check status GitlabCheck OK tags GITLAB_TAGS CUSTOM_TAGS count 1 aggregator assert_service_check GitlabCheck PROMETHEUS_SERVICE_CHECK_NAME status GitlabCheck OK tags CUSTOM_TAGS count 1 for metric in ALLOWED_METRICS aggregator assert_metric gitlab format metric tags CUSTOM_TAGS count 1
release to pypi a specific check as it is on the repo head,task help u target u The check to release u dry run u Runs the task without publishing the package def release_upload ctx target dry_run False u n Release to PyPI a specific check as it is on the repo HEAD n if target not in AGENT_BASED_INTEGRATIONS raise Exit u Provided target is not an Agent based Integration username os environ get u DD_PYPI_USERNAME password os environ get u DD_PYPI_PASSWORD if not username and password raise Exit u Please set DD_PYPI_USERNAME and DD_PYPI_PASSWORD env vars and try again print u Building and publishing on PyPI format target with ctx cd target ctx run u python setup py bdist_wheel hide u stdout print u Build done uploading the package if not dry_run cmd u twine upload u p dist format username password ctx run cmd warn True print u Done
enables python tools for visual studio to attach to this process remotely to debug python code .,def enable_attach secret address 0 0 0 0 DEFAULT_PORT certfile None keyfile None redirect_output True if not ssl and certfile or keyfile raise ValueError could not import the ssl module SSL is not supported on this version of Python if sys platform cli import clr x_tracing clr GetCurrentRuntime GetLanguageByExtension py Options Tracing x_frames clr GetCurrentRuntime GetLanguageByExtension py Options Frames if not x_tracing or not x_frames raise RuntimeError IronPython must be started with X Tracing and X Frames options to support PTVS remote debugging global _attach_enabled if _attach_enabled raise AttachAlreadyEnabledError ptvsd enable_attach has already been called in this process _attach_enabled True atexit register vspd detach_process_and_notify_debugger server socket socket proto socket IPPROTO_TCP server setsockopt socket SOL_SOCKET socket SO_REUSEADDR 1 server bind address server listen 1 def server_thread_func while True client None raw_client None try try client addr server accept if certfile client ssl wrap_socket client server_side True ssl_version ssl PROTOCOL_TLSv1 certfile certfile keyfile keyfile write_bytes client PTVSDBG write_int client PTVSDBG_VER response read_bytes client 7 if response PTVSDBG continue dbg_ver read_int client if dbg_ver PTVSDBG_VER continue client_secret read_string client if secret is None or secret client_secret write_bytes client ACPT else write_bytes client RJCT continue response read_bytes client 4 if response INFO try pid os getpid except AttributeError pid 0 write_int client pid exe sys executable or write_string client exe try username getpass getuser except AttributeError username write_string client username try impl platform python_implementation except AttributeError try impl sys implementation name except AttributeError impl Python major minor micro release_level serial sys version_info os_and_arch platform system if os_and_arch os_and_arch sys platform try if sys maxsize 2 32 os_and_arch 64 bit else os_and_arch 32 bit except AttributeError pass version s s s s s impl major minor micro os_and_arch write_string client version client recv 1 elif response ATCH debug_options vspd parse_debug_options read_string client if redirect_output debug_options add RedirectOutput if vspd DETACHED write_bytes client ACPT try pid os getpid except AttributeError pid 0 write_int client pid major minor micro release_level serial sys version_info write_int client major write_int client minor write_int client micro vspd attach_process_from_socket client debug_options report True vspd mark_all_threads_for_break vspd STEPPING_ATTACH_BREAK _attached set client None else write_bytes client RJCT elif response REPL if not vspd DETACHED write_bytes client ACPT vspd connect_repl_using_socket client client None else write_bytes client RJCT except socket error OSError pass finally if client is not None client close server_thread threading Thread target server_thread_func server_thread setDaemon True server_thread start frames f sys _getframe while True f f f_back if f is None break frames append f frames reverse cur_thread vspd new_thread for f in frames cur_thread push_frame f def replace_trace_func for f in frames f f_trace cur_thread trace_func replace_trace_func sys settrace cur_thread trace_func vspd intercept_threads for_attach True
create b - spline surface from control points of bezier surface,def create_bspline_surface array bspline_surface None bezier_surface Geom_BezierSurface array bezier_array TColGeom_Array2OfBezierSurface 1 1 1 1 bezier_array SetValue 1 1 bezier_surface GetHandle temp GeomConvert_CompBezierSurfacesToBSplineSurface bezier_array if temp IsDone poles temp Poles GetObject Array2 uknots temp UKnots GetObject Array1 vknots temp VKnots GetObject Array1 umult temp UMultiplicities GetObject Array1 vmult temp VMultiplicities GetObject Array1 udeg temp UDegree vdeg temp VDegree bspline_surface Geom_BSplineSurface poles uknots vknots umult vmult udeg vdeg 0 0 return bspline_surface
register a signal to be watched,def add_watching self signal hierarchy None if not hierarchy hierarchy self default_hierarchy self watching append hierarchy signal
"verifies data and its signature . if verification fails , an sspi.error will be raised .",def verify self data sig sigbuf win32security PySecBufferDescType sigbuf append win32security PySecBufferType len data sspicon SECBUFFER_DATA sigbuf append win32security PySecBufferType len sig sspicon SECBUFFER_TOKEN sigbuf 0 Buffer data sigbuf 1 Buffer sig self ctxt VerifySignature sigbuf self _get_next_seq_num
build query parameter input ` query_params ` : dictionary output string with format ` ? key = val&key2=val2 `,def build_query_string query_params None if query_params is None return qs for key elem in query_params items qs key str elem return qs 1
adds the given user / list of users to the given group / groups .,def user_add self group user assert self check group Group does not exist s group if not self user_check group user self _cuisine core sudo usermod a G s s group user
boolean indicating whether section exists in this inifile @param sectionname : name of the section,def checkSection self sectionName try return self __configParser has_section sectionName except Exception as err raise ValueError Failed to check if the specified section s exists nERROR s sectionName str err
"clean up disk by deleting all non protected partitions if force = true , delete all partitions included protected",def erase self force False if force self _clearMBR return for partition in self partitions if not partition protected partition delete
fetch the data from the online source .,def _fetch_online self config query_string None u n Fetch the data from the online source n n By default it will query just one result page from the online source n When a query_string is given multiple pages can be retrieved in order n to increase the changes of returning a useful result set n The size of the history to be searched through is specified in SEARCH_MAX_HISTORY n see _more_history_allowed for the specific implementation n n param config SocialFeedConfiguration to use n param query_string the search term to filter on default None n if not hasattr self u query_cls raise NotImplementedError u query_cls needs to be defined query self query_cls config username query_string paginator query get_paginator raw oldest_post next paginator if query_string for _raw _oldest_post in paginator if not _raw break oldest_post_date self _convert_raw_item oldest_post posted if not self _more_history_allowed oldest_post_date break if _oldest_post u id oldest_post u id logger warning u Trying to fetch older items but received same result set Breaking the loop break oldest_post _oldest_post raw _raw return raw
return 2d y coordinates in the parameter space .,property def y_data self raise NotImplementedError
returns the set of all things known so far .,def getThings self self _process return self _things
plot timeseries of amoc transport measured at 35s.,def amoc_south expts plt figure figsize 12 6 if not isinstance expts list expts expts for expt in tqdm_notebook expts leave False desc experiments psi_amoc_south cc diagnostics calc_amoc_south expt psi_amoc_south plot label expt IPython display clear_output plt title AMOC Transport at 35S plt xlabel Time plt ylabel Transport Sv plt legend fontsize 10 loc best
get the existing analysis for the ` using ` elasticsearch connection,def existing_analysis using es connections get_connection using index_name settings ELASTICSEARCH_CONNECTIONS using index_name if es indices exists index index_name return stringer es indices get_settings index index_name index_name settings index get analysis return DOES_NOT_EXIST
: param url : the base url,def __init__ self url self root_url url
sets the flag if last hop responded .,def set_last_hop_responded self last_hop for packet in last_hop packets if packet rtt self last_hop_responded True break
generate filename of the song to be downloaded .,def sanitize_title title ok _ if const args no_spaces title title replace _ title slugify title ok ok lower False spaces True return title
from rgb triplet to yuv space . apprximation of the rgb - lab conversion . : param v : : return : corresponding yuv triplet,def rgb_to_yuv v m np array 0 299 0 587 0 114 0 14713 0 28886 0 436 0 615 0 51499 0 10001 return m dot np array v
assign photon energies to an event list .,def test_simulate_energies self ev EventList ncounts 100 ev simulate_energies self spectrum
selection sort sorts an array by placing the minimum element element at the beginning of an unsorted array . : param array a given array : return the given array sorted,def selection_sort array length len array for i in range 0 length min_index i for j in range i 1 length if array j array min_index min_index j if min_index i array min_index array i array i array min_index return array
searches the default sidefx install locations for the most up to date install of houdini and returns the normalized path and version as a tuple .,def find_latest_houdini install regex common_install versions for folder in os listdir install if re match regex folder versions append folder current_name Houdini 0 0 0 current_mmb 0 0 0 for ver in versions mmb version_tuple ver if len mmb 3 raise Exception Unexpected version format newer False if mmb 0 current_mmb 0 newer True elif mmb 0 current_mmb 0 if mmb 1 current_mmb 1 newer True elif mmb 1 current_mmb 1 if mmb 2 current_mmb 2 newer True if newer current_name ver current_mmb mmb return os path join install current_name current_mmb
return a list of the programmer names supported by this cpu .,def list_programmers self return jlink stlink
download the file at url to target using powershell ( which will validate trust ) . raise an exception if the command can not complete .,def download_file_powershell url target target os path abspath target ps_cmd System Net WebRequest DefaultWebProxy Credentials System Net CredentialCache DefaultCredentials new object System Net WebClient DownloadFile url r target r vars cmd powershell Command ps_cmd _clean_check cmd target
initialise the option parser for ' gr_modtool makexml ',def setup_parser self parser ModTool setup_parser self parser usage prog info options Call prog without any options to run it interactively Note This does not work on Python blocks return parser
"ensure that delete works properly in "" clear "" mode",patch requests sessions Session request def test_delete_clear_with_sheet_success self mock mock return_value MagicMock status_code 204 client SheetsuClient self kwargs response client delete sheet Sheet1 column name value Meg self assertIsNone response
write this object to a file in stl * ascii * format .,def write_ascii self file from stl ascii import write write self file
this function updates the stratigraphic layers based active layer composition .,def update_active_layer self actlayer elev verbose False comm mpi COMM_WORLD rank comm Get_rank size comm Get_size time0 time clock ero actlayer 0 self alay 0 ero ero 0 0 0 0 depo actlayer 0 self alay 0 depo depo 0 0 0 0 newH newS PDalgo pdstack updatecstrati self depoThick self step 1 self layerThick self step 1 ero depo self depoThick self step 1 0 newS self layerThick self step 1 newH self paleoDepth self step elev if rank 0 and verbose print Update active layer due to wave induced erosion deposition time clock time0 return
collates the posterior probabilities and calls snvs for each reference base .,def variantCallSamFileTargetFn target samFile referenceFastaFile outputVcfFile tempPosteriorProbFiles options expectationsOfBasesAtEachPosition for tempPosteriorProbFile in tempPosteriorProbFiles fileHandle open tempPosteriorProbFile r expectationsOfBasesAtEachPosition2 cPickle load fileHandle for key in expectationsOfBasesAtEachPosition2 if key not in expectationsOfBasesAtEachPosition expectationsOfBasesAtEachPosition key dict zip BASES 0 0 len BASES for base in BASES expectationsOfBasesAtEachPosition key base expectationsOfBasesAtEachPosition2 key base fileHandle close variantCalls refSequences getFastaDictionary referenceFastaFile errorSubstitutionMatrix loadHmmSubstitutionMatrix options errorModel evolutionarySubstitutionMatrix getNullSubstitutionMatrix for refSeqName refPosition in expectationsOfBasesAtEachPosition refBase refSequences refSeqName refPosition expectations expectationsOfBasesAtEachPosition refSeqName refPosition totalExpectation sum expectations values assert totalExpectation 0 posteriorProbs calcBasePosteriorProbs dict zip BASES map lambda x float expectations x totalExpectation BASES refBase evolutionarySubstitutionMatrix errorSubstitutionMatrix for base in BASES if base refBase and posteriorProbs base options threshold variantCalls append refSeqName refPosition base posteriorProbs base vcfWrite referenceFastaFile refSequences variantCalls outputVcfFile vcfCalls vcfRead outputVcfFile calls set map lambda x x 0 x 1 1 x 2 variantCalls assert vcfCalls calls
"initialize or reset all of our internal state variables for a given connection . if we disconnect and reconnect , all of our state needs to be wiped .",def _init_connection_state self for timer in self _active_timers keys self remove_timeout timer if global_sigint_watcher global_sigint_watcher stop if global_sigterm_watcher global_sigterm_watcher stop if self _io_watcher self _io_watcher stop super LibevConnection self _init_connection_state
create an allocator for a buffer of the specified capacity .,def __init__ self capacity self capacity capacity self starts self sizes
"given a model class , find all related objects , exploring children recursively , returning a ` list ` of strings representing the relations for select_related",def _get_subclasses_recurse self model levels None u n Given a Model class find all related objects exploring children n recursively returning a list of strings representing the n relations for select_related n related_objects f for f in model _meta get_fields if isinstance f OneToOneRel rels rel for rel in related_objects if isinstance rel field OneToOneField and issubclass rel field model model and model is not rel field model subclasses if levels levels 1 for rel in rels if levels or levels is None for subclass in self _get_subclasses_recurse rel field model levels levels subclasses append rel get_accessor_name LOOKUP_SEP subclass subclasses append rel get_accessor_name return subclasses
"return the fraction of ` hit`/`num ` , as a string .",def rate hit num if num 0 return 1 else return 4g float hit num
json encoding will be laundered to remove string differences .,def CompareEncoded self expected_encoded actual_encoded self assertEquals json loads expected_encoded json loads actual_encoded
unzips a file if it is a zip file .,def UnzipArchive archive_path unzip_path if not archive_path and zipfile is_zipfile archive_path raise ValueError Attempting to unzip a non archive file at s archive_path if not os path exists unzip_path os makedirs unzip_path if sys platform startswith darwin assert os path isabs unzip_path unzip_cmd ditto x k archive_path unzip_path proc subprocess Popen unzip_cmd bufsize 0 stdout subprocess PIPE stderr subprocess PIPE proc communicate return try with zipfile ZipFile archive_path r as archive VerifySafeArchive archive assert os path isabs unzip_path unzip_path_without_prefix unzip_path if sys platform startswith win unzip_path u unzip_path archive extractall path unzip_path SetUnzippedDirPermissions archive unzip_path except if unzip_path_without_prefix and os path isdir unzip_path_without_prefix RemoveDir unzip_path_without_prefix raise
"test , whether the given point is on the curve ( p , q , n )",def element point p q n if point x y point return x x x p x q n y y n else return True
driver for client code generation .,def GenerateClient args codegen _GetCodegenFromFlags args if codegen is None logging error Failed to create codegen exiting return 128 _WriteGeneratedFiles args codegen if args init_file none _WriteInit codegen
unbound_segments : unbound_terminal forward_slash unbound_segments | unbound_terminal,def p_unbound_segments self p p 0 p 1 if len p 2 p 0 extend p 3
translate arguments back into a standard bcbio_vm ipython submission command .,def _get_ipython_cmdline args cmd bcbio_vm py ipython args sample_config args scheduler args queue numcores str args numcores has_timelimit False for resource in args resources cmd r resource if resource startswith timelimit has_timelimit True if not has_timelimit and args queue in AWS_QUEUES cmd r timelimit 0 for opt_arg in timeout retries tag tmpdir fcdir systemconfig if getattr args opt_arg cmd s opt_arg str getattr args opt_arg return join cmd
enforce boundary conditions : rtype : np.ndarray,def boundary boundary_cells boundary_cells np concatenate 0 boundary_cells 0 boundary_cells 0 boundary_cells 2 boundary_cells 1 boundary_cells 1 return boundary_cells
"args : x ( np.ndarray ) : training data of shape[n_samples , n_features ] y ( np.ndarray ) : target values of shape[n_samples , 1 ] reg_parameter ( float ) : float to determine strength of regulatrization penalty if 0 , then no linear regression without regularization is performed",def fit self X y n_samples n_features np shape X kernel_values np zeros n_samples n_samples for row in range n_samples for col in range n_samples kernel_values row col self kernel X row X col P cvxopt matrix np outer y y kernel_values tc d q cvxopt matrix np ones n_samples 1 A cvxopt matrix y 1 n_samples tc d b cvxopt matrix 0 tc d if self C 0 G_max np identity n_samples 1 G_min np identity n_samples G cvxopt matrix np vstack G_max G_min h_max cvxopt matrix np zeros n_samples h_min cvxopt matrix np ones n_samples self C h cvxopt matrix np vstack h_max h_min else G cvxopt matrix np identity n_samples 1 h cvxopt matrix np zeros n_samples minimization cvxopt solvers qp P q G h A b alphas np ravel minimization x for index alpha in enumerate alphas if alpha 10 6 self SValphas append alpha self SVinputs append X index self SVoutputs append y index self intercept self SVoutputs 0 for SV in range len self SValphas self intercept self SValphas SV self SVoutputs SV self kernel self SVinputs SV self SVinputs 0 self learned True return self
"stores ( i.e. , registers ) a key with the key manager .",def store_key self ctxt key kwargs if ctxt is None raise exception Forbidden key_id self _generate_key_id self keys key_id key return key_id
raise exception . forbidden ( ) if context is not a user or an admin context .,def require_context ctxt if not ctxt is_admin and not is_user_context ctxt raise exception Forbidden
return the corners of the ccd,def find_corners self x1 self xpos 0 5 self width x2 self xpos 0 5 self width y1 self ypos 0 5 self height y2 self ypos 0 5 self height return x1 x2 y1 y2
use |api_features| to determine the dependencies apis have on permissions . add descriptions to |permissions| based on those dependencies .,def _AddDependencyDescriptions permissions api_features for name permission in permissions iteritems if partial in permission or not permission platforms continue has_deps False if name in api_features for dependency in api_features name get dependencies if dependency startswith permission has_deps True if has_deps permission partial permissions generic_description html
crawls the server find all pages that are connected to the pages at |seed_url|s . return the links that are valid on the server but are not in part of the connected component containing the |root_pages| . these pages are orphans and can not be reached simply by clicking through the server .,def GetOrphanedPages self pages_to_check deque self _root_pages union self _always_detached found set self _root_pages self _always_detached while pages_to_check item pages_to_check popleft target_page self _pages item if target_page status 200 redirected_page self _FollowRedirections item 1 if not redirected_page is None target_page self _pages redirected_page for link in target_page links if link not in found found add link pages_to_check append link all_urls set url for url page in self _pages iteritems if page status 200 return url for url in all_urls found if url endswith html
build a dataset from a directory .,def construct_set_from_dir dir_path verbose True assert os path isdir dir_path Invalid path format dir_path def is_image_file filename Check if a filename has an extension of an image return any filename endswith extension for extension in img_extensions set_data if verbose print Fetching files subdirs from format dir_path _ num_folders dir_get_size dir_path counter 0 prgbar progressbar ProgressBar max_value num_folders for dname in os listdir dir_path subdir_path os path join dir_path dname if not os path isdir subdir_path continue for _ _ fnames in sorted os walk subdir_path class_name dname set_data class_name for fname in fnames if is_image_file fname set_data class_name append fname if verbose counter 1 prgbar update counter return set_data
this example view for testing do n't use in your project it takes to params ' name ' and number name is for pdf name if did n't pass the name it takes dynamic name from database . number is simple context variable for displying page number,def example_view request if name in request GET response convert_html_to_pdf request request name request GET get name None context page 20 else num request GET get number 20 response convert_html_to_pdf request request context page num return response
"this is the worker function to get the next recipe from the pending queue , save it , and put all the related urls on the pending queue for other workers to process",def fetch src save db collection p f while True url p get if url in f queue p task_done else try recipe src url if save recipe save if db is not None and collection is not None recipe store db collection f put url map lambda x p put x filter lambda link link url recipe getOtherRecipeLinks except ValueError print warning could not fetch url p task_done if PAUSE_CRAWLER sleep randint PAUSE_TIME_RANGE 0 PAUSE_TIME_RANGE 1
start a package using the rest api,def _start_package self release_id package_id u n Start a package using the REST API n n param release_id n return n response self client post u releases packages start format release_id package_id content_type u application json self assertEqual response status_code 204 return response
turn style - forcing on if bar - forcing is on .,def configure self options conf super ProgressivePlugin self configure options conf if getattr options verbosity 0 1 and getattr options enable_plugin_id False print Using with id and verbosity 2 or higher with nose progressive causes visualization errors Remove one or the other to avoid a mess if options with_bar options with_styling True
yield to simulator issuing event at each state change,def taxi_process ident trips start_time 0 time yield Event start_time ident leave garage for i in range trips time yield Event time ident pick up passenger time yield Event time ident drop off passenger yield Event time ident going home
ensure default cron - apt file to download all updates does not exist .,def test_cron_apt_config_deprecated File f File etc cron apt action d 3 download assert not f exists
returns a theano mode that detects if any negative value occurs in the evaluation of a theano function . this mode should raise a negativevariableerror if it ever detects any variable having a negative value during the execution of the theano function .,def get_neg_detection_mode raise NotImplementedError TODO implement this function
update the application binary . likely this binary would come from the existing contents of flash on a board .,def set_binary self binary self binary binary
creates a button and returns the dictionary containing the button data,staticmethod def button button_type title None url None payload None webview_height full if len payload 1000 raise CharacterCountExceeded Max number of characters allowed are 1000 The number of characters in the payload are s len payload button type type title title if button_type web_url button url url button webview_height_ratio webview_height elif button_type postback button payload payload elif button_type phone_number button payload payload elif button_type element_share button pop title elif button_type account_link button url url button pop title elif button_type account_unlink button pop title return button
saves all the annotations to json,def to_json self return json dumps k v if not k startswith _ else for k v in self data items
"link_to commands can be written as pairs , instead of triplets",def test_LINK_TO_pairs self ids self partner create self cr UID name foo self partner create self cr UID name bar self partner create self cr UID name baz commands map lambda id 4 id ids results self partner resolve_2many_commands self cr UID child_ids commands name self assertEqual sorted_by_id results sorted_by_id id ids 0 name foo id ids 1 name bar id ids 2 name baz
interpolate paths into the given encoding command .,def shell_command self input_path output_path u n Interpolate paths into the given encoding command n args u input input_path u output output_path return shlex split self command args
method to initialize the tile processor based on custom parameters from the configuration file,def setup self parameters self parameters parameters
permanently removes record from table .,def delete_record self record record delete
the current average latency or none .,property def round_trip_time self if self _address in self _host_to_round_trip_time return self _host_to_round_trip_time self _address return self _round_trip_time
set the callback method that will receive the audio stream caught by the microphone : param callback : callback method : return :,def set_callback self callback self callback callback
"when this function returns , you are a daemon .",def daemon username None groupname None use_syslog None log_file None logfile None verbose False capture_output True twisted_error_log_level ERROR twisted_info_log_level INFO capture_stderr_log_level ERROR capture_stdout_log_level INFO capture_stderr_name stderr capture_stdout_name stdout log_level DEBUG log_twisted True pidfile None use_localtime False assert log_file is None or logfile is None logfile was provided for backwards compatibility You cannot specify both log_file and logfile if log_file is None log_file logfile try if os name mac raise NotImplementedError Daemonization doesn t work on macs if noisy print in daemon uid os getuid gid os getgid if uid 0 and username is None raise Exception If you start with root privileges you need to provide a username argument so that daemon can shed those privileges before returning if username uid getuid_from_username username if noisy print setting username to uid of s which is d username uid if uid os getuid and os getuid 0 raise Exception When specifying a uid other than your own you must be running as root for setuid to work Your uid is d while the specified user s has uid d os getuid username uid gid getgid_from_username username if groupname if noisy print setting groupname to gid of s which is d groupname gid gid getgid_from_groupname groupname pid_dir os path split pidfile 0 if pid_dir and not os path exists pid_dir os mkdir pid_dir os chown pid_dir uid gid checkPID pidfile if use_syslog is None use_syslog sys platform darwin and not log_file if log_file if use_syslog raise Exception You have specified both a log_file and that the daemon should use_syslog Specify one or the other print Calling injectLogger injectLogger use_syslog False log_file log_file log_level log_level capture_output capture_output verbose verbose capture_stdout_name capture_stdout_name capture_stderr_name capture_stderr_name twisted_info_log_level twisted_info_log_level twisted_error_log_level twisted_error_log_level capture_stdout_log_level capture_stdout_log_level capture_stderr_log_level capture_stderr_log_level use_localtime use_localtime elif use_syslog injectLogger use_syslog True log_level log_level verbose verbose capture_output capture_output capture_stdout_name capture_stdout_name capture_stderr_name capture_stderr_name twisted_info_log_level twisted_info_log_level twisted_error_log_level twisted_error_log_level capture_stdout_log_level capture_stdout_log_level capture_stderr_log_level capture_stderr_log_level else raise Exception You are attempting to daemonize without a log file and with use_syslog set to false A daemon must output to syslog a logfile or both if pidfile is None pid_dir os path join var run app_name pidfile os path join pid_dir app_name pid daemonize open pidfile wb write str os getpid if not os path exists pidfile raise Exception pidfile s does not exist pidfile os chmod pidfile stat S_IRUSR stat S_IWUSR stat S_IROTH stat S_IRGRP if os getuid 0 if uid is not None or gid is not None switchUID uid gid if os getuid uid raise Exception failed to setuid to uid d uid if os getgid gid raise Exception failed to setgid to gid d gid except log exception daemonizing may have failed import traceback traceback print_exc raise
write data to a file .,def _writeFile self path data f _open path wb f write data f flush f close
( internal ) create an ssl socket,def createInternetSocket self sock tcp Port createInternetSocket self return SSL Connection self ctxFactory getContext sock
print a traceback as densely as possible .,def printBriefTraceback self file None elideFrameworkCode 0 self printTraceback file elideFrameworkCode detail brief
build a document from a json object .,staticmethod def from_json json_obj job_doc None if json_obj and isinstance json_obj types DictionaryType local_obj copy deepcopy json_obj try pop_f local_obj pop job pop_f models JOB_KEY kernel pop_f models KERNEL_KEY git_branch pop_f models GIT_BRANCH_KEY job_doc JobDocument job kernel git_branch job_doc id pop_f models ID_KEY None for key val in local_obj iteritems setattr job_doc key val except KeyError job_doc None return job_doc
"asserts that metric_name{**labels } changed according to a provided predicate function between the frozen registry and now . a frozen registry can be obtained by calling saveregistry , typically at the beginning of a test case .",def assertMetricCompare self frozen_registry predicate metric_name registry REGISTRY labels saved_value self getMetricFromFrozenRegistry metric_name frozen_registry labels current_value self getMetric metric_name registry registry labels self assertFalse current_value is None METRIC_DIFF_ERR_NONE_EXPLANATION metric_name self formatLabels labels saved_value current_value self assertTrue predicate saved_value current_value METRIC_COMPARE_ERR_EXPLANATION metric_name self formatLabels labels saved_value current_value
"creates app database . if database already exists , drops existing",def create_db engine hlp create_engine if database_exists engine url drop_database engine url create_database engine url return engine
creates the thumbnail by using default.engine,def _create_thumbnail self source_image geometry_string options thumbnail u n Creates the thumbnail by using default engine n logger debug u Creating thumbnail file s at s with s thumbnail name geometry_string options ratio default engine get_image_ratio source_image options geometry parse_geometry geometry_string ratio image default engine create source_image geometry options default engine write image options thumbnail size default engine get_image_size image thumbnail set_size size
read a mailcap file and return a dictionary keyed by mime type .,def readmailcapfile fp warnings warn readmailcapfile is deprecated use getcaps instead DeprecationWarning 2 caps _ _readmailcapfile fp None return caps
"array index for given ( ell , m ) mode",njit i8 i8 i8 i8 def LM_index ell m ell_min return ell ell 1 ell_min 2 m
validates a schema_class against a cyclone request,def _validate_request self request_handler args kwargs data headers request_handler request headers body request_handler request body path_args args path_kwargs kwargs arguments request_handler request arguments schema self schema schema context update conf request_handler conf metrics request_handler metrics db request_handler db routers request_handler routers log self log return schema load data
splits input on given dimension and then squeezes that dimension .,deprecated 2016 08 01 Please use tf unpack instead def split_squeeze dim num_split tensor_in return array_ops_ squeeze t squeeze_dims dim for t in array_ops_ split dim num_split tensor_in
tests optimization of sequence of atrous convolutions .,def testAtrousSequence self padding SAME np random seed 1 with self test_session for height in range 15 17 for width in range 15 17 x_shape 3 height width 2 x np random random_sample x_shape astype np float32 for kernel in 1 3 5 f_shape kernel kernel 2 2 f 0 01 np random random_sample f_shape astype np float32 for rate in range 2 4 y1 tf nn atrous_conv2d x f rate padding padding y1 tf nn atrous_conv2d y1 f rate padding padding y1 tf nn atrous_conv2d y1 f rate padding padding pad_bottom 0 if height rate 0 else rate height rate pad_right 0 if width rate 0 else rate width rate pad 0 pad_bottom 0 pad_right y2 tf space_to_batch x paddings pad block_size rate y2 tf nn conv2d y2 f strides 1 1 1 1 padding padding y2 tf nn conv2d y2 f strides 1 1 1 1 padding padding y2 tf nn conv2d y2 f strides 1 1 1 1 padding padding y2 tf batch_to_space y2 crops pad block_size rate self assertAllClose y1 eval y2 eval rtol 0 01 atol 0 01
the names of ` series ` output by the ` transform ` .,property def output_names self return _make_tuple_of_string self _output_names
adds a metadata information for a single session.run ( ) call .,def add_run_metadata self run_metadata tag global_step None if tag in self _session_run_tags raise ValueError The provided tag was already used for this event type self _session_run_tags tag True tagged_metadata event_pb2 TaggedRunMetadata tagged_metadata tag tag tagged_metadata run_metadata run_metadata SerializeToString event event_pb2 Event wall_time time time tagged_run_metadata tagged_metadata if global_step is not None event step int global_step self _event_queue put event
use the rest interface to fetch a wave and return it .,def fetch_wavelet self wave_id wavelet_id None proxy_for_id None raw_deltas_from_version 1 return_raw_snapshot False return self get_waveservice fetch_wavelet wave_id wavelet_id proxy_for_id raw_deltas_from_version return_raw_snapshot
return a pretty result for the result,def pretty_result self room_id None color False color_func with_color if color else lambda x _ x return difficulty user_name grade percentage 2f on date format difficulty color_func self full_difficulty color nick_color self lit_difficulty user_name self user fullname_colored room_id if color else self user fullname room_id grade color_func self lit_grade percentage self percentage date self created_at strftime d m y
open a connection to a database using a jdbc driver and return a connection instance .,def connect jclassname driver_args jars None libs None if _gateway_is_running gateway java_gateway JavaGateway else driver_args driver_args if isinstance driver_args str else driver_args if jars classpath os pathsep join jars if isinstance jars list else jars else classpath None if libs javaopts libs if isinstance libs list else libs else javaopts gateway java_gateway JavaGateway launch_gateway port 25333 classpath classpath javaopts javaopts die_on_exit True java_gateway java_import gateway jvm java sql DriverManager gateway jvm Class forName jclassname connection gateway jvm DriverManager getConnection driver_args if _converters is None types_map for type in gateway jvm Class forName java sql Types getFields types_map type getName type getInt None _init_converters types_map return Connection connection _converters
return a hash with the desired storage for the given es instance,def es_storage os_logging_facts dc_name pvc_claim root elasticsearch deploy_config os_logging_facts root deploymentconfigs get dc_name if deploy_config storage deploy_config volumes elasticsearch storage if storage get hostPath return dict kind hostpath path storage get hostPath get path if len pvc_claim strip 0 return dict kind pvc pvc_claim pvc_claim return dict kind emptydir
return whether all the labels already exist,def all_user_labels_exist self current_labels self get_current_labels for current_host_labels in current_labels rbool self compare_labels current_host_labels if rbool False return False return True
returns all of the defined secrets,def get_secrets self return self get Secret secret_path or
determine the status of the web scenario,def get_status status rval 0 if disabled in status return 1 return rval
group together similar failures from different hosts .,def deduplicate_failures failures groups defaultdict list for failure in failures group_key tuple sorted key value for key value in failure items if key host try groups group_key append failure except TypeError return failures result for failure in failures group_key tuple sorted key value for key value in failure items if key host if group_key not in groups continue failure host tuple sorted g_failure host for g_failure in groups pop group_key result append failure return result
check if image is already in local docker index .,def is_image_local self image result self execute_module docker_image_facts name image return bool result get images and not result get failed
a no - op migration for marking the kilo release .,def upgrade pass
wrapper which allows for testing when not running from shell .,def fix_tester string ast RedBaron string ast fix_imports ast ast fix_function_calls ast return ast dumps
construct list of java arguments based on our argument list .,def jvm_opts argv mem_opts prop_opts pass_args for arg in argv if arg startswith D prop_opts append arg elif arg startswith XX prop_opts append arg elif arg startswith Xm mem_opts append arg else pass_args append arg if mem_opts and getenv _JAVA_OPTIONS is None mem_opts default_jvm_mem_opts return mem_opts prop_opts pass_args
"input : frame id as in original dataset ( 15 fps ) output : coordinates with respect to the resolution of detection ( h_grid , w_grid )",def get_GT_coordinates_SALSA self fid showWarning True room self room all_detections np loadtxt groundtruth txt if fid 3 45 0 and showWarning print for accurate ground truth use fid 3 i 45 gt_line fid 3 45 detections all_detections gt_line GT_coordinates for det_id in range detections shape 0 rec_ID detections det_id if rec_ID 1 y rec_ID room H_grid x rec_ID room H_grid GT_coordinates append x y return np asarray GT_coordinates
create a new wolf - sheep model with the given parameters .,def __init__ self height 20 width 20 initial_sheep 100 initial_wolves 50 sheep_reproduce 0 04 wolf_reproduce 0 05 wolf_gain_from_food 20 grass False grass_regrowth_time 30 sheep_gain_from_food 4 self height height self width width self initial_sheep initial_sheep self initial_wolves initial_wolves self sheep_reproduce sheep_reproduce self wolf_reproduce wolf_reproduce self wolf_gain_from_food wolf_gain_from_food self grass grass self grass_regrowth_time grass_regrowth_time self sheep_gain_from_food sheep_gain_from_food self schedule RandomActivationByBreed self self grid MultiGrid self height self width torus True self datacollector DataCollector Wolves lambda m m schedule get_breed_count Wolf Sheep lambda m m schedule get_breed_count Sheep for i in range self initial_sheep x random randrange self width y random randrange self height energy random randrange 2 self sheep_gain_from_food sheep Sheep x y self True energy self grid place_agent sheep x y self schedule add sheep for i in range self initial_wolves x random randrange self width y random randrange self height energy random randrange 2 self wolf_gain_from_food wolf Wolf x y self True energy self grid place_agent wolf x y self schedule add wolf if self grass for agent x y in self grid coord_iter fully_grown random choice True False if fully_grown countdown self grass_regrowth_time else countdown random randrange self grass_regrowth_time patch GrassPatch x y self fully_grown countdown self grid place_agent patch x y self schedule add patch self running True
attempting to subtract an item from the cart that is n't in there should be a no - op,def test_subtract_item_from_cart__item_doesnt_exist self response self client post api cart subtract item format self black_desk_chair id self assertEqual response status_code 200 cart response json self assertEqual len cart items 0
"postgresql has a native uuid type , so use it if we 're using postgresql .",def load_dialect_impl self dialect if dialect name postgresql return dialect type_descriptor UUID else return dialect type_descriptor CHAR 32
": param roll_parameters_object : roll parameters specific to this instrument : param dict_of_futures_contract_prices : dict , keys are contract date ids ' yyyymmdd '",classmethod def create_from_prices rollCalendar dict_of_futures_contract_prices roll_parameters_object list_of_contract_dates dict_of_futures_contract_prices sorted_contract_ids approx_calendar _generate_approximate_calendar list_of_contract_dates roll_parameters_object adjusted_calendar _adjust_to_price_series approx_calendar dict_of_futures_contract_prices adjusted_calendar_with_carry _add_carry_calendar adjusted_calendar roll_parameters_object roll_calendar rollCalendar adjusted_calendar_with_carry return roll_calendar
test load all variants from file,def test_get_all_variants self deletion_snps t join 125 T 124 1 124 500 497 1 1 ref1 qry1 t join 126 A 124 1 124 500 497 1 1 ref1 qry1 t join 127 C 124 1 124 500 497 1 1 ref1 qry1 deletion_snps snp Snp x for x in deletion_snps deletion_variant variant Variant deletion_snps 0 deletion_variant update_indel deletion_snps 1 deletion_variant update_indel deletion_snps 2 just_a_snp t join 386 C T 383 115 115 500 497 1 1 ref1 qry1 snp_variant variant Variant snp Snp just_a_snp insertion_snps t join 479 G 480 0 22 500 504 1 1 ref2 qry2 t join 479 A 481 0 22 500 504 1 1 ref2 qry2 t join 479 T 482 0 22 500 504 1 1 ref2 qry2 t join 479 A 483 0 22 500 504 1 1 ref2 qry2 insertion_snps snp Snp x for x in insertion_snps insertion_variant variant Variant insertion_snps 0 for i in range 1 len insertion_snps insertion_variant update_indel insertion_snps i variants_from_file snp_file get_all_variants os path join data_dir snp_file_test_get_all_variants snps self assertEqual len variants_from_file 3 self assertEqual variants_from_file 0 deletion_variant self assertEqual variants_from_file 1 snp_variant self assertEqual variants_from_file 2 insertion_variant
"checks no analysis are called before a transformation , as the transformation could invalidate the analysis .",def verify_dependencies self for i in range 1 len self deps assert not isinstance self deps i Transformation and isinstance self deps i 1 Analysis invalid dep order for s self
get the current tile coordinates .,def get_tile self x y u Get the current tile coordinates n n Coordinates positions n n 3 2 n n n 0 1 n n Parameters n x int n x coordinate of the tile n y int n y coordinate of the tile n n rtype float float float float float float float float float float float float n returns The 4 coordinates with the following order x0 y0 z0 x1 y1 z1 x3 y3 z3 n idx self grid y x y 4 3 return self vertex_list vertices idx idx 12
save a new token to the database .,staticmethod def tokensetter token request args kwargs if request grant_type refresh_token tok RefreshToken refresh_token token refresh_token user_id request user id db session add tok db session commit
number of fmap channels of input layer .,property def nifm self return self input_layer nofm
calculate machine current injections ( in network reference frame ),def calc_currents self vt Vd np abs vt np sin self states delta np angle vt Vq np abs vt np cos self states delta np angle vt Eqpp self states Eqpp Edpp self states Edpp Ra self params Ra Xdpp self params Xdpp Xqpp self params Xqpp if self speed_volt omega self states omega else omega 1 Id Eqpp Ra Xqpp omega Vd Edpp Vq omega Xdpp Ra 2 omega omega Xqpp Iq Vd omega Ra Id omega Edpp Xqpp p Vd self params Ra Id Id Vq self params Ra Iq Iq q Vq Id Vd Iq S np complex p q delta self states delta In Iq 1j Id np exp 1j self states delta Im In self Yg vt self signals Id Id self signals Iq Iq self signals Vd Vd self signals Vq Vq self signals P p self signals Q q self signals Vt np abs vt self signals Vang np angle vt return Im
augments the exampleandextracts with featurespredictionslabels .,def _AugmentExtracts fpl_dict example_and_extracts for name val in fpl_dict iteritems val val get encoding NODE_SUFFIX if isinstance val tf SparseTensorValue example_and_extracts extracts name types MaterializedColumn name name value val values 0 _MAX_SPARSE_FEATURES_PER_COLUMN elif isinstance val np ndarray val val 0 if not np isscalar val val val 0 _MAX_SPARSE_FEATURES_PER_COLUMN example_and_extracts extracts name types MaterializedColumn name name value val else raise TypeError Unexpected fpl type s str val
compute all the possible relations if there is a common ( homogeneous ) ouput .,def compute_nets self kret None kret range len self retrievers if kret is None else kret kret kret if type kret int else kret nets for r in kret nets append self retrievers r compute_neighnets self selector return nets
loads a public key from pem encoded data .,abc abstractmethod def load_pem_public_key self data
! test configuration @param self this object @return none,def testConfig self Config SetDefault ns3 OnOffApplication PacketSize ns core UintegerValue 123
main for build and test .,def main argv if len argv 2 or argv 1 lower not in mac windows linux print Usage build_and_test py OS_target print print OS_target can be Mac Windows or Linux return os chdir os path dirname os path realpath __file__ os_dir s s argv 1 0 1 upper argv 1 1 lower print Build and test file unpacker library for s Portable Server os_dir if BuildLibrary os_dir argv 1 lower windows print Library built RunTests
handle get request for icon .,tornado web asynchronous def get self icon layer_id icon icon encode ascii ignore self set_header Content Type image png tornado web local_server_ LocalIconHandler self icon int layer_id self finish
cache the response based on whether or not the user is authenticated .,def cache_on_auth timeout def _decorator view_func wraps view_func assigned available_attrs view_func def _wrapped_view request args kwargs key_prefix _auth_ s_ request user is_authenticated return cache_page timeout key_prefix key_prefix view_func request args kwargs return _wrapped_view return _decorator
use to create a footer area at the bottom of the panel .,register tag name footer def do_footer parser token nodelist parser parse endfooter parser delete_first_token return FooterNode nodelist
main function to run the audio polyphonic version of patterns finding .,def main parser argparse ArgumentParser description Discovers the audio polyphonic motives given a WAV file and a CSV file formatter_class argparse ArgumentDefaultsHelpFormatter parser add_argument wav_file action store help Input WAV file parser add_argument c dest csv_file action store default None help Input CSV file to read MIDI notes for output parser add_argument b dest bpm action store type float default None help Beats Per Minute of the wave file parser add_argument o action store default results txt dest output help Output results parser add_argument pk action store_true default False dest read_pk help Read Pickle File parser add_argument spk action store_true default False dest ssm_read_pk help Read SSM Pickle File parser add_argument th action store default 0 35 type float dest tol help Tolerance level from 0 to 1 parser add_argument r action store default 2 type int dest rho help Positive integer number for calculating the score parser add_argument ismir action store_true default False dest is_ismir help Produce the plots that appear on the ISMIR paper parser add_argument t action store_true default False dest tonnetz help Whether to use Tonnetz or not parser add_argument s action store_true default False dest sonify help Sonify the patterns args parser parse_args start_time time time logging basicConfig format asctime s levelname s message s level logging INFO process args wav_file args output csv_file args csv_file bpm args bpm tol args tol read_pk args read_pk ssm_read_pk args ssm_read_pk rho args rho is_ismir args is_ismir tonnetz args tonnetz sonify args sonify logging info Done Took 2f seconds time time start_time
calls super and sets the field_dict on the object .,def __init__ self name field_list None minimum None maximum None kwargs u n Calls super and sets the field_dict on the object n n param unicode name The name of this field n param list field_list A list of fields the names n of the fields are what is used as the key in the dictionary n param dict kwargs The standard arguments for BaseField __init__ n self field_list field_list or super DictField self __init__ name kwargs self minimum minimum self maximum maximum
"helper to lookup the distro store object , basically detecting the url . handle occasional proxy errors",def _storeForDistro fetcher guest for ignore in range 0 10 try return urldetect getDistroStore guest fetcher except Exception as e if 502 in str e logging debug Caught proxy error s str e time sleep 0 5 continue raise raise
run the dashboard driver . the ctestsourcedirectory argument specifies where the directory that ctest will run over . there should be a cmakelists.txt file in this location . the projectrepobasedir argument specifies root of the source code repository for the project .,def run_driver ctestSourceDirectory projectRepoBaseDir origDir os getcwd try print n print Tribits Driver Dashboard tdd_driver py print n print nPWD os getcwd n print projectRepoBaseDir projectRepoBaseDir print tribitsDDDir tribitsDDDir tribitsDir os path abspath os path join tribitsDDDir print tribitsDir tribitsDir tddDashboardRootDir os path dirname projectRepoBaseDir if TDD_DASHBOARD_ROOT in os environ tddDashboardRootDir os environ TDD_DASHBOARD_ROOT print tddDashboardRootDir tddDashboardRootDir os chdir tddDashboardRootDir if verbose nNew PWD os getcwd tddUseSystemCTest False if TRIBITS_TDD_USE_SYSTEM_CTEST in os environ and os environ TRIBITS_TDD_USE_SYSTEM_CTEST 1 tddUseSystemCTest True print tddUseSystemCTest tddUseSystemCTest if tddUseSystemCTest ctestExe getCmndOutput which ctest True False else ctestExe install_ctest tddDashboardRootDir tribitsDir print nctestExe ctestExe if not os path exists ctestExe print error ctest does not exist after installation sys exit 3 ctestExe ctestExe replace ctestVersion getCmndOutput ctestExe version True False print ctestVersion ctestVersion print n print Running the main dashboards as CTest tests print n sys exit invoke_ctest ctestExe os path join tribitsDDDir TribitsDriverDashboard cmake tddDashboardRootDir TDD_DASHBOARD_ROOT tddDashboardRootDir CTEST_SOURCE_DIRECTORY ctestSourceDirectory CTEST_UPDATE_DIRECTORY projectRepoBaseDir CTEST_BINARY_DIRECTORY tddDashboardRootDir TDD_BUILD finally os chdir origDir
get all the symbols defined in this scope,property def syms self syms self symbols values return sorted syms key lambda v v name
determine the greatest common type .,def get_common_type self a b loc typ_a self get_type a typ typ_b self get_type b typ if self equal_types typ_a typ_b return typ_a if isinstance typ_a ast PointerType and self equal_types typ_b int return typ_a if isinstance typ_b ast PointerType and self equal_types typ_a int return typ_b all_type_names float double int8_t int16_t int32_t int64_t uint8_t uint16_t uint32_t uint64_t all_types self get_type n for n in all_type_names type_lu type t t bits t for t in all_types type_prios ast UnsignedIntegerType 1 ast SignedIntegerType 2 ast FloatType 3 reverz v k for k v in type_prios items a type typ_a b type typ_b if a in type_prios and b in type_prios ct reverz max type_prios a type_prios b cb max typ_a bits typ_b bits key ct cb if key in type_lu return type_lu key raise SemanticError Types and do not commute format typ_a typ_b loc
"open file , check magic number and read header",def _open self head_data self fp read 14 if head_data 0 2 BM raise SyntaxError Not a BMP file offset i32 head_data 10 14 self _bitmap offset offset
return the specific value for all files,def get self name val if name file for file_name bc in self __bc if file_name val return bc return None else l for file_name bc in self __bc l append bc get name val return list self _iterFlatten l
add ( post ) or remove ( delete ) a notification type,action detail True methods PUT DELETE permission_classes IsAuthenticated url_name notification_types url_path notification_types P notification_type serializer_class EmptySerializer def modify_notification_types self request pk notification_type membership get_object_or_404 GroupMembership objects group self get_object user request user self check_object_permissions request membership serializer_class None if request method PUT serializer_class GroupMembershipAddNotificationTypeSerializer elif request method DELETE serializer_class GroupMembershipRemoveNotificationTypeSerializer serializer serializer_class membership data notification_type notification_type partial True serializer is_valid raise_exception True self perform_update serializer return Response GroupMembershipInfoSerializer membership data
create a new module ( app version ) .,def bound_lvnf_stats self kwargs kwargs tenant_id self tenant tenant_id kwargs lvnf self lvnf return lvnf_stats kwargs
test calling stop ( ) with invalid basedir path,def test_bad_basedir self self setupUpIsWorkerDir False self assertEqual stop stop self config 1 unexpected exit code self isWorkerDir assert_called_once_with self config basedir
"< ? xml version=""1.0 "" encoding=""utf-8 "" ? > < signedidentifiers > < signedidentifier > < id > unique - value</id > < accesspolicy > < start > start - time</start > < expiry > expiry - time</expiry > < permission > abbreviated - permission - list</permission > < /accesspolicy > < /signedidentifier > < /signedidentifiers >",def _convert_xml_to_signed_identifiers response if response is None or response body is None return None list_element ETree fromstring response body signed_identifiers _dict for signed_identifier_element in list_element findall SignedIdentifier id signed_identifier_element find Id text access_policy AccessPolicy access_policy_element signed_identifier_element find AccessPolicy if access_policy_element is not None start_element access_policy_element find Start if start_element is not None access_policy start parser parse start_element text expiry_element access_policy_element find Expiry if expiry_element is not None access_policy expiry parser parse expiry_element text access_policy permission access_policy_element findtext Permission signed_identifiers id access_policy return signed_identifiers
interprets the console on the loaded code .,def interpret self if not self _interpret_lines self _setup return False success self _interpret_lines self _code compare_all True success self _interpret_lines self _teardown return success
"given a list of parameters , picks a random parameter to change , and decreases or increases it slightly .",staticmethod def uniform_slight ranges parameters ret copy parameters print Neighbor old ret index random randint 0 len parameters 1 print ranges if isinstance ranges index 0 bool ret index random uniform 0 1 0 5 elif random randint 0 1 0 ret index ret index 0 1 ranges index 1 ranges index 0 else ret index ret index 0 1 ranges index 1 ranges index 0 print Neighbor new ret return ret
this method is called right after the injection attack .,def post_injection self pass
prefix = ' person / b2cfa6ca14d1f274465 ' suffix = ' 1 ',tornado web authenticated def post self prefix suffix _ self app get_translate_func self current_user if in suffix row action suffix split 1 else row action suffix view instance self app get_object_from_url prefix path reporef_list s int row 1 if prefix count 2 parts prefix split path join parts 3 path url prefix reporef_list row subitem instance get_field path form RepoRefForm self instance subitem path url form save self redirect self app make_url url
return the list of all textual attributes of the object .,def get_text_data_list self return self value
"given a database and a filename of a media , return the media filename is full form , eg ' graves / tomb.png ' becomes ' /home / me / genea / graves / tomb.png",def media_path_full db filename if os path isabs filename return filename mpath media_path db return os path join mpath filename
return the type of the event .,def get_type self return self __type
"check if the observation is of reading type pulse args : obxdict(dict ) : observation in dictionary returns : bool : true if the observation is of this reading type , false otherwise .",def isPulse obxDict readingCode getReadingCode obxDict return readingCode X201 4
return the platonic icosahedral graph .,def icosahedral_graph create_using None description adjacencylist Platonic Icosahedral Graph 12 2 6 8 9 12 3 6 7 9 4 7 9 10 5 7 10 11 6 7 11 12 7 12 9 10 11 12 10 11 12 G make_small_undirected_graph description create_using return G
prints a sudoku thingy nicely .,def printSudoku su print for i in range 9 print format su i replace 0 if i 1 3 0 print
check whether the given vm name matches any of the regex match objects,def match matchers vm_name for matcher in matchers if matcher match vm_name return True else return False
tests creating pending requests using /api / requests .,pytest mark tier 3 def test_create_pending_requests self collection appliance requests_pending create_pending_requests collection appliance rest_api requests_pending
converts mesh - object to desired projection and representation(dxf - entity type ),def export self ctx drawing ob mx mx_n kwargs me self _getMeshData ctx ob self _settings if me vertices if self INSTANCES and me users 1 and not self PROJECTION and not ob modifiers and self _settings apply_modifiers if drawing containsBlock me name entities self _writeInsert drawing ob mx me name else allpoints v co for v in me vertices identity_matrix mathutils Matrix identity allpoints self projected_co allpoints identity_matrix faces edges for e in me edges edges append e key faces v index for v in f verts for f in me faces entities self _writeMeshEntities allpoints edges faces kwargs if entities drawing addBlock me name flag 0 base 0 0 0 entities entities entities self _writeInsert ob mx me name kwargs else return self _standard_way drawing me mx mx_n
create the ui for the rig parameters .,def parameters_ui layout params r layout row col r column align True row col row align True for i axis in enumerate x y z row prop params copy_rotaion_axes index i toggle True text axis r layout row r prop params tweak_extra_layers r active params tweak_extra_layers col r column align True row col row align True for i in range 8 row prop params tweak_layers index i toggle True text row col row align True for i in range 16 24 row prop params tweak_layers index i toggle True text col r column align True row col row align True for i in range 8 16 row prop params tweak_layers index i toggle True text row col row align True for i in range 24 32 row prop params tweak_layers index i toggle True text
recives vision data and maniupulates widget @param data : list of objects of type mrgraphicsobject,def drawGui self data None if data None data self __pushedData retList if type data list for obj in data retList append self drawObj obj return retList
execute ` type - at - pos ` command .,def run self view logger logger debug Running type at pos self view erase_status flow_type thread ExecFlowCommand self get_cmd self get_content thread start self check_thread thread
check exception handling if params are faulty,def test_init with assert_raises ValueError dealer Dealer 24 n_participants s_secrets access_structures with assert_raises ValueError dealer Dealer p256 1 s_secrets access_structures
check to make sure the defined waypoints have the necessary parameters given the provided options and correct the waypoints when possible . @rtype : bool,def _check_options self if self _traj trajectory_options interpolation_type TrajectoryOptions CARTESIAN self _check_cartesian_options
compute the 2 's compliment of int value val,def twos_comp val bits if val 1 bits 1 0 val 1 bits return val
test a restricted domain with an allowed parent .,def test_is_query_restricted_true_with_parent_false self self dns query_restrictions 2 3 4 5 example com False 4 5 example com True self assertFalse self dns is_query_restricted 1 2 3 4 5 example com
powers token validation ( not using onetouch ),auth route verify methods GET POST login_required def verify form VerifyForm request form user User query get session user_id if request method GET send_authy_token_request user authy_id if form validate_on_submit user_entered_code form verification_code data verified verify_authy_token user authy_id str user_entered_code if verified ok user authy_status approved db session add user db session commit flash You re logged in Thanks for using two factor verification success return redirect url_for main account else form errors verification_code Code invalid please try again return render_template verify html form form
gets the file name of the loaded sdl2_ttf library .,def get_dll_file return dll libfile
set a value in the cache .,def set self key value raise NotImplementedError
runs a command in a virtualenv ( which has been specified using the virtualenv context manager,def run_venv command kwargs run source s bin activate env virtualenv command kwargs
not required . in es all is index ! !,def sql_indexes_for_field self model f style return
check if the number is a valid grid .,def is_valid number try return bool validate number except ValidationError return False
used to retrieve the latest trades that have occurred for a specific market .,def get_market_history self market count return self api_query getmarkethistory market market count count
test that the queryset returned is as expected a lettingqueryset,def test_get_queryset_expired self expired_date datetime utcnow replace tzinfo pytz utc timedelta days 1 sale SaleFactory create expires_at expired_date request self factory get reverse sales detail kwargs slug sale slug request user AnonymousUser with self assertRaises Http404 DetailPageView as_view request slug sale slug
returns the total frames length of the video .,property def frames_length self return self _video shape 0
return data in text table presentation,def render_text_table sheet write_title content if write_title content s n sheet name table Texttable max_width 0 data sheet to_array if isinstance data GeneratorType data list data if len data 0 return content table set_cols_dtype t len data 0 if len sheet colnames 0 table set_chars table header list _cleanse_a_row data 0 else table add_row list _cleanse_a_row data 0 for sub_array in data 1 new_array _cleanse_a_row sub_array table add_row list new_array content table draw return content
constructor : param connection : a psycopg2 connection,def __init__ self connection self __connection connection self __cursor connection cursor
if given a string _ validate_error ( ) should return it wrapped in a dict .,def test_validate_error_with_string assert db _validate_error Something went wrong message Something went wrong
"called after a resource object is serialised , before it is returned .",def after_serialise_object view_instance obj
send a torrent / nzb file to the downloader,def download self data None media None filedata None if not media media if not data data if not filedata log error Unable to get NZB file s traceback format_exc return False log info Sending s to NZBGet data get name nzb_name ss s nzb self createNzbName data media rpc self getRPC try if rpc writelog INFO CouchPotato connected to drop off s nzb_name log debug Successfully connected to NZBGet else log info Successfully connected to NZBGet but unable to send a message except socket error log error NZBGet is not responding Please ensure that NZBGet is running and host setting is correct return False except xmlrpclib ProtocolError as e if e errcode 401 log error Password is incorrect else log error Protocol Error s e return False if re search 0 rpc version xml_response rpc append nzb_name self conf category False standard_b64encode filedata strip else xml_response rpc append nzb_name self conf category tryInt self conf priority False standard_b64encode filedata strip if xml_response log info NZB sent successfully to NZBGet nzb_id md5 data url couchpotato_id couchpotato nzb_id groups rpc listgroups file_id item LastID for item in groups if item NZBFilename nzb_name confirmed rpc editqueue GroupSetParameter 0 couchpotato_id file_id if confirmed log debug couchpotato parameter set in nzbget download return self downloadReturnId nzb_id else log error NZBGet could not add s to the queue nzb_name return False
: type root : treenode : rtype : list[int ],def rightSideView self root if root is None return view pre root while pre view append pre 1 val now for node in pre if node left now append node left if node right now append node right pre now return view
creates an instance of adam .,def __init__ self learning_rate 0 001 beta1 0 9 beta2 0 999 epsilon 1e 08 name adam super Adam self __init__ name name self _learning_rate learning_rate self _beta1 beta1 self _beta2 beta2 self _epsilon epsilon
switch focus to the default frame .,def default_content self self _driver execute Command SWITCH_TO_FRAME id None
marshals the firefox options to a ` moz : firefoxoptions ` object .,def to_capabilities self opts if self _binary is not None opts binary self _binary _start_cmd if len self _preferences 0 opts prefs self _preferences if self _proxy is not None self _proxy add_to_capabilities opts if self _profile is not None opts profile self _profile encoded if len self _arguments 0 opts args self _arguments opts update self log to_capabilities if len opts 0 return Options KEY opts return
returns none if straddress is invalid . otherwise returns integer version of address .,def get_bcaddress_version strAddress addr b58decode_chk strAddress if addr is None or len addr 21 return None version addr 0 return ord version
test that the module - level docstring is linted correctly .,def check_module self test_str messages stmt astroid parse test_str if messages ctx self assertAddsMessages messages else ctx self assertNoMessages with ctx self checker process_tokens tokenize_str test_str self checker visit_module stmt
test that global admins have no read access,def test_no_global_admin_read_access self self assertFalse has_studio_read_access self global_admin self ccx_course_key
"tests the workflow for the internal reporting user table , end to end .",when_vertica_available def test_internal_reporting_user self self task launch LastCountryOfUserPartitionTask interval self INTERVAL n reduce tasks str self NUM_REDUCERS self task launch LoadInternalReportingUserToWarehouse date self DATE n reduce tasks str self NUM_REDUCERS self validate_output
log summary information about every request made .,def log_response_hook response args kwargs log info s d f s response request method response status_code response elapsed total_seconds response url
index the text of a document .,def index_document self text url title text text index n strip docwords words text docid len self documents self documents append Document title url len docwords for word in docwords if word not in self stopwords self index word docid 1
marshal and write multiple outgoing pamqp frames to the socket .,def write_frames self channel_id frames_out data_out EMPTY_BUFFER for single_frame in frames_out data_out pamqp_frame marshal single_frame channel_id self heartbeat register_write self _io write_to_socket data_out
"create table in the database : param table : table name : param columns : column array : param types : type array : param primary_key_index : an array of indices of primary keys in columns , e.g. [ 0 ] means the first column is the primary key : param is_ifnotexists : create table if not exists keyword",def create self table columns types primary_key_index is_ifnotexists True return True
thumbnail url generator for vimeo videos .,def generate_thumbnail_download_link_vimeo video_id_from_shortcode video_metadata urlopen https vimeo com api v2 video str video_id_from_shortcode json read video_metadata_parsed json loads video_metadata decode utf 8 video_thumbnail_large_location video_metadata_parsed 0 thumbnail_large return video_thumbnail_large_location
get a list of values for this key . @param key the key to search for @return a list of values or empty list,def findall self key obj self find key if obj is None obj list if isinstance obj list return obj return obj
appends a line in the filehead state .,def appendFileheadLine self match if options debug print sys stderr CALLBACK appendFileheadLine self __closeComment self comment self output append self fsm current_input
specifies passive events ( e.g. simple counts ) that will need to be met before any active events start . these can be used to wait until all of the provided events have occurred before starting an active attack .,def use_events_for_synchronization self events self _issue_set_event_command self SETUP_COMMAND_SET_SYNCHRONIZATION events
: return : path at which this db operates,def root_path self return self _root_path
return the captured sensorvalue in the specified time range,def getData self dateFrom dateTo outputDataset for dataset in self data if dataset timestamp dateTo if dataset timestamp dateFrom outputDataset append dataset return outputDataset
"the synth 's waveform type ; one of `` "" sawtooth "" `` , `` "" square "" `` , `` "" sine "" ``",property def waveform self return self _params waveform
merges serialized protocol buffer data into this message .,def MergeFromString self serialized raise NotImplementedError
"test open ( ) , close ( ) and isopen ( ) functions .",def test_open self self device open self assertEqual self device isOpen True self device close self assertEqual self device isOpen False
"registers an event handler "" function "" for "" event "" . when event is emitted each registered event handler is called in the order of "" priority "" . calling order of event handlers with same "" priority "" is undefined .",def on self event function priority 0 assert callable function if event not in self __listeners self __listeners event self __listeners event append priority function self __listeners event sort reverse True key lambda listener listener 0 return self
removes a class from the top level element of the widget .,def remove_class self className if className in self _dom_classes self _dom_classes c for c in self _dom_classes if c className return self
unswap works with instances of swapevent loaded from strings .,def test_unswap_swaptext initial 0 Norbert 1 Dave 2 Kyle 3 Dennis 4 Vincent 5 Bryan 6 Dylan 7 Andrew 8 Joseph 9 Bob swap_text 5 swapped with 8 at 2017 09 07T20 40 40 3 swapped with 9 at 2017 09 07T20 40 20 8 swapped with 4 at 2017 09 07T20 39 59 8 swapped with 6 at 2017 09 07T20 40 52 5 swapped with 0 at 2017 09 07T20 39 52 9 swapped with 2 at 2017 09 07T20 40 12 0 swapped with 5 at 2017 09 07T20 39 44 2 swapped with 9 at 2017 09 07T20 39 37 8 swapped with 6 at 2017 09 07T20 40 07 2 swapped with 6 at 2017 09 07T20 40 50 2 swapped with 4 at 2017 09 07T20 40 30 solution 0 Norbert 1 Dave 2 Vincent 3 Bob 4 Kyle 5 Dylan 6 Bryan 7 Andrew 8 Joseph 9 Dennis swaps to_swapevent swap_text assert unswap initial swaps solution
validate that the supplied email address is unique for the site .,def clean_email self if RegistrationProfile objects email__iexact self cleaned_data email raise forms ValidationError _ u This email address is already in use Please supply a different email address return self cleaned_data email
"save the data into a file . return true is file successfully saved , otherwise false .",def saveFile self fileid data kwargs raise NotImplementedError You must override the implementaion of saveFile for your file server For example check out the S3FileServer
creates a camera that views the scene .,def __init__ self roll None kwargs super Camera self __init__ kwargs self _kml roll roll
configures all needed database stuff depending on the backend used,def handle_app self app options names for model in get_models app if issubclass model Partitionable names append model __name__ model_instance model model_instance get_partition prepare if not names self stderr write Unable to find any partitionable models in an app app __name__ split 0 n else self stdout write Successfully re configured the database for the following models join names n
test that the list of files in the manifest is the same as the actual file list .,pytest mark min_mender_version 1 0 0 def test_files_list_integrity self versioned_mender_image version versioned_mender_image 0 mender_image versioned_mender_image 1 if version 1 output subprocess Popen tar xOf mender_image header tar gz tar xzO headers 0000 files stdout subprocess PIPE shell True loaded_json json load output stdout manifest_list loaded_json files output wait else output subprocess check_output tar xOf mender_image manifest manifest_list line split 1 for line in output strip split n if version 1 tar_list else tar_list version header tar gz output subprocess Popen tar xOf mender_image data 0000 tar gz tar tz stdout subprocess PIPE shell True for line in output stdout line line rstrip n r if version 1 tar_list append line else tar_list append data 0000 line output wait assert sorted manifest_list sorted tar_list
return a boolean indicating wether the request is a post patch or put request,def _is_marshal_request self return request method in POST PATCH PUT
initiate detector and find key points on an image parameters ---------- image : 2d uint8 numpy array - image edgethreshold : int - parameter for opencv detector nfeatures : int - parameter for opencv detector nlevels : int - parameter for opencv detector patchsize : int - parameter for opencv detector returns ------- keypoints : list - coordinates of keypoint on image descriptors : list - binary descriptos of kepoints,def find_key_points image edgeThreshold 34 nFeatures 100000 nLevels 7 patchSize 34 kwargs if cv2 __version__ startswith 3 detector cv2 ORB_create detector setEdgeThreshold edgeThreshold detector setMaxFeatures nFeatures detector setNLevels nLevels detector setPatchSize patchSize else detector cv2 ORB detector setInt edgeThreshold edgeThreshold detector setInt nFeatures nFeatures detector setInt nLevels nLevels detector setInt patchSize patchSize print ORB detector initiated keyPoints descriptors detector detectAndCompute image None print Key points found d len keyPoints return keyPoints descriptors
build packet from provided header fields and data payload,staticmethod def mk_packet op ep sn param1 0 param2 0 data return struct pack hdr_fmt op ep 0 sn param1 param2 0 len data data
this method closes the connection to rabbitmq .,def _close self LOG info _LI Closing connection self _open False if self _channel self _channel close self _channel None if self _connection self _connection close self _connection None self _closing False LOG debug _ Connection Closed
report status changes for hosting devices .,def update_hosting_device_status self context host status_info for status hd_ids in six iteritems status_info hd_spec hosting_device status status for hd_id in hd_ids self _dmplugin update_hosting_device context hd_id hd_spec if status const HD_DEAD or status const HD_ERROR self _dmplugin handle_non_responding_hosting_devices context host hd_ids
handle rpc cast from plugin to delete a tap flow,def delete_tap_flow self context tap_flow_msg host pass
get a list of available ip filters for this quiz .,def get_available_quiz_ip_filters request_ctx course_id quiz_id request_kwargs path v1 courses course_id quizzes quiz_id ip_filters url request_ctx base_api_url path format course_id course_id quiz_id quiz_id response client get request_ctx url request_kwargs return response
create a content object that will obtain the content from reader .,def content_from_reader reader content_type buffer_now if content_type is None content_type UTF8_TEXT if buffer_now contents list reader reader lambda contents return Content content_type reader
replace tokens in a file and write out the substitution .,def replace_source_tokens file_path lookup out_path if not path isfile file_path raise InternalException File does not exist format file_path try source_file open file_path r source source_file read except Exception raise InternalException Unable to read from source file template Template source output template safe_substitute lookup try output_file open out_path w output_file write output except Exception raise InternalException Unable to write to output file
computes the confusion matrix from predictions and labels,def confusion_matrix predictions labels num_classes None name None with ops op_scope predictions labels num_classes name confusion_matrix as name predictions ops convert_to_tensor predictions name predictions dtype dtypes int64 labels ops convert_to_tensor labels name labels dtype dtypes int64 if num_classes is None num_classes math_ops maximum math_ops reduce_max predictions math_ops reduce_max labels 1 shape array_ops pack num_classes num_classes indices array_ops transpose array_ops pack predictions labels values array_ops ones_like predictions dtype dtypes int32 cm_sparse ops SparseTensor indices indices values values shape shape zero_matrix array_ops zeros math_ops to_int32 shape dtypes int32 return sparse_ops sparse_add zero_matrix cm_sparse
returns weights of the dnn weight layers .,property def weights_ self return self _session run w for w in self _graph get_collection dnn_weights self get_tensor_value linear_regression weights 0
train a classifier model using an rdd training dataset : param training_rdd : the rdd of the training dataset : param kwargs : additional key - value params for the training ( if any ) : return :,def train_model training_rdd kwargs return LogisticRegressionWithLBFGS train training_rdd regType _REGULARIZATION intercept _INTERCEPT kwargs
a word - wrap function that preserves existing line breaks and most spaces in the text . expects that existing line breaks are posix newlines ( ) .,def wrap_onspace text width return reduce lambda line word width width s s s line n len line line rfind n 1 len word split n 1 0 width word text split
read the contents of data memory at an address .,def CCpeekdatabyte self adr self data adr 255 adr 65280 8 self writecmd self APP 145 2 self data return ord self data 0
returns a string suitable for rfc 2822 compliant message - id optional idstring if given is a string used to strengthen the uniqueness of the message i d .,def make_msgid idstring None timeval int time time 100 pid os getpid randint random getrandbits 64 if idstring is None idstring else idstring idstring idhost socket getfqdn msgid d d d s s timeval pid randint idstring idhost return msgid
returns a list of the available modes of the port .,property def modes self self _modes value self get_attr_set self _modes modes return value
"distance based initialization . randomly choose a start point , then : if determ = = true : choose point farthest from the clusters chosen so far , otherwise : randomly choose new points proportionally to their distance .",def k_init X K determ m n twod X shape clusters np zeros K n clusters 0 X int np floor np random rand m dist np sum np power X np ones m 1 clusters 0 2 axis 1 ravel for i in range 1 K if determ j np argmax dist else pr np cumsum np array dist pr pr pr 1 j np where np random rand pr 0 0 clusters i X j new_dist np sum np power X np ones m 1 clusters i 2 axis 1 ravel dist np minimum dist new_dist return clusters
: type nums : list[int ] : rtype : list[int ],def productExceptSelf self nums n len nums res 1 for i in range n product 1 for i in range 1 n for j in range i res j nums i product nums i 1 res i product return res
"loads data from file : param filename : : param numattrs : number of column in file , excluding class column : return :",def loadDataset filename numattrs csvfile open filename r lines csv reader csvfile dataset list lines for x in range len dataset for y in range numattrs dataset x y float dataset x y return dataset
display details for a specified volume .,click command click argument volume_id environment pass_env def cli env volume_id file_manager SoftLayer FileStorageManager env client file_volume file_manager get_file_volume_details volume_id file_volume utils NestedDict file_volume table formatting KeyValueTable Name Value table align Name r table align Value l storage_type file_volume storageType keyName split _ pop 0 table add_row ID file_volume id table add_row Username file_volume username table add_row Type storage_type table add_row Capacity GB iGB file_volume capacityGb used_space int file_volume bytesUsed if file_volume bytesUsed else 0 if used_space 1 10 table add_row Used Space dB used_space elif used_space 1 20 table add_row Used Space dKB used_space 1 10 elif used_space 1 30 table add_row Used Space dMB used_space 1 20 else table add_row Used Space dGB used_space 1 30 if file_volume get provisionedIops table add_row IOPs int file_volume provisionedIops if file_volume get storageTierLevel table add_row Endurance Tier file_volume storageTierLevel table add_row Data Center file_volume serviceResource datacenter name table add_row Target IP file_volume serviceResourceBackendIpAddress if file_volume fileNetworkMountAddress table add_row Mount Address file_volume fileNetworkMountAddress if file_volume snapshotCapacityGb table add_row Snapshot Capacity GB file_volume snapshotCapacityGb if snapshotSizeBytes in file_volume parentVolume table add_row Snapshot Used Bytes file_volume parentVolume snapshotSizeBytes table add_row of Active Transactions i file_volume activeTransactionCount if file_volume activeTransactions for trans in file_volume activeTransactions if transactionStatus in trans and friendlyName in trans transactionStatus table add_row Ongoing Transaction trans transactionStatus friendlyName table add_row Replicant Count u file_volume get replicationPartnerCount 0 if file_volume replicationPartnerCount 0 if message in file_volume replicationStatus table add_row Replication Status s file_volume replicationStatus message else table add_row Replication Status s file_volume replicationStatus replicant_list for replicant in file_volume replicationPartners replicant_table formatting Table Replicant ID replicant id replicant_table add_row Volume Name utils lookup replicant username replicant_table add_row Target IP utils lookup replicant serviceResourceBackendIpAddress replicant_table add_row Data Center utils lookup replicant serviceResource datacenter name replicant_table add_row Schedule utils lookup replicant replicationSchedule type keyname replicant_list append replicant_table table add_row Replicant Volumes replicant_list if file_volume get originalVolumeSize original_volume_info formatting Table Property Value original_volume_info add_row Original Volume Size file_volume originalVolumeSize if file_volume get originalVolumeName original_volume_info add_row Original Volume Name file_volume originalVolumeName if file_volume get originalSnapshotName original_volume_info add_row Original Snapshot Name file_volume originalSnapshotName table add_row Original Volume Properties original_volume_info env fout table
search for a package by name or summary,def test_searchByNameAndSummary self query apache pkgs client packages search nameAndSummary self session_key query self assertTrue pkgs None self assertTrue len pkgs 0 for p in pkgs self assertTrue p has_key id self assertTrue p has_key name self assertTrue p has_key epoch self assertTrue p has_key version self assertTrue p has_key release self assertTrue p has_key arch self assertTrue p has_key description self assertTrue p has_key summary
reset the changed status for these entries,def reset self val 0 for k v in self data items self data k v 0 val
"parse commandline , process config file key = value mappings",def main configFilename newMappings parseCommandline mapNewSettings configFilename readConfigFile newMappings
redirect to a given url while setting the chosen language in the session or cookie . the url and the language code need to be specified in the request parameters .,def set_language request next request REQUEST get next if not is_safe_url url next host request get_host next request META get HTTP_REFERER if not is_safe_url url next host request get_host next response http HttpResponseRedirect next if request method POST lang_code request POST get language None if lang_code and check_for_language lang_code if hasattr request session request session django_language lang_code else response set_cookie settings LANGUAGE_COOKIE_NAME lang_code return response
all inline references are pending under mysql,def sql_for_inline_foreign_key_references self field known_models style return True
persist a user i d and a backend in the request . this way a user does n't have to reauthenticate on every request . note that data set during the anonymous session is retained when the user logs in .,def login request user if user is None user request user if SESSION_KEY in request session if request session SESSION_KEY user pk request session flush else request session cycle_key request session SESSION_KEY user pk request session BACKEND_SESSION_KEY user backend if hasattr request user request user user rotate_token request user_logged_in send sender user __class__ request request user user
returns an object containing the state of the warnings module,def get_warnings_state return warnings filters
returns the kml representation of this polygon .,property def kml self inner_kml join innerBoundaryIs s innerBoundaryIs self i 1 kml for i in xrange self num_interior_rings return Polygon outerBoundaryIs s outerBoundaryIs s Polygon self 0 kml inner_kml
assign an extended slice by rebuilding entire list,def _assign_extended_slice_rebuild self start stop step valueList indexList range start stop step if len valueList len indexList raise ValueError attempt to assign sequence of size d to extended slice of size d len valueList len indexList newLen len self newVals dict zip indexList valueList def newItems for i in xrange newLen if i in newVals yield newVals i else yield self _get_single_internal i self _rebuild newLen newItems
parse arguments provided in letucetdaf.py command,def main args sys argv 1 parser argparse ArgumentParser parser add_argument js jirasync help Defines the synchronization scheme with Jira Synchronize files publish results in jira or all mixed default none choices none sync pub all parser add_argument ep epics help Defines the epics to be tested separated by commas Use all for complete test default all parser add_argument tg tags help Defines the tags to be tested separated by commas default parser add_argument ft features help Defines the features to be testeds separated by commas Use all to test them all default all parser add_argument en environment help Defines the environment to execute test e g dev int default dev parser add_argument ts testsuite help Selects the testsuite default all choices comp int e2e all parser add_argument sd suitedir help Base dir path for testsuites in the project hierarchy default parser add_argument tm timestamp help Stores the results in timestamped folders action store_true args parser parse_args epics timestamp tags if args timestamp timestamp datetime now strftime d m Y_ H M S if args jirasync pub or args jirasync all jira True if args tags for item in args tags split tags join tags tag item if args jirasync sync or args jirasync all jirasync True else jirasync False if args epics epics args epics split if args environment copyfile settings args environment properties json properties json if args features features args features split if args suitedir suite_dir args suitedir if args suitedir 1 else args suitedir if comp in args testsuite or all in args testsuite run_tests component suite_dir epics features timestamp jirasync tags if e2e in args testsuite or all in args testsuite run_tests e2e suite_dir epics features timestamp jirasync tags if int in args testsuite or all in args testsuite run_tests integration suite_dir epics features timestamp jirasync tags try failures ResultChecker timestamp get_results except print There has not been generated any lettuce report exit 1 exit failures if __name__ __main__ main
"returns the specified attribute of a module , specified by a string .",def from_dotted_path fullpath module attr fullpath rsplit 1 return getattr __import__ module attr attr
returns a series based on ` results ` from timeline,def create_series self series for timeline_object in self timeline results count timeline_object count series insert 0 count self query_total self query_total count label self query 0 30 if len self query 30 label label label label str self query_total series insert 0 label return series
gets a page and processes it to a string . unwanted html tags get stripped by the strip_crap parser .,def get_doc self link try r requests get link if not r status_code requests codes ok return soup BeautifulSoup r text html parser self strip_unwanted_tags soup return self pp pre_process soup get_text except return
"delete roles from user , returns simple json listing remaining roles",role_api route api user int user_id roles methods DELETE oauth require_oauth def delete_roles user_id user current_user if user id user_id current_user check_role permission edit other_id user_id user get_user_or_abort user_id if not request json or roles not in request json abort 400 Requires role list role_list Role query filter_by name role get name one for role in request json get roles user delete_roles role_list acting_user current_user db session commit return jsonify roles r as_json for r in user roles
parse lines of an edge list representation of a bipartite graph .,def parse_edgelist lines comments delimiter None create_using None nodetype None data True from ast import literal_eval G _prep_create_using create_using for line in lines p line find comments if p 0 line line p if not len line continue s line strip split delimiter if len s 2 continue u s pop 0 v s pop 0 d s if nodetype is not None try u nodetype u v nodetype v except raise TypeError Failed to convert nodes s s to type s u v nodetype if len d 0 or data is False edgedata elif data is True try edgedata dict literal_eval join d except raise TypeError Failed to convert edge data s to dictionary d else if len d len data raise IndexError Edge data s and data_keys s are not the same length d data edgedata for edge_key edge_type edge_value in zip data d try edge_value edge_type edge_value except raise TypeError Failed to convert s data s to type s edge_key edge_value edge_type edgedata update edge_key edge_value G add_node u bipartite 0 G add_node v bipartite 1 G add_edge u v attr_dict edgedata return G
"create / release floating ip by nat rules for this ip with relation to internal ip for current node , save selected public_ip in runtime properties",def _floatingip_operation operation vca_client ctx service_type get_vcloud_config get service_type gateway get_gateway vca_client ctx target node properties floatingip edge_gateway internal_ip get_vm_ip vca_client ctx gateway nat_operation None public_ip ctx target instance runtime_properties get PUBLIC_IP or ctx target node properties floatingip get PUBLIC_IP if operation CREATE CheckAssignedInternalIp internal_ip gateway if public_ip CheckAssignedExternalIp public_ip gateway else public_ip get_public_ip vca_client gateway service_type ctx nat_operation _add_nat_rule elif operation DELETE if not public_ip ctx logger info Can t get external IP format public_ip return nat_operation _del_nat_rule else raise cfy_exc NonRecoverableError Unknown operation 0 format operation external_ip check_ip public_ip nat_operation gateway SNAT internal_ip external_ip nat_operation gateway DNAT external_ip internal_ip if not save_gateway_configuration gateway vca_client return ctx operation retry message Waiting for gateway retry_after 10 if operation CREATE ctx target instance runtime_properties PUBLIC_IP external_ip else if is_ondemand service_type if not ctx target node properties floatingip get PUBLIC_IP del_ondemand_public_ip vca_client gateway ctx target instance runtime_properties PUBLIC_IP ctx del ctx target instance runtime_properties PUBLIC_IP
"a month < 01 should give 404 , a month > 01 should redirect and display an error message . a year that is outside of the current year + /- 50 years should also redirect and display an error message .",def test_list_view_incorrect_year_and_or_month_in_url self u n A month 01 should give 404 a month 01 should redirect n and display an error message n A year that is outside of the current year 50 years n should also redirect and display an error message n message u invalid dates u 2015 u 00 u 2015 u 42 u 1015 u 01 u 4015 u 22 for year month in six iteritems dates response self client get reverse u calendar list kwargs u year year u month month self assertContains response message
initialize parameters for api class .,def __init__ self self base_url https books zoho com api v3
set exchange rate for the currency .,def set_exchange_rate self exchange_rate self exchange_rate exchange_rate
delete ps will delete all vms and volumes using this ps .,def delete_primary_storage primary_storage_uuid session_uuid None action api_actions DeletePrimaryStorageAction action uuid primary_storage_uuid action timeout 600000 test_util action_logger Delete Primary Storage uuid s primary_storage_uuid evt account_operations execute_action_with_session action session_uuid return evt inventory
get list of objects under a path on s3,def test_list self url push_to_s3 __file__ modis pds testing unittests fnames s3_list os path dirname url self assertEqual len fnames 1 self assertEqual fnames 0 url del_from_s3 url
creates a emphasized text text object,def __init__ self uri text None kwargs super Link self __init__ kwargs self uri uri self text text
return subscription for a particular node and event .,def check_node node event node_subscriptions key for key in constants NOTIFICATION_TYPES if node subscription NotificationSubscription load utils to_subscription_key node _id event for notification_type in node_subscriptions users getattr subscription notification_type if users for user in users exclude date_disabled__isnull False if node has_permission user read node_subscriptions notification_type append user _id return node_subscriptions
test all channels with long messages .,def test_AllChannelsLong data join random choice string letters for i in range 500000 for channel in sneakers Exfil list_channels f partial unit_channel channel data f description Test the channel with a very long message format channel yield f
define whatever function we want to optimize .,def f w sol return np sum np square sol w
starts the preview of the picamera . works only on the display connected directly on the raspberry pi .,def startPreview self self picam start_preview
construct a : class:`segment2d ` between two points .,def __init__ self p0 p1 self _p0 Vector2D p0 self _p1 Vector2D p1
count lines in fn . slightly modified version of http://stackoverflow.com/a/27518377,def countlines fn u Count lines in fn Slightly modified version of n http stackoverflow com a 27518377 with open fn u rb as f bufgen takewhile lambda x x f read 1024 1024 for _ in repeat None ln sum buf count n for buf in bufgen return ln
move bracket region to different points,def move self begin end return self _replace begin begin end end
return true if the handle is a window,def iswindow handle return bool win32functions IsWindow handle
"driver may call the code below in order to update the status . self.plugin.update_status(pool , pool[""id "" ] , constants . active )",abc abstractmethod def create_pool self pool pass
allows access to properties as an attribute :,def __getattr__ self key args kwds if key in super Entity self __getattribute__ __slots__ return super Entity self __getattr__ key else return self components key
"string version of the object , shows the same info as the contents of the .files file",def __str__ self ret for x in in out tmpin tmpout tmp ret ret self files x n for x in self files psps ret ret x n return ret
currently used to record start time for tests dump start msg of testcase to log,def startTest self test self __tcRunLogger info Started Test s str self __testName self __startTime time time
: param lng_rad : lng of px in radians : param lat_rad : lat of px in radians : param p0_lng : lng of p0 in radians : param p0_lat : lat of p0 in radians : param pm1_lng : lng of pm1 in radians : param pm1_lat : lat of pm1 in radians : param p1_lng : lng of p1 in radians : param p1_lat : lat of p1 in radians : return : shortest distance between px and the polygon section ( pm1 - --p0 - --p1 ) in radians,jit f8 f8 f8 f8 f8 f8 f8 f8 f8 nopython True cache True def compute_min_distance lng_rad lat_rad p0_lng p0_lat pm1_lng pm1_lat p1_lng p1_lat u n param lng_rad lng of px in radians n param lat_rad lat of px in radians n param p0_lng lng of p0 in radians n param p0_lat lat of p0 in radians n param pm1_lng lng of pm1 in radians n param pm1_lat lat of pm1 in radians n param p1_lng lng of p1 in radians n param p1_lat lat of p1 in radians n return shortest distance between pX and the polygon section pm1 p0 p1 in radians n px_cartesian coords2cartesian lng_rad p0_lng lat_rad p1_cartesian coords2cartesian p1_lng p0_lng p1_lat pm1_cartesian coords2cartesian pm1_lng p0_lng pm1_lat px_cartesian y_rotate p0_lat px_cartesian p1_cartesian y_rotate p0_lat p1_cartesian pm1_cartesian y_rotate p0_lat pm1_cartesian rotation_rad atan2 p1_cartesian 2 p1_cartesian 1 p1_cartesian x_rotate rotation_rad p1_cartesian lng_p1_rad atan2 p1_cartesian 1 p1_cartesian 0 px_retrans_rad cartesian2rad x_rotate rotation_rad px_cartesian temp_distance distance_to_point_on_equator px_retrans_rad 0 px_retrans_rad 1 max min px_retrans_rad 0 lng_p1_rad 0 rotation_rad atan2 pm1_cartesian 2 pm1_cartesian 1 p1_cartesian x_rotate rotation_rad pm1_cartesian lng_p1_rad atan2 p1_cartesian 1 p1_cartesian 0 px_retrans_rad cartesian2rad x_rotate rotation_rad px_cartesian return min temp_distance distance_to_point_on_equator px_retrans_rad 0 px_retrans_rad 1 max min px_retrans_rad 0 lng_p1_rad 0
clears answers * in place *,def clear self self answers clear
performs a separate scan on each axis of length size*step . should be used after the fiber has been somewhat alligned,def _cross_scan xyz size step y_axis cur_pos xyz get_coordinates new_pos cur_pos 0 cur_pos 1 size step cur_pos 2 xyz set_coordinates new_pos for i in xrange size y_axis append float _get_signal stages xyz step R cur_pos xyz get_coordinates new_pos cur_pos 0 cur_pos 1 size step cur_pos 2 xyz set_coordinates new_pos x_axis cur_pos xyz get_coordinates new_pos cur_pos 0 size step cur_pos 1 cur_pos 2 xyz set_coordinates new_pos for i in xrange size y_axis append float _get_signal stages xyz step B cur_pos xyz get_coordinates new_pos cur_pos 0 size step cur_pos 1 cur_pos 2 xyz set_coordinates new_pos return y_axis x_axis
"return string representation , i.e. , cc ... c(gate ) .",def __str__ self return C self _n str self _gate
"if value not passed , use super widget .",def test_render_without_value self widget widgets ImageClearableFileInput base_widget ClearableFileInput html widget render photo None base_html base_widget render photo None self assertEqual base_html html
"on the off - chance there 'd be several roots , let 's dep them together and return the first one",def get_root sent r for idx cols in enumerate sent if cols HEAD u 0 r append idx if len r 1 for i in range 1 len r gov d_row sent r i 1 ID sent r i d_row HEAD gov d_row PHEAD gov d_row DEPREL u dep d_row PDEPREL u dep return int sent r 0 ID 1
clear contents of image buffer .,def clear self self _buffer 0 LCDWIDTH LCDHEIGHT 8
returns the list of requested elections related to us .,def get_requested_elections self return Election objects filter Q agora__in self user administrated_agoras all Q creator self user Q is_approved False Q result_tallied_at_date None filter archived_at_date None exclude name delegation order_by voting_extended_until_date voting_starts_at_date
set up test data for the whole testcase ( only run once for the testcase ),classmethod def setUpTestData cls data_gen run
"gets the next "" undo "" action . used primarily for changing menu text .",def get_undo self if self have_undo return self history self curidx else return None
transform x back to original space .,def inverse_transform self X if not self fit_inverse_transform raise NotFittedError The fit_inverse_transform parameter was not set to True when instantiating and hence the inverse transform is not available K self _get_kernel X self X_transformed_fit_ return np dot K self dual_coef_
"check if multiling shall be enabled ( in templates ) . simply , if languages tuple contains more than one language , we return boolean true ; otherwise - boolean false .",register tag def multiling_is_enabled parser token bits token contents split if not len bits in 1 3 raise template TemplateSyntaxError s tag takes five arguments at most bits 0 if 3 len bits if as bits 2 raise template TemplateSyntaxError Invalid syntax for s You must specify a name for translated object bits 0 as_var bits 1 else as_var None return MultilinIsEnabledNode as_var as_var
"return string of the ref 's commit hash if valid , else none .",def get_sha1_or_none repo ref commit repo rev parse revs only ref strip return commit if commit else None
"return a list of ( name , email ) tuples from the branch .",def get_author_names_emails self return self _data names_emails
overwrites the nil_slot ( first row ) of the input tensor with zeros .,def zero_nil_slot t name None with tf name_scope name zero_nil_slot t as name t tf convert_to_tensor t name t s tf shape t 1 z tf zeros tf pack 1 s return tf concat 0 z tf slice t 1 0 1 1 name name
execute until success and return only the standard output .,def _execute self cmd count RETRY_COUNT delay RETRY_DELAY command_type None upper_timeout CONFIG argus upper_timeout return self _backend remote_client run_command_with_retry cmd count count delay delay command_type command_type upper_timeout upper_timeout 0
returns the refresh token : return : refresh token,def get_refresh_token self self _json self _jstore get_data return self _json access_manager get self _user get refresh_token
import tag names from the ` open - images ` dataset,def import_tags_from_openimages filename with open filename as fh reader csv reader fh for row in reader tag models Tag tag foreign_identifier row 0 strip tag name row 1 strip tag source openimages log debug Adding tag s tag name tag save
"given a list of events per frame , returns a list of gpu frame times .",def _GPUFrameTimes events_per_frame return _CalculateFrameTimes events_per_frame lambda event event duration
configure and prepare target platform for network control .,def Open self wpr_mode extra_wpr_args assert not self is_open Network controller is already open self _wpr_mode wpr_mode self _extra_wpr_args extra_wpr_args self _InstallTestCa
write markdown documentation for a class .,def md_module module_obj module_path None module_link None def should_doc name return type module_obj __dict__ name types ModuleType and not name startswith _ stuff_to_doc sorted obj for name obj in module_obj __dict__ iteritems if should_doc name classes_to_doc functions_to_doc for s in stuff_to_doc if type s types TypeType classes_to_doc append s elif type s types FunctionType functions_to_doc append s command devil utils markdown py if module_link command extend module link module_link if module_path command append os path relpath module_path _DEVIL_ROOT heading_text module_obj __name__ if module_link heading_text md_link heading_text module_link content md_heading heading_text level 1 md_italic This page was autogenerated by s md_inline_code join command for c in classes_to_doc content md_class c for f in functions_to_doc content md_function f print n join content return 0
rest component request processing . register the master on the slave .,def process self membership_list logging info colored green Received membership list self slave update_membership membership_list
scan a remote service and retrieve the fingerprint for its tls certificate . the fingerprint is appended to the global results list .,def run self try fp attempt_observation_for_service self sid self timeout_sec self sni if fp None results add self sid fp else stats failures 1 stats failure_socket 1 except Exception as e self _record_failure e logging error Error scanning 0 1 format self sid e logging exception e self global_stats num_completed 1 self global_stats active_threads 1 if self sid in self global_stats threads del self global_stats threads self sid
a view that reads a session variable,def check_session_view request return HttpResponse request session get session_var NO
test when router does n't have an opinion ( i.e. createmodel should run ) .,override_settings DATABASE_ROUTERS AgnosticRouter def test_create_model self self _test_create_model test_mltdb_crmo should_run True
signal that a file has completed . file size corresponds to the actual size accumulated by all the chunks .,def file_complete self file_size raise NotImplementedError
sets up a : class:`progressbarhandler ` to handle progess logs for a given module .,def show_progress name kwargs logger logging getLogger name logger setLevel logging INFO logger addHandler ProgressBarHandler kwargs
configtest - invalid api ( file ),def test_invalid_api self self render_config_template event_logs name Application api file self start_beat extra_args configtest check_wait exit_code 1 assert self log_contains Failed to create new event log file API is not available
"returns matrix_1*matrix_2 , where both arguments are matricies of compatible length",def matrix_multiply matrix_1 matrix_2 assert len matrix_1 0 len matrix_2 incompatible matrices acc for i in range len matrix_1 acc for j in range len matrix_2 0 acc i sum vector_multiply matrix_1 i column matrix_2 j assert type acc list matrix_multiply output not list assert type acc 0 list matrix_multiply output not matrix return acc
extracts an element value from an xml string .,def getUniqueElementValueFromXmlString xmlString elementName xmlStringAsDom xml dom minidom parseString xmlString elementsByName xmlStringAsDom getElementsByTagName elementName elementValue None if len elementsByName 0 elementValue elementsByName 0 toxml replace elementName replace elementName return elementValue
replaces the deserialized part of the buffer .,def set_deserialized_buffer self new_buffer u n Replaces the deserialized part of the buffer n self _deserialized_buffer new_buffer
sets the directory that contains the language bundles .,def set_locale_dir locale_dir global _locale_dir if not locale_dir raise ValueError locale_dir must be valid _locale_dir locale_dir
models should be unique ( on name field ),def test_unique self with self assertRaises ValidationError bird Bird name Helen Clark bird_duplicate Bird name Helen Clark bird full_clean bird save bird_duplicate full_clean bird_duplicate save
sets up the function to restore inception variables from checkpoint .,def setup_inception_initializer self if self mode inference saver tf train Saver self inception_variables def restore_fn sess tf logging info Restoring Inception variables from checkpoint file s self config inception_checkpoint_file saver restore sess self config inception_checkpoint_file self init_fn restore_fn
function for power on / off tradfri lightbulb,def tradfri_power_group hubip apiuser apikey groupid value tradfriHub coaps 5684 15004 format hubip groupid if value on payload 5850 1 else payload 5850 0 api m put u k e format coap apiuser apikey payload tradfriHub if os path exists coap result os popen api else sys stderr write libcoap could not find libcoap n sys exit 1 return result
"set repeat mode . to repeat a single track , set both `` repeat `` and `` single `` . : class:`true ` the tracklist is played repeatedly . : class:`false ` the tracklist is played once .",def set_repeat self value options return self mopidy_request core tracklist set_repeat value value options
counts up all of the missed phones and syllables . returns : a dictionary with the total count of each phone missed,def count_all self dict_list self count_bigrams 0 0 self count_bigrams 0 1 self count_bigrams 1 0 self count_bigrams 1 1 count_freq for dictionary in dict_list for key in dictionary if key in count_freq count_freq key dictionary key else count_freq key dictionary key return count_freq
"since copying relations is so complex , leave this to the implementing class",def clone_relations self src_obj dst_obj pass
extract host and port from an url string,def fromURL self url if url lower startswith socket url url 9 try if in url url options url split 1 for option in options split if in option option value option split 1 else value None if option logging logging basicConfig self logger logging getLogger pySerial socket self logger setLevel LOGGER_LEVELS value self logger debug enabled logging else raise ValueError unknown option r option host port url split 1 port int port if not 0 port 65536 raise ValueError port not in range 0 65535 except ValueError as e raise SerialException expected a string in the form rfc2217 host port option option s e return host port
removes ourself from the bout and close all associated sockets .,def _remove_self self self conn close self stateq put die self bout remove_player self name
"given a command , mode , and a path string , return the path which",def which cmd mode os F_OK os X_OK path None def _access_check fn mode return os path exists fn and os access fn mode and not os path isdir fn if os path dirname cmd if _access_check cmd mode return cmd return None if path is None path os environ get PATH os defpath if not path return None path path split os pathsep if sys platform win32 if not os curdir in path path insert 0 os curdir pathext os environ get PATHEXT split os pathsep if any cmd lower endswith ext lower for ext in pathext files cmd else files cmd ext for ext in pathext else files cmd seen set for dir in path normdir os path normcase dir if not normdir in seen seen add normdir for thefile in files name os path join dir thefile if _access_check name mode return name return None
adds a user to the users file .,def add_user username chat_id logger logging getLogger if not USERS_FILE_PATH parent exists USERS_FILE_PATH parent mkdir parents True USERS_FILE_PATH touch users load_yaml_file USERS_FILE_PATH with USERS_FILE_PATH open mode w encoding utf 8 as users_file logger info Registering user s username is_new username not in users users username str chat_id users_file write yaml dump users default_flow_style False return is_new
"this server 's opinion about who the primary is , or none .",property def primary self return self _primary
"make typical names above shorter , while keeping recognizable",def env_shortname s s s replace NoFrameskip if s 10 Roboschool s s 10 i s rfind v if i 1 s s i return s lower
get the date create for a submission,def get_date_created self submission_id cursor self postgres_db cursor query SELECT inserted_at FROM submissions WHERE id format submission_id cursor execute query result cursor fetchone 0 cursor close return result
create necessary directories in a working directory for the mounts in the containers .,shared_task bind True throws HTTPError def do_docker_create self label parameters environment name image volumes memory_limit folders command for folder in folders try os makedirs folder 1533 except OSError if not os path isdir folder raise config configparser SafeConfigParser for section in parameters if not config has_section section config add_section section for key value in parameters section items if not key units if not config has_option section key config set map str section key value for folder in folders with open os path join folder input ini w as f config write f client Client base_url settings DOCKER_URL config client create_host_config binds volumes mem_limit memory_limit container client create_container image name name host_config config command command environment environment labels label container_id container get Id return container_id
execute / sends a capi ( command api ) command to eos .,def _run_eos_cmds self commands switch LOG info _LI Executing command on Arista EOS s commands try ret switch execute commands LOG info _LI Results of execution on Arista EOS s ret return ret except Exception msg _ Error occurred while trying to execute commands cmd s on EOS host s cmd commands host switch LOG exception msg
validate a domain by using the domain 's validation method .,def validate_domain domain hash_str _get_validation_hash domain validators WebDomain ROBOTSTXT url robots txt regex User agent hash_str r n r n Disallow WebDomain WEBSCANFILE url webscan html regex hash_str WebDomain METAFIELD url regex meta name os2webscanner content hash_str validator validators domain validation_method url urljoin domain root_url validator url r _do_request url if r is None return False match re search validator regex r re I return match is not None
create a private category on nodebb,def create self name label hidden 1 uid 1 kwargs payload name name label label _uid uid hidden hidden return self client post api v2 category private payload
did we find the search bar in the ui,def is_browser_on_page self return self q css self search_bar_selector present
add locale paths to settings for comprehensive theming .,def _add_theming_locales theme_locale_paths settings COMPREHENSIVE_THEME_LOCALE_PATHS for locale_path in theme_locale_paths settings LOCALE_PATHS path locale_path
checks that student answer requests submitted to track.views via get are correctly logged in the trackinglog db table,def test_get_answers_to_log self requests event my_event event_type my_event_type page my_page event json object event_type unichr 512 page my_page with mock patch dict django conf settings FEATURES ENABLE_SQL_TRACKING_LOGS True for request_params in requests response self client get reverse user_track request_params self assertEqual response status_code 200 self assertEqual response content success tracking_logs TrackingLog objects order_by dtcreated log tracking_logs 0 self assertEqual log event request_params event self assertEqual log event_type request_params event_type self assertEqual log page request_params page
collects any information that 's necessary to execute this transformer 's transform method .,classmethod def collect cls block_structure block_structure request_xblock_fields days_early_for_beta collect_merged_date_field block_structure transformer cls xblock_field_name start merged_field_name cls MERGED_START_DATE default_date DEFAULT_START_DATE func_merge_parents min func_merge_ancestors max
emits a settings changed event for each field that has changed .,def emit_field_changed_events instance user db_table excluded_fields None hidden_fields None def clean_field field_name value Prepare a field to be emitted in a JSON serializable format If field_name is a hidden field return None if field_name in hidden_fields return None if isinstance value Country if value code return value code else return None return value excluded_fields excluded_fields or hidden_fields hidden_fields or changed_fields getattr instance _changed_fields for field_name in changed_fields if field_name not in excluded_fields old_value clean_field field_name changed_fields field_name new_value clean_field field_name getattr instance field_name emit_setting_changed_event user db_table field_name old_value new_value if hasattr instance _changed_fields del instance _changed_fields
returns a boolean if any given named marketing links are configured .,def is_any_marketing_link_set names return any is_marketing_link_set name for name in names
test that theme templates are used instead of default templates .,with_comprehensive_theme test theme def test_template_override self resp self client get signin self assertEqual resp status_code 200 self assertContains resp Login Page override for test theme
go to the nested container page .,def go_to_nested_container_page self unit self go_to_unit_page container unit xblocks 1 go_to_container return container
"given a message ( either request or response ) , say whether it has a valid signature or not .",def has_valid_signature method headers_dict body_dict access_key secret_key _ expected_signature _ generate_signed_message method headers_dict body_dict access_key secret_key authorization headers_dict Authorization auth_token post_signature authorization split _ post_access_key auth_token split if post_access_key access_key log error Posted access key does not match ours log debug Their access s Our access s post_access_key access_key return False if post_signature expected_signature log error Posted signature does not match expected log debug Their sig s Expected s post_signature expected_signature return False return True
returns an iterator over all of the blocks in a course .,def iter_blocks course def visit block get child blocks yield block for child in block get_children for descendant in visit child yield descendant return visit course
return the note by note i d .,def _read self note_id notes self server get_all_notes result self server filter_by_id notes note_id if result self respond content result 0 else self respond 404 404 Not Found
"creates a div which identifies the aside , points to the original block , and writes out the json_init_args into a script tag .",def wrap_aside self block aside view frag context extra_data block id quote_slashes unicode block scope_ids usage_id url selector asideBaseUrl runtime class LmsRuntime if self request_token extra_data request token self request_token return self _wrap_ele aside view frag extra_data
return dictionary prepared with module content and type for indexing .,def index_dictionary self xblock_body super CapaDescriptor self index_dictionary capa_content re sub re compile solution solution script script style style a z hint a z hint re DOTALL re VERBOSE self data capa_content escape_html_characters capa_content capa_body capa_content capa_content display_name self display_name if content in xblock_body xblock_body content update capa_body else xblock_body content capa_body xblock_body content_type self INDEX_CONTENT_TYPE xblock_body problem_types list self problem_types return xblock_body
test staff user can search cohort and public content if selected from preview menu .,def test_cohorted_search_user_staff_masquerade_cohort_content self self _auto_auth self staff_user username self staff_user email False self _goto_staff_page set_staff_view_mode Student in self content_group_a self courseware_search_page search_for_term self visible_to_all_html assert self visible_to_all_html in self courseware_search_page search_results html 0 self courseware_search_page clear_search self courseware_search_page search_for_term self group_a_and_b_html assert self group_a_and_b_html in self courseware_search_page search_results html 0 self courseware_search_page clear_search self courseware_search_page search_for_term self group_a_html assert self group_a_html in self courseware_search_page search_results html 0 self courseware_search_page clear_search self courseware_search_page search_for_term self group_b_html assert self group_b_html not in self courseware_search_page search_results html 0
it should return ` num ` items .,def test_num self d make_date 2017 02 15 for i in range 2 6 c IndividualCreatorFactory pub PublicationFactory PublicationRoleFactory publication pub creator c role_name ReadingFactory create_batch i publication pub start_date d end_date d data most_read_creators_card num 3 self assertIn object_list data self assertEqual len data object_list 3
load data to the machine .,def load_to_machine self netlist controller self _routing_region build_routes minimise True sys_mem filter_mem routing_mem region_utils create_app_ptr_and_region_files netlist vertices_memory self _vertex self _sys_region self _filter_region self _routing_region None self _sys_region write_region_to_file sys_mem self _filter_region write_subregion_to_file filter_mem self _routing_region write_subregion_to_file routing_mem
"print out a useful , human readable summary",def write_test_summary self self write n n RESULT nTotal number of checks d self total self write Total number of checks passed d self passed self write Total number of mini checks d self written self write Total number of mini checks passed d self written_passed failure_message_list self get_failure_message_list if len failure_message_list 0 self write n FAILURE SUMMARY n for msg in failure_message_list self write msg
yield n successive chunks from l. source : http://stackoverflow.com/a/2130042,def chunks l n newn int len l n for i in xrange 0 n 1 yield l i newn i newn newn yield l n newn newn
"this test checks that remove_old_deps handles reverse dependencies properly during yum update . specifically , remove_old_deps should remove precisely the packages which are not required by any package currently installed or pending installation . two cases :",staticmethod def buildPkgs pkgs args pkgs installed_1 FakePackage dep1 1 0 0 noarch pkgs installed_1 yumdb_info reason dep pkgs installed_2 FakePackage dep2 1 0 0 noarch pkgs installed_2 yumdb_info reason dep pkgs installed_3 FakePackage pkg1 1 0 0 noarch pkgs installed_3 yumdb_info reason user pkgs installed_4 FakePackage dep3 1 0 0 noarch pkgs installed_4 yumdb_info reason dep pkgs installed_1 addRequiringPkg pkgs installed_2 pkgs installed_2 addRequiringPkg pkgs installed_3 pkgs installed_4 addRequiringPkg pkgs installed_2 pkgs installed_2 addRequiresPkg pkgs installed_1 pkgs installed_2 addRequiresPkg pkgs installed_4 pkgs installed_3 addRequiresPkg pkgs installed_4 pkgs installed_3 addRequiresPkg pkgs installed_2 pkgs update_2 FakePackage dep2 2 0 0 noarch pkgs update_2 addRequires dep1 EQ 0 1 0 pkgs update_3 FakePackage pkg1 2 0 0 noarch pkgs update_3 addRequires dep2 EQ 0 1 0 pkgs update_4 FakePackage pkg1 2 0 0 noarch pkgs update_4 addRequires dep1 EQ 0 1 0
"invokes callback that should return a ( request , response ) tuple . representing the soap request and response respectively . ps -- parsedsoap instance representing http body . request -- twisted.web.server.request",classmethod def processRequest cls ps kw resource kw resource request kw request method getattr resource wsa_ s _get_element_nsuri_name ps body_root 1 try req_pyobj rsp_pyobj method ps ps address request request except TypeError as ex log err ERROR service s is broken method MUST return request response self __class__ __name__ raise except Exception as ex log err failure when calling bound method raise return rsp_pyobj
return the repository origin remote url via the command line .,def get_repo_url repo_url str subprocess check_output git remote get url origin shell True repo_url repo_url repo_url index 1 3 return repo_url
github jedi - vim issue # 44,def test_keyword defs Script print goto_definitions if is_py3 assert d docstring for d in defs else assert defs assert Script import goto_assignments completions Script import 1 1 completions assert len completions 10 and if in c name for c in completions assert Script assert goto_definitions
see pull request # 684 for details .,def test_path_issues source from datetime import assert jedi Script source completions
move cursor forward # of chars,def moveForward self chars sys stdout write x1b str chars C
check if my ip is a tor exit node,def check_tortp myip exit if myip in exit ipaddress notify TorTP Congratulations TorTP is working s myip else notify TorTP Sorry TorTP is not working s myip sys exit 1 return myip
"sets up the command history , and starts regular autosaves .",def init_history self self history_manager HistoryManager shell self parent self hist_file self pytest_hist_file self configurables append self history_manager
creates a random fake repo statistics .,def get_fake_repo_statistics return number_of_loose_objects 127 number_of_loose_refs 15 number_of_pack_files 15 number_of_packed_objects 67 number_of_packed_refs 0 size_of_loose_objects 29466 size_of_packed_objects 9646
"checks for gcc , g++ and the dragonegg plugin .",def checkDragonegg self if not self checkDragoneggPlugin return False pfx if os getenv LLVM_GCC_PREFIX is not None pfx os getenv LLVM_GCC_PREFIX cc 0 1 gcc format self path pfx cxx 0 1 g format self path pfx return self checkCompilers cc cxx
builds an gravatar < img > tag from an user or email,def gravatar user_or_email size GRAVATAR_DEFAULT_SIZE alt_text css_class gravatar if hasattr user_or_email email email user_or_email email else email user_or_email try url escape get_gravatar_url email email size size except return return mark_safe img class css_class src src width width height height alt alt format css_class css_class src url width size height size alt alt_text
more than 3 neighbors dies .,def test_advance_overcrowding self start 1 1 1 1 1 1 1 1 1 end 1 0 1 0 0 0 1 0 1 b ConwayBoard board start b advance self assert_array_equal b board end
return a context manager that temporarily replaces the sys stream * stream_name * with a stringio and returns it .,contextlib contextmanager def captured_output self stream_name orig_stdout getattr sys stream_name setattr sys stream_name StringIO try yield getattr sys stream_name finally setattr sys stream_name orig_stdout
test that text wrapping matches internal extra options .,def test_SequenceWrapper_drop_whitespace_subsequent_indent WIDTH 10 as_subprocess def child t TestTerminal pgraph u join a ab abc abcd abcde abcdef abcdefgh abcdefghi abcdefghij abcdefghijk abcdefghijkl abcdefghijklm abcdefghijklmn abcdefghijklmno 4 pgraph_colored u join t color n 7 t bold ch if ch else for n ch in enumerate pgraph internal_wrapped textwrap wrap pgraph width WIDTH break_long_words False drop_whitespace True subsequent_indent u 3 my_wrapped t wrap pgraph width WIDTH drop_whitespace True subsequent_indent u 3 my_wrapped_colored t wrap pgraph_colored width WIDTH drop_whitespace True subsequent_indent u 3 assert internal_wrapped my_wrapped first_l internal_wrapped 0 last_l internal_wrapped 1 my_first_l my_wrapped_colored 0 my_last_l my_wrapped_colored 1 assert len first_l t length my_first_l assert len last_l t length my_last_l internal_wrapped my_wrapped_colored assert len internal_wrapped 1 t length my_wrapped_colored 1 assert len internal_wrapped len my_wrapped_colored child
convert a string to a long integer .,def str2long s if type s not in types StringType types UnicodeType raise ValueError the input must be a string l 0L for i in s l 8 l ord i return l
this fetches and updates server version,def _update_server_version self version VersionService self get_url self local_config get http_headers if disablesslcert in self command_dict version disable_ssl_cert_validation try content version get_server_version if content server_version content get versionNo log info zanata python client version s zanata server API version s self local_config get client_version server_version self remote_config update server_version server_version except UnAvaliableResourceException log info zanata python client version s self local_config get client_version log error Can not retrieve the server version server may not support the version service except UnavailableServiceError log error Service Temporarily Unavailable stop processing sys exit 1
todo : we should validate the parameter first,def __init__ self protected_settings public_settings self blobs self backup_metadata None self public_config_obj None self private_config_obj None self blobs None self customSettings None self snapshotTaskToken get the public configuration self commandToExecute public_settings get CommonVariables command_to_execute self taskId public_settings get CommonVariables task_id self locale public_settings get CommonVariables locale self logsBlobUri public_settings get CommonVariables logs_blob_uri self statusBlobUri public_settings get CommonVariables status_blob_uri self commandStartTimeUTCTicks public_settings get CommonVariables commandStartTimeUTCTicks self vmType public_settings get CommonVariables vmType if CommonVariables customSettings in protected_settings keys self customSettings protected_settings get CommonVariables customSettings self publicObjectStr public_settings get CommonVariables object_str if self publicObjectStr is not None and self publicObjectStr if sys version_info 3 decoded_public_obj_string base64 b64decode self publicObjectStr decoded_public_obj_string decoded_public_obj_string decode ascii else decoded_public_obj_string base64 standard_b64decode self publicObjectStr decoded_public_obj_string decoded_public_obj_string strip decoded_public_obj_string decoded_public_obj_string strip self public_config_obj json loads decoded_public_obj_string self backup_metadata self public_config_obj backupMetadata if self logsBlobUri is None or self logsBlobUri self logsBlobUri protected_settings get CommonVariables logs_blob_uri if self statusBlobUri is None or self statusBlobUri self statusBlobUri protected_settings get CommonVariables status_blob_uri if CommonVariables snapshotTaskToken in self public_config_obj keys self snapshotTaskToken self public_config_obj CommonVariables snapshotTaskToken elif CommonVariables snapshotTaskToken in protected_settings keys self snapshotTaskToken protected_settings get CommonVariables snapshotTaskToken first get the protected configuration self privateObjectStr protected_settings get CommonVariables object_str if self privateObjectStr is not None and self privateObjectStr if sys version_info 3 decoded_private_obj_string base64 b64decode self privateObjectStr decoded_private_obj_string decoded_private_obj_string decode ascii else decoded_private_obj_string base64 standard_b64decode self privateObjectStr decoded_private_obj_string decoded_private_obj_string strip decoded_private_obj_string decoded_private_obj_string strip self private_config_obj json loads decoded_private_obj_string self blobs self private_config_obj blobSASUri
"returns a tuple containing a file 's ( size ( int ) , mime type ( str ) , and hash ( str ) ) .",def redis_get_file_metadata request_or_response_id filepath is_update False data redis get _get_file_metadata_key request_or_response_id filepath is_update decode split data 0 int data 0 return tuple data
"uses the rmsprop update rule , which uses a moving average of squared gradient values to set adaptive per - parameter learning rates .",def rmsprop x dx config None if config is None config config setdefault learning_rate 0 01 config setdefault decay_rate 0 99 config setdefault epsilon 1e 08 config setdefault cache np zeros_like x next_x None cache config cache lr config learning_rate dc config decay_rate ep config epsilon cache cache dc 1 dc dx 2 next_x x lr dx np sqrt cache ep config cache cache return next_x config
"downloads the ' mushroom ' dataset , saving it to the output path specified and returns the data .",def load_mushroom data_path FIXTURES name mushroom data load_numpy name data_path data_path return data
wrapper function for passing cli arguments to the mhandler add_media ( ) function for processing .,def main deluge False config args Args get_arguments deluge handler MHandler config added handler add_media validated True args sys stdout write added return added
ensure that the status code is not 500 .,def evaluate_clause self app_container url http 0 1 _ah stop format app_container host 8080 r requests get url self assertIn r status_code _STATUS_CODES Request to _ah stop failed
\some comment @param bar : the parameter value . @type bar : its type .,def func bar some comment param bar The parameter value type bar Its type pass
"set of all ancestors of starts ( incl ) , but stop walk at stops ( excl )",def ancestorset self starts stops None raise NotImplementedError
overriding deleter decorator for the property,def deleter self fdel self fdel fdel return self
"given a list of template names , returns the first that can be loaded .",def select_template template_name_list for template_name in template_name_list try return get_template template_name except TemplateDoesNotExist continue raise TemplateDoesNotExist join template_name_list
"do a marginal optimization param : m : the specified cluster number return : ( z , o ) z : the matrix rep for cliques and clusters o : the matrix rep for nodes and cliques",def marginal_optimization self m self LOG debug Starting to merge marginals node_card self node_card jtree_in_node_index self jtree_in_node_index d self nodes_num n self cliques_num O self jt_rep log_p self log_p_func log_node_card np log node_card sum_log_node_card sum log_node_card M self construct_difference m prev_Z np random rand n m self LOG debug Optimization starting for i in range self max_iter self LOG debug The optimization iteration str i 1 tmp1 cvx sum_entries prev_Z axis 0 value tmp2 np log tmp1 1 sum_log_node_card tmp3 np dot prev_Z M Z cvx Variable n m t cvx Variable 1 m r cvx Variable objective cvx Minimize cvx log_sum_exp t self _lambda r constraints Z 0 Z np ones m 1 dtype int np ones n 1 dtype int r np ones 1 m m 1 2 dtype int 2 np ones 1 n dtype int cvx mul_elemwise tmp3 Z M cvx sum_entries tmp3 tmp3 axis 0 0 np ones 1 n dtype int Z 1 log_p Z t np dot log_node_card O Z tmp2 cvx mul_elemwise np power tmp1 1 np ones 1 n dtype int Z 0 prob cvx Problem objective constraints result prob solve solver SCS verbose False prev_Z 0 n 0 m Z value return prev_Z O
toggle between the list view and dashboard view .,def toggle_segment_view request u Toggle between the list view and dashboard view n n param request The http request n type request django http HttpRequest n returns A redirect to the original page n rtype django http HttpResponseRedirect n n if request user has_perm u wagtailadmin access_admin if request session u segment_view u dashboard request session u segment_view u list elif request session u segment_view u dashboard request session u segment_view u dashboard return HttpResponseRedirect request META get u HTTP_REFERER u return HttpResponseForbidden
clear contents of output window .,def OnClear self event self text_ctrl_output Clear
test that inexact integer powers are rounded in the right direction .,def test_pow_integer_direction random seed 1234 for prec in 10 53 200 for i in range 50 a random randint 1 prec 1 1 prec b random randint 2 100 ab a b assert to_int mpf_pow from_int a from_int b prec round_down ab assert to_int mpf_pow from_int a from_int b prec round_up ab
"v = [ -pi ,- pi+1/10 .. ,pi ]",def bench_R10 def srange min max step v min while max v 1 evalf 0 v append v 1 step return v 1 v srange pi pi sympify 1 10
reorder limits in a expression containing a sum or a product .,def reorder expr arg new_expr expr for r in arg if len r 2 raise ValueError r Invalid number of arguments index1 r 0 index2 r 1 if not isinstance r 0 int index1 expr index r 0 if not isinstance r 1 int index2 expr index r 1 new_expr new_expr reorder_limit index1 index2 return new_expr
shorten the length of a quantum circuit .,def random_reduce circuit gate_ids seed None from sympy utilities randtest import _randrange if not gate_ids return circuit if isinstance circuit Mul circuit circuit args ids flatten_ids gate_ids randrange _randrange seed while ids i randrange len ids id ids pop i if find_subcircuit circuit id 1 break else return circuit return replace_subcircuit circuit id
calculate and return all the legal pluggings ( mappings of labels to holes ) of this semantics given the constraints .,def pluggings self u n Calculate and return all the legal pluggings mappings of labels to n holes of this semantics given the constraints n record self _plug_nodes self top_hole self top_most_labels record return record
messagelistenerimpl correctly notify with handle .,def test_MarketListeners_notify_with_handle_success self p self _create_valid_plaintext_message test_handle signature test_signature l MessageListenerImpl self ws self db l notify p signature self db messages save_message assert_called_with 746573745f67756964 u test_handle test_pubkey u test_subject ORDER u test_message 10 test_avatar_hash signature False self ws push assert_called_with self _create_valid_message_json test_handle
should we run as a separate process ?,property def off_process self if not hasattr self _off_process print WTF format self type self return self _off_process
return true if the stream can be read from .,def readable self return True
get all the values assigned to this keyword .,def get_values self keyword default join_with None split_on None kw keyword lower if kw in self keywords vals kv value for kv in self lines if kv kw_lower kw else vals default if join_with is None return vals val_str join_with join vals if split_on is None return val_str else return val_str split split_on
plots the population pareto front in a 2-d graph,def plot_pareto_fronts self rgb 0 0 0 comp 0 1 symbol o size 6 fronts from numpy import linspace import matplotlib pyplot as plt if len comp 2 raise ValueError Invalid components of the objective function selected for plot p_dim self problem f_dimension if p_dim 1 raise ValueError Pareto fronts of a 1 dimensional problem cannot be plotted if not all c in range 0 p_dim for c in comp raise ValueError You need to select valid components of the objective function p_list self compute_pareto_fronts if len fronts 0 n len p_list consistent d n for d in fronts if consistent count False 0 raise ValueError Check your fronts list there seem to be not enough fronts p_list p_list idx for idx in fronts cl list zip linspace 0 9 if rgb 0 else 0 1 0 9 len p_list linspace 0 9 if rgb 1 else 0 1 0 9 len p_list linspace 0 9 if rgb 2 else 0 1 0 9 len p_list for id_f f in enumerate p_list for ind in f plt plot pop ind cur_f comp 0 pop ind cur_f comp 1 symbol color cl id_f markersize size x pop ind cur_f comp 0 for ind in f y pop ind cur_f comp 1 for ind in f tmp a b for a b in zip x y tmp sorted tmp key lambda k k 0 plt step c 0 for c in tmp c 1 for c in tmp color cl id_f where post return plt gca
check that adjusted scores are almost zero on random labels,def test_adjustment_for_chance n_clusters_range 2 10 50 90 n_samples 100 n_runs 10 scores uniform_labelings_scores adjusted_rand_score n_samples n_clusters_range n_runs max_abs_scores np abs scores max axis 1 assert_array_almost_equal max_abs_scores 0 02 0 03 0 03 0 02 2
"this method will get the packet , takes what does need to be taken and let the remaining go , so it returns two values . first value which belongs to this field and the second is the remaining which does need to be dissected with other "" field classes "" . @param pkt : holds the whole packet @param s : holds only the remaining data which is not dissected yet .",def getfield self pkt s cstream 1 if pkt underlayer name TCP cstream dissector check_stream pkt underlayer underlayer fields src pkt underlayer underlayer fields dst pkt underlayer fields sport pkt underlayer fields dport pkt underlayer fields seq s if not cstream 1 s cstream remain value ls s split length len ls if length 1 value command ls 0 if length 2 remain ls 1 value value Parameters remain return value else i 1 remain while i length if i 1 remain remain ls i else remain remain ls i i i 1 value value Parameters remain return value else return ls 0
gather all fields which ca n't be edited .,property def non_editable_metadata_fields self non_editable_fields super VerticalBlock self non_editable_metadata_fields non_editable_fields extend self fields due return non_editable_fields
called when the stopframerecorder menu entry is selected,def stopFrameRecorderCallback self self notifyModelTask STOPFRAMERECORDER
read .ann files and look up corresponding spans in .txt files : param textfolder : : return :,def readAnn textfolder data dev flist os listdir textfolder for f in flist if not f endswith ann continue f_anno open os path join textfolder f rU f_text open os path join textfolder f replace ann txt rU for l in f_text text l for l in f_anno anno_inst l strip n split t if len anno_inst 3 anno_inst1 anno_inst 1 split if len anno_inst1 3 keytype start end anno_inst1 else keytype start _ end anno_inst1 if not keytype endswith of keyphr_text_lookup text int start int end keyphr_ann anno_inst 2 if keyphr_text_lookup keyphr_ann print Spans don t match for anno l strip in file f
registers the given model with algolia engine .,def register self model index_cls AlgoliaIndex auto_indexing None u n Registers the given model with Algolia engine n n If the given model is already registered with Algolia engine a n RegistrationError will be raised n if self is_registered model raise RegistrationError u is already registered with Algolia engine format model if not issubclass index_cls AlgoliaIndex raise RegistrationError u should be a subclass of AlgoliaIndex format index_cls index_obj index_cls model self client self __settings self __registered_models model index_obj if isinstance auto_indexing bool and auto_indexing or self __auto_indexing post_save connect self __post_save_receiver model pre_delete connect self __pre_delete_receiver model logger info u REGISTER s model
"return the most - specific value for key along path , or default .",def find_config self path key default None trail path or while trail nodeconf self config get trail if key in nodeconf return nodeconf key lastslash trail rfind if lastslash 1 break elif lastslash 0 and trail trail else trail trail lastslash return default
"tests over the time period offset : offset - n to see if the pair reverts to the mean . specifically , we are doing this by testing at each closing price in this time period to see if the long position is higher than its sma at the same time the short position is below its sma .",def mean_reversion_test hd1 hd2 n 20 offset 20 hold_time 30 return_index False short_pos long_pos get_short_long hd1 hd2 n offset short_sma sma short_pos offset offset long_sma sma long_pos offset offset for i in xrange offset max offset hold_time 0 1 if short_pos close i short_sma and long_pos close i long_sma if return_index return i return 1 if return_index return i return 0
"checks whether existing ' main_vm ' fits the requirements , modifies it if needed and returns the vm object and guest_worker .",error_context context_aware def get_vm_with_worker self no_consoles 0 no_serialports 0 spread None quiet False vm self get_vm_with_ports no_consoles no_serialports spread quiet guest_worker qemu_virtio_port GuestWorker vm return vm guest_worker
"when the build is finished , we copy the javascript files ( if specified ) to the build directory ( the static folder )",def build_finished app exception if app config offline_skin_js_path is not None copy_static_entry path join app builder srcdir app config offline_skin_js_path path join app builder outdir _static app builder if app config offline_wavedrom_js_path is not None copy_static_entry path join app builder srcdir app config offline_wavedrom_js_path path join app builder outdir _static app builder
a soundspotter returns new audio based on target_file using source_files inputs : target - name of target media sources - list of file names of source media p - feature parameter dict [ features.defalt_params ( ) ] win - sequence of vectors size for temporal context [ 20 ] hop - number of vectors to advance per query [ 10 ] num_hits - number of matches to find per query vector [ 1 ] beta - stiffness coefficient for mixing based on distances [ 2.0 ] x - pre - computed features for target y - list of pre - computed features for sources outputs : y - new audio signal,def soundspotter target_file source_files p default_params win 20 hop 10 num_hits 1 beta 2 0 X None Y None X X if X is not None else extract_target_feature_sequences target_file p win hop Y Y if Y is not None else extract_source_feature_sequences source_files p win hop bounds _feature_list_to_bounds Y matches distances match_sequences X Y num_hits y reconstruct_audio matches distances bounds target_file source_files p win hop beta y isnan y 0 return y
add a name - value pair to the enumeration .,classmethod def add cls name value u attr cls value attr _name name setattr cls name attr
builds an argparse parser for docker client connection flags .,def docker_client_arg_parser docker_parser argparse ArgumentParser add_help False docker_parser add_argument docker url help The url of the docker demon docker_parser add_argument strict docker tls action store_true help Do not disable strict tls checks for the docker client mac os x only docker_parser add_argument timeout type int default 60 help Set the default timeout when interacting with the docker demon return docker_parser
checks if the used my_print_defaults tool supports login - paths .,def check_login_path_support self assert self _tool_path First the required MySQL tool must be found E g use method search_my_print_defaults_tool out_file tempfile TemporaryFile if self _verbosity 0 subprocess call self _tool_path help stdout out_file else null_file open os devnull w b subprocess call self _tool_path help stdout out_file stderr null_file out_file seek 0 help_output out_file read out_file close if login path in help_output return True else return False
"this command loads config.yaml and the current env - ironment , creates a single merged dict , and prints to stdout .",cli command click argument config_yaml click argument output_csv app_cli pass_context def run ctx config_yaml output_csv c app get_config_dict ctx config_yaml session requests_cache CachedSession cache_name cache backend sqlite expire_after seconds_to_cache all_df None for ticker in c config options covered_calls option Options ticker yahoo session session df option get_all_data df covered_calls_process_dataframe df if all_df is None all_df df copy deep True else all_df all_df append df covered_calls_csv_out output_csv all_df
refreshes an existing jwt by creating a new one that is a copy of the old except that it has a refrehsed access expiration .,app route refresh methods GET def refresh old_token guard read_token_from_header new_token guard refresh_jwt_token old_token ret access_token new_token return flask jsonify ret 200
plot cost as 3d and contour .,def plot_cost_3D x y costfunc mb_history None lim 10 0 N 250 ms np linspace lim lim N bs np linspace lim lim N cost np zeros N N for m_idx in range N for b_idx in range N cost m_idx b_idx costfunc x y ms m_idx bs b_idx fig plt figure fig set_tight_layout True ax1 fig add_subplot 1 2 1 projection 3d ax1 set_xlabel b ax1 set_ylabel m msgrid bsgrid np meshgrid ms bs surf ax1 plot_surface msgrid bsgrid cost cmap cm coolwarm ax2 fig add_subplot 1 2 2 ax2 contour msgrid bsgrid cost ax2 set_xlabel b ax2 set_ylabel m if mb_history ms bs zip mb_history plt plot bs ms rx mew 3 ms 5 plt show
ensure a ` no - monitoring ` flag in git yields false internally .,def test_is_monitored_negative self u response mock MagicMock response status_code 200 response text u monitoring no monitoring self consumer requests_session mock MagicMock self consumer requests_session get return_value response self consumer is_retired mock MagicMock self consumer is_retired return_value False package u php pecl timecop expected False actual self consumer is_monitored package self assertEquals expected actual
get the color pairs for the specified ` color_tag ` and ` context_color_tag ` .,def get_color_pair self color_tag context_color_tag None use_default True if isinstance color_tag string_types color_tag color_tag pairs list filter None self color_map get tag for tag in color_tag if not pairs and use_default pair self color_map get self default_color_tag if pair pairs pair if context_color_tag ctx_pair self get_color_pair color_tag context_color_tag use_default False if ctx_pair pairs ctx_pair 1 ctx_pair pairs return join x 0 for x in pairs join x 1 for x in reversed pairs
this procedure writes out each of the sources related to the repository,def __write_referenced_sources self handle repository self database get_repository_from_handle handle repository_handles handle for object_type handle in self database find_backlink_handles handle Source source_nbr 0 for source_handle in repository_handles src self database get_source_from_handle source_handle for reporef in src get_reporef_list if reporef ref repository handle source_nbr 1 self doc start_paragraph REPO Section title nbr s name s type s call s nbr source_nbr name src get_title type str reporef get_media_type call reporef get_call_number self doc write_text title self doc end_paragraph
loads freebase snapshot of proper noun entities .,def load_kb print Loading knowledge base snapshot __fb_dbp_file open DATA_DIR fb_dbp_snapshot txt r global KB_SNP_DBP for line in __fb_dbp_file cols line strip split t KB_SNP_DBP add cols 1 __fb_dbp_file close
shortcut the get the extension version .,property def version self return self ext get version None
"first var is title , second var is url context variable",def __init__ self vars self vars map Variable vars
args : app_config ( appconfig ) : * * options :,def handle_app_config self app_config options is_resource_pkg_installed False try import import_export resources is_resource_pkg_installed True except pass resource_file os path join app_config path resources py admin_file os path join app_config path admin py res_file_content admin_file_content has_resource_class options get resource and is_resource_pkg_installed for model in app_config get_models if not options get all if input Do you want to create for y n format model __name__ n continue if not res_file_content if os path exists resource_file with open resource_file as f res_file_content f read if not admin_file_content if os path exists admin_file with open admin_file as f admin_file_content f read if ADMIN_IMPORTS not in admin_file_content admin_file_content ADMIN_IMPORTS admin_file_content if not res_file_content t template Template RES_IMPORT_TEMPLATE res_file_content t render template Context dict app_name app_config name model_class model __module__ model __name__ if model_class not in res_file_content t template Template RES_CLASS_TEMPLATE res_file_content t render template Context dict model_name model __name__ model_class model_class if model __name__ not in admin_file_content tmpl ADMIN_CLASS_WITH_RES_TEMPLATE if has_resource_class else ADMIN_CLASS_TEMPLATE t template Template tmpl admin_file_content t render template Context dict model_name model __name__ if has_resource_class with open resource_file w as f f write res_file_content with open admin_file w as f f write admin_file_content
"takes in a list of documents and returns x , a matrix where each row is an example and each column is the mean word vector in that document .",def get_mean_word_vector self docs n len docs X np empty n self word_vec_len doc_vec np zeros self word_vec_len for idx doc in enumerate docs doc_vec reduce lambda x y x y token vector for token in self nlp doc doc_vec n X idx doc_vec return X
create a new mac_ssl object .,def __init__ self key msg None digestmod None if digestmod is None import md5 digestmod md5 if key None return self digestmod digestmod self outer digestmod new self inner digestmod new self digest_size digestmod digest_size ipad 6 40 opad 40 self inner update key self inner update ipad self outer update key self outer update opad if msg is not None self update msg
retrieve the given member in the given group .,def RetrieveMember self member_id group_id uri self _ServiceUrl member True group_id member_id return self _GetProperties uri
"initialize a new instance , passing the time and delay functions",def __init__ self timefunc _time delayfunc time sleep self _queue self _lock threading RLock self timefunc timefunc self delayfunc delayfunc
displays the program parameter list and usage information,def show_help stdout usage sys argv 0 f path stdout stdout option description stdout h help this text here stdout f digested file with model A positional data of PS stdout sys exit 1
"by calling : meth:`buffer_chunk ` as necessary , buffer data until reaching a size greater than or equal to the specified `` size `` , or until all available data is buffered .",def buffer_to self size if self _entityreader current_size self _fileobj_len while current_size size data raw_data self buffer_chunk current_size len data if not raw_data break
"run a command and return a tuple with ( stdout , stderr , exit_code )",def run_cmd app cmd os environ FLASK_APP app process subprocess Popen shlex split cmd stdout subprocess PIPE stderr subprocess PIPE stdout stderr process communicate return stdout stderr process wait
"get a random batch of data from the specified bucket , prepare for step .",def get_batch self data bucket_id encoder_size decoder_size self buckets bucket_id encoder_inputs decoder_inputs for _ in xrange self batch_size encoder_input decoder_input random choice data bucket_id encoder_pad data_utils PAD_ID encoder_size len encoder_input encoder_inputs append list reversed encoder_input encoder_pad decoder_pad_size decoder_size len decoder_input 1 decoder_inputs append data_utils GO_ID decoder_input data_utils PAD_ID decoder_pad_size batch_encoder_inputs batch_decoder_inputs batch_weights for length_idx in xrange encoder_size batch_encoder_inputs append np array encoder_inputs batch_idx length_idx for batch_idx in xrange self batch_size dtype np int32 for length_idx in xrange decoder_size batch_decoder_inputs append np array decoder_inputs batch_idx length_idx for batch_idx in xrange self batch_size dtype np int32 batch_weight np ones self batch_size dtype np float32 for batch_idx in xrange self batch_size if length_idx decoder_size 1 target decoder_inputs batch_idx length_idx 1 if length_idx decoder_size 1 or target data_utils PAD_ID batch_weight batch_idx 0 0 batch_weights append batch_weight return batch_encoder_inputs batch_decoder_inputs batch_weights
get a dict of grouped docs,def test_grouped_docs self r self solr query test_config SOLR_COLLECTION q group True group field id group ngroups True self assertEqual len r docs 10 self assertTrue doclist in r docs 0
"given an event , return the sample value . the default is for sensorevent . override if you have a different event definition .",def _event_to_val self evt return evt val
adds the passed entity and the specified fields to the queue .,def addQueue self sgEntity sgFields if not isinstance sgEntity ShotgunORM SgEntity raise TypeError expected an SgEntity got s sgEntity if not self __engineThread isAlive raise RuntimeError engine thread is not running try undoFields pullFields sgFields set sgFields for name field in sgEntity fields sgFields items pullFields append name field _SgField__isUpdatingEvent clear undoFields append field if len pullFields 0 return ShotgunORM LoggerQueryEngine debug qEng s addQueue qEng self ShotgunORM LoggerQueryEngine debug sgEntity sgEntity s sgEntity sgEntity ShotgunORM LoggerQueryEngine debug sgFields sgFields s sgFields pullFields with self pullFields set pullFields eq None t sgEntity type if self _entityQueue has_key t eq self _entityQueue t else eq self _entityQueue t eq valid False eqLen len eq if eqLen 0 entities weakref ref sgEntity q SgQueryJob t entities pullFields eq append q self _pendingQueries append q valid True elif eqLen 1 q eq 0 qEntities q entities if len qEntities 1 qEntity list qEntities 0 if qEntity sgEntity q fields update pullFields valid True if not valid for q in eq qFields q fields if len pullFields len qFields continue sharedFields pullFields qFields if len sharedFields 1 q entities add weakref ref sgEntity pullFields sharedFields if len pullFields 0 break if len pullFields 1 entities weakref ref sgEntity q SgQueryJob t entities pullFields eq append q self _pendingQueries append q self _qEvent set eq sort reverse True except Exception as e ShotgunORM LoggerQueryEngine error e for field in undoFields field _SgField__isUpdatingEvent set raise
whether this primitive is a dict that accepts arbitrary entries .,property def additionalProperties self if not hasattr self _swagger_definition additionalProperties return None return self _swagger_definition additionalProperties not in None False
method for sending call request on behalf of rest controller .,def call self method_name cctxt self client prepare version self API_VERSION topic self topic return cctxt call self method_name
normalize a mac address from the pypowervm format to the neutron format .,def norm_mac mac mac mac lower replace return join mac i i 2 for i in range 0 len mac 2
"perform a cluster action , e.g. reset - task .",def _action self cluster_id body url mgmt clusters s action cluster_id resp body self api client post url body body common check_for_exceptions resp body url
set the location of the keyboard cursor for the tableview .,def set_cursor self location
write ddl to truncate the specified ` table `,status_logger def truncate self table truncate_sql serial_key_sql super PostgresFileWriter self truncate table self f write n TRUNCATE table_name s n truncate_sql s n table_name table name truncate_sql truncate_sql if serial_key_sql self f write n serial_key_sql s n serial_key_sql serial_key_sql
": param logs : iterable of log lines ( without newlines ) : param fail_reason : str , description of failure or none if successful : param image_id : str , id of built container image : param annotations : dict , data captured during build step which should be annotated to openshift build : param labels : dict , data captured during build step which should be set as labels on openshift build : param skip_layer_squash : boolean , direct post - build plugins not to squash image layers for this build",def __init__ self logs None fail_reason None image_id None annotations None labels None skip_layer_squash False assert fail_reason is None or bool fail_reason If fail_reason provided can t be falsy assert bool fail_reason bool image_id Either fail_reason or image_id should be provided not both self _logs logs or self _fail_reason fail_reason self _image_id image_id self _annotations annotations self _labels labels self _skip_layer_squash skip_layer_squash
polls with a pub_date in the future should not be displayed on the index page .,def test_index_view_with_a_future_poll self create_poll question Future poll days 30 response self client get reverse polls index self assertContains response No polls are available status_code 200 self assertQuerysetEqual response context latest_poll_list
decorator to check xsrf token .,def xsrf_required func def xsrf_wrapper request args kwds if request method POST post_token request POST get xsrf_token if not post_token return HttpTextResponse Missing XSRF token status 403 account models Account current_user_account if not account return HttpTextResponse Must be logged in for XSRF check status 403 xsrf_token account get_xsrf_token if post_token xsrf_token xsrf_token account get_xsrf_token 1 if post_token xsrf_token msg u Invalid XSRF token if request POST msg extend u u However this was the data posted to the server u for key in request POST msg append u s s key request POST key msg extend u u 10 u Please reload the previous page and post again return HttpTextResponse u n join msg status 403 return func request args kwds return xsrf_wrapper
this is the environment implementation of : attr:`baseguideline.name ` . this must return a : ref:`type - string ` or `` none `` . the returned value will be normalized with : func:`normalizers.normalizeguidelinename ` .,def _get_name self self raiseNotImplementedError
returns ' < self.name > ' .,def __str__ self return s self name
return a bool value indicating wheather the sensor is in active or standby mode .,def GetMode self return MPL MPL3115A2_Mode
"this route proxies graphs returned by the graph module . the pnp4nagios / graphite image url have to be in the get attributes , encoded with urlencode . the graphs metamodule takes care of that . this route should not be usefull anywhere else .",def proxy_graph url app request GET get url try r requests get url if r status_code 200 logger error WebUI graph Image URL not found d s r status_code url app bottle response status r status_code app bottle response content_type application json return json dumps status ko message r content except Exception as e logger error WebUI graph exception s str e app bottle response status 409 app bottle response content_type application json return json dumps status ko message str e app response content_type str r headers content type app response set_header Cache Control public max age 300 return r content
connects scrolling detector to a scrolled window . detects scrolling when the vertical scrollbar adjustment value is changed,def connect_scrolled_window self adj self _scrolled_window get_vadjustment adj connect value changed self _value_changed_cb
downloads and analyzes a bunch of random wikipedia articles using online vb for lda .,def main batchsize 64 D 3300000 0 K 10 if len sys argv 2 documentstoanalyze int D batchsize else documentstoanalyze int sys argv 1 vocab file dictnostops txt readlines W len vocab olda onlineldavb OnlineLDA vocab K D 1 0 K 1 0 K 1024 0 0 7 for iteration in range 0 documentstoanalyze docset articlenames wikirandom get_random_wikipedia_articles batchsize gamma bound olda update_lambda docset wordids wordcts onlineldavb parse_doc_list docset olda _vocab perwordbound bound len docset D sum map sum wordcts print d rho_t f held out perplexity estimate f iteration olda _rhot numpy exp perwordbound if iteration 10 0 numpy savetxt lambda d dat iteration olda _lambda numpy savetxt gamma d dat iteration gamma
get the mark data for the free energy charts,memoize def get_marks return pipe os path join get_path marks yaml read_yaml
create and initialize a astroid function node,def build_function name args None defaults None flag 0 doc None args defaults args or defaults or func Function name doc func args argsnode Arguments argsnode args for arg in args argsnode args append Name argsnode args 1 name arg argsnode args 1 parent argsnode argsnode defaults for default in defaults argsnode defaults append const_factory default argsnode defaults 1 parent argsnode argsnode kwarg None argsnode vararg None argsnode parent func if args register_arguments func return func
gets llil generator for jump equal conditional jump : param src : source for comparison bpf_k or bpf_x : return : function to generate llil for je,def get_je_llil src def je_llil il inst src_il aluret_src_IL src il inst cond il compare_equal 4 il reg 4 a src_il return jc_il il inst cond return je_llil
test initial attributes of client .,pytest mark parametrize hmc_name hmc_version api_version fake hmc 2 13 1 1 8 def test_client_initial_attrs self hmc_name hmc_version api_version session FakedSession fake host hmc_name hmc_version api_version client Client session assert client session is session assert isinstance client cpcs CpcManager assert client cpcs session is session assert isinstance client metrics_contexts MetricsContextManager assert client metrics_contexts session is session assert client metrics_contexts client is client
description : run profiling on the target apk loaded,staticmethod def do_profiler args try from framework brains apk enumeration profiler import Profiler p Profiler globals apk p run_profiler except ImportError as e print t red 0 format datetime now Unable to import Profiler Logger run_logger e message
a mlp layer with activation layer and bn : param input_layer : input sym : param n_hidden : # of hidden neurons : param activation : the activation function : return : the symbol as output,def mlp_layer input_layer n_hidden activation None BN False l mx sym FullyConnected data input_layer num_hidden n_hidden if activation is not None l mx sym Activation data l act_type activation if BN l mx sym BatchNorm l return l
check if the host is virtualized with openvz .,def _is_vm_openvz root_path return os path exists os path join root_path proc vz
"returns a set of mount points that have the "" bind "" option by parsing /etc / mtab .",def _get_bound_mount_points self bound_points set if not self _mtab_file or not os path isfile self _mtab_file return bound_points file open self _mtab_file r for line in file try device mount_point filesystem options line split 4 mount_point codecs decode mount_point unicode_escape except ValueError continue if bind in options split bound_points add mount_point return bound_points
return the directory path where the client binaries are .,def get_bindir config None try bindir config bindir except AttributeError bindir None if bindir is None bindir os path dirname os path abspath sys argv 0 return bindir
submit a commandsequence to the server for simulation,def simulate self commands self checkServer if isinstance commands str xml commands elif isinstance commands CommandSequence xml commands getXML else raise Exception Expecting CommandSequence or XML text return self client simulateScan xml
return the tags linked in html .,def get_tags self entry u n Return the tags linked in HTML n try return format_html_join u u a href target blank a reverse u zinnia tag_detail args tag tag for tag in entry tags_list except NoReverseMatch return conditional_escape entry tags
"return the list of warnings associated with this request , or none if there are n't any",def get_warnings self if self warnings and len self warnings 0 return self warnings
"html display of db results . if ` columns ` is omitted , it 's autodetected ` rows ` should be a list of dicts .",def resultTableToHtml rows columns None ignore_columns if not rows return No rows columns columns or sorted rows 0 keys columns c for c in columns if c not in ignore_columns ret table border 1 tr join th s th c for c in columns tr for row in rows ret tr join td s td htmlStr row c for c in columns tr ret table br n return ret
get the exception matching the mysql error,def get_mysql_exception errno msg None sqlstate None try return _CUSTOM_ERROR_EXCEPTIONS errno msg msg errno errno sqlstate sqlstate except KeyError pass try return _ERROR_EXCEPTIONS errno msg msg errno errno sqlstate sqlstate except KeyError pass if not sqlstate return DatabaseError msg msg errno errno try return _SQLSTATE_CLASS_EXCEPTION sqlstate 0 2 msg msg errno errno sqlstate sqlstate except KeyError return DatabaseError msg msg errno errno sqlstate sqlstate
set parameter value on parameter server @param key : parameter key @type key : str @param val : parameter value @type val : xmlrpc legal value,def __setitem__ self key val with self _lock self target setParam rospy names get_caller_id rospy names resolve_name key val
downloads data from ec2 itself .,def downloadData regionsNames args from multiprocessing import Pool cpu_count pool Pool cpu_count print nTotal number of regions str len regionsNames for num name in enumerate regionsNames f pool apply_async getSpotPricesFromRegion args num name callback cbLogPrices if num len regionsNames 1 f get pool close pool join
a ' choices with data ' field given as a list,def test_choices_with_data_defined_as_list self spec Fields Name F Choices with data 1 2 res self _invalid_specification spec expected F Choices with data Must be a mapping self assertIn expected res
function called when you cancel delete nic confirmation dialog,def on_canceldialogdeletehostnic_clicked self widget data None self builder get_object dialogdeletehostnic hide
independent command for making this bot leave a room .,def leaveroom bot cmd params user room reply ReplyObject params bot removeSpaces params if not params params room title if bot leaveRoom params return reply response Leaving room r succeeded format r params return reply response Could not leave room r format r params
add a measurement function to this world .,def add_measurement self function self measurement_functions append function self measurements append
multiplys this vector with a scalar or a vector - list object .,def __imul__ self rhs if hasattr rhs __getitem__ xx yy rhs v self _v v 0 xx v 1 yy else v self _v v 0 rhs v 1 rhs return self
reads current user credentials from saved file,def get_cred self try store Storage os path join self _appdir gcal_credentials return store locked_get except self _log exception Failed to get google authentication credential return None
add information needed to train bounding - box regressors .,def add_bbox_regression_targets roidb assert len roidb 0 assert max_classes in roidb 0 Did you call prepare_roidb first num_images len roidb num_classes roidb 0 gt_overlaps shape 1 for im_i in range num_images rois roidb im_i boxes max_overlaps roidb im_i max_overlaps max_classes roidb im_i max_classes roidb im_i bbox_targets _compute_targets rois max_overlaps max_classes num_classes class_counts np zeros num_classes 1 cfg EPS sums np zeros num_classes 4 squared_sums np zeros num_classes 4 for im_i in range num_images targets roidb im_i bbox_targets for cls in range 1 num_classes cls_inds np where targets 0 cls 0 if cls_inds size 0 class_counts cls cls_inds size sums cls targets cls_inds 1 sum axis 0 squared_sums cls targets cls_inds 1 2 sum axis 0 means sums class_counts stds np sqrt squared_sums class_counts means 2 for im_i in range num_images targets roidb im_i bbox_targets for cls in range 1 num_classes cls_inds np where targets 0 cls 0 roidb im_i bbox_targets cls_inds 1 means cls if stds cls 0 0 roidb im_i bbox_targets cls_inds 1 stds cls return means ravel stds ravel
filter the queryset by the user of the request .,def get_queryset self return models Activity objects prefetch_related blocks select_related task user task__project task__project__customer filter user self request user
get names of the set flags,def test_get_bit_info self data 0 data constants FieldFlag BLOB data constants FieldFlag BINARY exp BINARY BLOB sort self assertEqual exp constants FieldFlag get_bit_info data sort
"raises badrequest if a participant id is invalid , or if the participant has a withdrawal status of no_use .",def validate_participant_id self session participant_id participant self get_with_session session participant_id if participant is None raise BadRequest Participant with ID d is not found participant_id raise_if_withdrawn participant return participant
this function opens up the window to view the table args : table ( dataframe ) : input pandas dataframe that should be displayed . edit_flag ( boolean ) : flag to indicate whether editing should be allowed . show_flag ( boolean ) : flag to indicate whether the window should be displayed,def view_table table edit_flag False show_flag True try from PyQt5 import QtWidgets except ImportError raise ImportError PyQt5 is not installed Please install PyQt5 to use GUI related functions in py_entitymatching em _viewapp QtWidgets QApplication instance if em _viewapp is None em _viewapp QtWidgets QApplication app em _viewapp datatable QtWidgets QTableWidget if edit_flag False datatable setEditTriggers QtWidgets QAbstractItemView NoEditTriggers datatable setRowCount len table index datatable setColumnCount len table columns for i in range len table index for j in range len table columns datatable setItem i j QtWidgets QTableWidgetItem str table iat i j list_col list table columns values datatable setHorizontalHeaderLabels list_col width min j 1 105 app desktop screenGeometry width 50 height min i 1 41 app desktop screenGeometry width 100 datatable resize width height datatable setWindowTitle Dataframe if show_flag datatable show em _viewapp QtWidgets QApplication instance if em _viewapp is None em _viewapp QtWidgets QApplication app em _viewapp app exec_ if edit_flag return datatable
toggles the background color for the exit speed frame,def _toggle_exit_speed_alert self alert_color if self exit_speed_color alert_color self exit_speed_color ColorScheme get_dark_background_translucent else self exit_speed_color alert_color
evaluate func repeatedly until it does not throw an assertion anymore or a timeout has been reached . returns the function value of the first successful function evaluation,def wait_for_it func timeout 10 steps 0 1 for i in range int timeout steps try return func except AssertionError pass time sleep steps return func
tests the fieldsanitizer.__str _ _ method .,def test__str__ self self assertEqual self fs __str__ field sanitizer styles
when posting we the response contains the contact i d and the status,def test_post_result_content self url reverse toggle enabled subdomain self writeitinstance slug self client login username self user username password fiera response self client post url data id self contact pk json_answer json loads response content self assertIn contact json_answer keys self assertEquals json_answer contact id self contact pk self assertFalse json_answer contact enabled response self client post url data id self contact pk json_answer json loads response content self assertTrue json_answer contact enabled
"bulk get similar terms for input expressions args : body , expressionoperation : the json encoded expression to be evaluated ( required ) context_id , int : the identifier of a context ( optional ) ( optional ) pos_type , str : part of speech ( optional ) ( optional ) get_fingerprint , bool : configure if the fingerprint should be returned as part of the results ( optional ) retina_name , str : the retina name ( required ) start_index , int : the start - index for pagination ( optional ) ( optional ) max_results , int : max results per page ( optional ) ( optional ) sparsity , float : sparsify the resulting expression to this percentage ( optional ) returns : array[term ]",def getSimilarTermsForBulkExpressionContext self retina_name body context_id None pos_type None get_fingerprint None start_index 0 max_results 10 sparsity 1 0 resourcePath expressions similar_terms bulk method POST queryParams headerParams Accept Application json Content Type application json postData None queryParams retina_name retina_name queryParams context_id context_id queryParams start_index start_index queryParams max_results max_results queryParams pos_type pos_type queryParams sparsity sparsity queryParams get_fingerprint get_fingerprint postData body response self apiClient _callAPI resourcePath method queryParams postData headerParams return term Term t for t in r for r in response json
: param other : uniformbindistributiontable : return : float,def __distance_to2_upper self other assert self upper other upper upper_bin_start self __getbinidx_raw other upper if self lower other upper else 0 upper fsum itertools islice self data upper_bin_start 1 len self data if upper_bin_start len self data upper self data upper_bin_start self __invstep self getbinupper upper_bin_start other upper return upper
add an empty dashboard to the given user 's account .,def add_empty_dashboard username password fqdn data json dumps widgets headers content type application json auth format username fqdn password url SERVER_URL api dashboards r requests post url data data headers headers auth auth r raise_for_status
"create an incident form . when the form is populated , the initial value of ` service_status ` is the worst status of the services involved .",def __init__ self args kwargs u Create an incident form When the form is populated the initial n value of service_status is the worst status of the services n involved super IncidentForm self __init__ args kwargs if self instance pk is not None and self instance services exists last_status self instance services latest u status status self fields u service_status initial last_status
test setting of incorrect value .,def test_set_incorrect self model ExampleModel some_object object with self assertRaises TypeError model datetime_field some_object
generates a results string from the last attribute selection .,property def results_string self return javabridge call self jobject toResultsString Ljava lang String
: param func : callable : param args : free params : param kwargs : named params : return whatever the func returns,def run_io_func_sync self func args kwargs None return self _io_executor apply func args kwargs
return a new sortedset with elements from the set and all * iterables*.,def union self iterables return self __class__ chain iter self iterables key self _key load self _load
get the list of nodes matching a query .,abc abstractmethod def find_nodes self query
@brief pull new frame and structured light ( sl ) frame from the stored video,def GetFrame self get_normal_frame_only False success frame self __vidcap read if success False raise TypeError Cannot pull new frame sl_frame self GetSLFrame self __frame_i 1 return frame sl_frame
determine interface through ' xintface ' heuristic tool,def det_interface log path out _ run_cmd os path join path xintface log_all True simple False intregexp re compile INTFACE s s D S s res intregexp search out if res return res group 1 else raise EasyBuildError Failed to determine interface output for xintface s out
"patch amber using ' update_amber ' tool , prior to applying listed patch files ( if any ) .",def patch_step self args kwargs if self cfg patchlevels latest cmd update_amber update for _ in range self cfg patchruns run_cmd cmd log_all True else for tree patch_level in zip AmberTools Amber self cfg patchlevels if patch_level 0 continue cmd update_amber update to s s tree patch_level for _ in range self cfg patchruns run_cmd cmd log_all True super EB_Amber self patch_step args kwargs
custom install procedure for trinity .,def install_step self version LooseVersion self version if version LooseVersion 2012 and version LooseVersion 2012 10 05 self inchworm self chrysalis self kmer self butterfly bwapluginver self cfg bwapluginver if bwapluginver self trinityplugin bwa s patched_multi_map bwapluginver if self cfg RSEMmod self trinityplugin RSEM mod cc os getenv CXX else self jellyfish inchworm_flags self inchworm run False chrysalis_flags self chrysalis run False cc os getenv CC cxx os getenv CXX lib_flags for lib in ncurses zlib libroot get_software_root lib if libroot lib_flags L s lib libroot if version LooseVersion 2 0 and version LooseVersion 3 0 regex_subs INCHWORM_CONFIGURE_FLAGS s s 1 s inchworm_flags CHRYSALIS_MAKE_FLAGS s s 1 s chrysalis_flags else regex_subs INCHWORM_CONFIGURE_FLAGS s s 1 s inchworm_flags CHRYSALIS_MAKE_FLAGS s s 1 s chrysalis_flags rsem MAKE s 1 CC s CXX s s CFLAGS_EXTRA s n cc cxx lib_flags lib_flags fastool MAKE s 1 CC s std c99 CFLAGS s CFLAGS n cc lib_flags apply_regex_substitutions Makefile regex_subs trinity_compiler None comp_fam self toolchain comp_family if comp_fam in toolchain INTELCOMP trinity_compiler intel elif comp_fam in toolchain GCC trinity_compiler gcc else raise EasyBuildError Don t know how to set TRINITY_COMPILER for s compiler comp_fam explicit_make_args if version LooseVersion 2 0 and version LooseVersion 3 0 explicit_make_args all plugins cmd make TRINITY_COMPILER s s trinity_compiler explicit_make_args run_cmd cmd self butterfly if not self cfg withsampledata try shutil rmtree os path join self cfg start_dir sample_data except OSError as err raise EasyBuildError Failed to remove sample data s err
connect to amqp server usgin blockingconnection .,def connect self try self connection pika BlockingConnection self _parameters self channel self connection channel LOGGER debug Connected except Exception as e LOGGER warning Could not connect to host r e self connect
"the template context processor that adds settings defined in ` settings_export ` to the context . if settings_export_variable_name is not set , the context variable will be ` settings ` .",def settings_export request variable_name getattr django_settings SETTINGS_EXPORT_VARIABLE_NAME settings return variable_name _get_exported_settings
computes the area of intersection of itself with another bb2d bounding box .,def intersection_area self other intersection_width max 0 0 min self xmax other xmax max self xmin other xmin intersection_height max 0 0 min self ymax other ymax max self ymin other ymin return float intersection_width intersection_height
instantiates the ` choleskyouterproduct ` bijector .,def __init__ self event_ndims 2 validate_args False name cholesky_outer_product self _graph_parents self _name name with self _name_scope init values event_ndims event_ndims ops convert_to_tensor event_ndims name event_ndims event_ndims tensor_util constant_value event_ndims if event_ndims is None or event_ndims not in 0 2 raise ValueError event_ndims must be a TF constant which is 0 or 2 self _static_event_ndims event_ndims super CholeskyOuterProduct self __init__ event_ndims event_ndims validate_args validate_args name name
creates a queue filled from a numpy array or pandas ` dataframe ` .,def enqueue_data data capacity shuffle False min_after_dequeue None num_threads 1 seed None name enqueue_input enqueue_size 1 num_epochs None with ops name_scope name if isinstance data np ndarray types dtypes int64 dtypes as_dtype data dtype queue_shapes data shape 1 get_feed_fn _ArrayFeedFn elif isinstance data collections OrderedDict types dtypes int64 dtypes as_dtype col dtype for col in data values queue_shapes col shape 1 for col in data values get_feed_fn _OrderedDictNumpyFeedFn elif HAS_PANDAS and isinstance data pd DataFrame types dtypes as_dtype dt for dt in data index dtype list data dtypes queue_shapes for _ in types get_feed_fn _PandasFeedFn else raise TypeError data must be either a numpy array or pandas DataFrame if pandas is installed got format type data __name__ if num_threads 1 and num_epochs is not None logging warning enqueue_data was called with num_epochs and num_threads 1 num_epochs is applied per thread so this will produce more epochs than you probably intend If you want to limit epochs use one thread if shuffle and num_threads 1 and num_epochs is not None logging warning enqueue_data was called with shuffle True num_threads 1 and num_epochs This will create multiple threads all reading the array dataframe in order adding to the same shuffling queue the results will likely not be sufficiently shuffled if not shuffle and num_threads 1 logging warning enqueue_data was called with shuffle False and num_threads 1 This will create multiple threads all reading the array dataframe in order If you want examples read in order use one thread if you want multiple threads enable shuffling if shuffle min_after_dequeue int capacity 4 if min_after_dequeue is None else min_after_dequeue queue data_flow_ops RandomShuffleQueue capacity min_after_dequeue dtypes types shapes queue_shapes seed seed else min_after_dequeue 0 queue data_flow_ops FIFOQueue capacity dtypes types shapes queue_shapes enqueue_ops feed_fns for i in range num_threads placeholders array_ops placeholder t for t in types enqueue_ops append queue enqueue_many placeholders seed_i None if seed is None else i 1 seed feed_fns append get_feed_fn placeholders data enqueue_size random_start shuffle seed seed_i num_epochs num_epochs runner fqr FeedingQueueRunner queue queue enqueue_ops enqueue_ops feed_fns feed_fns queue_runner add_queue_runner runner full math_ops cast math_ops maximum 0 queue size min_after_dequeue dtypes float32 1 0 capacity min_after_dequeue summary_name queue sfraction_over_ d_of_ d_full queue name min_after_dequeue capacity min_after_dequeue summary scalar summary_name full return queue
teardown any state that was previously setup with a call to setup_class .,classmethod def teardown_class cls print Hello from teardown
create the dictionary to hold the bipartite graph table .,def createDict self for g in self geneList for i in self targetList self table g i 0
decodes the event message to its status bits,def decode self event raise NotImplementedException
returns the path to the given object .,def obj_to_ref obj ref s s obj __module__ get_callable_name obj try obj2 ref_to_obj ref if obj obj2 raise ValueError except Exception raise ValueError Cannot determine the reference to s repr obj return ref
returns the filtered queryset based on the value provided in the query string and retrievable via ` self.value ( ) ` .,def queryset self request queryset if self value is not None calendar_user_id_list CalendarUserProfile objects values_list user_id flat True filter manager_id self value return queryset filter id__in calendar_user_id_list else return queryset
the command line arguments must be provided .,def test_commandLineRequired self opt tap Options self assertRaises UsageError opt parseOptions
l{threadedresolver.gethostbyname } returns a l{deferred } which fires with the value returned by the call to l{socket.gethostbyname } in the threadpool of the reactor passed to l{threadedresolver.__init__}.,def test_success self ip 10 0 0 17 name foo bar example com timeout 30 reactor FakeReactor self addCleanup reactor _stop lookedUp resolvedTo def fakeGetHostByName name lookedUp append name return ip self patch socket gethostbyname fakeGetHostByName resolver ThreadedResolver reactor d resolver getHostByName name timeout d addCallback resolvedTo append reactor _runThreadCalls self assertEqual lookedUp name self assertEqual resolvedTo ip reactor _clock advance timeout 1 self assertEqual reactor _clock calls
"the user record returned by i{getpwuid } , i{getpwnam } , and i{getpwall } has a length .",def test_recordLength self db self database username password uid gid gecos dir shell self getExistingUserInfo for entry in db getpwuid uid db getpwnam username db getpwall 0 self assertIsInstance len entry int self assertEqual len entry 7
check that c{_clearignores } ensures that previously ignored errors get captured .,def test_clearIgnores self self observer _ignoreErrors ZeroDivisionError self observer _clearIgnores f makeFailure self observer gotEvent message time time time isError 1 system failure f why None self assertEqual self observer getErrors f
handle a ' form feed ' byte - generally used to request a screen refresh / redraw .,def handle_FF self self terminal eraseDisplay self terminal cursorHome self drawInputLine
"returns a list of scripts for a twisted subproject ; this works in any of an svn checkout , a project - specific tarball .",def getScripts projname basedir scriptdir os path join basedir bin projname if not os path isdir scriptdir scriptdir os path join basedir bin if not os path isdir scriptdir return thingies os listdir scriptdir for specialExclusion in svn _preamble py _preamble pyc if specialExclusion in thingies thingies remove specialExclusion return filter os path isfile os path join scriptdir x for x in thingies
load a scenario into the workbench and fetch it using self.client,def load_scenario self xml view_name None student_id tester1 import workbench urls from workbench scenarios import SCENARIOS add_xml_scenario SCENARIOS clear add_xml_scenario test Test Scenario xml scenario_url scenario test if view_name scenario_url view_name scenario_url student_id student_id return self client get scenario_url
parses command - line arguments .,def parse_args self argv parser optparse OptionParser parser add_option n no site packages action store_true help Do not inherit packages from global Python install return parser parse_args argv 1 0
update plugin and then return updated result to user,def update self plugin_name values return self _patch plugins s plugin_name values plugin
receives the input given by the user from gen_payload.py,def ms_module exploit return 1 multi browser java_rhino nset target 1 2 windows browser ms11_050_mshtml_cobjectelement 3 windows browser adobe_flashplayer_flash10o 4 windows browser cisco_anyconnect_exec 5 windows browser ms11_003_ie_css_import 6 windows browser wmi_admintools 7 windows browser ms10_090_ie_css_clip 8 windows browser java_codebase_trust 9 windows browser java_docbase_bof 10 windows browser webdav_dll_hijacker 11 windows browser adobe_flashplayer_avm 12 windows browser adobe_shockwave_rcsl_corruption 13 windows browser adobe_cooltype_sing 14 windows browser apple_quicktime_marshaled_punk 15 windows browser ms10_042_helpctr_xss_cmd_exec 16 windows browser ms10_018_ie_behaviors 17 windows browser ms10_002_aurora 18 windows browser ms10_018_ie_tabular_activex 19 windows browser ms09_002_memory_corruption 20 windows browser ms09_072_style_object 21 windows browser ie_iscomponentinstalled 22 windows browser ms08_078_xml_corruption 23 windows browser ie_unsafe_scripting 24 multi browser firefox_escape_retval 25 windows browser mozilla_mchannel 26 auxiliary server browser_autopwn get exploit ERROR
constructs source for a landsat 8 image,def get_source image extent uri image sourceUri band_maps source 1 target name image filename index get_band_num image cell_size width image resolutionMeters height image resolutionMeters return Source uri band_maps cell_size
schedules a screen to replace the current one .,def replace_screen self ui_screen args None log debug Replacing screen s ui_screen try execute_new_loop self _screen_stack pop execute_new_loop except ScreenStackEmptyException raise ScreenStackEmptyException Switch screen is not possible when there is no screen scheduled screen ScreenData ui_screen args execute_new_loop self _screen_stack append screen self redraw
creates labels which represent the tree level of each node when generating option labels .,def label_from_instance self obj return u s s i self level_indicator getattr obj depth 1 smart_unicode obj obj depth
attempt to use an unsupported formatting flag,def test_format_response_unsupported_format response Response response __setstate__ _content field value with pytest raises ValueError as err format_response xml response assert not a supported format in str err value
builds a dictionary of all the messages available in a set of files .,def GetMessages file_protos for file_proto in file_protos _FACTORY pool Add file_proto return _FACTORY GetMessages file_proto name for file_proto in file_protos
: rtype list[str ] : return : the port list for this instance type,def getPorts self import params return self parsePortsConfig params mongod_ports
split a row of text into list of cells .,def _split_row self row border u if border if row startswith u row row 1 if row endswith u row row 1 return row split u
deploy the specified branch to the remote host .,def deploy branch master host censusreporter org sudo mkdir p s root_dir sudo chown www data www data s root_dir sudo apt get update sudo apt get install y git sudo apt get install y apache2 libapache2 mod wsgi sudo a2enmod wsgi sudo rm f etc apache2 sites enabled 000 default sudo rm f etc apache2 sites enabled s host sudo rm f etc apache2 sites available s host upload_template server apache2 site etc apache2 sites available s host use_sudo True context domainname host django_project_path s censusreporter code_dir django_static_path s censusreporter apps census static code_dir django_venv_path s lib python2 7 site packages virtualenv_dir sudo a2ensite s host sudo apt get install y python setuptools sudo easy_install pip sudo pip install virtualenv sudo virtualenv no site packages s virtualenv_dir sudo rm f s lib python2 7 site packages censusreporter pth virtualenv_dir append s lib python2 7 site packages censusreporter pth virtualenv_dir s censusreporter code_dir use_sudo True append s lib python2 7 site packages censusreporter pth virtualenv_dir s censusreporter apps code_dir use_sudo True append s bin activate virtualenv_dir export DJANGO_SETTINGS_MODULE config prod settings use_sudo True with settings warn_only True if sudo test d s code_dir failed sudo git clone git github com censusreporter censusreporter git s code_dir with cd code_dir sudo git pull origin s branch sudo source s bin activate pip install r requirements txt virtualenv_dir sudo chown www data www data R s s code_dir virtualenv_dir sudo echo flush_all nc localhost 11211 sudo service apache2 restart
returns the hermann - mauguin symbol for the spacegroup,property def symbol self return self hm
""" return value of address .",app route slave_ids 1 function_codes 1 2 addresses list range 0 10 def read_data_store slave_id function_code address return data_store address
"returns error bit of last reading . if this bit is set ( = 1 ) , there 's problem with the thermocouple - it can be damaged or loosely connected : return : error bit value",def error self return self _error
"returns true if monitor was added , otherwise false .",def addMonitor self monitorFriendlyName monitorURL url self baseUrl url newMonitor apiKey s self apiKey url monitorFriendlyName s monitorFriendlyName url monitorURL s monitorType 1 monitorURL url monitorAlertContacts s monitorAlertContacts url noJsonCallback 1 format json success response self requestApi url if success return True else return False
csv lists should remain sorted by mmsi .,pytest mark parametrize path _get_csv_lists def test_csv_list_sorted path with open path as f assert is_sorted _mmsi_reader f
"nested serializer gets the full object , but some field serializers need the actual model their data lives in , that is , the translation . we detect it here .",def to_representation self instance translation get_cached_translation instance ret OrderedDict for field in self _readable_fields try try attribute field get_attribute instance except WrongManager FieldDoesNotExist attribute field get_attribute translation except SkipField continue if attribute is None ret field field_name None else ret field field_name field to_representation attribute return ret
calculates probability of tier being a word tier,def word_probability average_duration mean 0 2465409 sd 0 03175723 return calculate_probability average_duration mean sd
do not show any output for an image that does not contain a barcode,def test_empty self res decode self empty self assertEqual res
evaluates an achievement for a given `` tracked_id `` . achievement can be an `` achievement `` class or a string of the name of an achievement class that has been registered with this tracker .,def evaluate self tracked_id achievement args kwargs achievement self achievement_for_id tracked_id achievement cur_level achievement current 0 achieved achievement achieved result achievement evaluate args kwargs self _backend set_level_for_id tracked_id achievement __class__ achievement current 0 self _check_signals tracked_id achievement cur_level achieved return result
returns the quad 's field at the distance z from the center,def getFuncValue self z if abs z self func getMaxX return 0 0 return self normalization self func getY abs z
computeing levenshtein distance by recursive : type src : string : type res : string : rtype cost : int,def levenshteinDistanceRecursive src res cost 0 if len src 0 return len res if len res 0 return len src if src 1 res 1 cost 0 else cost 1 return min levenshteinDistance src 1 res 1 levenshteinDistance src res 1 1 levenshteinDistance src 1 res 1 cost
test all partition tables are existing after upgrade by names,pytest mark parametrize pre post ptable_name ids pytest_ids ptable_name def test_positive_partition_tables_by_name pre post assert existence pre post
point all read operations on cdeep app to spoken database .,def db_for_read self model hints if model _meta app_label cdeep return cdeep return None
creates and archives all the .isolated files for the tests at once .,def archive_isolated_triggers isolate_server tree_isolated tests logging info archive_isolated_triggers s s tree_isolated tests tempdir tempfile mkdtemp prefix u run_swarming_tests_on_swarming_ try isolateds for test in tests test_name os path basename test isolated algo sha 1 command python test includes tree_isolated read_only 0 version 1 4 v os path join tempdir test_name isolated tools write_json v isolated True isolateds append v cmd isolateserver py archive isolate server isolate_server isolateds if logging getLogger isEnabledFor logging INFO cmd append verbose items i split for i in check_output cmd splitlines assert len items len tests assert all items i 1 endswith os path basename tests i isolated for i in xrange len tests return zip tests i 0 for i in items finally shutil rmtree tempdir
returns a list of all tests that match the given annotation filters .,def GetAnnotatedTests self annotation_filter_list return test for test in self GetTestMethods if self _IsTestMethod test and self _AnnotationsMatchFilters annotation_filter_list self GetTestAnnotations test
return list of expanded pattern strings .,def ExpandPattern pattern it return pattern replace x for x in it
validates the criteria matrix to ensure that the inputs are,def validate_input pairwise_matrix col_sums _log info Validating matrix random_index 0 0 0 0 58 0 9 1 12 1 24 1 32 1 41 1 45 1 49 roots for row in pairwise_matrix roots append math pow reduce operator mul row 1 1 0 5 root_sum sum roots priority_vec for item in roots priority_vec append item root_sum priority_row for i in range 0 len col_sums priority_row append col_sums i priority_vec i priority_row_sum sum priority_row consistency_index priority_row_sum len col_sums len col_sums 1 consistency_ratio consistency_index random_index len col_sums return consistency_ratio 0 5
setup the formatting and reporting level of the application log . : rtype : streamhandler,def init_console_log console_log_handler logging StreamHandler sys stdout console_log_handler setFormatter logging Formatter LOG_STRING_FORMAT LOG_DATE_FORMAT root_logger logging getLogger root_logger addHandler console_log_handler root_logger setLevel logging INFO logging getLogger vcr setLevel logging WARNING logging getLogger requests setLevel logging WARNING logging getLogger BaseHTTPServer setLevel logging WARNING logging getLogger test server setLevel logging INFO return console_log_handler
"> > > from hamcrest import not _ > > > allure_report = getfixture('allure_report_with_params')('--allure - severities = trivial ' ) > > > assert_that(allure_report , ... not_(has_test_case('test_method_with_normal_severity ' ) ) ... )",pytest allure severity pytest allure severity_level NORMAL def test_method_with_normal_severity self pass
ensure an already authenticated user is redirected,def test_register_authenticated self backend RegistrationBackend request request_factory_login self factory self user self assertEqual 302 backend create_view request status_code
returns a list of subscriptions that provide the product .,def get_product_subscriptions self prod results valid_ent for valid_ent in self sorter valid_entitlement_certs if prod in valid_ent products return results
this is called after the signal handlers have been set . you can override the default signal handlers if you like . more on that below .,def post_signal_setup self print postSignalSetup called in manager
"transform main activity , secondary activity and partners list in multi columns and translate column names .",def transform_and_translate_data json_data try data pd DataFrame columns atividade_principal data_situacao tipo nome telefone atividades_secundarias situacao bairro logradouro numero cep municipio uf abertura natureza_juridica fantasia cnpj ultima_atualizacao status complemento email efr motivo_situacao situacao_especial data_situacao_especial qsa data data append json_data ignore_index True except Exception as e logger error Error trying to transform and translate data logger error json_data raise e def decompose_main_activity value struct value if struct return pd Series struct 0 rename_axis code main_activity_code text main_activity else return pd Series index main_activity_code main_activity def decompose_secondary_activities value struct value if struct and struct 0 get text N xc3 xa3o informada new_attributes pd Series activity rename_axis code secondary_activity_ i_code index 1 text secondary_activity_ i index 1 for index activity in enumerate struct return pd concat new_attributes else return pd Series def decompose_partners_list value struct value if struct and len struct 0 new_attributes pd Series partner rename_axis nome_rep_legal partner_ i_legal_representative_name index 1 qual_rep_legal partner_ i_legal_representative_qualification index 1 pais_origem partner_ i_contry_origin index 1 nome partner_ i_name index 1 qual partner_ i_qualification index 1 for index partner in enumerate struct return pd concat new_attributes else return pd Series data data rename columns abertura opening atividade_principal main_activity atividades_secundarias secondary_activities bairro neighborhood cep zip_code complemento additional_address_details data_situacao_especial special_situation_date data_situacao situation_date efr responsible_federative_entity fantasia trade_name logradouro address motivo_situacao situation_reason municipio city natureza_juridica legal_entity nome name numero number situacao_especial special_situation situacao situation telefone phone tipo type uf state ultima_atualizacao last_updated data main_activity data main_activity fillna data secondary_activities data secondary_activities fillna data qsa data qsa fillna data pd concat data drop main_activity secondary_activities qsa axis 1 data main_activity apply decompose_main_activity data secondary_activities apply decompose_secondary_activities data qsa apply decompose_partners_list axis 1 return data
returns a dict of structural kernels . i have tried to make this as notationally similar to gough & thompson ( 1991 ) as possible .,def kernel ell nu eig fgong G 6 67232e 08 M R fgong glob 2 x eig 0 y1 eig 1 y2 eig 2 y3 eig 3 xi_r y1 R xi_h y2 R L2 if ell 0 else 0 0 xi_r r fgong var 1 0 m M np exp fgong var 1 1 P_0 fgong var 1 3 rho_0 fgong var 1 4 Gamma1 fgong var 1 9 c02 Gamma1 P_0 rho_0 Y 1 fgong var 1 5 fgong var 1 16 omega 2 0 np pi nu sigma np sqrt R 3 G M omega L2 ell ell 1 L np sqrt L2 m_0 4 np pi integrate P_0 r 2 r eta m_0 r 3 dxi_r_dr np hstack 0 0 np diff xi_r np diff r chi dxi_r_dr 2 xi_r r L2 eta r chi 0 0 0 drho_0_dr np hstack 0 0 np diff rho_0 np diff r rho drho_0_dr xi_r rho_0 chi psi 4 np pi G 2 ell 1 integrate rho r ell 2 r 1 ell 2 r L complement rho r 0 ell r ell 1 r dpsi_dr np hstack 0 0 np diff psi np diff r g_0 G m_0 r 2 I trapz rho_0 xi_r 2 L2 eta 2 r 2 r K_c2_rho rho_0 c02 chi 2 r 2 2 I sigma 2 K_rho_c2 K_c2_rho return c2 rho K_c2_rho K_rho_c2
convenience method that stops and removes running container,def stop_and_remove self self stop self remove
turn a signed request with an access key into a keystone token .,def authenticate self context auth_payload auth_context if not self oauth2_api raise exception Unauthorized _ s not supported self method access_token_id auth_payload access_token_id if not access_token_id raise exception ValidationError attribute oauth2_token target request headers context headers uri controller V3Controller base_url context context path http_method POST required_scopes all_info request_validator validator OAuth2Validator server oauth2_core Server request_validator body access_token access_token_id valid oauthlib_request server verify_request uri http_method body headers required_scopes if valid auth_context user_id oauthlib_request user return None else msg _ Could not validate the access token raise exception Unauthorized msg
can capture the response body with field renaming,def test_response_body_with_field_renaming self with self graph flask test_request_context g show_response_fields dict foo baz request_info RequestInfo self options test_func None request_info capture_response MagicMock data foo bar status_code 200 dct request_info to_dict assert_that dct is_ equal_to dict operation test_func method GET func test_func success True status_code 200 response_body dict baz bar
pipelines requests and returns responses .,def send_request_batch self requests q Queue Queue 100 def send for method params in requests rid self _next_id self _next_id 1 q put rid body jsonrpc 2 0 id rid method method params params self _send body q put None threading Thread target send start while True rid q get if rid is None break yield self read_message want lambda msg msg get id rid
this function will return true if we have the setting to use lots activated .,api model def check_group_lot self return self env res users has_group stock group_production_lot
"compute mean squared error versus ideal response across frequency band . h -- coefficients bands -- list of ( left , right ) tuples relative to 1==nyquist of passbands",def mse self h bands w H freqz h worN 1024 f w np pi passIndicator np zeros len w bool for left right in bands passIndicator f left f right Hideal np where passIndicator 1 0 mse np mean abs abs H Hideal 2 return mse
evaluates rosenblatt 's shifted histogram estimators for each point on the dataset ' data ' .,def rsh data points None data ma array data copy False if points is None points data else points np array points copy False ndmin 1 if data ndim 1 raise AttributeError The input array should be 1D only n data count r idealfourths data axis None h 1 2 r 1 r 0 n 1 0 5 nhi data None points None h sum 0 nlo data None points None h sum 0 return nhi nlo 2 0 n h
convert a list of primary keys to a json dict .,def field_pklist_to_json self model pks app_label model _meta app_label model_name model _meta model_name return app app_label model model_name pks list pks
samples a grasp from the root level .,def sample self depth_limit post_opt True return self sample_warm_start self root_node depth_limit post_opt post_opt
return a root name for a shared library .,def _LibraryRoot self rootfinder re match lib so os path basename self _native_library if rootfinder return rootfinder group 1 else return None
connect to host : port and request list of tabs return list of dicts of data about open tabs .,def find_tabs self response requests get http s s json self host self port self tablist json loads response text return self tablist
test for invalid submission of listen_type ' playing_now ' which contains timestamp ' listened_at ',def test_playing_now_with_ts self with open self path_to_data_file playing_now_with_ts json r as f payload json load f response self send_data payload self assert400 response self assertEqual response json code 400
this is used for an optimization that tells hadoop how many reduce tasks should be used for a hadoop job . by default we 'll tell hadoop to use the number of reduce slots in the cluster .,def default_parallel self if self cluster_size 1 0 return self cluster_size 1 mortartask NUM_REDUCE_SLOTS_PER_MACHINE else return 1
run the wx event loop by processing pending events only .,def inputhook_wx1 context try app wx GetApp if app is not None assert wx Thread_IsMain evtloop wx EventLoop ea wx EventLoopActivator evtloop while evtloop Pending evtloop Dispatch app ProcessIdle del ea except KeyboardInterrupt pass return 0
write a notebook to a file like object,def write self nb fp kwargs return fp write self writes nb kwargs
finish up all displayhook activities .,def finish_displayhook self sys stdout flush sys stderr flush if self msg content data self session send self pub_socket self msg ident self topic self msg None
ask a kernel to shut down by its kernel uuid,kernel_method def request_shutdown self kernel_id restart False
"if ' forward ' is true ( resp . false ) , proceed forwards ( resp . backwards ) through the line that contains ' position ' until an unmatched closing ( resp . opening ) parenthesis is found . returns a tuple containing the position of this parenthesis ( or -1 if it is not found ) and the number commas ( at depth 0 ) found along the way .",def _find_parenthesis self position forward True commas depth 0 document self _text_edit document char document characterAt position while category char Cc and position 0 if char and depth 0 commas 1 elif char if forward and depth 0 break depth 1 elif char if not forward and depth 0 break depth 1 position 1 if forward else 1 char document characterAt position else position 1 return position commas
get the contents of a file .,def get_contents_if_file contents_or_file_name try if parse urlparse contents_or_file_name scheme definition_url contents_or_file_name else path os path abspath contents_or_file_name definition_url parse urljoin file request pathname2url path return request urlopen definition_url read decode utf8 except Exception return contents_or_file_name
add the ` six.moves ` module as a dynamically defined runtime module node and all modules mapped by ` six._sixmetapathimporter ` as aliased module nodes to the passed graph .,def pre_safe_import_module api real_to_six_module_name eval_statement import six print Iterate over the six _moved_attributes list rather than the six _importer known_modules dictionary as urllib specific moved modules are overwritten in the latter with unhelpful LazyModule objects for moved_module in six _moved_attributes If this is a moved module or attribute map the corresponding module In the case of moved attributes the attribute s module is mapped while the attribute itself is mapped at runtime and hence ignored here if isinstance moved_module six MovedModule six MovedAttribute print r r moved_module mod six moves moved_module name print api add_runtime_package api module_name for real_module_name six_module_name in real_to_six_module_name items api add_alias_module real_module_name six_module_name
prints the pozyx 's position and possibly sends it as a osc packet,def printPublishPosition self position network_id self remote_id if network_id is None network_id 0 print POS ID x mm pos x y mm pos y z mm pos z format 0x 0 4x network_id pos position if self osc_udp_client is not None self osc_udp_client send_message position network_id int position x int position y int position z
locate the given ` mark ' in ` payload ' and return its index .,def locateMark mark payload index payload find mark 0 const MAX_PADDING_LENGTH const MARK_LENGTH if index 0 log debug Could not find the mark just yet return None if len payload index const MARK_LENGTH const HMAC_SHA256_128_LENGTH log debug Found the mark but the HMAC is still incomplete return None log debug Successfully located the mark return index
send all the extended orport commands we want to send .,def _send_ext_orport_commands self self _write_ext_orport_command EXT_OR_CMD_TB_USERADDR s s self peer_addr host self peer_addr port self _write_ext_orport_command EXT_OR_CMD_TB_TRANSPORT s self transport_name self _write_ext_orport_command EXT_OR_CMD_TB_DONE
determine file type from file location,def determine_type self file if file find left 1 return 0 0 1 elif file find right 1 return 0 1 0 elif file find forward 1 return 1 0 0 else print Unknown image type file return 0 0 0
check validity of an ip address,def is_valid_ip ip_address valid True try socket inet_aton ip_address strip except valid False return valid
pauses test execution until user clicks ` ok ` button .,def pause_execution message Test execution paused Press OK to continue MessageDialog message show
expects a valid path to a .torrent file or a hex - encoded infohash . returns a binary infohash .,def infohash_from_infohash_or_path x if not len x 40 return infohash_from_path x n parse_infohash x if n return n return infohash_from_path x
insert data into the excerpt table,def insert_into_excerpt self data self _insert_into_table excerpt data
find all the pages in the lookup table that are identifed by the args and invalidate the / any cache for them .,def bulk_invalidate lookup_identifier supplementary_identifier None relevant_records CachedPageRecord objects filter parent_identifier lookup_identifier if supplementary_identifier relevant_records relevant_records filter supplementary_identifier supplementary_identifier keys_to_delete record base_cache_key for record in relevant_records logging info Bulk invalidation of these keys s str keys_to_delete nginx_cache delete_many keys_to_delete
returns an instance of the activity storage,classmethod def get_activity_storage cls options options serializer_class cls activity_serializer options activity_class cls activity_class if cls activity_storage_class is not None activity_storage cls activity_storage_class options return activity_storage
check that same user is not being added as a hacker to a hackathon again,def validate self data if self instance is None unique_check Hacker objects filter user_id data user id hackathon_id data hackathon id if len unique_check 0 raise serializers ValidationError A User cannot be added as a Hacker to the same Hackathon again return data
get all host templates in a cluster . @param cluster_name : cluster name . @return : apilist of apihosttemplate objects for all host templates in a cluster . @since : api v3,def get_all_host_templates resource_root cluster_name default return call resource_root get HOST_TEMPLATES_PATH cluster_name ApiHostTemplate True api_version 3
trains a deep lstm model on the tiny shakespeare dataset .,def train num_training_iterations report_interval reduce_learning_rate_interval graph_tensors dataset_train build_graph lstm_depth FLAGS lstm_depth batch_size FLAGS batch_size num_embedding FLAGS num_embedding num_hidden FLAGS num_hidden truncation_length FLAGS truncation_length sample_length FLAGS sample_length max_grad_norm FLAGS max_grad_norm initial_learning_rate FLAGS learning_rate reduce_learning_rate_multiplier FLAGS reduce_learning_rate_multiplier optimizer_epsilon FLAGS optimizer_epsilon saver_hook _configure_saver FLAGS checkpoint_dir FLAGS checkpoint_interval with tf train SingularMonitoredSession hooks saver_hook checkpoint_dir FLAGS checkpoint_dir as sess start_iteration sess run graph_tensors global_step for train_iteration in range start_iteration num_training_iterations if train_iteration 1 report_interval 0 train_loss_v valid_loss_v _ sess run graph_tensors train_loss graph_tensors valid_loss graph_tensors train_step train_generated_string_v sess run graph_tensors train_generated_string train_generated_string_human dataset_train to_human_readable train_generated_string_v 0 indices 0 tf logging info d Training loss f Validation loss f Sample s train_iteration train_loss_v valid_loss_v train_generated_string_human else train_loss_v _ sess run graph_tensors train_loss graph_tensors train_step tf logging info d Training loss f train_iteration train_loss_v if train_iteration 1 reduce_learning_rate_interval 0 sess run graph_tensors reduce_learning_rate tf logging info Reducing learning rate test_loss sess run graph_tensors test_loss tf logging info Test loss f test_loss
plot the mean tally value against all sampled detector data .,magicPlotDocDecorator def spreadPlot self xdim None fixed None ax None xlabel None ylabel None logx False logy False loglog False autolegend True if self allTallies is None raise SamplerError Data from all sampled files has been freed and cannot be used in this plot method samplerData self slice fixed tallies slices self _getSlices fixed if len samplerData shape 1 raise SerpentToolsException Data must be constrained to 1D not format samplerData shape xdata autoX self _getPlotXData xdim samplerData xlabel xlabel or autoX ax ax or pyplot axes N self _index allTallies self allTallies copy order F for n in range N plotData allTallies n slices ax plot xdata plotData SPREAD_PLOT_KWARGS ax plot xdata samplerData label Mean value N format N if autolegend ax legend ax set_xlabel xlabel ax set_ylabel ylabel or Tally Data if loglog or logx ax set_xscale log if loglog or logy ax set_yscale log return ax
removes all the match records and from database .,def delete_matches db cursor connect cursor execute TRUNCATE matches db commit db close
should do all work with updating weights .,def updateModel self raise NotImplementedError
"close a websocket connection and wait for the server side . if we do n't wait here , there are sometimes leak warnings in the tests .",gen coroutine def close self ws ws close yield self close_future
parses host names from a comma - separated list or a filename .,def parse_hostnames_optional list_option file_option if bool list_option and bool file_option die Cannot specify both filename and list for the same option hostnames None if file_option hostnames _parse_hostname_file file_option elif list_option hostnames _parse_hostname_list list_option return hostnames
make sure we handle 404 exceptions properly : return :,def test_APIGet404 self with self assertRaises MissingException as e result APIGet programsd self assertTrue e exception message index 404 0
replace the solution button with the solution code .,def process_cell path cell modified False for cell_source_line in cell source m re match div id sol cell_source_line if m modified True solution_code get_cell_content_as_string cell solution_code solution_code split code pre 1 solution_code solution_code rsplit pre code n div maxsplit 1 0 cell cell_type code cell source Replaced by notebook preprocessor n solution_code cell outputs cell execution_count 0 return modified
copy dowload link to clipboard : param link : dowload link for file : return : none,def copy_to_clipboard link try pyperclip copy link except print There is no copy paste environment please install one of the following packages sudo apt get install sudo apt get install xclip print Link copied to clipboard
writes a histogram summary if possible .,def histogram name tensor family None def function tag scope gen_summary_ops write_histogram_summary context context summary_writer_resource training_util get_global_step tag tensor name scope return summary_writer_function name tensor function family family
updates the progress bar according to the parameter i. : param i : the progress of the process,def update self i assert self progress is not None self progress update i
this function purges a workflow i d from the output database .,def purge_wf_uuid_from_dashboard_database rundir output_db wfparams utils slurp_braindb rundir wf_uuid wfparams get wf_uuid None if wf_uuid is None return expunge delete_dashboard_workflow output_db wf_uuid
read the close value and clear currently_in_file,def set_close_val self assert self iwf currently_in_file self iwf currently_in_file None type object self iwf _get assert type h type self close_value object
test that ` get_config ` adds a url to a repo correctly .,def test_get_config_adds_url self config get_config yaml load DUMMY_CONFIG expect git github com davedash wheeljack git eq_ expect config repos wheeljack url
extra quantities given by the model .,jit def extra_quantities k a ecc_0 ecc_f inc_0 inc_f argp f beta_ beta ecc_0 ecc_f inc_0 inc_f argp V_0 circular_velocity_fast k a delta_V_ delta_V V_0 ecc_0 ecc_f beta_ t_f_ delta_V_ f return delta_V_ beta_ t_f_
"some punctuation characters break the search api 's query parsing if they 're not escaped . some punctuation characters break even if escaped . there 's no documentation as to which characters should be escaped and which should be completely removed , so to stop _ all _ errors , we remove all common punctuation to avoid brokenness .",def strip_special_search_characters string for char in string_module punctuation if char not in ALLOWED_PUNCTUATION string string replace char u return string
convert current screen to json objects,def screen_to_json self current_screen self peppy current_screen screen self peppy screens current_screen return self json_factory screen_to_json current_screen screen
"returns 0 or 1 based on whether there is cached data , returns 0 is cache data is stale",def isCached self return 0
"returns a forwardingdict with parent items of self , eg unrolled once .",property def parent self return self copy _attr_list self _attr_list 1
open a log file for writing,def __init__ self filename newfilename filename ii 0 while os path exists filename newfilename filename 3i ii ii 1 if newfilename filename os rename filename newfilename self outfile open filename w print Began logging at s time strftime M d Y H M S time localtime file self outfile
"get prilimenery file info . this includes record lengts , if records are packable ... etc .",def get_bfr_info bfr info_list section bfr next for record in section info_obj BUFRRecordInfo info_obj name record name info_obj unit record unit info_obj index record index try pdata pack_record record info_obj var_type pdata __class__ __name__ info_obj packable_2d True except RecordPackError as e info_obj packable_2d False info_obj var_type get_type record try info_obj max_length len record data except TypeError as e pass info_list append info_obj last_section section for section in bfr for record in section info_obj info_list record index if info_obj packable_1d try if True in record data last_section record index data info_obj packable_1d False except TypeError if record data last_section record index data info_obj packable_1d False try N len record data if N info_obj max_length info_obj max_length N if info_obj packable_2d pdata pack_record record if info_obj var_type is int info_obj var_type pdata __class__ __name__ except TypeError as e info_obj packable_2d False if info_obj var_type is int info_obj var_type record data __class__ __name__ except RecordPackError as e info_obj packable_2d False if info_obj var_type is int info_obj var_type get_type record last_section section bfr reset for info_obj in info_list info_obj dimension_length info_obj max_length info_obj dimension_name dim_ d info_obj max_length return info_list
return a list of display modes .,def getDisplayModes self obj modes Texture return modes
set the user interface locale strings .,def retranslateUi self self form setWindowTitle QtGui QApplication translate ship_tank Create a new tank None self widget QtGui QLabel ShipLabel setText QtGui QApplication translate ship_tank Ship None
: type root : treenode : rtype : int,def longestConsecutive self root return self longestConsecutive_helper root 10000 1
gets a properly - escaped link to the resource .,def get_resource_link resource return Markup u a href s target _blank s a url_for resourceview details_view id resource id escape resource name
- transforms the source and destination coordinates to sumo junctions id - resolves the routing demand by using a dijkstra algorithm - sends the route ( list of geographic coordinates ) back to the client,def processRouteRequest src destinations junctionsDict graphDict route first True if isJunction src src iter junctionsDict getJunctionId src 0 next srcJunction True else srcJunction False for dest in destinations if isJunction dest dest iter junctionsDict getJunctionId dest 1 next destJunction True else destJunction False try tmpRoute dijkstra shortestPath graphDict src dest except Exception as e Logger exception e return constants ROUTE_ERROR_CONNECTION None if first and srcJunction and tmpRoute tmpRoute pop 0 elif first and len tmpRoute 1 and tmpRoute 1 getOppositeEdge tmpRoute 0 tmpRoute pop 0 if destJunction and tmpRoute tmpRoute pop if not first tmpRoute pop 0 route extend tmpRoute first False if tmpRoute src tmpRoute 1 else src dest if len route 1 and route 2 getOppositeEdge route 1 route pop return 0 route
returns the first token in the previous line as token .,def GetFirstTokenInPreviousLine token first_in_line GetFirstTokenInSameLine token if first_in_line previous return GetFirstTokenInSameLine first_in_line previous return None
args : options : a runtime option class from optparse queue_maker : a factory method that returns objects implementing a queue interface ( put()/get ( ) ) .,def __init__ self options queue_maker self _options options self _queue_maker queue_maker self _topics
write the given package file into the given mtd partition .,def WriteRawImageUbifs self partition fn self script append assert package_extract_file fn s partition s img partition partition fn fn
"generate a sequence of ( sentence , metadata ) pairs .",def get_sentences iterable label_to_rel dict label rel for rel label in enumerate RELEVANCE_LABELS context lxml etree iterparse iterable events start end rel None for action elem in context if action start if elem tag in label_to_rel rel label_to_rel elem tag elif elem tag DOC metadata dict fromkeys DOCNO TARGET_QID ORIGINAL_DOCNO sentence_count 0 elif action end if elem tag SENTENCE sentence_count 1 yield unicode elem text id str sentence_count rel str rel docno metadata DOCNO qid metadata TARGET_QID original_docno metadata ORIGINAL_DOCNO elif elem tag in label_to_rel rel None elif elem tag DOC or elem tag ROOT pass else metadata elem tag elem text elem clear
"returns an iterator over data rows , i.e. dicts with column values .",def rows self for i in range self count row for k in self keys row k self k i yield row
"return selected cells as a list of tuples ( row , column ) .",def cells self return row col for col in self cols for row in self rows
get a keygrip of the primary gpg key of the specified user .,def gpg_version sp subprocess u args gpg_command u version output check_output args args sp sp line output split n 0 line line split 1 line line split 0 return line split v 1
add domain objects to the toctree dynamically .,def add_domain_to_toctree app doctree docname toc app env tocs docname for desc_node in doctree traverse addnodes desc try ref_id desc_node children 0 attributes ids 0 except KeyError IndexError as e app warn Invalid desc node s e continue try ref_text desc_node 0 attributes fullname split 1 split 0 except KeyError IndexError ref_text desc_node 0 astext split 1 split 0 parent_node _traverse_parent node desc_node objtypes addnodes desc nodes section if parent_node toc_reference _get_toc_reference app parent_node toc docname if toc_reference toc_insertion_point _traverse_parent toc_reference nodes bullet_list 1 if toc_insertion_point and isinstance toc_insertion_point 0 nodes bullet_list new_insert toc_insertion_point 0 to_add _build_toc_node docname anchor ref_id text ref_text new_insert append to_add else to_add _build_toc_node docname anchor ref_id text ref_text bullet True toc_insertion_point append to_add
deprecated . use `` pivot_table `` instead .,def pivot_annual series freq None msg pivot_annual is deprecated Use pivot_table instead warnings warn msg FutureWarning index series index year index year years algorithms unique1d year if freq is not None freq freq upper else freq series index freq if freq D width 366 offset np asarray index dayofyear 1 offset isleapyear year offset 59 1 columns lrange 1 367 elif freq in M BM width 12 offset np asarray index month 1 columns lrange 1 13 elif freq H width 8784 grouped series groupby series index year defaulted grouped apply lambda x x reset_index drop True defaulted index defaulted index droplevel 0 offset np asarray defaulted index offset isleapyear year offset 1416 24 columns lrange 1 8785 else raise NotImplementedError freq flat_index year years min width offset flat_index _ensure_platform_int flat_index values np empty len years width values fill np nan values put flat_index series values return DataFrame values index years columns columns
label a test as ' slow ' .,def slow t t slow True return t
return a list all python packages found within directory ' where ',classmethod def find cls where exclude include out cls _find_packages_iter convert_path where out cls require_parents out includes cls _build_filter include excludes cls _build_filter ez_setup __pycache__ exclude out filter includes out out filterfalse excludes out return list out
keeps the geos geometry in synch with the context .,property def _geom self gtag self gtag if gtag self _gtag or self _is_empty self empty self __geom__ n self factory self context 0 self context 1 self _gtag gtag return self __geom__
odd extension at the boundaries of an array,def odd_ext x n axis 1 if n 1 return x if n x shape axis 1 raise ValueError The extension length n d is too big It must not exceed x shape axis 1 which is d n x shape axis 1 left_end axis_slice x start 0 stop 1 axis axis left_ext axis_slice x start n stop 0 step 1 axis axis right_end axis_slice x start 1 axis axis right_ext axis_slice x start 2 stop n 2 step 1 axis axis ext np concatenate 2 left_end left_ext x 2 right_end right_ext axis axis return ext
normalize a description adding the platform byteorder .,def normalize_descr descr out for item in descr dtype item 1 if isinstance dtype str if dtype 0 not in onebyte dtype 1 1 if onebyte or dtype 0 in S V b dtype dtype else dtype byteorder dtype if len item 2 and np prod item 2 1 nitem item 0 dtype item 2 else nitem item 0 dtype out append nitem elif isinstance item 1 list l for j in normalize_descr item 1 l append j out append item 0 l else raise ValueError Expected a str or list and got s type item return out
get a random user agent string .,def get_random_user_agent return random choice user_agents_list
minimization of scalar function of one or more variables using a trust - region algorithm .,def _minimize_trust_region fun x0 args jac None hess None hessp None subproblem None initial_trust_radius 1 0 max_trust_radius 1000 0 eta 0 15 gtol 0 0001 maxiter None disp False return_all False callback None inexact True unknown_options _check_unknown_options unknown_options if jac is None raise ValueError Jacobian is currently required for trust region methods if hess is None and hessp is None raise ValueError Either the Hessian or the Hessian vector product is currently required for trust region methods if subproblem is None raise ValueError A subproblem solving strategy is required for trust region methods if not 0 eta 0 25 raise Exception invalid acceptance stringency if max_trust_radius 0 raise Exception the max trust radius must be positive if initial_trust_radius 0 raise ValueError the initial trust radius must be positive if initial_trust_radius max_trust_radius raise ValueError the initial trust radius must be less than the max trust radius x0 np asarray x0 flatten nfun fun wrap_function fun args njac jac wrap_function jac args nhess hess wrap_function hess args nhessp hessp wrap_function hessp args if maxiter is None maxiter len x0 200 warnflag 0 trust_radius initial_trust_radius x x0 if return_all allvecs x m subproblem x fun jac hess hessp k 0 while True try p hits_boundary m solve trust_radius except np linalg linalg LinAlgError as e warnflag 3 break predicted_value m p x_proposed x p m_proposed subproblem x_proposed fun jac hess hessp actual_reduction m fun m_proposed fun predicted_reduction m fun predicted_value if predicted_reduction 0 warnflag 2 break rho actual_reduction predicted_reduction if rho 0 25 trust_radius 0 25 elif rho 0 75 and hits_boundary trust_radius min 2 trust_radius max_trust_radius if rho eta x x_proposed m m_proposed if return_all allvecs append x if callback is not None callback x k 1 if m jac_mag gtol warnflag 0 break if k maxiter warnflag 1 break status_messages _status_message success _status_message maxiter A bad approximation caused failure to predict improvement A linalg error occurred such as a non psd Hessian if disp if warnflag 0 print status_messages warnflag else print Warning status_messages warnflag print Current function value f m fun print Iterations d k print Function evaluations d nfun 0 print Gradient evaluations d njac 0 print Hessian evaluations d nhess 0 result OptimizeResult x x success warnflag 0 status warnflag fun m fun jac m jac nfev nfun 0 njev njac 0 nhev nhess 0 nit k message status_messages warnflag if hess is not None result hess m hess if return_all result allvecs allvecs return result
get a list of names for the scales on this dimension .,def keys self with phil return key for key _ in self items
checks whether a tree ensemble has been initialized .,def tree_ensemble_is_initialized_op tree_ensemble_handle name None _ctx _context context if _ctx in_graph_mode _ _ _op _op_def_lib _apply_op_helper TreeEnsembleIsInitializedOp tree_ensemble_handle tree_ensemble_handle name name _result _op outputs _inputs_flat _op inputs _attrs None else tree_ensemble_handle _ops convert_to_tensor tree_ensemble_handle _dtypes resource _inputs_flat tree_ensemble_handle _attrs None _result _execute execute TreeEnsembleIsInitializedOp 1 inputs _inputs_flat attrs _attrs ctx _ctx name name _execute record_gradient TreeEnsembleIsInitializedOp _inputs_flat _attrs _result name _result _result return _result
extract the subgraph that can reach any of the nodes in ' dest_nodes ' .,tf_export graph_util extract_sub_graph def extract_sub_graph graph_def dest_nodes if not isinstance graph_def graph_pb2 GraphDef raise TypeError graph_def must be a graph_pb2 GraphDef proto if isinstance dest_nodes six string_types raise TypeError dest_nodes must be a list name_to_input_name name_to_node name_to_seq_num _extract_graph_summary graph_def _assert_nodes_are_present name_to_node dest_nodes nodes_to_keep _bfs_for_reachable_nodes dest_nodes name_to_input_name nodes_to_keep_list sorted list nodes_to_keep key lambda n name_to_seq_num n out graph_pb2 GraphDef for n in nodes_to_keep_list out node extend copy deepcopy name_to_node n out library CopyFrom graph_def library out versions CopyFrom graph_def versions return out
"draw an image into the specified rectangle . if width and height are omitted , they are calculated from the image size . also allow file names as well as images . this allows a caching mechanism",def drawInlineImage self canvas preserveAspectRatio False anchor sw width self width height self height if width 1e 06 or height 1e 06 return False x y self width self height scaled aspectRatioFix preserveAspectRatio anchor self x self y width height self imgwidth self imgheight if not canvas bottomup y y height canvas _code append q s 0 0 s cm fp_str self width fp_str self height x y for line in self imageData canvas _code append line canvas _code append Q return True
selected confidence interval of the trimmed mean along the given axis .,def trimmed_mean_ci data limits 0 2 0 2 inclusive True True alpha 0 05 axis None data ma array data copy False trimmed mstats trimr data limits limits inclusive inclusive axis axis tmean trimmed mean axis tstde mstats trimmed_stde data limits limits inclusive inclusive axis axis df trimmed count axis 1 tppf t ppf 1 alpha 2 0 df return np array tmean tppf tstde tmean tppf tstde
multi - dimensional fourier shift filter .,def fourier_shift input shift n 1 axis 1 output None input numpy asarray input output return_value _get_output_fourier_complex output input axis _ni_support _check_axis axis input ndim shifts _ni_support _normalize_sequence shift input ndim shifts numpy asarray shifts dtype numpy float64 if not shifts flags contiguous shifts shifts copy _nd_image fourier_shift input shifts n axis output return return_value
concatenate small gradient tensors together for reduction .,def pack_small_tensors tower_grads max_bytes 0 max_group 0 small_indices large_indices for idx g _ in enumerate tower_grads 0 if g dtype dtypes float32 and 4 g shape num_elements max_bytes small_indices append idx else large_indices append idx small_ranges small_singles extract_ranges small_indices range_size_limit max_group large_indices sorted large_indices small_singles num_gv len tower_grads 0 packing if small_ranges new_tower_grads for dev_idx gv_list in enumerate tower_grads assert len gv_list num_gv new_gv_list for r in small_ranges key d d dev_idx len new_gv_list new_gv_list append pack_range key packing gv_list r packing_var_placeholder for i in large_indices new_gv_list append gv_list i new_tower_grads append new_gv_list return new_tower_grads packing else return tower_grads None
convert a unicode character code to a unicode character . ( directive option conversion function . ),def unicode_code code Convert a Unicode character code to a Unicode character Directive option conversion function Codes may be decimal numbers hexadecimal numbers prefixed by 0x x x U u or u e g U 262E or XML style numeric character entities e g x262E Other text remains as is Raise ValueError for illegal Unicode code values try if code isdigit return unichr int code else match unicode_pattern match code if match value match group 1 or match group 2 return unichr int value 16 else return code except OverflowError as detail raise ValueError code too large s detail
"adjust the h , s , v channels of an image by a constant ammount . this is similar to the add ( ) mixer function , but operates over the entire image at once . thus all three additive values , h , s , v , must be supplied simultaneously .",def hsv_add self h_amt s_amt v_amt pool ThreadDispatch self img self stateimg _colormixer hsv_add h_amt s_amt v_amt pool run
"build , register and upload to pypi",task def upload local python setup py sdist register upload
"( ? : \,)|(?:""\,"")|(?:'\ , ' )",def t_COMMA t t lexer begin ipunchecked return t
steps through css rules and applies each to all the proper elements as @style attributes prepending any current @style attributes .,def _apply_styles self rules self stylesheet cssRules rulesOfType 1 elem_prop_map elem_style_map for rule in rules selectors rule selectorText split elements for selector in selectors elements select self soup selector for elem in elements if elem not in elem_prop_map elem_prop_map elem elem_prop_map elem append specificity self _get_rule_specificity rule props rule style getProperties for elem props in elem_prop_map items if elem not in elem_style_map elem_style_map elem cssutils css CSSStyleDeclaration props sorted props key lambda p p specificity for prop_list in map lambda obj obj props props for prop in prop_list elem_style_map elem prop name prop value for elem style_declaration in elem_style_map items if elem has_key style elem style u s s style_declaration cssText replace n elem style else elem style style_declaration cssText replace n
unit test for updating a document,def test_update_one self self engine add_one self language self engine update_one self lookup name foobar data self engine get_one self lookup self assertIsNone data self engine delete_one foobar
helper function used by ` run ` .,def get_server_setting self protocol host 127 0 0 1 port 8000 debug False ssl None sock None workers 1 loop None backlog 100 has_log True if isinstance ssl dict cert ssl get cert or ssl get certificate key ssl get key or ssl get keyfile if cert is None or key is None raise ValueError SSLContext or certificate and key required context create_default_context purpose Purpose CLIENT_AUTH context load_cert_chain cert keyfile key ssl context server_settings protocol protocol request_handler self request_handler log self log netlog self netlog host host port port sock sock ssl ssl signal self signal debug debug request_timeout self request_timeout request_max_size self request_max_size keep_alive self keep_alive loop loop backlog backlog has_log has_log for event_name settings_name reverse in before_server_start before_start False after_server_start after_start False before_server_stop before_stop True after_server_stop after_stop True listeners self listeners event_name copy if reverse listeners reverse listeners partial listener self app for listener in listeners server_settings settings_name listeners if debug self log setLevel logging DEBUG if host and port proto http if ssl is not None proto https self log info Goin Fast format proto host port return server_settings
parses global protect users xml .,def parse_globalprotect_users self user_count 0 vpn_users root ET fromstring self _gp_users nodes root findall result gp portal users user for user in nodes user_count 1 vpn_users append user find username text if user_count 0 self _sensors gp_users join vpn_users else self _sensors gp_users None self _sensors gp_user_count user_count
ask the user a question and return the result,def ask_question question legal while 1 response int input question if response in legal return response print illegal input please input data within legal n
a parametrized vector class for state vectors mirroring that of pythonmultimapping,def Vec t class Vector Structure _fields_ data POINTER t outer c_size_t inner c_size_t def numpy self return np ctypeslib as_array as_buffer self data self outer self inner return Vector
helper function for initializing the bom if one was specified .,staticmethod def load_bom options bom_path options bom_path if hasattr options bom_path else None bom_version options bom_version if hasattr options bom_version else None have_bom_path 1 if bom_path else 0 have_bom_version 1 if bom_version else 0 if have_bom_path have_bom_version 1 raise_and_log_error ConfigError Expected exactly one of bom_path or bom_version if bom_path check_path_exists bom_path why options bom_path return BomSourceCodeManager bom_from_path bom_path if not bom_version raise_and_log_error UnexpectedError Not reachable cause NotReachable logging debug Retrieving bom version s bom_version return HalRunner options retrieve_bom_version bom_version
: type alert_path : str : type override_path : str : type state_path : str : type zk : kazoo.client.kazooclient : type pd : zoom.common.pagerduty.pagerduty : type exceptions : list,def __init__ self alert_path override_path state_path zk pd exceptions self _path alert_path self _override_path override_path self _state_path state_path self _zk zk self _pd pd self _exceptions exceptions self _threads list
"returns the object with the given ` i d ` . if ` connection ` is given , then get the object from the given connection ( otherwise use the default or configured connection )",def get id connection None
return the main index template .,login_required def index request status controller get_user_app_status request user if ui_mode in status status ui_mode UI_DESCRIPTIONS status ui_mode if src_domain in status status src_domain SRC_DOMAIN_DESCRIPTIONS status src_domain return render_to_response index html page_title Overview status status context_instance RequestContext request
add the given prefix to all the fields in the form .,def add_prefix form prefix dotted False def rename_func field_name if dotted if field_name return prefix field_name else return prefix else return prefix field_name return rename form rename_func
starts the seo sync thread .,app deploy def startSeoSyncThread self schedule scheduler time time time sleep def syncSeoBlogs self syncSeoBlogs schedule enter self sync_interval 1 syncSeoBlogs schedule enter self sync_interval 1 syncSeoBlogs scheduleRunner Thread name blog html for seo target schedule run scheduleRunner daemon True scheduleRunner start log info Started the seo html synchronization
helper method for converting sampled signal band into output bits .,staticmethod def convertBand band_samples return band_samples 0
test writing goatools goea results to a python module as a list of nts .,def test_wrpy nature_data get_goea_results goea_results nt for nt in nature_data goea_results if nt p_fdr_bh 0 05 nts_goea get_goea_nts_prt goea_results _run nts_goea next iter nts_goea _fields
"given line , return optional attribute synonym value in a namedtuple .",def _get_synonym self line mtch self attr2cmp synonym match line text scope typename dbxrefs _ mtch groups typename typename strip dbxrefs set dbxrefs split if dbxrefs else set return self attr2cmp synonym nt _make text scope typename dbxrefs
"given a geneid , return the string geneid or a gene symbol .",def __get_genestr self itemid if self id2symbol is not None symbol self id2symbol get itemid None if symbol is not None return symbol if isinstance itemid int return str itemid return itemid
decorator to turn a function into a loom op .,def as_loom_op inputs outputs name None if isinstance inputs loom TypeShape inputs inputs single_output isinstance outputs loom TypeShape if single_output outputs outputs def decorator f Decorator to turn a function into a loom op scope_name f __name__ if name is None else name with tf variable_scope None scope_name as scope class AsLoomOp loom LoomOp def __init__ self super AsLoomOp self __init__ inputs outputs self _reuse False def instantiate_batch self tensors with tf variable_scope scope reuse self _reuse self _reuse True tensors f tensors return tensors if single_output else tensors return AsLoomOp return decorator
"send out wall - following robots in all directions , to look for the next point in the guiding line",def _send_out_robots self solution guiding_line i ns self _find_unblocked_neighbors guiding_line i robot_paths for n in ns robot_path robot_path append guiding_line i robot_path append self _midpoint guiding_line i n robot_path append n robot_paths append robot_path for j path in enumerate robot_paths last_diff path 1 0 path 3 0 path 1 1 path 3 1 last_dir self directions index last_diff robot_paths j self _follow_walls last_dir path 1 path guiding_line i 1 robot_paths p for p in robot_paths if p is not None if len robot_paths 0 raise Exception No valid solution found shortest_robot_path robot_paths 0 min_len len shortest_robot_path for j path in enumerate robot_paths 1 if len path min_len shortest_robot_path path min_len len path solution shortest_robot_path 1 return guiding_line index solution 1
respond to a `` post `` request .,def challenge_post self environ start_response pass
"given text containing a list of recipes , calculate the recipe information they hold and return as a list of bagname , filter lists .",def _recipe_lines self body recipe_lines if len body lines body rstrip split n for line in lines if in line bag query_string line split filter_string query_string else bag line filter_string if bag startswith bags bagname bag split 2 bagname unquote bagname else bagname bag recipe_lines append bagname filter_string return recipe_lines
"` retcode ` is the return code to expect to mean "" success "" . set ` buffered ` to false to disable line - buffering the output , which may cause stdout and stderr to become more entangled than usual .",def __init__ self retcode 0 buffered True timeout None self retcode retcode self buffered buffered self timeout timeout
checks that the round - tripped string is the same as the original,def check_roundtrip self oosource assert self roundtripstring oosource oosource
computes exponential kde for each photon in ` ph ` .,def _kde_laplace_self ph tau ph_size ph size ipos ineg 0 0 rates np zeros ph_size dtype np float64 nph np zeros ph_size dtype np int16 tau_lim 5 tau for i t in enumerate ph while ipos ph_size and ph ipos t tau_lim ipos 1 while t ph ineg tau_lim ineg 1 delta_t np abs ph ineg ipos t rates i np exp delta_t tau sum nph i ipos ineg return rates nph
create a new spark configuration .,def __init__ self loadDefaults True _jvm None _jconf None if _jconf self _jconf _jconf else from pyspark context import SparkContext SparkContext _ensure_initialized _jvm _jvm or SparkContext _jvm self _jconf _jvm SparkConf loadDefaults
the input tuples are converted to python dicts for this function .,def python_dict_expected args kwargs return _function_decorator args kwargs input_conversion CascadingBaseOperationWrapper ConvertInputTuples PYTHON_DICT
end - point to receive mail from an external smtp server .,http route mail receive type json auth none def receive self req dbs req jsonrequest get databases for db in dbs message dbs db decode base64 try registry openerp registry db with registry cursor as cr mail_thread registry mail thread mail_thread message_process cr SUPERUSER_ID None message except psycopg2 Error pass return True
authenticated user should receive 403 ( denied ) on non - public pages .,def testPrivateAuthenticated self try self login public_views view for view _ in self views public self views authenticated for view args in chain from_iterable list self views values if view not in public_views self assertDenied view args finally self logout
the full pattern has a full set of event types :,def test_full_pattern_resource_types self rts self full_pattern get_resource_types self event_type self assertEqual rts count 1 self assertEqual rts 0 self twofacet_product rts self full_pattern get_resource_types self event_type_cite self assertEqual rts count 1 rts self full_pattern get_resource_types self event_type_use self assertEqual rts count 2 rts self full_pattern get_resource_types self event_type_consume self assertEqual rts count 1 rts self full_pattern get_resource_types self event_type_work self assertEqual rts count 1
verifies the status data is correct .,def test_status self resp self app get service v1 status json assert resp content_type application json result json loads resp data import datetime from victims web blueprints service_v1 import EOL assert result version 1 assert result recommended is False assert result eol EOL isoformat assert result supported datetime datetime now EOL assert result endpoint service v1
"write out a file of transcript->gene mappings . use the installed tx2gene.csv if it exists , else write a new one out",def tx2genefile gtf out_file None installed_tx2gene os path join os path dirname gtf tx2gene csv if file_exists installed_tx2gene return installed_tx2gene if file_exists out_file return out_file with file_transaction out_file as tx_out_file with open tx_out_file w as out_handle for k v in transcript_to_gene gtf items out_handle write join k v n return out_file
searches the provided modules for the named class and returns it .,def find_class_by_name name modules modules getattr module name None for module in modules return next a for a in modules if a
test function for the matplotlib gnuplot wrapper,def test_gnuplot_wrapper pl gnuplot_wrapper pl plot 1 2 3 label test123 pl savefig 123 png pl close pl gnuplot_wrapper pl subplot 2 2 1 pl plot 1 2 3 7 3 2 4 3 pl subplot 2 2 2 pl semilogx 1 2 34 0 1 2 3 label semilogx pl xlabel xxx1 pl subplot 2 2 3 pl semilogy 1 2 34 0 1 2 3 label semilogy pl semilogy 2 3 4 0 9 5 2 label semilogy2 pl ylabel yyy1 pl subplot 2 2 4 pl loglog 1 10 100 2 4 8 label loglog pl grid pl savefig 2x2_test png pl close
"cvc(i ) is true < = > i-2,i-1,i has the form consonant - vowel - consonant and also if the second c is not w , x or y. this is used when trying to restore an e at the end of a short e.g.",def cvc self i if i self k0 2 or not self cons i or self cons i 1 or not self cons i 2 return 0 ch self b i if ch w or ch x or ch y return 0 return 1
download setuptools from a specified location and return its filename,def download_setuptools version DEFAULT_VERSION download_base DEFAULT_URL to_dir os curdir delay 15 import urllib2 shutil egg_name setuptools s py s egg version sys version 3 url download_base egg_name saveto os path join to_dir egg_name src dst None if not os path exists saveto try from distutils import log if delay log warn This script requires setuptools version s to run even to display help I will attempt to download it for you from s but you may need to enable firewall access for this script first I will start the download in d seconds Note if this machine does not have network access please obtain the file s and place it in this directory before rerunning this script version download_base delay url from time import sleep sleep delay log warn Downloading s url src urllib2 urlopen url data _validate_md5 egg_name src read dst open saveto wb dst write data finally if src src close if dst dst close return os path realpath saveto
runs gtest_break_on_failure_unittest _ and verifies that it does ( or does not ) have a seg - fault .,def RunAndVerify self env_var_value flag_value expect_seg_fault SetEnvVar BREAK_ON_FAILURE_ENV_VAR env_var_value if env_var_value is None env_var_value_msg is not set else env_var_value_msg env_var_value if flag_value is None flag elif flag_value 0 flag s 0 BREAK_ON_FAILURE_FLAG else flag s BREAK_ON_FAILURE_FLAG command EXE_PATH if flag command append flag if expect_seg_fault should_or_not should else should_or_not should not has_seg_fault Run command SetEnvVar BREAK_ON_FAILURE_ENV_VAR None msg when s s an assertion failure in s s cause a seg fault BREAK_ON_FAILURE_ENV_VAR env_var_value_msg join command should_or_not self assert_ has_seg_fault expect_seg_fault msg
"helper function to asynchronously call read ( ) on a calculator::value and return a promise for the result . ( in the future , the generated code might include something like this automatically . )",def read_value value return value read then lambda result result value
"this function takes in a case result and returns the standing phase angle ( spa ) and voltage magnitude ( svd ) differences . columns of diffs matrix are [ voltage , angle ] .",def SPA_difference case_result n case_result branch shape 0 diffs np zeros shape n 2 for i in range n bus1 int case_result branch i 0 1 bus2 int case_result branch i 1 1 diffs i case_result bus bus1 7 9 case_result bus bus2 7 9 return diffs
return a gdal spatialreference object .,property def srs self if hasattr self _srs return self _srs clone else try self _srs gdal SpatialReference self wkt return self srs except Exception as e msg e try self _srs gdal SpatialReference self proj4text return self srs except Exception as e msg e raise Exception Could not get OSR SpatialReference from WKT s nError n s self wkt msg
return self.__field_name or ' site ' or ' sites ' .,def _get_field_name self if not self __field_name try self model _meta get_field site except FieldDoesNotExist self __field_name sites else self __field_name site return self __field_name
"sqlite will in some cases , e.g. when returning columns from views and subselects , return column names in ' alias.""column "" ' format instead of simply ' column ' .",def column_name_converter self name if self connection Database sqlite_version_info 3 7 15 return name split 1 strip else return name
return the objs in suitably sized batches for the used connection .,def get_del_batches self objs field conn_batch_size max connections self using ops bulk_batch_size field name objs 1 if len objs conn_batch_size return objs i i conn_batch_size for i in range 0 len objs conn_batch_size else return objs
make sure that the file is writeable . useful if our source is read - only .,def make_writeable self filename if sys platform startswith java return if not os access filename os W_OK st os stat filename new_permissions stat S_IMODE st st_mode stat S_IWUSR os chmod filename new_permissions
casts the @str_val to a float to handle the occassional decimal point in int fields from data providers .,def safe_int str_val f float str_val i int f return i
returns a test suite for all frange tests .,def suite return unittest TestSuite ImgResInstanceTestCase
: type irc_paramlist : list[str ] : type conn : cloudbot.client.client : type irc_raw : str,asyncio coroutine hook irc_raw NICK def on_nick irc_paramlist conn irc_raw old_nick nick_re search irc_raw group 1 new_nick str irc_paramlist 0 if new_nick startswith new_nick new_nick 1 if old_nick conn nick conn nick new_nick logger info tracker Bot nick changed from to format conn name old_nick new_nick
instantiate a linoderesponse from the http response,def __init__ self response connection self body self _decompress_response response response if PY3 self body b self body decode utf 8 self status response status self headers dict response getheaders self error response reason self connection connection self invalid LinodeException 255 Invalid JSON received from server self objects self errors self parse_body if not self success raise self errors 0
create a simple resource map with one science metadata document and any number of science data objects .,def createSimpleResourceMap ore_pid scimeta_pid sciobj_pid_list ore ResourceMap ore oreInitialize ore_pid ore addMetadataDocument scimeta_pid ore addDataDocuments sciobj_pid_list scimeta_pid return ore
list all the files in a given directory with specified extenstion .,def list_files dir_path file_extension files for root dirnames filenames in os walk dir_path for fname in filenames if fname endswith file_extension files append os path join root fname return files
test that ancestor terms are correct,def test_ancestors self self assertTrue self dsrepair_term is not None self assertEqual len self go get_ancestors self dsrepair_term go_id 25
groups all_values by key_func then applies merge_func to the groups .,def _MergeLikeValuesCommon all_values key_func merge_func all_values list all_values merge_groups GroupStably all_values key_func res for merge_group in merge_groups v0 merge_group 0 vM merge_func v0 merge_group if vM res append vM return res
scrape results ( url ) from html,def parse_links self html links soup bs4 BeautifulSoup html lxml for span in soup findAll div links a href for a in span findAll a class ac algo fz l ac 21th lh 24 href True if a href not in links return links
creates the relationships between terms in our graph database that are present in our ontology .,def create_term_relationships db mapping for term in mapping if mapping term relationships nodeId mapping term node_id childNode db node nodeId for type parentId parentName in mapping term relationships parentNodeId mapping parentId node_id parentNode db node parentNodeId childNode relationships create type parentNode log debug RELATIONSHIP parent s child s parentName childNode get name
store plugin - specific data .,def set self key value raise NotImplementedError
"create a convolution matrix h for the vector x of size len(x ) times n. then , the result of np.dot(h,v ) where v is a vector of length n is the same as np.convolve(x , v ) .",def convmtx x n import scipy as s c np concatenate x np zeros n 1 r np zeros n return s linalg toeplitz c r
"returns a tuple of all function args and kwargs , expanded so that varargs and kwargs are not nested . the args are ordered by their position in the function signature .",def expandedcallargs fn args kwargs return tuple flatten orderedcallargs fn args kwargs
this request need for get balance : return : < yourbalance > ok | 1 error !,def getbalance self fullurl s action getbalance key s self settings url_response self settings key request get fullurl if in request text if self logenabled self log info 2CaptchaUpload Balance s request text return request text elif request text ERROR_KEY_DOES_NOT_EXIST if self logenabled self log error 2CaptchaUpload You used the wrong key in the query return 1 elif request text ERROR_WRONG_ID_FORMAT if self logenabled self log error 2CaptchaUpload Wrong format ID CAPTCHA ID must contain only numbers return 1
return assessment model as json object,def as_dict self return c name getattr self c name for c in self __table__ columns
this filter performs semi - automatic multithresholding of a data set . voxels are automatically classified into a chosen number of classes such that inter - class variance of the voxel values is minimized . the output is a label map with one label per voxel class .,def transform_scalars self dataset number_of_thresholds 1 enable_valley_emphasis False self progress value 0 self progress maximum 100 STEP_PCT 10 20 70 90 100 try import itk import itkExtras import itkTypes from vtkmodules vtkCommonDataModel import vtkImageData from tomviz import itkutils from tomviz import utils except Exception as exc print Could not import necessary module s raise exc returnValues None try self progress value STEP_PCT 0 self progress message Converting data to ITK image itk_image itkutils convert_vtk_to_itk_image dataset itk_input_image_type type itk_image itk_threshold_image_type itk_input_image_type otsu_filter itk OtsuMultipleThresholdsImageFilter itk_input_image_type itk_threshold_image_type New otsu_filter SetNumberOfThresholds number_of_thresholds otsu_filter SetValleyEmphasis enable_valley_emphasis otsu_filter SetInput itk_image itkutils observe_filter_progress self otsu_filter STEP_PCT 1 STEP_PCT 2 try otsu_filter Update except RuntimeError return print Otsu threshold s s otsu_filter GetThresholds itk_image_data otsu_filter GetOutput py_buffer_type itk_threshold_image_type voxel_type itkExtras template itk_threshold_image_type 1 0 if voxel_type is itkTypes F or voxel_type is itkTypes D self progress message Casting output to integral type py_buffer_type itk Image UC3 caster itk CastImageFilter itk_threshold_image_type py_buffer_type New caster SetInput itk_image_data itkutils observe_filter_progress self caster STEP_PCT 2 STEP_PCT 3 try caster Update except RuntimeError return itk_image_data caster GetOutput self progress value STEP_PCT 3 self progress message Saving results label_buffer itk PyBuffer py_buffer_type GetArrayFromImage itk_image_data label_map_dataset vtkImageData label_map_dataset CopyStructure dataset utils set_array label_map_dataset label_buffer isFortran False self progress value STEP_PCT 4 returnValues returnValues label_map label_map_dataset except Exception as exc print Problem encountered while running s self __class__ __name__ raise exc return returnValues
return the segmentpen that can ' draw ' on this glyph .,def getPen self return self _pen
1 . start application layer of ecu s,def start self monitor False for ecu_id in self ecus if self ecus ecu_id startup_delay self _sim_env process self _start_delayed self ecus ecu_id else self _sim_env process self ecus ecu_id ecuSW app_lay main self _sim_env process self ecus ecu_id ecuSW comm_mod datalink_lay process 2 Start the bus running in parallel to the ECUs for bus_id in self buses self _sim_env process self buses bus_id process 3 Start the monitor object if monitor monitor set_monitor_env self _sim_env proc self _sim_env process monitor monitor proc2 self _sim_env process monitor monitor_publish monitor set_sim_process proc 4 Start the environmant try self _sim_env run until self _sim_env now self _app_lifetime del self _sim_env except AttributeError pass except traceback print_exc ECULogger log_traceback logging info Simulation terminated
"take a psc file string and return two strings : ( 1 ) the file header containing the "" fix : "" line and ( 2 ) the remainder of file .",def strip_fixed fstr Fi cStringIO StringIO Fi write fstr Fi seek 0 Fo cStringIO StringIO Fhead None for line in Fi if line 4 FIX Fhead string strip line Fo write n else Fo write line Fo seek 0 return Fhead Fo read
"write a line to the log file , but also check if the log file is not too bit and truncate if required",def write_log self line self log_file info line
here is an example of what a section header looks like in the html of a google document :,def _extract_sections self self _sections header h P level d class a name P id a span P title span h d l re split header self _content l pop 0 while l section Section level int l pop 0 2 id l pop 0 title l pop 0 decode utf8 content l pop 0 section id slugify section title if section level 1 self _sections append section
"make the asm for add , mult , and sub .",def make_asm self spotmap home_spots get_reg asm_code ctype self arg1 ctype size ctype size arg1_spot spotmap self arg1 arg2_spot spotmap self arg2 temp get_reg spotmap self output arg1_spot arg2_spot if temp arg1_spot if not self _is_imm64 arg2_spot asm_code add self Inst temp arg2_spot size else temp2 get_reg temp asm_code add asm_cmds Mov temp2 arg2_spot size asm_code add self Inst temp temp2 size elif temp arg2_spot if not self _is_imm64 arg1_spot asm_code add self Inst temp arg1_spot size else temp2 get_reg temp asm_code add asm_cmds Mov temp2 arg1_spot size asm_code add self Inst temp temp2 size if not self comm asm_code add asm_cmds Neg temp None size elif not self _is_imm64 arg1_spot and not self _is_imm64 arg2_spot asm_code add asm_cmds Mov temp arg1_spot size asm_code add self Inst temp arg2_spot size elif self _is_imm64 arg1_spot and not self _is_imm64 arg2_spot asm_code add asm_cmds Mov temp arg1_spot size asm_code add self Inst temp arg2_spot size elif not self _is_imm64 arg1_spot and self _is_imm64 arg2_spot asm_code add asm_cmds Mov temp arg2_spot size asm_code add self Inst temp arg1_spot size if not self comm asm_code add asm_cmds Neg temp None size else raise NotImplementedError never reach because of constant folding if temp spotmap self output asm_code add asm_cmds Mov spotmap self output temp size
get the weight of classes . the default value is 1 .,def get_class_weight hypes class_weights for i cl in enumerate hypes classes class_weights i 1 0 if weight in cl class_weights i float cl weight return class_weights
switch from synchronous to async operations,def switch_to_async self mainloop self iostream IOStream self sl s self iostream _add_io_state self iostream io_loop WRITE
read the capabilities list from a yubikey > = 4.0.0,def _read_capabilities self frame yubikey_frame YubiKeyFrame command SLOT YK4_CAPABILITIES self _device _write frame response self _device _read_response r_len yubico_util ord_byte response 0 if not yubico_util validate_crc16 response r_len 3 raise YubiKey4_USBHIDError Read from device failed CRC check return response 1 r_len 1
returns the listitem 's icon image,def get_icon self return self _icon
convert the exit code as returned by os.popen().close ( ) to a string,def exitCode2Description code if os WIFEXITED code return exited with status s os WEXITSTATUS code elif os WIFSIGNALED code sig os WTERMSIG code return crashed with signal s s signame sig sig else return exit code s code
three pointers scanning algorithm similar to 014 3sum,def threeSumClosest self num target min_distance 1 32 num sort min_summation 0 for i val in enumerate num j i 1 k len num 1 while j k lst val num j num k if min_distance abs target sum lst min_summation sum lst if sum lst target return min_summation min_distance abs target min_summation elif sum lst target k 1 else j 1 return min_summation
bfs the q stores the intermediate result of sum of squares : type n : int : rtype : int,def numSquares_bfs self n q 0 visited False for _ in xrange n 1 level 0 while q level 1 l len q for i in xrange l for j in xrange 1 int math sqrt n 1 nxt q i j j if nxt n and visited nxt continue elif nxt n visited nxt True q append nxt elif nxt n return level else break q q l return None
": param start , end : indices : return : the sum from start to end",def query self start end return self tree query self tree root start end 1
does the candidate hoststruct match the ip or range of ip addresses represented by this ? @param[in ] candidate the ip address to be tested @return candidate matches this or not,def match_bin self candidate u n Does the candidate hoststruct match the IP or range of IP addresses represented by this n param in candidate the IP address to be tested n return candidate matches this or not n if self wildcard return True try if not candidate family self hoststructs 0 family return False c0 self memcmp candidate binary self hoststructs 0 binary if len self hoststructs 1 return c0 0 c1 self memcmp candidate binary self hoststructs 1 binary return c0 0 and c1 0 except PolicyError return False except Exception as e assert isinstance candidate HostStruct u Wrong type Expected HostStruct but received s candidate __class__ __name__ return False
query aws organization for accounts with creation status of ' succeeded ' . returns a list of dictionary .,def scan_created_accounts log org_client log debug running status org_client list_create_account_status States SUCCEEDED created_accounts status CreateAccountStatuses while NextToken in status and status NextToken status org_client list_create_account_status States SUCCEEDED NextToken status NextToken created_accounts status CreateAccountStatuses return created_accounts
test usage using django 's filter tag :,def test_markdown_filter_with_templatetag_in_django_filterwrapper self u n Test usage using Django s filter tag n n filter apply_markup markdown n some text n endfilter n text expected s MARKDOWN result render_to_string u test_templatetag_filterwrapper html u text text u filter u markdown result result strip self assertEqual result expected
return an array identifying those array elements that fall within the given interval .,def in_interval bounds arr lower upper bounds mask True if lower is not None mask np logical_and mask arr lower if upper is not None mask np logical_and mask arr upper return mask
"access minutes ( 1,2,3,4 ) needs hardware / wiring dependent implementation this implementation assumes the minutes to be wired as the last four leds of the led - strip",def mapMinutes self min if min 1 return self LED_COUNT 4 elif min 2 return self LED_COUNT 3 elif min 3 return self LED_COUNT 2 elif min 4 return self LED_COUNT 1 else print WARNING Out of range when mapping minutes print min return 0
"utility function for dealing with a traversal result ( list of fragmentflows ) creates a list of cutoff flows from the inputs and outputs from a fragment traversal . ios is a list of fragmentflows : param parent : the node generating the cutoffs : param ios : a list of fragment flows whose termination is null ( non - nulls ignored ) : return : { set of grouped io flows } , [ list of internal non - null flows ]",def group_ios parent ios out defaultdict float internal external set for ff in ios if ff term is_null if ff fragment direction Input magnitude ff magnitude else magnitude ff magnitude out ff fragment flow magnitude else internal append ff for flow value in out items if value 0 direction Output else direction Input external add FragmentFlow cutoff parent flow direction abs value return external internal
returns the number of symbols that start with _ _ syscall_meta this is a fast way to determine the number of system calls,def _get_table_size_meta self return len n for n in self profile get_all_symbol_names if n startswith __syscall_meta__
tests that setting non - string names raises typeerrors .,def testNameSetToBadType self def f newName self nameable name newName self assertRaises TypeError f 4 self assertRaises TypeError f foo self assertRaises TypeError f foo bar
create a new equation . must pass the left hand side ( variable name ) .,def __init__ self lhs desc rhs if in lhs new_lhs new_desc lhs split 1 new_desc replace new_lhs new_lhs strip new_desc new_desc strip self __init__ new_lhs new_desc rhs return if in lhs lhs rhs lhs split 1 lhs lhs strip rhs replace self LeftHandSide lhs self Description desc if type rhs str rhs Equation ParseString rhs self TermList for t in rhs self AddTerm t
: param int xdo_delay : default pause between keystrokes . : param str display : reserved for future use . : param kwargs :,def __init__ self xdo_delay 0 display None kwargs super XdoPlatformRpcs self __init__ kwargs self display Xlib display Display display self libxdo xdo Xdo display self xdotool_delay xdo_delay self x_atoms name self display intern_atom name for name in _X_PROPERTIES
returns list of tracks matching query,property def results self tracks for t in self data track Tracks id t id tracks append track data 0 return tracks
"test tree copy : directory , distant target",def test_tree_copy_dir_distant self self _tree_copy_dir NODE_DISTANT
get the business group id for a reservation http://pubs.vmware.com/vra-62/index.jsp#com.vmware.vra.programming.doc/guid-588865ae-0134-4087-b090-c725790c052c.html parameters : tenant = vra tenant . if null then it will default to vsphere.local businessgroupname = for future use . need to be able to fetch id from business group name,def getBusinessGroupId self tenant None buisenessGroupName None host self host token self token if tenant is None tenant vsphere local url https host identity api tenants tenant subtenants format host host tenant tenant headers Content Type application json Accept application json Authorization token r requests get url url headers headers verify False checkResponse r businessGroupId r json return businessGroupId
contrast limited adaptive histogram equalization .,def equalize_adapthist image ntiles_x 8 ntiles_y 8 clip_limit 0 01 nbins 256 args None ntiles_x ntiles_y clip_limit nbins nbins if image ndim 2 lab_img color rgb2lab skimage img_as_float image l_chan lab_img 0 l_chan np max np abs l_chan l_chan skimage img_as_uint l_chan args 0 rescale_intensity l_chan out_range 0 NR_OF_GREY 1 new_l _clahe args astype float new_l rescale_intensity new_l out_range 0 100 lab_img new_l shape 0 new_l shape 1 0 new_l image color lab2rgb lab_img image rescale_intensity image out_range 0 1 else image skimage img_as_uint image args 0 rescale_intensity image out_range 0 NR_OF_GREY 1 out _clahe args image out shape 0 out shape 1 out image rescale_intensity image return image
adjust the brightness off an image with an offset and factor .,def brightness self factor offset pool ThreadDispatch self img self stateimg _colormixer brightness factor offset pool run
filter input unitlesson to be acceptable for this edge .,register filter def filter_input edge obj return edge filter_input obj
try to conver a variable to a torch tensor .,def to_tensor data dtype None use_cuda None converter list _list_to_tensor tuple _list_to_tensor np ndarray torch from_numpy Variable lambda x x if type data in converter tensor converter type data data elif torch is_tensor data tensor data else raise ValueError Invalid data type format type data __name__ tensor _convert_tensor tensor dtype use_cuda return tensor
element - wise square of the input y = x * x,def square x return Square forward x
remove symlinks using a directory 's dtags .,def unload_dtags rootpath dirpath tags dtags list_tags dirpath dirpath pathlib readlink dirpath for tagname in tags tagpath tagnames tag2path rootpath tagname if posixpath samefile dirpath tagpath os unlink tagpath
"summary : performs miscellaneous end of episode tasks ( # printing out useful information , saving stuff , etc . )",def end_of_episode self self add_new_weak_learner self most_recent_episode if self markov_window 0 self model self weak_learners self markov_window else self model self weak_learners Agent end_of_episode self
"load the specified keyring by name ( a fully - qualified name to the keyring , such as ' keyring.backends.file.plaintextkeyring ' )",def load_keyring keyring_name class_ _load_keyring_class keyring_name class_ priority return class_
"checks device to see if its a usb serial device . the caller already filters on the subsystem being ' tty ' . if serial_num or vendor is provided , then it will further check to see if the serial number and vendor of the device also matches .",def is_usb_serial device vid None pid None vendor None serial None args kwargs if ID_VENDOR not in device return False if vid is not None if device ID_VENDOR_ID vid return False if pid is not None if device ID_MODEL_ID pid return False if vendor is not None if ID_VENDOR not in device return False if not device ID_VENDOR startswith vendor return False if serial is not None if ID_SERIAL_SHORT not in device return False if not device ID_SERIAL_SHORT startswith serial return False return True
handle even more bogus if - modified - since values gracefully,def test_invalid_if_modified_since2 self file_name file txt invalid_date 1291108438 Wed 20 Oct 2010 14 05 00 GMT response self client get views s s self prefix file_name HTTP_IF_MODIFIED_SINCE invalid_date response_content join response with open path join media_dir file_name rb as fp self assertEqual fp read response_content self assertEqual len response_content int response Content Length
test that a task throws an exception if the name is empty,def test_task_initialization_fails_if_name_is_empty self name self assertRaises Exception Task name
create plots showing correctly classified taxa for different relative distance values .,def _percent_correct_plot self rel_dists taxa_for_dist_inference output_prefix print print Relative divergence thresholds rank threshold parent taxa child taxa ranks sorted rel_dists keys rel_dist_thresholds for i in xrange ranks 0 ranks 1 parent_rank i child_rank i 1 parent_rds for taxa rd in rel_dists parent_rank iteritems if taxa in taxa_for_dist_inference parent_rds append rd parent_p50 np_percentile parent_rds 50 child_rds for taxa rd in rel_dists child_rank iteritems if taxa in taxa_for_dist_inference child_rds append rd child_p50 np_percentile child_rds 50 r y_parent y_child y_mean_corr for test_r in np_linspace parent_p50 child_p50 100 parent_cor float sum 1 for rd in parent_rds if rd test_r len parent_rds child_cor float sum 1 for rd in child_rds if rd test_r len child_rds r append test_r y_parent append parent_cor y_child append child_cor y_mean_corr append 0 5 parent_cor 0 5 child_cor self fig clear self fig set_size_inches 6 6 ax self fig add_subplot 111 ax plot r y_parent k label Taxonomy rank_labels i ax plot r y_child k label Taxonomy rank_labels i 1 ax plot r y_mean_corr r label mean legend ax legend loc upper left legend draw_frame False max_mean max y_mean_corr r_max_values r i for i rd in enumerate y_mean_corr if rd max_mean r_max_value np_mean r_max_values print s t 3f t d t d Taxonomy rank_labels parent_rank r_max_value len parent_rds len child_rds rd_indices i for i rd in enumerate y_mean_corr if rd max_mean for rd_index in xrange 0 len rd_indices 1 if rd_indices rd_index rd_indices rd_index 1 1 print Warning There are multiple local maxima so estimated relative divergence threshold will be invalid rel_dist_thresholds append r_max_value y_min _y_max ax get_ylim ax axvline x r_max_value ymin 0 ymax 1 color r ls ax text r_max_value 0 001 y_min 0 01 3f r_max_value horizontalalignment left ax set_xlabel relative distance ax set_ylabel taxa correctly classified self prettify ax self fig tight_layout pad 1 self fig savefig output_prefix s_ s png Taxonomy rank_labels parent_rank Taxonomy rank_labels child_rank dpi 96 print return rel_dist_thresholds
read in a string and return the split string without stopwords,def remove_stopwords s return x for x in s lower split if x not in stopwords and len x 1
set amqp message attribute : timestamp .,timestamp setter def timestamp self value self _update_properties timestamp value
convert synonyms to analyzed form with snowball analyzer .,def process_synonyms es synonyms processed_synonyms for line in synonyms processed_line for synonym in line response es indices analyze text synonym analyzer snowball synonym_tokens join item token for item in response tokens processed_line append synonym_tokens processed_line join processed_line processed_synonyms append processed_line return processed_synonyms
view decorator that requires that the user is part any publisher group permissions .,def publisher_user_required func wraps func def wrapped request args kwargs if is_publisher_user request user return func request args kwargs else return HttpResponseForbidden u Must be Publisher user to perform this action return wrapped
creates a new figure on the board .,def spawn_figure self figure figwidth figure width figcol self ncols figwidth 2 figure mincol figrow figure minrow figcenter figrow figcol if self _figure_conflicts figure figcenter return False self fig figure self figcenter figcenter return True
stores flags for and provides utilities for generating build files .,def __init__ self build_file_name None aux_build_file_name None hand_written_build_file_name None exclude_project_targets None print_headers None env_file_name None default_jvm_platform None jooq_config_file None module_list_file None self build_file_name build_file_name or self __DEFAULT_BUILD_NAME_GEN self aux_build_file_name aux_build_file_name or self __DEFAULT_BUILD_NAME_AUX self hand_written_build_file_name hand_written_build_file_name or self __DEFAULT_BUILD_NAME self exclude_project_targets exclude_project_targets self generated_ini_file env_file_name or self __DEFAULT_GENERATED_INI_FILE self default_jvm_platform default_jvm_platform or self __DEFAULT_JVM_PLATFORM_NAME self jooq_config_file jooq_config_file or self __DEFAULT_JOOQ_CONFIG_FILE self module_list_file module_list_file or self __DEFAULT_MODULE_LIST_FILE if self exclude_project_targets is None self exclude_project_targets parents external protos self print_headers print_headers if self print_headers is None self print_headers True self platforms_to_settings self settings_to_platforms self pom_file_cache self os_to_java_homes
returns a list of site records which are pending credit .,def pending_sites self pending_sites for site in self fleet sites all if UserSite objects filter user self user site site pending True exists pending_sites append site return pending_sites
samples torch - rnn model . calls bachbot / scripts / torchrnn / sample.zsh .,click command click argument checkpoint type click Path exists True required True click option t temperature type float default 0 9 click option s start text file type click Path exists True help Primer UTF file def sample checkpoint temperature start_text_file if not start_text_file start_text START_DELIM else start_text codecs open start_text_file r utf8 read 320 subprocess call BACHBOT_DIR scripts torchrnn sample zsh 0 1 2 format checkpoint temperature start_text shell True
main solving algorithm of the monge - ampere deflection - field potential problem using a finite difference scheme .,def solve X Y flux0 flux dt tol chk False interval 1000 nan_exception True start_chk False start_phin None start_step None save_dir None Nstep 50000 plasma_x np copy X plasma_y np copy Y flux0 np copy flux0 flux np copy flux flux_mean np mean flux if start_chk start_phin os path abspath start_phin if save_dir is not None save_dir os path abspath save_dir if start_chk and start_phin None or start_step None raise Exception Please specify a checkpoint phin file and starting step if start_chk if not os path isfile start_phin raise Exception Please specify a valid starting checkpoint file for phin if type start_step int raise Exception Please provide a valid starting step if save_dir is not None if not os path isdir save_dir raise Exception Please specify a valid save directory if start_chk phin np loadtxt start_phin delimiter if not start_chk phin 0 5 plasma_x 2 plasma_y 2 plasma_Nx plasma_Ny plasma_x shape dx plasma_x 1 0 plasma_x 0 0 dy plasma_y 0 1 plasma_y 0 0 plasma_Lx plasma_x 1 0 plasma_x 0 0 plasma_Ly plasma_y 0 1 plasma_y 0 0 phix np zeros plasma_Nx plasma_Ny phiy np zeros plasma_Nx plasma_Ny phixx np zeros plasma_Nx plasma_Ny phiyy np zeros plasma_Nx plasma_Ny phixy np zeros plasma_Nx plasma_Ny RMSfluxerror np zeros Nstep pointfluxerror np zeros Nstep Nxrand int np floor np random ranf plasma_Nx 1 Nyrand int np floor np random ranf plasma_Ny 1 if chk if save_dir None np savetxt os path join os getcwd plasma_x txt plasma_x delimiter np savetxt os path join os getcwd plasma_y txt plasma_y delimiter else np savetxt os path join save_dir plasma_x txt plasma_x delimiter np savetxt os path join save_dir plasma_y txt plasma_y delimiter flux_interp sp interpolate RegularGridInterpolator plasma_x 0 plasma_y 0 flux method linear bounds_error False fill_value flux_mean for timestep in range Nstep if start_chk timestep start_step timestep 1 print timestep if nan_exception and np any np isnan phin raise Exception The reconstruction algorithm is unstable phix phiy np gradient phin dx dy phix 0 plasma_x 0 phix plasma_Nx 1 plasma_x plasma_Nx 1 phiy 0 plasma_y 0 phiy plasma_Ny 1 plasma_y plasma_Ny 1 phixx phixy np gradient phix dx dy _ phiyy np gradient phiy dx dy phixy 0 0 phixy plasma_Nx 1 0 phixy 0 0 phixy plasma_Ny 1 0 det phixx phiyy phixy 2 fluxn flux_interp phix phiy Fn np log fluxn np absolute det flux0 phi_derived phin dt Fn pointfluxerror timestep phi_derived Nxrand Nyrand phin Nxrand Nyrand RMSfluxerror timestep np sqrt np mean phi_derived phin 2 phin phi_derived if np linalg norm Fn tol break if chk if timestep interval 0 if save_dir None np savetxt phin str timestep txt phin delimiter np savetxt phix str timestep txt phix delimiter np savetxt phiy str timestep txt phiy delimiter else np savetxt save_dir phin str timestep txt phin delimiter np savetxt save_dir phix str timestep txt phix delimiter np savetxt save_dir phiy str timestep txt phiy delimiter return phin phix phiy
will give the player a choice of quitting or restarting,def dead spk You have run out of all your lives What do you wish to do Press return to start over or press escape to leave 2
test to ensure there are actions when appending with a player,def test_append_move_error_player_actions self assert_raises UndefinedOperationError self extensive_game root append_move self extensive_game players 0 assert_raises UndefinedOperationError self extensive_game root append_move self extensive_game players 0 0
return top 20 absolute factors .,def component_top_factors component allgenes_array max_size 20 abs_component np abs component size min component size max_size unordered_ixs np argpartition abs_component size size ixs unordered_ixs np argsort abs_component unordered_ixs 1 if ixs size 0 return return list zip np array allgenes_array ixs tolist component ixs tolist
return the db backend used to create this dataset,override def get_backend self return self train_db_task backend
call all registered validation methods on this spec .,def __check self key None oldvalue None newvalue None kw for func in six itervalues self __checks func self key oldvalue newvalue
retrieve the output of a sql query taking advantage of the dns resolution mechanism by making request back to attacker 's machine .,def dnsUse payload expression start time time retVal None count 0 offset 1 if conf dnsName and Backend getIdentifiedDbms in DBMS MSSQL DBMS ORACLE DBMS MYSQL DBMS PGSQL output hashDBRetrieve expression checkConf True if output and PARTIAL_VALUE_MARKER in output or kb dnsTest is None output None if output is None kb dnsMode True while True count 1 prefix suffix s randomStr length 3 alphabet DNS_BOUNDARIES_ALPHABET for _ in xrange 2 chunk_length MAX_DNS_LABEL 2 if Backend getIdentifiedDbms in DBMS ORACLE DBMS MYSQL DBMS PGSQL else MAX_DNS_LABEL 4 2 _ _ _ _ _ _ fieldToCastStr _ agent getFields expression nulledCastedField agent nullAndCastField fieldToCastStr extendedField re search s re escape fieldToCastStr expression group 0 if extendedField fieldToCastStr nulledCastedField extendedField replace fieldToCastStr nulledCastedField fieldToCastStr extendedField nulledCastedField queries Backend getIdentifiedDbms substring query nulledCastedField offset chunk_length nulledCastedField agent hexConvertField nulledCastedField expressionReplaced expression replace fieldToCastStr nulledCastedField 1 expressionRequest getSQLSnippet Backend getIdentifiedDbms dns_request PREFIX prefix QUERY expressionReplaced SUFFIX suffix DOMAIN conf dnsName expressionUnescaped unescaper escape expressionRequest if Backend getIdentifiedDbms in DBMS MSSQL DBMS PGSQL query agent prefixQuery s expressionUnescaped query s s query queries Backend getIdentifiedDbms comment query forgedPayload agent payload newValue query else forgedPayload safeStringFormat payload expressionUnescaped randomInt 1 randomInt 3 Request queryPage forgedPayload content False noteResponseTime False raise404 False _ conf dnsServer pop prefix suffix if _ _ extractRegexResult s P result s prefix suffix _ re I _ decodeHexValue _ output output or _ offset len _ if len _ chunk_length break else break output decodeHexValue output if conf hexConvert else output kb dnsMode False if output is not None retVal output if kb dnsTest is not None dataToStdout s INFO s s n time strftime X retrieved if count 0 else resumed safecharencode output if count 0 hashDBWrite expression output if not kb bruteMode debugMsg performed d queries in 2f seconds count calculateDeltaSeconds start logger debug debugMsg elif conf dnsName warnMsg DNS data exfiltration method through SQL injection warnMsg is currently not available for DBMS s Backend getIdentifiedDbms singleTimeWarnMessage warnMsg return safecharencode retVal if kb safeCharEncode else retVal
dummy function to let modulefinder know what tables may be dynamically imported . generated by metatools / buildtablelist.py .,def _moduleFinderHint from import B_A_S_E_ from import C_B_D_T_ from import C_B_L_C_ from import C_F_F_ from import C_O_L_R_ from import C_P_A_L_ from import D_S_I_G_ from import E_B_D_T_ from import E_B_L_C_ from import F_F_T_M_ from import G_D_E_F_ from import G_M_A_P_ from import G_P_K_G_ from import G_P_O_S_ from import G_S_U_B_ from import J_S_T_F_ from import L_T_S_H_ from import M_A_T_H_ from import M_E_T_A_ from import O_S_2f_2 from import S_I_N_G_ from import S_V_G_ from import T_S_I_B_ from import T_S_I_D_ from import T_S_I_J_ from import T_S_I_P_ from import T_S_I_S_ from import T_S_I_V_ from import T_S_I__0 from import T_S_I__1 from import T_S_I__2 from import T_S_I__3 from import T_S_I__5 from import V_D_M_X_ from import V_O_R_G_ from import _c_m_a_p from import _c_v_t from import _f_e_a_t from import _f_p_g_m from import _g_a_s_p from import _g_l_y_f from import _h_d_m_x from import _h_e_a_d from import _h_h_e_a from import _h_m_t_x from import _k_e_r_n from import _l_o_c_a from import _m_a_x_p from import _n_a_m_e from import _p_o_s_t from import _p_r_e_p from import _s_b_i_x from import _v_h_e_a from import _v_m_t_x
do a shape comparison ( glyph area or rendered ) and add results to stats .,def _shape path_a path_b stats diff_type font_size render_path diff_threshold 0 diff_finder shape_diff ShapeDiffFinder path_a path_b stats ratio_diffs True diff_threshold diff_threshold if diff_type area diff_finder find_area_diffs elif diff_type shape diff_finder find_shape_diffs elif diff_type area shape product diff_finder find_area_shape_diff_products else diff_finder find_rendered_diffs font_size render_path
wrapper for inserting int64 features into example proto .,def _int64_feature value if not isinstance value list value value return tf train Feature int64_list tf train Int64List value value
"returns the namespaced , cached , audited waffle class for grades .",def waffle return WaffleSwitchNamespace name WAFFLE_NAMESPACE log_prefix u Grades
cleans the note object or raises a validationerror .,def clean self json_body if json_body is None raise ValidationError Note must have a body body json loads json_body if not isinstance body dict raise ValidationError Note body must be a dictionary self uri strip_tags body get uri self text strip_tags body get text self quote strip_tags body get quote ranges body get ranges if ranges is None or len ranges 1 raise ValidationError Note must contain exactly one range self range_start ranges 0 start self range_start_offset ranges 0 startOffset self range_end ranges 0 end self range_end_offset ranges 0 endOffset self tags tags strip_tags tag for tag in body get tags if len tags 0 self tags join tags
the command should update the user 's enrollment .,patch student management commands change_enrollment logger ddt data email False 3 username False 3 email True 0 username True 0 ddt unpack def test_convert_users self method noop expected_conversions mock_logger user_str join getattr user method for user in self users user_ids u id for u in self users self assertEqual len CourseEnrollment objects filter mode honor user_id__in user_ids 0 noop noop if noop else command_args course course to honor from audit method user_str noop format course text_type self course id noop noop method method user_str user_str call_command change_enrollment command_args split self assertEqual len CourseEnrollment objects filter mode honor user_id__in user_ids expected_conversions mock_logger info assert_called_with Successfully updated i out of i users len self users len self users
test that raises commanderror for invalid team i d .,def test_given_invalid_team_id_raises_command_error self team_id u team4 error_str Argument is not a course_team team_id format team_id with self assertRaisesRegexp CommandError error_str call_command reindex_course_team team_id
attempt to enroll the user .,def post self request args kwargs user request user valid course_key error self _is_data_valid request if not valid return DetailResponse error status HTTP_406_NOT_ACCEPTABLE embargo_response embargo_api get_embargo_response request course_key user if embargo_response return embargo_response course_id unicode course_key enrollment CourseEnrollment get_enrollment user course_key if enrollment and enrollment is_active msg Messages ENROLLMENT_EXISTS format course_id course_id username user username return DetailResponse msg status HTTP_409_CONFLICT course courses get_course course_key if CourseEnrollment is_enrollment_closed user course msg Messages ENROLLMENT_CLOSED format course_id course_id log info u Unable to enroll user s in closed course s user id course_id return DetailResponse msg status HTTP_406_NOT_ACCEPTABLE honor_mode CourseMode mode_for_course course_key CourseMode HONOR audit_mode CourseMode mode_for_course course_key CourseMode AUDIT default_enrollment_mode audit_mode or honor_mode if default_enrollment_mode msg Messages ENROLL_DIRECTLY format username user username course_id course_id if not default_enrollment_mode sku msg Messages NO_SKU_ENROLLED format enrollment_mode default_enrollment_mode slug course_id course_id username user username log info msg self _enroll course_key user default_enrollment_mode slug self _handle_marketing_opt_in request course_key user return DetailResponse msg else msg Messages NO_DEFAULT_ENROLLMENT_MODE format course_id course_id return DetailResponse msg status HTTP_406_NOT_ACCEPTABLE
the view should return http 403 status if the user is not logged in .,def test_login_required self self client logout self assertEqual 403 self _post_to_view status_code
creates and returns a minimal blockdata object with the give values .,def _create_block self content_block_value block BlockData self location block display_name self display_name block weight content_block_value weight block_grades_transformer_data block transformer_data get_or_create GradesTransformer block_grades_transformer_data max_score content_block_value raw_possible setattr block_grades_transformer_data GradesTransformer EXPLICIT_GRADED_FIELD_NAME content_block_value explicit_graded return block
this returns a configuration value for a site configuration or microsite configuration which has an org_filter that matches with the argument .,def get_value_for_org org val_name default None from openedx core djangoapps site_configuration models import SiteConfiguration if SiteConfiguration has_org org return SiteConfiguration get_value_for_org org val_name default else return microsite get_value_for_org org val_name default
"updates a saved course grade , but does not update the subsection grades the user has in this course .",receiver SUBSECTION_SCORE_CHANGED def recalculate_course_grade_only sender course course_structure user kwargs CourseGradeFactory update user course course course_structure course_structure
test that the singular validator works properly,def test_happy_path_singular_1 self result validate_textbook_json json dumps self tb1 self assertEqual self tb1 result
load a coverage file from an open file object .,def _load_coverage F header_length 6 dtype np int16 header F readline for i in range header_length make_tuple lambda t t split 0 float t split 1 header dict make_tuple line for line in header M np loadtxt F dtype dtype nodata int header NODATA_value if nodata 9999 M nodata 9999 return M
build a path from * file_paths * and search for a `` _ _ version _ _ `` string inside .,def find_version file_paths version_file read file_paths version_match re search __version__ version_file re M if version_match return version_match group 1 raise RuntimeError Unable to find version string
": param inputs : : param backbone : resnet101 , resnet152 , mobilenet - v2 - 1.0",def __init__ self inputs trainable True backbone resnet152 self backbone backbone super __init__ inputs trainable
human - readable file size . http://stackoverflow.com/questions/1094841,def filesize_fmt num for x in b KB MB GB if num 1024 0 return 3 1f s num x num 1024 0 return 3 1f s num TB
"return_example(*args , * * kwargs )",staticmethod def return_example args kwargs for proc in Class_Example _return_example_first Class_Example _return_example_second Class_Example _return_example_third try return proc args kwargs except TypeError continue
compute error - corrected distance between two sets of preferences .,def comparePrefs prefs1 prefs2 sites None distmetric half_sum_abs_diff chars dms_tools2 AAS assert len prefs1 1 provide prefs for multiple replicates assert len prefs2 1 provide prefs for multiple replicates prefs expectcols site chars for homolog homologprefs in enumerate prefs1 prefs2 1 for rep repprefs in enumerate homologprefs 1 iprefs pandas read_csv repprefs iprefs site iprefs site astype str assert set iprefs columns set expectcols 0 missing expected columns format repprefs prefs append iprefs expectcols assign homolog homolog replicate rep if sites is None sites list set intersection set p site for p in prefs assert isinstance sites list and len sites no sites to analyze sites natsort natsorted list map str sites signed True assert all set p site set sites for p in prefs not all prefs have all sites prefs p p site isin sites for p in prefs prefs pandas concat prefs prefs site pandas Categorical prefs site sites prefs prefs sort_values site set_index site dists within between for hi repi hj repj in itertools combinations h rep for h in 1 2 for rep in prefs query homolog h replicate unique 2 prefsi prefs query homolog hi and replicate repi chars prefsj prefs query homolog hj and replicate repj chars assert prefsi index equals prefsj index disttype True within False between hi hj dists disttype append prefDistance prefsi loc r prefsj loc r distmetric for r in sites for disttype dist in dists items distseries pandas DataFrame dist columns sites transpose apply computeRMS axis 1 prefs RMSD disttype distseries prefs RMSDcorrected prefs RMSDbetween prefs RMSDwithin rmsds RMSDcorrected RMSDbetween RMSDwithin prefmeans for homolog in 1 2 prefmeans homolog prefs reset_index query homolog homolog groupby site chars mean prefs prefs prefs index duplicated keep first rmsds dprefs prefmeans 1 prefmeans 2 dprefs dprefs div dprefs abs sum axis 1 axis 0 mul 2 fillna 0 dprefs dprefs mul prefs RMSDcorrected axis 0 prefs prefs join dprefs return prefs rmsds chars reset_index
test_grades_all all should be set to false if another grade is set to true,def test_grades_all self self filters grades C True values self get_values 10 self assertEqual len values 1 self assertEqual values 0 value C
rpc to be execute on remote device : name : name of rpc in string format,ensure_connected def execute_rpc self name return self rpc name
- os_server : nics : port - id=1234,def test_nics_string_port_id self args os_server _network_args self module self cloud assert args 0 port id 1234
this method executes the cli command on the target node(s ) and returns the output . the module then exits based on the output . : param cli : the complete cli string to be executed on the target node(s ) . : param module : the ansible module to fetch command,def run_cli module cli cliswitch module params pn_cliswitch state module params state command get_command_from_state state cmd shlex split cli result out err module run_command cmd print_cli cli split cliswitch 1 if result 0 module exit_json command print_cli stderr err strip msg s operation failed command changed False if out module exit_json command print_cli stdout out strip msg s operation completed command changed True else module exit_json command print_cli msg s operation completed command changed True
returns ecsattributes object containing attributes from ecs container instance with names matching to attrs.attributes ( ecsattributes object ) .,def attrs_get_by_name self attrs attr_objs targetType container instance attributeName attr name for attr in attrs try matched_ecs_targets attr_found for attr_obj in attr_objs for attr_found in self ecs list_attributes cluster self cluster attr_obj attributes except ClientError as e self module fail_json msg Can t connect to the cluster s str e matched_objs target for target in matched_ecs_targets if target targetId self ecs_arn results name match name value match get value None for match in matched_objs return EcsAttributes self module results
return a json with a random real tweet .,view_config route_name json real renderer json def json_real request session request dbsession real_tweet session query Tweet order_by func random first return tweet real_tweet tweet
"return a proxy object which behaves like experimentlog , but actually redirects to a remote process with a single experimnetlog object",def get_proxy self return LogProxy
test file apu_nasa_mc3e_dsd.txt reads in and returns non none object .,def test_read_file_does_not_return_none self self assertIsNotNone self dsd reader returned a None object
group block indexes with appropriate layout pairs,def associate_blocks blocks layout_pairs start_peb_num seq_blocks for layout_pair in layout_pairs seq_blocks sort by_image_seq blocks blocks layout_pair 0 ec_hdr image_seq layout_pair append seq_blocks return layout_pairs
apply theme style attributes to this instance and its children .,def stylize self for child in self children child stylize style theme current get_dict self for key val in style iteritems kvc set_value_for_keypath self key val self layout
get the fscore of the validation set . gives a good indication of score on public leaderboard,def fscore prediction target torch FloatTensor 0 17 for i _ y in enumerate val_loader target torch cat target y 0 fscore fbeta_score target numpy prediction numpy 0 23 beta 2 average samples return fscore
set an attribute of an object to a specific value .,def _set_attribute self obj attr value field obj _meta get_field attr if field max_length is not None and len value field max_length cleaned_value value field max_length logger warn The attribute s was trimmed from s to s attr value cleaned_value else cleaned_value value old_value getattr obj attr if cleaned_value old_value setattr obj attr cleaned_value return True return False
"in this test , there is a small amount of variance in both the masks and the features . note that if you put the average mask at 1 instead of 0.5 it fails because the ' corrected ' data will be non - gaussian ( as it gets clipped between 0 and 1 ) . similarly , if you put the noise in the data as 0 it does n't work because you get singular matrices .",def test_synthetic_2d_easy data generate_synthetic_data 2 100 1 0 0 01 2 0 5 0 0 01 0 0 0 1 0 01 2 0 0 5 0 0 0 01 kk KK data points_for_cluster_mask 1e 100 num_starting_clusters 10 kk cluster_mask_starts test_approximately_well_clustered kk clusters 2 100
test a valid domain is required .,def test_bad_domain self user john bad domain com self assertSystemExit user old pw new pw
compare whether two things are the same .,def __cmp__ self other if isinstance other Address if __eq__ other return 0 else return 1 else return NotImplemented
"imports : func : from a python file at : path : and executes it with * args , * * kwargs arguments . everytime this function is called the module is reloaded so that you can alter your debug code while the application is running .",def inject_path path try dirname os path dirname path if dirname not in sys path exists_in_sys False sys path append dirname else exists_in_sys True module_name os path splitext os path split path 1 0 if module_name in sys modules reload sys modules module_name else __import__ module_name if not exists_in_sys sys path remove dirname except Exception as e return e
repli : test main ( ) and synchronize_files ( ),def test_synchronize_files def quote_paths inputpaths return join s path for path in inputpaths filein path_sample_files input tuxsmall jpg filein2 path_sample_files input testaa txt filein3 path_sample_files input sub testsub txt inputpaths path_sample_files output repli dir i i 1 True for i in xrange 4 outpath path_sample_files output repli dirout report_file path_sample_files output repli_report csv fileout path_sample_files output repli dir i tuxsmall jpg i 1 for i in xrange 4 fileout2 path_sample_files output repli dir i testaa txt i 1 for i in xrange 4 if i 2 path_sample_files output repli dir3 sub True fileout3 path_sample_files output repli dir3 sub testsub txt for f in fileout shutil copy2 filein f for f in fileout2 shutil copy2 filein2 f shutil copy2 filein3 fileout3 dirorig path_sample_files output repli dirorig True shutil copy2 filein dirorig shutil copy2 filein2 dirorig shutil copy2 filein3 path_sample_files output repli dirorig sub True filedb path_sample_files output repli_rfigc_db csv for i f in enumerate fileout tamper_file f i A for i f in enumerate fileout2 if i 2 tamper_file f 0 A res1 filepath dir1 dir2 dir3 dir4 hash correct error_code errors testaa txt X X X OK tuxsmall jpg X X X X OK sub testsub txt O OK errcode rep synchronize_files inputpaths outpath report_file report_file assert errcode 0 with open report_file rb as rfile rout rfile read assert res1 in rout errcode rep main i s o s r s f silent quote_paths inputpaths outpath report_file assert errcode 0 with open report_file rb as rfile rout rfile read assert res1 in rout res2 filepath dir1 dir2 dir3 dir4 hash correct error_code errors testaa txt X X O OK OK tuxsmall jpg X X X X OK OK sub testsub txt O OK OK assert rfigc main i s d s g f silent dirorig filedb 0 errcode rep synchronize_files inputpaths outpath database filedb report_file report_file assert errcode 0 with open report_file rb as rfile rout rfile read assert res2 in rout errcode rep main i s o s r s d s f silent quote_paths inputpaths outpath report_file filedb assert errcode 0 with open report_file rb as rfile rout rfile read assert res2 in rout tamper_file fileout 1 10 B tamper_file fileout 2 10 C tamper_file fileout 3 10 D tamper_file fileout2 0 0 A tamper_file fileout2 1 0 A tamper_file fileout2 2 0 A res3 filepath dir1 dir2 dir3 dir4 hash correct error_code errors testaa txt X X X KO KO File could not be totally repaired according to rfigc database tuxsmall jpg X X X X OK KO Unrecoverable corruptions because of ambiguity in file tuxsmall jpg on characters 0xa But merged file is correct according to rfigc database sub testsub txt O OK OK ptee StringIO errcode rep synchronize_files inputpaths outpath database filedb report_file report_file ptee ptee assert errcode 1 with open report_file rb as rfile rout rfile read ptee seek 0 errmsg ptee read assert len errmsg 0 assert res3 in rout errcode rep main i s o s r s d s f silent quote_paths inputpaths outpath report_file filedb assert errcode 1 with open report_file rb as rfile rout rfile read ptee seek 0 errmsg ptee read assert len errmsg 0 assert res3 in rout
"type : : ( int , int ) - > int return : : greatest common divisor",def gcd a b while b is not 0 a b b a b return a
read from network interface queue packets to remote endpoint sender,def _read_netif self self _log debug readif buff self _netif read self _protocol mtu 64 addr d d d d buff 20 buff 21 buff 22 buff 23 self _read_buff append addr buff
get complex from prefix and xml element .,def getComplexByPrefix prefix valueComplex xmlElement value evaluate getEvaluatedValue prefix xmlElement if value None valueComplex getComplexByDictionaryListValue value valueComplex x evaluate getEvaluatedFloat prefix x xmlElement if x None valueComplex complex x getComplexIfNone valueComplex imag y evaluate getEvaluatedFloat prefix y xmlElement if y None valueComplex complex getComplexIfNone valueComplex real y return valueComplex
""" parse a gcode line and add it to the altshell skein .",def parseLine self line splitLine line split if len splitLine 1 return firstWord splitLine 0 if line edge outer or line edge inner self state 1 elif firstWord edge if self state 3 if self repository useM320M321 value self distanceFeedRate addLine M320 else self distanceFeedRate addLine M126 self state 0 elif firstWord M101 if self state 1 self state 2 self distanceFeedRate addLine line if self state 2 if self repository useM320M321 value self distanceFeedRate addLine M321 else self distanceFeedRate addLine M127 self state 3
get intersection loops for a pair of loop lists .,def getLoopsIntersectionByPair importRadius loopsFirst loopsLast radiusSide 0 01 importRadius corners getLoopsListsIntersections loopsFirst loopsLast corners getInsetPointsByInsetLoops loopsFirst True loopsLast radiusSide corners getInsetPointsByInsetLoops loopsLast True loopsFirst radiusSide allPoints corners allPoints getInsetPointsByInsetLoops getInBetweenLoopsFromLoops importRadius loopsFirst True loopsLast radiusSide allPoints getInsetPointsByInsetLoops getInBetweenLoopsFromLoops importRadius loopsLast True loopsFirst radiusSide return trianglemesh getDescendingAreaLoops allPoints corners importRadius
parse a helical move gcode line and send the commands to the extruder .,def helicalMove self isCounterclockwise splitLine if self oldLocation None return location Vector3 self oldLocation self setFeedrate splitLine setPointToSplitLine location splitLine location location self oldLocation center Vector3 self oldLocation indexOfR getIndexOfStartingWithSecond R splitLine if indexOfR 0 radius getDoubleAfterFirstLetter splitLine indexOfR halfLocationMinusOld location self oldLocation halfLocationMinusOld 0 5 halfLocationMinusOldLength halfLocationMinusOld length centerMidpointDistance math sqrt radius radius halfLocationMinusOldLength halfLocationMinusOldLength centerMinusMidpoint getRotatedWiddershinsQuarterAroundZAxis halfLocationMinusOld centerMinusMidpoint normalize centerMinusMidpoint centerMidpointDistance if isCounterclockwise center setToVec3 halfLocationMinusOld centerMinusMidpoint else center setToVec3 halfLocationMinusOld centerMinusMidpoint else center x getDoubleForLetter I splitLine center y getDoubleForLetter J splitLine curveSection 0 5 center self oldLocation afterCenterSegment location center beforeCenterSegment self oldLocation center afterCenterDifferenceAngle getAngleAroundZAxisDifference afterCenterSegment beforeCenterSegment absoluteDifferenceAngle abs afterCenterDifferenceAngle steps int math ceil max absoluteDifferenceAngle 2 4 absoluteDifferenceAngle beforeCenterSegment length curveSection stepPlaneAngle getPolar afterCenterDifferenceAngle steps 1 0 zIncrement afterCenterSegment z beforeCenterSegment z float steps for step in range 1 steps beforeCenterSegment getRoundZAxisByPlaneAngle stepPlaneAngle beforeCenterSegment beforeCenterSegment z zIncrement arcPoint center beforeCenterSegment self moveExtruder arcPoint self moveExtruder location self oldLocation location
check that we can normalize to the sum of all bins,def test_whole_ws self output_ws NormaliseToUnity normalise_to_unity_test self assertEqual output_ws readY 0 0 0 1 if output_ws DeleteWorkspace output_ws
tests proper error handling when passing wrong properties or not passing required ones .,def test_wrong_properties self self assertRaises RuntimeError EnggFocus Bank 1 OutputWorkspace nop self assertRaises RuntimeError EnggFocus InputWrkspace anything_goes Bank 1 OutputWorkspace nop self assertRaises ValueError EnggFocus InputWorkspace foo_is_not_there Bank 1 OutputWorkspace nop self assertRaises RuntimeError EnggFocus InputWorkspace self __class__ _data_ws bnk 2 OutputWorkspace nop tbl CreateEmptyTableWorkspace self assertRaises RuntimeError EnggFocus InputWorkspace self __class__ _data_ws Detectors tbl OutputWorkspace nop self assertRaises RuntimeError EnggFocus InputWorkspace self __class__ _data_ws Bank 2 DetectorPositions tbl SpectrumNumbers 1 10 OutputWorkspace nop self assertRaises RuntimeError EnggFocus InputWorkspace self __class__ _data_ws DetectorPositions tbl SpectrumNumbers 999999999999999 OutputWorkspace nop self assertRaises ValueError EnggFocus InputWorkspace self __class__ _data_ws DetectorPositions tbl SpectrumNumbers 3 NormaliseByCurrent 4 OutputWorkspace nop self assertRaises RuntimeError EnggFocus InputWorkspace self __class__ _data_ws DetectorPositions tbl SpectrumNumbers 3 MaskBinsXMins 1 2 3 MaskBinsXMaxs 10 20 OutputWorkspace nop self assertRaises RuntimeError EnggFocus InputWorkspace self __class__ _data_ws DetectorPositions tbl SpectrumNumbers 3 MaskBinsXMins 1 2 3 OutputWorkspace nop self assertRaises RuntimeError EnggFocus InputWorkspace self __class__ _data_ws DetectorPositions tbl SpectrumNumbers 3 MaskBinsXMaxs 10 20 30 OutputWorkspace nop
"displays a widget in a window . : param widget_name : a qualified name of a widget , ie mantidqt.mywidget.mywidget : param script : a qualified name of a test function that can be run after the widget is created . the test function must have the signature :",def open_in_window widget_name script raw_input Please attach the Debugger now if required Press any key to continue setup_library_paths app QApplication w create_widget widget_name w setWindowTitle widget_name w show if script is not None try script_iter iter run_script script w pause_timer QTimer pause_timer setSingleShot True def idle if not pause_timer isActive try pause_sec script_iter next if pause_sec is not None pause_timer start int pause_sec 1000 except StopIteration pass except traceback print_exc timer QTimer timer timeout connect idle timer start except pass sys exit app exec_
reads vibrational modes ( frequencies and atomic displacements ) . : param file_obj : file object from which we read : param data : python dictionary to which k - point data should be added,def _read_modes self file_obj None data None freq num_freq 3 self _num_atoms AbinsModules AbinsConstants ROTATIONS_AND_TRANSLATIONS dim 3 atomic_disp np zeros shape num_freq self _num_atoms dim dtype AbinsModules AbinsConstants COMPLEX_TYPE end_msg while not self _parser block_end file_obj file_obj msg end_msg or self _parser file_end file_obj file_obj self _read_freq_block file_obj file_obj freq freq self _read_atomic_disp_block file_obj file_obj disp atomic_disp data frequencies np asarray freq astype dtype AbinsModules AbinsConstants FLOAT_TYPE casting safe data k_vectors np asarray 0 0 0 0 0 0 astype dtype AbinsModules AbinsConstants FLOAT_TYPE casting safe data weights np asarray 1 0 self _num_k 1 masses np asarray data atoms atom_ s atom mass for atom in range self _num_atoms temp1 np trace np einsum lki lkj lkij atomic_disp atomic_disp axis1 2 axis2 3 temp2 np einsum ij j ij temp1 masses norm np sum temp2 axis 1 atomic_disp np einsum ijk i ijk atomic_disp 1 0 np sqrt norm atomic_disp np einsum ijk j ijk atomic_disp np sqrt masses data atomic_displacements np asarray np transpose a atomic_disp axes 1 0 2
"function2d returns the 2d version of the bivariategaussian . input may be in two forms : 1 ) 1d array ( e.g. pos.ravel ( ) ) . this will be reshaped into an nx*ny*2 array , so it must contain nx*ny*2 elements . 2 ) 3d array of size a*b*2 . a and b are arbitrary integers . output : a 2d array either size nx*ny ( intput type 1 ) or a*b ( input type 2 ) with intensities of the bivariategaussian .",def function2D self t if t ndim 1 nX int self getAttributeValue nX nY int self getAttributeValue nY pos t reshape nX nY 2 elif t ndim 3 pos t X pos 0 Y pos 1 A self getParamValue 0 MuX self getParamValue 1 MuY self getParamValue 2 SigX self getParamValue 3 SigY self getParamValue 4 SigP self getParamValue 5 Bg self getParamValue 6 SigXY SigX SigY SigP Z A bivariate_normal X Y sigmax SigX sigmay SigY mux MuX muy MuY sigmaxy SigXY Z Bg return Z
performs convolution with an instrument resolution workspace .,def _convolve_with_res self resolution_ws function_ws_name logger notice Convoluting sample s with resolution s function_ws_name resolution_ws ConvolveWorkspaces OutputWorkspace function_ws_name Workspace1 function_ws_name Workspace2 resolution_ws
returns the request counts per day for a given resource and period .,def analytics self resource_type username id None start None end None resource_type self _validate_resource_type resource_type username self _validate_username username start end self _validate_period start end id self _validate_id resource_type id params if id is not None params update id id if start is not None and end is not None params update period start end uri URITemplate self baseuri resourceType username expand resourceType resource_type username username resp self session get uri params params resp geojson resp json self handle_http_error resp return resp
collect command line options and use gsl - lite package .,def main parser argparse ArgumentParser description Use gsl lite package epilog formatter_class argparse RawTextHelpFormatter parser add_argument v verbose action store_true help report additional information parser add_argument q quiet action store_true help do not report the cmake commands issued parser add_argument build folder dest build_folder default defBuildFolder type str metavar F help the CMake build folder deflt format deflt defBuildFolder parser add_argument generator dest generator default defGenerator type str metavar G help the CMake generator deflt format deflt defGenerator parser add_argument compiler dest compiler default defCompiler type str metavar C help the CMake compiler deflt format deflt defCompiler parser add_argument config dest config metavar C help the CMake configuration Debug Release parser add_argument install prefix dest install_pfx default defInstallPrefix type str metavar P help the CMake install prefix deflt format deflt defInstallPrefix parser add_argument cmake prefix dest cmake_pfx type str metavar P help the CMake prefix path parser add_argument gsl lite dir dest gsl_lite_dir type str metavar D help the gsl lite directory opt parser parse_args useGslLitePackage opt
creates a directory structure if it does n't exist yet .,def create_path path try os makedirs path except OSError as exception if exception errno errno EEXIST raise Exception Failed to create directory structure s Error s path exception
ensure that the ossec transport key pair exists . these keys are used to protect the connection between the ossec - server and ossec - agent .,pytest mark xfail pytest mark parametrize keyfile var ossec etc sslmanager key var ossec etc sslmanager cert def test_ossec_keyfiles File Sudo keyfile with Sudo f File keyfile assert f is_file assert oct f mode 0440 assert f user root assert f group ossec
"config handler for the "" server "" namespace .",def _server_namespace_handler k v atoms k split 1 if len atoms 1 if not hasattr cherrypy servers cherrypy servers servername k atoms if servername not in cherrypy servers from cherrypy import _cpserver cherrypy servers servername _cpserver Server cherrypy servers servername subscribe if k on if v cherrypy servers servername subscribe else cherrypy servers servername unsubscribe else setattr cherrypy servers servername k v else setattr cherrypy server k v
display the gui and load a file . this function should be called after the menu entry for the file is selected .,def execute self context filename self properties filepath log info user selected s filename self export_file filename context context return FINISHED
returns the data for the user specified by < id>. < i d > is the pardot id of the target user .,def read_by_id self id None kwargs response self _post path do read id id format id id params kwargs return response
a hook for filtering out certain dirs .,def filterDir self baseName fullPath return not baseName in self _ignoreBasenames or fullPath in self _ignoreDirs
add sql fragment to query .,def add self expr type text required False self _add_expr expr self _params type required
inserts reservoir level and timestamp info into an sqlite database .,def store_reservoir_level self timestamp reservoir_level self _cursor execute INSERT INTO reservoir_level VALUES _serialize_timestamp timestamp reservoir_level
keras classifier wrapper . note that the wrapped classifier should spit logits as output .,def __init__ self model u n Keras classifier wrapper n Note that the wrapped classifier should spit logits as output n layer_id len model layers 2 self model Model inputs model layers 0 input outputs model layers layer_id output self softmax Sequential self softmax add Lambda lambda X softmax X axis 1 input_shape 10
"setup our flask test app , this only gets executed once .",pytest yield_fixture scope session def app params DEBUG False TESTING True SERVER_NAME localhost 5000 WEBPACK_ASSETS_URL https yourdomainname_or_asset_cdn com assets _app create_app settings_override params ctx _app app_context ctx push _app add_url_rule index index yield _app ctx pop
create an event to call func ( ) at the time ' when ' .,def __init__ self when func self when when self func func
returns a bit vector representation ( list of ints ) of a pil image .,def imageToVector image image image convert 1 dither Image NONE vector numpy array list image getdata 100 astype uint32 return vector
asserts that two records are equal . pretty crude for now .,def assert_equal_records a b assert_equal a dtype b dtype for f in a dtype names af bf operator getitem a f operator getitem b f if not af is masked and not bf is masked assert_equal operator getitem a f operator getitem b f return
method to calculate the penalty on the basis of the value and alarm level .,def get_penalty self sase 0 0 for i in range self nreadings sase self get_value time sleep self interval sase sase self nreadings print SASE sase alarm self get_alarm pen 0 0 if alarm 0 95 alarm self pen_max if alarm 0 7 alarm self pen_max 2 0 pen alarm pen sase self niter 1 self penalties append pen self times append time time self values append sase self alarms append alarm return pen
closes the existing database connection and re - opens it .,def reconnect self self close self _db MySQLdb connect self _db_args self _db autocommit True
args : browser ( selenium.webdriver ) : the selenium - controlled browser that this page is loaded in . locator ( str ) : the locator that identifies which xblock this : class:`.xblock - editor ` relates to .,def __init__ self browser locator super BaseComponentEditorView self __init__ browser self locator locator
a set of assertions for an anonymous xblockuser .,def assert_is_anon_xb_user self xb_user self assertFalse xb_user opt_attrs ATTR_KEY_IS_AUTHENTICATED self assertIsNone xb_user full_name self assertListEqual xb_user emails
"enable the settings for a custom theme , whose files should be stored in env_root / themes / theme_name ( e.g. , edx_all / themes / stanford ) . at this moment this is actually just a fix for collectstatic , ( see https://openedx.atlassian.net/browse/tnl-726 ) , but can be improved with a full theming option also for studio in the future ( see lms.startup )",def enable_theme if settings THEME_NAME settings THEME_NAME None return assert settings FEATURES USE_CUSTOM_THEME settings FAVICON_PATH themes name images favicon ico format name settings THEME_NAME theme_root settings ENV_ROOT themes settings THEME_NAME settings STATICFILES_DIRS append u themes format settings THEME_NAME theme_root static
creates course action state entries with different states for the given action model class . creates both displayable ( should_display = true ) and non - displayable ( should_display = false ) entries .,def init_course_action_states self action_class def create_course_states starting_course_num ending_course_num state should_display True Creates a list of course state tuples by creating unique course locators with course numbers from starting_course_num to ending_course_num CourseState namedtuple CourseState course_key state should_display return CourseState CourseLocator org course run str num state should_display for num in range starting_course_num ending_course_num NUM_COURSES_WITH_STATE1 3 NUM_COURSES_WITH_STATE2 3 NUM_COURSES_WITH_STATE3 3 NUM_COURSES_NON_DISPLAYABLE 3 self courses_with_state1 create_course_states 0 NUM_COURSES_WITH_STATE1 state1 self courses_with_state2 create_course_states NUM_COURSES_WITH_STATE1 NUM_COURSES_WITH_STATE1 NUM_COURSES_WITH_STATE2 state2 self courses_with_state3 create_course_states NUM_COURSES_WITH_STATE1 NUM_COURSES_WITH_STATE2 NUM_COURSES_WITH_STATE1 NUM_COURSES_WITH_STATE2 NUM_COURSES_WITH_STATE3 state3 self course_actions_displayable_states self courses_with_state1 self courses_with_state2 self courses_with_state3 self courses_with_state3_non_displayable create_course_states NUM_COURSES_WITH_STATE1 NUM_COURSES_WITH_STATE2 NUM_COURSES_WITH_STATE3 NUM_COURSES_WITH_STATE1 NUM_COURSES_WITH_STATE2 NUM_COURSES_WITH_STATE3 NUM_COURSES_NON_DISPLAYABLE state3 should_display False for CourseState in self course_actions_displayable_states self courses_with_state3_non_displayable action_class objects update_state CourseState course_key CourseState state should_display CourseState should_display allow_not_found True
test returns proper value when have proper access,patch class_dashboard views has_instructor_access_for_class def test_section_problem_grade_distribution_has_access self has_access has_access return_value True response views section_problem_grade_distrib self request test test test 1 self assertEqual json dumps self simple_data response content
assert that a new course which has a required survey but user has not answered it yet,def test_user_not_yet_answered_required_survey self self assertTrue must_answer_survey self course self student temp_course CourseFactory create course_survey_required False self assertFalse must_answer_survey temp_course self student temp_course CourseFactory create course_survey_required True course_survey_name NonExisting self assertFalse must_answer_survey temp_course self student
test enrollment data is shown .,patch dict settings FEATURES DISPLAY_ANALYTICS_ENROLLMENTS True override_settings ANALYTICS_DASHBOARD_URL def test_show_enrollments_data self response self client get self url self assertTrue h2 Enrollment Information h2 in response content self assertTrue td Verified td in response content self assertTrue td Audit td in response content self assertTrue td Honor td in response content self assertTrue td Professional td in response content self assertFalse self get_dashboard_enrollment_message in response content
generates a set of image files based on image_file and stores them according to the sizes and filenames specified in ` profile_image_names ` .,def create_profile_images image_file profile_image_names image_obj Image open image_file width height image_obj size if width height side width if width height else height image_obj image_obj crop width side 2 height side 2 width side 2 height side 2 storage get_profile_image_storage for size name in profile_image_names items scaled_image_file _get_scaled_image_file image_obj size try storage save name scaled_image_file finally scaled_image_file close
ensure the notification function is not triggered when the unenrollment is for any mode other than verified ( i.e. any mode other than one for which refunds are presently supported ) . see the todo associated with xcom-371 in the signals module in the commerce package for more information .,mock patch commerce signals send_refund_notification ddt data CourseMode HONOR CourseMode PROFESSIONAL CourseMode AUDIT CourseMode NO_ID_PROFESSIONAL_MODE CourseMode CREDIT_MODE def test_notification_not_verified self mode mock_send_notification self course_enrollment mode mode with mock_create_refund status 200 response 1 2 3 self send_signal self assertFalse mock_send_notification called
test for inheritance subclass should not be tracked when superclass is called in a @donottrack decorated function,def test_donottrack_child_too self log_capt ModelWithCallStackMngr id_field 1 save ModelWithCallStckMngrChild id_field 1 child_id_field 1 save donottrack_subclass self assertEqual len log_capt call_args_list 0
restrict the user from accessing the course .,def _restrict_course self course_key country Country objects create country us restricted_course RestrictedCourse objects create course_key course_key enroll_msg_key embargo access_msg_key embargo CountryAccessRule objects create restricted_course restricted_course rule_type CountryAccessRule BLACKLIST_RULE country country
custom jsonificaton to support obj.to_dict protocol .,def jsonify obj status 200 headers None data JSONEncoder encode obj if callback in request args cb request args get callback data s s s cb cb data return Response data headers headers status status mimetype application json
recursively turn an object into a python primitive .,def obj_to_primitive obj if isinstance obj ObjectListBase return obj_to_primitive x for x in obj elif isinstance obj CloudpulseObject result for key in obj obj_fields if obj obj_attr_is_set key or key in obj obj_extra_fields result key obj_to_primitive getattr obj key return result else return obj
gets flatten plugins data form clusters from installation structures collection : param structure_keys_paths : list of keys paths in the installation structure : param cluster_keys_paths : list of keys paths in the cluster : param node_keys_paths : list of keys paths in the node : param inst_structures : list of installation structures : return : list of flatten plugins info,def get_flatten_nodes self structure_keys_paths cluster_keys_paths node_keys_paths inst_structures return self _get_flatten_subcluster_data nodes structure_keys_paths cluster_keys_paths node_keys_paths inst_structures
generates a weights according to the tricube bisquare function .,def tricube_bisquare_weights data n len data s6 6 median map abs data weights tricube_weights n weights2 for i in range 2 n weights2 append weights i 1 data i s6 2 2 return weights2 0 weights2 0 weights2
get a probability distribution over alternatives,def alternative_probabilities self prop language dictionaries country None key self cache_key prop language dictionaries country country if key not in self cache properties self get_property prop language country country default None if properties is None return None None alternatives probs alternative_probabilities properties if alternatives is None return None None forms form_probs for props prob in zip alternatives probs phrases phrase_probs self form_probabilities props language dictionaries dictionaries forms extend p props for p in phrases form_probs extend prob p for p in phrase_probs sample_probability properties get sample_probability if sample_probability is not None sample_phrases for dictionary in dictionaries phrases self sample_phrases get language dictionary for canonical surface_forms in six iteritems phrases sample_phrases append canonical sample_phrases extend surface_forms forms extend p properties for p in sample_phrases form_probs extend float sample_probability len sample_phrases len sample_phrases try check_probability_distribution form_probs except AssertionError print values were format forms raise form_probs_cdf cdf form_probs self cache key forms form_probs_cdf return self cache key
instantiate a vm template with a given hostname and owner .,def template_to_instance template hostname owner cluster template cluster beparams vcpus template vcpus hvparams hv template hypervisor or cluster info default_hypervisor kvm hv kvm pvm hv xen pvm hvm hv xen hvm kvm_or_hvm kvm or hvm kvm_or_pvm kvm or pvm if kvm_or_hvm hvparams update boot_order template boot_order hvparams update cdrom_image_path template cdrom_image_path hvparams update nic_type template nic_type hvparams update disk_type template disk_type if kvm_or_pvm hvparams update kernel_path template kernel_path hvparams update root_path template root_path if kvm hvparams update cdrom2_image_path template cdrom2_image_path hvparams update serial_console template serial_console memory template memory if has_balloonmem cluster minram template minmem beparams minmem minram beparams maxmem memory else beparams memory memory vcpus template vcpus disk_size template disks 0 size kwargs os template os hypervisor hv ip_check template ip_check name_check template name_check beparams beparams no_install template no_install start template start hvparams hvparams if template iallocator default_iallocator cluster info default_iallocator kwargs update iallocator default_iallocator else kwargs update pnode template pnode if template snode kwargs update snode template snode elif template disk_template drdb msg Disk template set to drdb but no secondary node set raise RuntimeError msg job_id cluster rapi CreateInstance create hostname template disk_template template disks template nics kwargs vm VirtualMachine vm cluster cluster vm hostname hostname vm ram memory if has_balloonmem cluster vm minram minram vm virtual_cpus vcpus vm disk_size disk_size vm owner owner vm ignore_cache True vm save job Job objects create job_id job_id obj vm cluster cluster job save vm last_job job vm save owner permissable grant admin vm return vm
nx : dllcharacteristics bit 0x100 signifies nxcompat ( dep ),def check_PE_NX executable arch bits get_PE_dll_characteristics executable return bits IMAGE_DLL_CHARACTERISTICS_NX_COMPAT IMAGE_DLL_CHARACTERISTICS_NX_COMPAT
test methods that take integer arguments,def testIntegerArguments self self assertRaises AssertionError self scene setSize moo baa
"query reverse dns for ( ip ) and return ( ip , hostname )",def __reverser__ arg host ip_version arg return host dns_resolve_reverse host
": param providers : a list or single provider used to connect to ethereum : type providers : instance of ` web3.providers.base.baseprovider ` : param hex - string addr : the address of the ens registry on - chain . if not provided , ens.py will default to the mainnet ens registry address .",def __init__ self providers None addr None self web3 init_web3 providers ens_addr addr if addr else ENS_MAINNET_ADDR self ens self web3 eth contract abi abis ENS address ens_addr self _resolverContract self web3 eth contract abi abis RESOLVER
short function that prepares map generation and then dispatches to generation modules,def dispatch_gen settings rmgseed 0 if rmgseed 0 print seed str rmgseed seed rmgseed module_name modules s __init__ settings module_name rmg_module __import__ module_name fromlist module_name max_attempts 5 for i in range max_attempts hmap None print i At attempt d of d for for module s to generate given these settings i 1 max_attempts settings module_name hmap rmg_module gen settings if hmap None print Successful at attempt d d for module s to generate given these settings i 1 max_attempts settings module_name break else print Failed at attempt d d for module s to generate given these settings i 1 max_attempts settings module_name return hmap
"read an image file ( png , bmp , jpeg ... ) .",def ffmpeg_read_image filename with_mask True if with_mask pix_fmt rgba else pix_fmt rgb24 reader FFMPEG_VideoReader filename pix_fmt pix_fmt check_duration False im reader lastread del reader return im
test capturing exceptions in a block by using ` capture_exceptions ` method provided by ` qtbot ` .,def test_capture_exceptions_qtbot_context_manager testdir testdir makepyfile import pytest from pytestqt qt_compat import qt_api QWidget qt_api QWidget Signal qt_api Signal class MyWidget QWidget on_event Signal def test_widget qtbot widget MyWidget qtbot addWidget widget def raise_on_event raise RuntimeError error widget on_event connect raise_on_event with qtbot capture_exceptions as exceptions widget on_event emit assert len exceptions 1 assert str exceptions 0 1 error result testdir runpytest result stdout fnmatch_lines 1 passed
signals the parent that an item has been added to the list : param item : str,Event def event_add self item
"writes several objects at once . @datas - can be dict : { key : value } or iterable container of tuples ( elliptics . ioattr , data )",def bulk_write self datas if type datas is dict return super Session self bulk_write datas items else return super Session self bulk_write datas
test getting connectivity status does not fail .,def connected_test self connected self network_interface Connected self assertIn connected True False
set which network services should be allowed on the target system firewall .,def set_enabled_services self enabled_services self _enabled_services list enabled_services self enabled_services_changed emit log debug Services that will be allowed through the firewall s self _enabled_services
"true if the device is marked boot dirty , false otherwise .",property def bootDirty self return bool self __device boot_dirty
return a short description of the company .,def desc self config return self _parse_response attribute description config
assert error raised if env is not found in json,def test_no_key_error_on_invalid_env load settings filename JSON env FOOBAR silent True
test private method trajectory._get_delta_annual ( ),def test_get_delta_annual_2 do_get_delta_annual_test SAMPLE_ANNUAL_PARALLAX_FILE_02
container = xcscheme object - scheme that is having an action performed xcparse_object = xcparse object scheme_config_settings = dictionary containing any additional environment variables to set,def performAction self container xcparse_object configuration_name additional_settings if self root for child in self root children project_path xcrun_helper resolvePathFromLocation child target ReferencedContainer container 2 path base_path container 2 path base_path project filter lambda proj proj path obj_path project_path xcparse_object projects if len project 0 project project 0 else project xcparse_object project_constructor project_path if USE_XCODE_BUILD 1 xcrun_helper perform_xcodebuild project container 1 name test additional_settings else print implement me
called by gui engine when confirm trigger is activated every screen that sends data to the game server should implement this method,def leave_confirm self pass
get distance functions for each column 's dtype,def _prepare_by_column_dtype self X if not isinstance X pandas DataFrame raise TypeError X must be a pandas DataFrame numeric_columns nominal_columns numeric_ranges fit_data numpy empty_like X for i dt in enumerate X dtypes col X iloc i if is_categorical_dtype dt if col cat ordered numeric_ranges append col cat codes max col cat codes min numeric_columns append i else nominal_columns append i col col cat codes elif is_numeric_dtype dt numeric_ranges append col max col min numeric_columns append i else raise TypeError unsupported dtype r dt fit_data i col values self _numeric_columns numpy asarray numeric_columns self _nominal_columns numpy asarray nominal_columns self _numeric_ranges numpy asarray numeric_ranges dtype float self X_fit_ fit_data
fill many paragraphs with optional indentation .,def fill text width initindent hangindent global para_re space_re if para_re is None para_re re compile n n n s s re M space_re re compile def findparas start 0 while True m para_re search text start if not m uctext unicode text start encoding encoding w len uctext while 0 w and uctext w 1 isspace w 1 yield uctext w encode encoding encoding uctext w encode encoding encoding break yield text start m start 0 m group 1 start m end 1 return join util wrap space_re sub util wrap para width width initindent hangindent rest for para rest in findparas
change the number of bytes that will be cached .,def resize self max_size after_cleanup_size None self _update_max_size max_size after_cleanup_size after_cleanup_size max_cache max int max_size 512 1 self _update_max_cache max_cache
creates an array from any object exposing the array interface .,def array source_array ctx None dtype None aux_types None if spsp is not None and isinstance source_array spsp csr csr_matrix return _sparse_array source_array ctx ctx dtype dtype aux_types aux_types elif isinstance source_array NDArray and source_array stype default return _sparse_array source_array ctx ctx dtype dtype aux_types aux_types else return _array source_array ctx ctx dtype dtype
object that mocks the urllib2 module to fake requests to mldata .,def __init__ self mock_datasets self mock_datasets mock_datasets
return all pkginfo files with testing catalogs .,def get_testing_pkginfos repo pkginfos pkginfo_dir os path join repo pkgsinfo for dirpath _ filenames in os walk pkginfo_dir for pfile in fname for fname in filenames if is_pkginfo fname try path os path join dirpath pfile pkginfo_file read_plist path except ExpatError continue if is_testing pkginfo_file and not is_placeholder pkginfo_file get name pkginfos path pkginfo_file return pkginfos
report a violation using reporter .,def _report self violation self _reporter report violation
save scikit learn pipeline to external location,def save_pipeline self pipeline location self create_work_folder pipeline_folder self work_folder pipeline if not os path exists pipeline_folder logger info creating folder s pipeline_folder os makedirs pipeline_folder tmp_file pipeline_folder p joblib dump pipeline tmp_file futil fu FileUtil aws_key self aws_key aws_secret self aws_secret futil copy pipeline_folder location
check if layer has tool changes : return : true or false,def has_tool_changes self for cmd _ in self lines if cmd and gcode is_tool_change cmd is not None self tool_change_count 1 return self tool_change_count
submits the currently selected form .,def submit self kw if self form is None raise BrowserError No form selected req self form click kw return self do_request req
mimics `` django.shortcuts.render `` but uses a templateresponse for `` mezzanine.core.middleware.templatefordevicemiddleware ``,def render request templates dictionary None context_instance None kwargs u n Mimics django shortcuts render but uses a TemplateResponse for n mezzanine core middleware TemplateForDeviceMiddleware n warnings warn u mezzanine utils views render is deprecated and will be removed in a future version Please update your project to use Django s TemplateResponse which now provides equivalent functionality DeprecationWarning dictionary dictionary or if context_instance context_instance update dictionary else context_instance RequestContext request dictionary return TemplateResponse request templates context_instance kwargs
create and save a customuser with the given username and password .,def _create_user self username password is_staff is_superuser extra_fields u now timezone now if not username raise ValueError u The given username must be set is_active extra_fields pop u is_active True user self model username username is_staff is_staff is_active is_active is_superuser is_superuser last_login now date_joined now extra_fields user set_password password user save using self _db return user
format the object 's representation the same as praw would .,def __repr__ self return UserNotes subreddit format self subreddit display_name
reads data from stream and switch state .,socket_exception def read self assert self status in WAIT_LEN WAIT_MESSAGE if self status WAIT_LEN self _read_len elif self status WAIT_MESSAGE read self socket recv self len len self message if len read 0 logger error can t read frame from socket get d of d bytes len self message self len self close return self message read if len self message self len self status WAIT_PROCESS
create a local cluster with 2 workers .,classmethod def setUpClass cls num_workers 2 gpu_mem_frac 0 7 num_workers default_config config_pb2 ConfigProto default_config gpu_options per_process_gpu_memory_fraction gpu_mem_frac workers _ test_util create_local_cluster num_workers num_ps 0 worker_config default_config cls _master_target workers 0 target
connect a ` check_numerics ` to every floating point tensor .,tf_export add_check_numerics_ops def add_check_numerics_ops if context executing_eagerly raise RuntimeError add_check_numerics_ops is not compatible with eager execution To check for Inf s and NaN s under eager execution call tfe seterr inf_or_nan raise once before executing the checked operations check_op for op in ops get_default_graph get_operations for output in op outputs if output dtype in dtypes float16 dtypes float32 dtypes float64 if op _get_control_flow_context is not None raise ValueError tf add_check_numerics_ops is not compatible with TensorFlow control flow operations such as tf cond or tf while_loop message op name str output value_index with ops control_dependencies check_op check_op array_ops check_numerics output message message return control_flow_ops group check_op
construct exponential distribution with parameter ` rate ` .,def __init__ self rate validate_args False allow_nan_stats True name Exponential parameters dict locals with ops name_scope name values rate as name self _rate ops convert_to_tensor rate name rate super Exponential self __init__ concentration array_ops ones dtype self _rate dtype rate self _rate allow_nan_stats allow_nan_stats validate_args validate_args name name self _reparameterization_type True self _parameters parameters self _graph_parents self _rate
creates experiment for gradient boosted decision trees .,def _make_experiment_fn output_dir data tf contrib learn datasets mnist load_mnist train_input_fn get_input_fn data train FLAGS batch_size eval_input_fn get_input_fn data validation FLAGS eval_batch_size return tf contrib learn Experiment estimator _get_tfbt output_dir train_input_fn train_input_fn eval_input_fn eval_input_fn train_steps None eval_steps FLAGS num_eval_steps eval_metrics None
run the forward pass of ptbmodel .,def call self input_seq training y self embedding input_seq if training y tf nn dropout y self keep_ratio y self rnn y training training 0 return self linear tf reshape y self _output_shape
check warping accuracy by comparing to hardcoded warped images .,def testSmileyFace self test_data_dir test test_src_dir_path contrib image python kernel_tests test_data input_file test_data_dir Yellow_Smiley_Face png with self test_session as sess input_image self load_image input_file sess control_points np asarray 64 59 180 64 59 39 111 180 39 111 90 143 58 134 180 58 134 control_point_displacements np asarray 10 5 10 5 10 5 10 5 0 0 0 0 0 10 20 10 25 10 10 75 control_points_op constant_op constant np expand_dims np float32 control_points 1 0 0 control_point_displacements_op constant_op constant np expand_dims np float32 control_point_displacements 1 0 0 float_image np expand_dims np float32 input_image 255 0 input_image_op constant_op constant float_image for interpolation_order in 1 2 3 for num_boundary_points in 0 1 4 warp_op _ sparse_image_warp sparse_image_warp input_image_op control_points_op control_points_op control_point_displacements_op interpolation_order interpolation_order num_boundary_points num_boundary_points with self test_session as sess warped_image sess run warp_op out_image np uint8 warped_image 0 255 target_file test_data_dir Yellow_Smiley_Face_Warp interp clamp png format interpolation_order num_boundary_points target_image self load_image target_file sess self assertAllClose target_image out_image atol 2 rtol 0 001
returns a md code block showing the function signature .,def _build_signature obj_info use_full_name True if obj_info full_name tf range return python tf range limit delta 1 dtype None name range tf range start limit delta 1 dtype None name range parts python parts extend dec for dec in obj_info decorators signature_template name sig if not obj_info signature sig elif len obj_info signature 1 sig obj_info signature 0 else sig n join s sig_item for sig_item in obj_info signature sig n sig n if use_full_name obj_name obj_info full_name else obj_name obj_info short_name parts append signature_template format name obj_name sig sig parts append n n return n join parts
set state when loading pickle .,def __setstate__ self state self __dict__ update state if description not in self __dict__ self description
test to ensure elif works as expected,def test_elif u two_way_conversion_test u if x y n print one nelif True n print two n n u if x y n console log one n else if true n console log two n n
flatten one level of nesting .,def flatten list_of_lists return itertools chain from_iterable list_of_lists
write a sequence of normally distributed histograms to writer .,def WriteHistogramSeries writer tag mu_sigma_tuples n 20 step 0 wall_time _start_time for mean stddev in mu_sigma_tuples data random normalvariate mean stddev for _ in xrange n histo _MakeHistogram data summary tf Summary value tf Summary Value tag tag histo histo event tf Event wall_time wall_time step step summary summary writer add_event event step 10 wall_time 100
"base distribution , p(x ) .",property def distribution self return self _distribution
a logging server to serialize writes to the log file from multiple processes .,def loggingserver log_file status_queue logging basicConfig filename os path expanduser log_file format asctime s processName 11s threadName 10s module 20s levelname 8s message s level logging INFO sock serversocket status_queue put sock sock getsockname sock start_accepting while True if not status_queue empty status_queue get sock close _drain_queue sock queue break try obj sock queue get True 10 _handleLogRecord obj except EmptyQueue pass
"scans ` input_buffer ` for lzma - like data . returns a list of ( position , "" the data found decompressed "" ) .",def get_lzma_chunks input_buffer ph possible_headers find_lzma_headers input_buffer ph append len input_buffer 1 result for this_header next_header in zip ph ph 1 try data length lzma_decode input_buffer this_header next_header except AssertionError continue result append this_header data return result
generate a method for the given thrift service .,def generate_method service_module service_name method_name assert service_module assert service_name assert method_name args_type getattr service_module method_name _args result_type getattr service_module method_name _result None serializer ThriftSerializer result_type if result_type is None def not_supported self args kwags raise OneWayNotSupportedError TChannel Thrift does not currently support oneway procedues return not_supported result_spec result_type thrift_spec endpoint s s service_name method_name gen coroutine def send self args kwargs params inspect getcallargs getattr service_module Iface method_name self args kwargs params pop self call_args args_type for name value in params items setattr call_args name value tracer tracing ClientTracer channel self tchannel span headers tracer start_span service service_name endpoint method_name headers body serializer serialize_body call_args header serializer serialize_header headers if hasattr self tchannel request tracing apply_trace_flag span self trace True with span response yield self tchannel request hostport self hostport service self service send arg1 endpoint arg2 header arg3 body headers self protocol_headers body yield response get_body else with span response yield self tchannel call scheme schemes THRIFT service self service arg1 endpoint arg2 header arg3 body hostport self hostport trace self trace tracing_span span body response body call_result serializer deserialize_body body if not result_spec raise gen Return None for exc_spec in result_spec 1 exc getattr call_result exc_spec 2 if exc is not None raise exc if result_spec 0 success getattr call_result result_spec 0 2 if success is not None raise gen Return success else raise gen Return None from thrift import Thrift raise Thrift TApplicationException Thrift TApplicationException MISSING_RESULT s failed did not receive a result as expected method_name send __name__ method_name return send
: return : command plugin class,pytest fixture def CommandPlugin from tests test_plugins commands_plugin import CommandPlugin return CommandPlugin
: param wallet_address : string representation of a wallet address : type wallet_address : str : raises valueerror : thrown when one of the arguments are invalid,def __init__ self wallet_address super WalletAddress self __init__ if not isinstance wallet_address str raise ValueError Wallet address must be a string self _wallet_address wallet_address
encode a crawl request message . : param message : message.impl of crawlrequestpayload.impl : return encoding ready to be sent of the network of the message,staticmethod def _encode_crawl_request message return pack crawl_request_format EMPTY_PK message payload requested_sequence_number 10
testing whether the right availability of a file is returned,def test_get_availability self download_state DownloadState self mock_download DLSTATUS_DOWNLOADING None 0 6 download_state stats spew self assertEqual download_state get_availability 0 download_state stats spew completed 1 0 self assertEqual download_state get_availability 1 0 download_state stats spew completed 0 6 self assertEqual download_state get_availability 0 0
return the next transaction number from the database,def get_next_transaction_number self highest_transaction_number self execute u SELECT MAX transaction_number FROM transactions fetchone if not highest_transaction_number 0 return 1 return highest_transaction_number 0 1
removes unwanted stripe artifact in frames with non - perfect bias or sky subtraction . encountered this case on an lbt data cube .,def frame_remove_stripes array lines array 50 lines np vstack lines array 50 mean lines mean axis 0 for i in range array shape 1 array i array i mean i return array
load list of messages from _ message files,def get_messages basepath mtype u path os path join basepath u _messages_ mtype u json messages if os path exists path with open path u r as msgfile messages json loads msgfile read return messages
equivalent to dividing each dimension with the corresponding width ( not width^2 ) and using the standard gaussian kernel .,def eval self X Y sigma2s self sigma2s Xs old_div X np sqrt sigma2s Ys old_div Y np sqrt sigma2s k KGauss 1 0 return k eval Xs Ys
list all issue types . optional parameter to list issue types by a given project .,click command click argument project_key default pass_accountable def issuetypes accountable project_key projects accountable issue_types project_key headers sorted id name description rows for key issue_types in sorted projects items for issue_type in issue_types rows append key v for k v in sorted issue_type items if k in headers rows insert 0 project_key headers print_table SingleTable rows
returns a date ranges for the given granularity based on the given date .,def get_date_ranges base_date granularity start end get_datetime_ranges make_aware datetime datetime combine base_date datetime time granularity return start date end date
check if command line flag is required to enable c99 support .,def check_c99_flags self return self _check_flags self _c99_flags self _c99_test_program c CFLAGS
"performs create , but firstly disables synchro of some user defined fields ( if any )",def create_with_fks ct obj pk skip getattr obj SYNCHRO_SKIP raw obj __class__ for f in skip setattr obj f getattr raw f return save_with_fks ct obj pk
initialise an instance of a module makefile .,def __init__ self args kw if qt not in kw kw qt QtCore QtGui QtHelp QtGuiModuleMakefile __init__ self args kw
"convenience function : detect file extension and read via atomistica or ase . if reading a netcdf files , frame numbers can be appended via ' @ ' . e.g. , a = read('traj.nc@5 ' )",def read fn kwargs ext fn fn rfind split if len ext 1 if ext 0 out or ext 0 dat dirname os path dirname fn if len dirname 0 dirname cycfn dirname cyc dat if os path exists cycfn return read_atoms fn cycfn cycfn return read_atoms fn elif ext 0 nc traj NetCDFTrajectory fn kwargs return traj 1 else return ase io read fn kwargs elif len ext 2 if ext 0 nc frame int ext 1 fn fn fn rfind traj NetCDFTrajectory fn return traj frame else return ase io read fn kwargs else return ase io read fn kwargs
token function pulled from django 1.11,def _make_token_with_timestamp self user timestamp ts_b36 int_to_base36 timestamp hash salted_hmac self key_salt unicode user pk unicode timestamp hexdigest 2 return s s ts_b36 hash
updates cluster assignments using distances . ties are broken randomly,def _update_clusters self def find_min_center dists minimizing_clusters np where dists np min dists 0 if len minimizing_clusters 1 return minimizing_clusters else return np random choice minimizing_clusters size 1 self clusters np apply_along_axis find_min_center 1 self dist ravel
add the signup towards the top of the list .,def prioritize_wl_signup waitlist_signup top_spot False wl waitlist_signup waitlist if top_spot waitlist_signup manual_order wl first_of_priority else waitlist_signup manual_order wl last_of_priority waitlist_signup save
exception occurs if items are empty in json credentials file .,def test_credentials_from_json_empty_items self path_to_json_credentials PATH_CRED credentials_usernameempty_PUBLIC json with self assertRaises CredentialsFormatError _inst PIDClientCredentials load_from_JSON path_to_json_credentials
only a person himself can update his own information,def can_update self user pk return user email pk or user is_admin
"converts article to a dict which can later be converted to json example format : { "" key "" : 111 "" date "" : "" 01/02/1999 "" , "" editor "" : "" james jamerson "" , "" title "" : "" a modest proposal "" , "" newspaper "" : "" random newspaper "" , "" location "" : location ( ) , "" link "" : "" www.website.example "" }",def toJSON self tempD tempD key self key tempD date 0 1 2 format self month self day self year if self issue editor is not None tempD editor self issue editor else tempD editor Unavailable if self title tempD title self title else tempD title Article str self key tempD newspaper self newspaper title tempD location str self newspaper location tempD link self link return tempD
tests the shape of the weights .,def test_weights self gmm gmm_lib GMM self num_centers initial_clusters self initial_means random_seed 4 config run_config RunConfig tf_random_seed 2 gmm fit input_fn self input_fn steps 0 weights gmm weights self assertAllEqual list weights shape self num_centers
"creates a ` wait_next_block ` function , that will wait ` timeout ` seconds ( ` none ` = indefinitely ) for a new block to appear .",def wait_next_block_factory app timeout None chain app services chain new_block_evt gevent event Event def _on_new_block app log DEV new block mined new_block_evt set chain on_new_head_cbs append _on_new_block def wait_next_block bn chain chain head number chain consensus_manager log waiting for new block block bn new_block_evt wait timeout new_block_evt clear if chain chain head number bn chain consensus_manager log new block event block chain chain head number elif chain chain head number bn chain consensus_manager log wait_next_block timed out block bn return wait_next_block
"returns all the legal moves for the given color . ( 1 for white , -1 for black",def get_legal_moves self color moves set for square in self get_squares color newmoves self get_moves_for_square square moves update newmoves return list moves
get a random seed based on expname and current time .,def get_seed expname if MPI COMM_WORLD Get_rank 0 s expname str time time return int join re findall d s 4294967295 return None
add a tensor or op as result with given name,def add_result self name result self results name result
find out what items are documented in source/*.rst see ` get_documented_in_lines ` .,def get_documented filenames documented for filename in filenames f open filename r lines f read splitlines documented update get_documented_in_lines lines filename filename f close return documented
this test tests the simplest water bridge to see if count_by_type ( ) works . : return :,def test_count_by_type_single_link self grofile Test gro file 5 1ALA N 1 0 000 0 000 0 000 1ALA H 2 0 100 0 000 0 000 2SOL OW 3 0 300 0 000 0 000 2SOL HW2 4 0 400 0 000 0 000 4ALA O 5 0 600 0 000 0 000 1 0 1 0 1 0 u MDAnalysis Universe StringIO grofile format gro wb WaterBridgeAnalysis u protein and resid 1 protein and resid 4 wb run verbose False assert_equal wb count_by_type tolist 1 4 ALA 1 H ALA 4 O 1 0
@params : image is the image that we 'll be messing with bounds is a quadrilateral - tuple specifying where to place the image data is what will be encoded in the qr code inserts a qr code into the image at the specified bounds the new qr code should fit the bounds and seem natural ( like it was the original imge ),def insertQR image bounds data pass
called on start of a test case .,def OnTestCaseStarting self run test variationCount if self firstIter or variationCount self lastTestCount 1 or variationCount self heartBeat 0 self _writeMsg On test variation d variationCount self firstIter False self lastTestCount variationCount
it should get report by name,def test_print_action_for_report_name_gets_report self with mock patch object self Model _get_report_from_name as mk expect test self Model print_action_for_report_name expect mk assert_called_once_with expect
"constructs connections from a square grid starting at ( 0 , 0 ) until ( size-1 , size-1 ) with connections between adjacent and diagonal nodes . diagonal nodes have a weight of weight*sqrt(2 ) : param size : the size of the square grid to construct - type : integer : param weight : the weight between orthogonal nodes . - type : numeric : return : none",def gridify self size weight rt2 math sqrt 2 acceptable_offsets 1 1 rt2 1 0 1 1 1 rt2 0 1 1 0 1 1 1 1 rt2 1 0 1 1 1 rt2 for x in range 0 size for y in range 0 size for offset in acceptable_offsets nx x offset 0 ny y offset 1 if nx 0 and ny 0 and nx size and ny size self add_edge x y nx ny weight offset 2
"for ` doc_id ` returns a list of : [ 0 ] the repo name and , [ 1 ] the path from the repo to the doc file . this is useful because ( if you know the remote ) , it lets you construct the full path .",def get_repo_and_path_fragment self doc_id shard self get_shard doc_id return shard name shard get_rel_path_fragment doc_id
list all answers : return :,def list self answers Answer query all return answers
"takes a chute object and uses the key : networkinterfaces to return a list of the internal network interfaces that will exist in the chute ( e.g. , eth0 , eth1 , ... )",def getInternalIntfList ch intfs ch getCache networkInterfaces if not intfs return None l for i in intfs l append i internalIntf return l
see connections . connection.__init _ _ ( ) for information about defaults .,gen coroutine def connect args kwargs from connections import Connection conn Connection args kwargs yield conn connect raise gen Return conn
imports puppet - foreman_scap_client puppet classes .,def import_scap_client_puppet_classes self Navigator self browser go_to_puppet_classes self click locators puppetclass import if self wait_until_element locators puppetclass environment_default_check self click locators puppetclass environment_default_check self click locators puppetclass update else self click locators puppetclass cancel
add / remove domain from / to organization .,tier2 def test_positive_update_domain session domain entities Domain create org entities Organization create with session session organization update org name domains resources assigned domain name org_values session organization read org name assert org_values domains resources assigned 0 domain name session organization update org name domains resources unassigned domain name org_values session organization read org name assert len org_values domains resources assigned 0 assert domain name in org_values domains resources unassigned
* deprecated * use keyword ` not deprecated with doc ` instead !,def deprecated_library_keyword self pass
creates a task to export an ee image .,staticmethod def image image description myExportImageTask config None config config or copy if scale not in config and crs_transform not in config config scale 1000 if driveFileNamePrefix not in config and gmeProjectId not in config config driveFileNamePrefix description if region in config config region Export _GetSerializedRegion config get region return Export _CreateTask Task Type EXPORT_IMAGE image description config
override superclass admin_view to provide our own auth flow .,def admin_view self view cacheable False def inner request args kwargs if not self has_permission request if request path reverse admin logout current_app self name index_path reverse admin index current_app self name return HttpResponseRedirect index_path from django contrib auth views import redirect_to_login if not request user is_authenticated return redirect_to_login request get_full_path reverse admin login current_app self name else return HttpResponseForbidden _ Permission Denied return view request args kwargs if not cacheable inner never_cache inner if not getattr view csrf_exempt False inner csrf_protect inner return update_wrapper inner view
combine the input files to a big output file,def _merge_files self input_files output_file with open output_file mode wb as out for input_file in input_files out write open input_file mode rb read
does the data look like a client to server ( cts ) or server to client ( stc ) traffic ?,staticmethod def _cts_or_stc data if data transport if data transport type TCP flags data transport flags if syn_ack in flags or fin_ack in flags return STC if syn in flags or fin in flags return CTS if sport in data transport sport data transport sport dport data transport dport if dport 1024 and sport dport return CTS if sport 1024 and sport dport return STC return STC if sport dport else CTS if src in data packet and dst in data packet src net_utils inet_to_str data packet src dst net_utils inet_to_str data packet dst if net_utils is_internal src and not net_utils is_internal dst return CTS if net_utils is_internal dst and not net_utils is_internal src return STC return CTS
convert a type code to the class it represents,def TypeCodeToType typeCode if typeCode in b d f s return float elif typeCode in i l return int elif typeCode in c return str else raise Exception Unrecognised type code typeCode return
grammar for files found in the overall input files .,classproperty staticmethod def file return Optional Word alphanums setResultsName alias Suppress Literal Suppress White Word approved_printables setResultsName filename
ensure tput reports the correct screen sizes when executed in the bash shell,def test_tput_output self screen_sizes 80 500 800 45 30 250 cols_cmd tput cols lines_cmd tput lines for size in screen_sizes self linux_pty_bash update_screen_size size 0 size 1 self _reset_shell_output for char in cols_cmd self linux_pty_bash send_keypress char self linux_pty_bash send_keypress enter data self _read_bytes_from_shell 512 timeout 0 5 cols data decode ascii split r n 1 self assertEqual int cols size 1 for char in lines_cmd self linux_pty_bash send_keypress char self linux_pty_bash send_keypress enter data self _read_bytes_from_shell 512 timeout 0 5 lines data decode ascii split r n 1 self assertEqual int lines size 0
reseeds all simulations such that each simulation is started with a unique seed . the random selection of new seeds is seeded with the value given in ' seed ' .,def reseed_simulations self seed self hawkes_simu _pp reseed_random_generator seed if seed 0 np random seed self seed new_seeds np random randint 0 2 31 1 self n_simulations new_seeds new_seeds astype int32 else new_seeds np ones self n_simulations dtype int32 seed for simu seed in zip self _simulations new_seeds simu seed seed item
read & parse response http headers,def read_http_resp_header self reader line reader read_line if line is None return line line line strip if not utils is_response line return None resp_header HttpResponseHeader resp_header status_line line try resp_header status_code int line split 1 except Exception pass lines line header_dict self read_headers reader lines if content length in header_dict resp_header content_len int header_dict content length if transfer encoding in header_dict and chunked in header_dict transfer encoding resp_header chunked True resp_header content_type header_dict content type resp_header compress utils get_compress_type header_dict content encoding resp_header connection_close header_dict connection close resp_header raw_data n join lines return resp_header
test query for the ads classic ned support - ned returns ambiguous results,httpretty activate def test_classic_query_search_ambiguous self NED_URL self app config get OBJECTS_NED_URL SOLRQUERY_URL self app config get OBJECTS_SOLRQUERY_URL neddata u NameResolver u NED Egret u Copyright u C 2018 California Institute of Technology u Preferred u ObjType u RefCode None u Value u G u Position u PosAngle 0 0 u UncSemiMinor 2 222222222e 05 u RefCode u 2010ApJS 189 37E u RA 10 68479292 u Dec 41 269065 u UncSemiMajor 2 222222222e 05 u Name u MESSIER 031 u Redshift u QualityFlag None u Uncertainty 1 29999999e 05 u RefCode u 1991RC3 9 C 0000d u Value 0 00100100006 u QueryTime u Tue Feb 13 08 22 54 2018 u Interpreted u Aliases a b c u Version u 2 0 u Supplied u NGC 224 u ResultCode 1 u StatusCode 100 solrdata u responseHeader u status 0 u QTime 89 u params u q u nedid 3C_273 OR nedid NGC_0224 year 2016 2018 u rows u 10000 u fl u bibcode u wt u json u response u start 0 u numFound 43 u docs u bibcode u 2016ApJ 817 111D u bibcode u 2016A A 587A 52M httpretty register_uri httpretty POST NED_URL content_type application json status 200 body s json dumps neddata httpretty register_uri httpretty GET SOLRQUERY_URL content_type application json status 200 body s json dumps solrdata r self client post url_for classicobjectsearch content_type application json data json dumps objects NGC 224 self assertTrue r status_code 200 expected u ambiguous NGC 224 a b c u data u 2016ApJ 817 111D u 2016A A 587A 52M self assertEqual r json expected
calculate start time given the end time based on relativedelta fields stored in the instance,def to_start self end begin end relativedelta relativedelta self to_custom_dict return begin
add cookies in the request to the cookiejar .,def getcookies self fp u2request self cookiejar extract_cookies fp u2request
not so applicable for this sample,def cluster_lsun start_centers 1 0 3 5 2 0 0 5 3 0 3 0 template_clustering start_centers FCPS_SAMPLES SAMPLE_LSUN criterion splitting_type BAYESIAN_INFORMATION_CRITERION template_clustering start_centers FCPS_SAMPLES SAMPLE_LSUN criterion splitting_type MINIMUM_NOISELESS_DESCRIPTION_LENGTH
creates a new ip interface instance,def create self name commands interface s name no switchport return self configure commands
"sec - default it takes 10 min counter - 10 so it will wait 10 min and reping again . if host is up , then it will return , else again sleep . it will repeat the same for counter times ( by default 10 times , so total 100 min ( 1 hour , 40 min )",def sleepIfPingHostDown hostname sec 600 counter 10 count 0 while count counter if pinghost hostname return else print s is down so taking d sec sleep count d hostname sec count time sleep sec count 1 if pinghost hostname return else sys exit 0
"return indexable ( by 0-based index ) dict of filters , but with default filters returned for indexes out of range . ( useful for dynamic string formatting in higher layers . )",property def safe_indexable self d defaultdict Filter d update enumerate self _filters return d
attempts to determine the amount of time a visitor has spent on the site based upon their information that 's in the database .,def _time_on_site self if self session_start seconds self last_update self session_start seconds hours seconds 3600 seconds hours 3600 minutes seconds 60 seconds minutes 60 return u i 02i 02i hours minutes seconds else return ugettext u unknown
"given an iterable of anything with start_time and finish_time attributes , asserts that there are no overlaps in the durations .",def assert_durations_not_overlapping durations seen_durations for duration in durations for seen in seen_durations if duration start_time seen start_time and seen finish_time is None or duration start_time seen finish_time raise AssertionError r overlaps with r duration seen seen_durations append duration
create a templatesuite instance from the given ' url factory ' and title .,def __init__ self create_url title loader jinja2 FileSystemLoader os path dirname __file__ env jinja2 Environment loader loader env filters as_html_fragment self as_html_fragment env filters result_url create_url result_url env filters source_url create_url source_url env filters diff_line_classification Diff line_classification env filters suppress_no_lineno Diff suppress_no_lineno env filters markdown self markdown env filters section_path lambda path join map str path env globals project_title title self node env get_template node html tmpl self content env get_template content html tmpl self diff env get_template diff html tmpl self page env get_template page html tmpl
return pretty - formatted item .,staticmethod def format item u schema u name None None u tgid None None u threads None None u private None None u shared None None u total None None format_item cli make_dict_to_table schema format_list cli make_list_to_table schema if isinstance item list return format_list item else return format_item item
get runtime classs raise key exception if runtime class does not exist,def get_runtime_cls runtime_name u Get runtime classs n Raise Key exception if runtime class does not exist n try runtime_cls plugin_manager load _RUNTIME_NAMESPACE runtime_name return runtime_cls except KeyError _LOGGER error u Runtime not supported s runtime_name raise
list all allocated ips and their owner,def list self u List all allocated IPs and their owner n ips allocated glob glob os path join self _base_path u for link in allocated try ip_owner os readlink link except OSError as err if err errno errno EINVAL continue raise ips append os path basename link os path basename ip_owner return ips
set mac address of the link,def link_set_addr devname macaddr u Set mac address of the link n n param str devname n The name of the network device n param str macaddr n The mac address n subproc check_call _IP_EXE u link u set u dev devname u address macaddr
function to plot output maps for a given instrument configuration .,def plot_maps ins_conf plot_odir odir os path abspath plot_odir opath os path join odir ins_conf output_prefix _maps pdf if ins_conf Use_Bandpass N len ins_conf Channel_Names else N len ins_conf Frequencies fig plt figure 1 figsize 8 N 3 def add_map maps i hp mollview maps 0 sub N 3 i 1 fig 1 hp mollview maps 1 sub N 3 i 1 fig 1 hp mollview maps 2 sub N 3 i 1 fig 1 return if not ins_conf Use_Bandpass for i f in enumerate ins_conf Frequencies m hp read_map ins_conf file_path f f extra_info total field 0 1 2 add_map m i elif self Use_Bandpass for i in enumerate ins_conf Channel_Names m hp read_map ins_conf file_path channel_name c extra_info total field 0 1 2 add_map m i fig savefig opath bbox_inches tight background white return fig
` context ` may be either a dictionary or a django context instance ( incl . requestcontext ) .,def render_jinja_to_string filename context request None template env get_template filename if request context RequestContext request context context to_dict_context context return template render context
create qcow2 image from tarball .,def create_qcow2 tar_file layer_file backing_file None size DEF_QCOW2_SIZE qemu_img_cmd qemu img create f qcow2 layer_file size if not backing_file logger info Creating base qcow2 image execute qemu_img_cmd logger info Formatting qcow2 image execute virt format format qcow2 partition none filesystem ext3 a layer_file else qemu_img_cmd insert 2 b qemu_img_cmd insert 3 backing_file logger info Creating qcow2 image with backing chain execute qemu_img_cmd mime_tar_file get_mime_type tar_file logger debug Detected mime type of archive s mime_tar_file tar_in_cmd guestfish a layer_file m dev sda tar in tar_file compression_fmts x gzip gzip gzip gzip x xz xz x bzip2 bzip2 x compress compress x lzop lzop mime_parts mime_tar_file split if mime_parts 0 application and mime_parts 1 in compression_fmts tar_in_cmd append compress compression_fmts mime_parts 1 execute tar_in_cmd
implements metadata_from_dict as required by the base class,def metadata_from_dict self metadata_dict dates list metadata_dict keys dates sort reverse True self total_scenes len dates self scenes_processed len dates self acquisition_list join date strftime m d Y for date in dates self clean_pixels_per_acquisition join str metadata_dict date clean_pixels for date in dates self clean_pixel_percentages_per_acquisition join str metadata_dict date clean_pixels 100 self pixel_count for date in dates self save
calculates the sum of unclaimed credit from this user 's credit notes .,register assignment_tag takes_context True def available_credit context notes commerce CreditNote unclaimed filter invoice__user user_for_context context ret notes values amount aggregate Sum amount amount__sum or 0 return 0 ret
take a list of matplotlib figures * figs * and convert to list of images .,def make_images figs kwargs images for fig in figs im make_image fig kwargs images append im return images
test the output of a pearson correlation with three groups .,def test_spearman_correlation_four_groups self np random seed 987654321 input_1 st norm rvs size 100 st norm rvs size 100 input_2 st weibull_min rvs 1 7 size 100 st norm rvs size 100 input_3 st norm rvs size 100 st norm rvs size 100 input_4_x st norm rvs size 100 input_4_y x st norm rvs 0 0 5 size 1 0 for x in input_4_x input_4 input_4_x input_4_y cs_x np concatenate input_1 0 input_2 0 input_3 0 input_4 0 cs_y np concatenate input_1 1 input_2 1 input_3 1 input_4 1 grp 1 100 2 100 3 100 4 100 input_array pd DataFrame a cs_x b cs_y c grp output Spearman Correlation Coefficient n r value p value Group 100 0 0079 0 9376 1 100 0 0140 0 8898 2 100 0 1227 0 2241 3 100 0 9006 0 0000 4 exp GroupCorrelation input_array a input_array b groups input_array c display False self assertTupleEqual 100 100 100 100 exp counts self assertTupleEqual 0 007932793279327931 0 014029402940294028 0 12266426642664265 0 9005940594059406 exp r_value self assertTupleEqual 0 007932793279327931 0 014029402940294028 0 12266426642664265 0 9005940594059406 exp statistic self assertTupleEqual 0 9375641178035645 0 8898160391011217 0 22405419866382636 3 0794115586718083e 37 exp p_value self assertEqual str exp output
divide the proxable functions into sets psi and omega .,def partition prox_fns try_diagonalize True quad_funcs func_opts True False for freq in True False if all fn lin_op is_gram_diag freq for fn in prox_fns func_opts freq get_diag_quads prox_fns freq if len func_opts True len func_opts False quad_funcs func_opts True else quad_funcs func_opts False psi_fns fn for fn in prox_fns if fn not in quad_funcs return psi_fns quad_funcs
test that naive dates are handled as utc .,def test_naive_dates_are_utc self response self app get 31st March 1978 headers X Forwarded Proto https naive_location urlparse response location path response self app get 31st March 1978 UTC headers X Forwarded Proto https utc_location urlparse response location path response self app get 31st March 1978 10 00 headers X Forwarded Proto https aest_location urlparse response location path self assertEqual naive_location utc_location self assertNotEqual naive_location aest_location
opens and reads an xml file,def open self name self path name with open name as ofile parser xml parsers expat ParserCreate parser StartElementHandler self startElement parser EndElementHandler self endElement parser CharacterDataHandler self characters parser ParseFile ofile self _prj modified False
retrieve tags from git url uses subprocess to take advantage of local auth / keys settings,def _get_tags_from_git self src proc subprocess Popen git ls remote src stdout subprocess PIPE universal_newlines True return proc communicate 0
"retrieve a function from a library , and set the data types .",def get_winfunc libname funcname restype None argtypes _libcache from ctypes import windll if libname not in _libcache _libcache libname windll LoadLibrary libname func getattr _libcache libname funcname func argtypes argtypes func restype restype return func
returns an index indicating the time since the last occurrence of a frequency .,def since_last index freq H unit None ambiguous infer since index to_period freq to_timestamp how s out pd TimedeltaIndex index tz_localize None values since values if unit unit pd Timedelta unit out out unit return out
return a tuple containing client authentication data .,def GetAuth self if self auth return self auth for elt in self ps GetMyHeaderElements if elt localName BasicAuth and elt namespaceURI ZSI_SCHEMA_URI d _auth_tc parse elt self ps self auth AUTH zsibasic d Name d Password return self auth ba self environ get HTTP_AUTHENTICATION if ba ba ba split if len ba 2 and ba 0 lower basic ba _b64_decode ba 1 self auth AUTH httpbasic tuple ba split return self auth self auth AUTH none return self auth
saves all passed criteria ( via request . post ) to the object .,def save_criteria self request for co in self get_criteria co delete for key model in request POST items if key startswith type try id key split 1 except KeyError continue operator request POST get operator s id position request POST get position s id criterion_class import_symbol model criterion criterion_class objects create content self operator operator position position if criterion get_value_type criterion MULTIPLE_SELECT value request POST getlist value s id else value request POST get value s id criterion update value content_type ContentType objects get_for_model self cache_key u criteria_for_model_ _ format self pk content_type pk cache delete cache_key
test the price vs. standard price for a variant .,def test_get_standard_price_2 self self p1 for_sale False self p1 save self v1 active_price False self v1 active_for_sale_price False self v1 save self assertEqual self v1 get_standard_price self request 1 0 self assertEqual self v1 get_price self request 1 0 self assertEqual self v1 get_for_sale False self p1 for_sale False self p1 save self v1 active_price False self v1 active_for_sale_price True self v1 save self assertEqual self v1 get_standard_price self request 1 0 self assertEqual self v1 get_price self request 1 0 self assertEqual self v1 get_for_sale False self p1 for_sale False self p1 save self v1 active_price True self v1 active_for_sale_price False self v1 save self assertEqual self v1 get_standard_price self request 2 0 self assertEqual self v1 get_price self request 2 0 self assertEqual self v1 get_for_sale False self p1 for_sale False self p1 save self v1 active_price True self v1 active_for_sale_price True self v1 save self assertEqual self v1 get_standard_price self request 2 0 self assertEqual self v1 get_price self request 2 0 self assertEqual self v1 get_for_sale False self p1 for_sale True self p1 save self v1 active_price False self v1 active_for_sale_price False self v1 save self assertEqual self v1 get_standard_price self request 1 0 self assertEqual self v1 get_price self request 0 5 self assertEqual self v1 get_for_sale True self p1 for_sale True self p1 save self v1 active_price False self v1 active_for_sale_price True self v1 save self assertEqual self v1 get_standard_price self request 1 0 self assertEqual self v1 get_price self request 1 5 self assertEqual self v1 get_for_sale True self p1 for_sale True self p1 save self v1 active_price True self v1 active_for_sale_price False self v1 save self assertEqual self v1 get_standard_price self request 2 0 self assertEqual self v1 get_price self request 0 5 self assertEqual self v1 get_for_sale True self p1 for_sale True self p1 save self v1 active_price True self v1 active_for_sale_price True self v1 save self assertEqual self v1 get_standard_price self request 2 0 self assertEqual self v1 get_price self request 1 5 self assertEqual self v1 get_for_sale True self p1 for_sale True self p1 save self v1 active_for_sale CHOICES_STANDARD self v1 save self assertEqual self v1 get_for_sale True self v1 active_for_sale CHOICES_YES self v1 save self assertEqual self v1 get_for_sale True self v1 active_for_sale CHOICES_NO self v1 save self assertEqual self v1 get_for_sale False self p1 for_sale False self p1 save self v1 active_for_sale CHOICES_STANDARD self v1 save self assertEqual self v1 get_for_sale False self v1 active_for_sale CHOICES_YES self v1 save self assertEqual self v1 get_for_sale True self v1 active_for_sale CHOICES_NO self v1 save self assertEqual self v1 get_for_sale False
initialize the syslog ( standard timestamp ) parsing module,def __init__ self options self name syslog self desc syslog standard timestamp parsing module self format_regex A Z a z 2 s d 1 2 s d 2 d 2 d 2 s S s d self fields date_stamp log_source source_process source_pid message self backup_format_regex None self backup_fields self tzone None self datestamp_type standard
"begins by playing c , then plays d for mem_length rounds if the opponent ever plays d twice in a row",def strategy self opponent if self grudge_memory self mem_length self grudge_memory 0 self grudged False if len opponent history 2 return C if self grudged self grudge_memory 1 return D elif not C in opponent history 2 self grudged True return D return C
writeheader ( ) is new in python 2.7,def WriteHeader dict_writer row_order ROW_ORDER if hasattr dict_writer writeheader dict_writer writeheader else dict_writer writer writerow ROW_ORDER
filter out spikes in data above a multiple of mad of the data .,def median_filter tr multiplier 10 windowlength 0 5 interp_len 0 05 debug 0 u n Filter out spikes in data above a multiple of MAD of the data n n Currently only has the ability to replaces spikes with linear n interpolation In the future we would aim to fill the gap with something n more appropriate Works in place on data n n type tr obspy core trace Trace n param tr trace to despike n type multiplier float n param multiplier n median absolute deviation multiplier to find spikes above n type windowlength float n param windowlength Length of window to look for spikes in in seconds n type interp_len float n param interp_len Length in seconds to interpolate around spikes n type debug int n param debug Debug output level between 0 and 5 higher is more output n n returns class obspy core trace Trace n n warning n Not particularly effective and may remove earthquake signals use with n caution n num_cores cpu_count if debug 1 data_in tr copy filt tr copy filt detrend u linear try filt filter u bandpass freqmin 10 0 freqmax tr stats sampling_rate 2 1 except Exception as e print u Could not filter due to error 0 format e data filt data del filt _windowlength int windowlength tr stats sampling_rate _interp_len int interp_len tr stats sampling_rate peaks with Timer as t pool Pool processes num_cores results pool apply_async _median_window args data chunk _windowlength chunk 1 _windowlength chunk _windowlength multiplier tr stats starttime windowlength tr stats sampling_rate debug for chunk in range int len data _windowlength pool close for p in results peaks p get pool join for peak in peaks tr data _interp_gap tr data peak 1 _interp_len print u Despiking took s s t secs if debug 1 plt plot data_in data u r label u raw plt plot tr data u k label u despiked plt legend plt show return tr
export site settings as a dictionary of dictionaries,def export_as_python request from askbot deps livesettings models import Setting LongSetting import pprint work both list Setting objects all both extend list LongSetting objects all for s in both if not work has_key s site id work s site id sitesettings work s site id if not sitesettings has_key s group sitesettings s group sitegroup sitesettings s group sitegroup s key s value pp pprint PrettyPrinter indent 4 pretty pp pformat work return render_to_response livesettings text txt text pretty mimetype text plain
find the currently active prefix for the given namespace .,def _prefix_for_namespace self namespace if namespace is None return None for inverted_nsmap in reversed self nsmaps if inverted_nsmap is not None and namespace in inverted_nsmap return inverted_nsmap namespace return None
"setter for hsv value [ hue , saturation , value ]",hsv setter def hsv self hsv_colour self _rgb hsv_to_rgb h hsv_colour 0 255 0 s hsv_colour 1 255 0 v hsv_colour 2 255 0
expression : if expression then term else term,def p_expression_if_then_else self p p 0 p 4 if p 2 else p 6
"saves the notification . this is done by deleting the old one , and then saving a new one , so the name property will change : return : none",def save self from xml etree cElementTree import tostring from vidispine_api import VSNotFound from pprint import pprint try self delete except VSNotFound pass url cls notification format cls self objectclass content self as_xml response_content self request url method POST body content pprint response_content
myroot is ignored in favour of eroot,def __init__ self myroot vardb self _vardb vardb self _cache_filename os path join vardb settings EROOT portage CACHE_PATH vdb_blockers pickle self _cache_version 1 self _cache_data None self _modified set self _load
splitter sends input values down two output channels .,forever def Splitter cin cout1 cout2 while True val cin read cout1 write val cout2 write val yield
check the operation of the createsuperuser management command,def test_createsuperuser_management_command self new_io StringIO call_command createsuperuser interactive False username joe email joe somewhere org stdout new_io command_output new_io getvalue strip self assertEqual command_output Superuser created successfully u User objects get username joe self assertEquals u email joe somewhere org self assertTrue u check_password new_io StringIO call_command createsuperuser interactive False username joe2 email joe2 somewhere org verbosity 0 stdout new_io command_output new_io getvalue strip self assertEqual command_output u User objects get username joe2 self assertEquals u email joe2 somewhere org self assertTrue u check_password new_io StringIO call_command createsuperuser interactive False username joe admin somewhere org email joe somewhere org stdout new_io u User objects get username joe admin somewhere org self assertEquals u email joe somewhere org self assertTrue u check_password
return a list of all the initial forms in this formset .,def _get_initial_forms self return self forms self initial_form_count
"converts the filename , content , mimetype triple into a mime attachment object .",def _create_attachment self filename content mimetype None if mimetype is None mimetype _ mimetypes guess_type filename if mimetype is None mimetype DEFAULT_ATTACHMENT_MIME_TYPE attachment self _create_mime_attachment content mimetype if filename attachment add_header Content Disposition attachment filename filename return attachment
start and return a download task,staticmethod def download self resource filename kw params kw pop params task self make_request TaskRunFailed method create resource resource params params return DownloadTask filename filename task task
returns a uuid(value ) if the value provided is a str .,def str_to_uuid value if isfunction value value value return UUID value if isinstance value string_types else value
@param in_swarms : [ str ] path to swarm output file . it describes which reads compose each swarm . @param in_count : [ str ] path to the count file . it contains the count by sample for each representative sequence . @param out_biom : [ str ] path to the output biom .,def __init__ self in_swarms in_count out_biom Cmd __init__ self swarm2biom py Converts swarm output to abundance file format BIOM clusters file in_swarms count file in_count output file out_biom version
turns on all debugging messages up to the specified level,def on self level if isinstance level int and level 0 and level 3 self _debug_level level
"sometimes you may need to access context or request variables to build your dashboard , this is what the `` init_with_context ( ) `` method is for . this method is called just before the display with a `` django.template.requestcontext `` as unique argument , so you can access to all context variables and to the `` django.http.httprequest `` .",def init_with_context self context pass
"use aliasfile to create aliases of files in srcdir matching prefix / ext in dstdir . if dstdir is null , use srcdir as dstdir . if replace is false and a file already exists in dstdir , report and do nothing . if copy is false create a symlink , else create a copy .",def add_aliases srcdir dstdir aliasfile prefix ext replace False copy False canonical_names False dry_run False if not path isdir srcdir print s is not a directory srcdir file sys stderr return if not dstdir dstdir srcdir elif not path isdir dstdir os makedirs dstdir prefix_len len prefix suffix_len len ext 1 filenames path basename f for f in glob glob path join srcdir s s prefix ext seq_to_file str_to_seq name prefix_len suffix_len name for name in filenames aliases read_emoji_aliases aliasfile aliases_to_create aliases_to_replace alias_exists False def check_alias_seq seq alias_str seq_to_str seq alias_name s s s prefix alias_str ext alias_path path join dstdir alias_name if path exists alias_path if replace aliases_to_replace append alias_name else print alias s exists alias_str file sys stderr alias_exists True return None return alias_name canonical_to_file for als trg in sorted aliases items if trg not in seq_to_file print target s for s does not exist seq_to_str trg seq_to_str als file sys stderr continue alias_name check_alias_seq als if alias_name target_file seq_to_file trg aliases_to_create alias_name target_file if canonical_names canonical_seq unicode_data get_canonical_emoji_sequence als if canonical_seq and canonical_seq als canonical_alias_name check_alias_seq canonical_seq if canonical_alias_name canonical_to_file canonical_alias_name target_file if canonical_names print adding d canonical aliases len canonical_to_file for seq f in seq_to_file iteritems canonical_seq unicode_data get_canonical_emoji_sequence seq if canonical_seq and canonical_seq seq alias_name check_alias_seq canonical_seq if alias_name canonical_to_file alias_name f print adding d total canonical sequences len canonical_to_file aliases_to_create update canonical_to_file if replace if not dry_run for k in sorted aliases_to_replace os remove path join dstdir k print replacing d files len aliases_to_replace elif alias_exists print aborting aliases exist file sys stderr return for k v in sorted aliases_to_create items if dry_run msg replace if k in aliases_to_replace else print s s s msg k v else try if copy shutil copy2 path join srcdir v path join dstdir k elif srcdir dstdir os symlink v path join dstdir k else raise Exception can t create cross directory symlinks yet except Exception as e print failed to create s s k v file sys stderr raise Exception oops str e print created d s len aliases_to_create copies if copy else symlinks
display the back references for an object .,def display_backlinks self active_handle for classname handle in self dbstate db find_backlink_handles active_handle name navigation_label self dbstate db classname handle 0 self model add _ classname name handle classname self set_has_data self model count 0
"a filter for gedcom files . this implements a filter that allows some differences to be ignored . the differences are not functional , but are related to changes in gramps version , file date / time and filename .",def gedfilt line if line startswith gedfilt prev None 8 gedfilt indx 0 return False retval True diftyp line 0 line line 1 partition level int line 0 token toss line line 2 partition if diftyp gedfilt prev gedfilt indx token level line gedfilt indx gedfilt indx 1 8 retval False elif diftyp gedfilt prev gedfilt indx token level line gedfilt indx gedfilt indx 1 8 if token VERS and gedfilt prev gedfilt indx 2 0 SOUR retval False elif token DATE and gedfilt prev gedfilt indx 2 0 NAME retval False elif token TIME and gedfilt prev gedfilt indx 2 0 DATE retval False elif token FILE and line endswith ged n retval False elif token FILE and tests in line retval False elif token COPR and Copyright c in line retval False elif token VERS and gedfilt prev gedfilt indx 1 0 VERS retval False elif token DATE and gedfilt prev gedfilt indx 2 0 NAME or gedfilt prev gedfilt indx 3 0 NAME retval False elif token TIME and gedfilt prev gedfilt indx 2 0 DATE or gedfilt prev gedfilt indx 3 0 DATE retval False elif token FILE and line endswith ged n retval False elif token FILE and tests in line retval False elif token COPR and Copyright c in line retval False return retval
merge the list of addresses from acquisition with our own .,def _merge_address_list self acquisition address_list self address_list for addendum in acquisition get_address_list for address in address_list equi address is_equivalent addendum if equi IDENTICAL break elif equi EQUAL address merge addendum break else self address_list append addendum
"move down pressed on the group if on a family group , allow to reorder the order of families as connected to this person .",def _move_down_group self groupindex ref self get_selected if not ref or ref 1 return if ref 0 0 return if ref 0 len self _groups 1 return index ref 0 1 flist self obj get_family_handle_list handle flist pop index flist insert index 1 handle self changed True self rebuild path index 2 self tree get_selection select_path path GLib idle_add self tree scroll_to_cell path
set relation to a person .,def set_relation self rel self rel rel
the directory where to save extra files,def datadir self return self _subdir
"pipeline passed before , but current page shows only failures .",vcr use_cassette f page_of_failures yaml def test_page_of_failures self p HP g DeployStaging with pytest raises gocd_parser handler history history_page HistoryPageException p set_info
returns an mlreader instance for this class .,classmethod def read cls return JavaH2OMLReader cls
test generation of a blank header .,def test_blank_header self HEADER Tag HEADER header True self assertEqual HEADER r n HEADER
( obj ) - > dict,def get_nc_dump_dict nc_group info OrderedDict if isinstance nc_group netCDF4 Dataset if get_dimensions_info nc_group info dimensions get_dimensions_info nc_group if get_variables_info nc_group info variables get_variables_info nc_group if get_global_attr_info nc_group info global attributes get_global_attr_info nc_group if nc_group groups for group_name group_obj in nc_group groups items try info group group_name get_nc_dump_dict group_obj except Exception continue return info
return a prototype scanner instance for scanning source files for fortran use & include statements,def FortranScan path_variable FORTRANPATH use_regex i s USE s s s NON_ INTRINSIC s s w include_regex i s s INCLUDE s w _ def_regex i s MODULE s PROCEDURE w scanner F90Scanner FortranScan FORTRANSUFFIXES path_variable use_regex include_regex def_regex return scanner
"validate ( template ) , de - duplicate ( by template ) , sort ( by label ) and return a list of `` ( template name , label ) `` choices for all plugins .",def get_all_choices cls args kwargs plugins cls get_plugins args kwargs all_choices reduce operator add plugin choices for plugin in plugins choices seen set for template label in all_choices if template in seen continue seen add template try validators template_name template except ValidationError continue choices append template label choices sorted choices key lambda a a 0 a 1 return choices
test that read_and_clean_csv_to_dataframe method can properly decode utf-8 characters,def test_read_convert_utf8 self input_data read_and_clean_csv_to_dataframe self input_filename utf_8_cell_value input_data iloc 6 0 self assertEqual type utf_8_cell_value unicode self assertEqual utf_8_cell_value 1 u ufffd
create a new ctr cipher from the mac in siv mode,def _create_ctr_cipher self mac_tag tag_int bytes_to_long mac_tag return self _factory new self _subkey_cipher self _factory MODE_CTR initial_value tag_int tag_int 9223372039002259456L nonce b self _cipher_params
"gets high , low and close data for an equity and calcualtes stocastic oscillator : param symbol : : param end_date : : return : tuple of % k and % d list of floats",def calculate_for_symbol self symbol end_date datetime today data self _data_for_symbol symbol self _num_periods self _window_size self _smoothing_window_size 2 end_date key None high_data x PastQuoteDataKeys ADJ_HIGH for x in data low_data x PastQuoteDataKeys ADJ_LOW for x in data close_data x PastQuoteDataKeys ADJ_CLOSE for x in data k d self calculate high_data low_data close_data return k self _num_periods d self _num_periods
builds an n - d butterworth filter,def __frequency_butterworth_filter shape cutoff order Builds an N D butterworth filter math f frac 1 0 1 0 w cutoff 2n The frequency origin of the returned filter is at the corners Parameters shape tuple The size of the filter M N cutoff double Cutoff frequency of the filter in the range 0 0 5 order positive int Order of the filter The higher it is the sharper the transition Returns butterworth_filter M N ndarray The butterworth filter for the given parameters Will be the same shape as was requested grid __adjusted_meshgrid shape grid_sq g 2 for g in grid grid_sq sum grid_sq radius np sqrt grid_sq return np fft ifftshift 1 0 radius cutoff 2 order 1 0
read the tree 's documents .,get documents def get_documents prefixes str document prefix for document in tree if utilities json_response request data prefixes prefixes return data else return template document_list prefixes prefixes
"for the polynomials in the list of strings * pols * and the solutions in * sols * for the values in the list * start * , a sweep through the parameter space will be performed in standard double precision to the target values of the parameters in the list * target*. the number of variables in the polynomials and the solutions must be the same and be equal to the value of * nvar*. the list of symbols in * pars * contains the names of the variables in the polynomials * pols * that serve as parameters . the size of the lists * pars * , * start * , and * target * must be same .",def standard_complex_sweep pols sols nvar pars start target from phcpy interface import store_standard_solutions as storesols from phcpy interface import store_standard_system as storesys storesys pols nbvar nvar storesols nvar sols from phcpy interface import load_standard_solutions as loadsols from phcpy phcpy2c2 import py2c_sweep_define_parameters_symbolically as define from phcpy phcpy2c2 import py2c_sweep_set_standard_start as set_start from phcpy phcpy2c2 import py2c_sweep_set_standard_target as set_target from phcpy phcpy2c2 import py2c_sweep_standard_complex_run as run nbq nbp len pols len pars parnames join pars nbc len parnames define nbq nvar nbp nbc parnames print setting the start and the target set_start nbp str start set_target nbp str target print calling run in standard double precision run 0 0 0 0 0 result loadsols return result
takes in a string which is the article body to be processed and cluster value predicted article_string - string returns the integer label for the cluster the text fits in,def predict_cluster article_string z cluster_prep article_string z join z km joblib load model kmeans_model pkl vectorizer joblib load model tf_vectorizer_obj pkl x_test vectorizer transform z res km predict x_test return res 0
called when the user launches the skill without specifying what they want,def on_launch launch_request session print on_launch requestId launch_request requestId sessionId session sessionId return get_welcome_response
return a list of contacted inventory hosts .,def keys self return self contacted keys
function to find the levenshtein distance between two words / sentences - gotten from http://rosettacode.org/wiki/levenshtein_distance#python,def lDistance firstString secondString if len firstString len secondString firstString secondString secondString firstString distances range len firstString 1 for index2 char2 in enumerate secondString newDistances index2 1 for index1 char1 in enumerate firstString if char1 char2 newDistances append distances index1 else newDistances append 1 min distances index1 distances index1 1 newDistances 1 distances newDistances return distances 1
used to shuffle the dataset at each iteration accoring to lengths .,def get_minibatches_idx_bucketing_both data ranges minibatch_size shuffle False idx_list create_buckets data ranges n len idx_list minibatches minibatch_start 0 for i in range n minibatch_size minibatches append idx_list minibatch_start minibatch_start minibatch_size minibatch_start minibatch_size if minibatch_start n minibatches append idx_list minibatch_start if shuffle np random shuffle minibatches return zip range len minibatches minibatches
log the given message to the app.log or global log as appropriate .,def __call__ self args kwargs if hasattr request app and hasattr request app log log request app log else log self return log error args kwargs
"find all .pbivcs.conf files ( if any ) furthest down the path , ordered by hierarchy i.e. ' /path / to / my/.pbivcs.conf ' would come before ' /path / to/.pbivcs.conf '",def _find_confs path splat tuple i for i in os path split os path abspath os path normpath path if i confs for i in range 1 len splat parent os path join splat i confpath os path join parent pbivcs conf if os path exists confpath confs append confpath return confs
--test = affected will work .,def test_affected_filter self args kubernetes_bazel parse_args affected build foo test foo with Stub kubernetes_bazel get_changed self fake_changed_valid with Stub os getenv self fake_sha kubernetes_bazel main args test self callstack 2 self assertIn foo test self assertNotIn bar test build self callstack 3 self assertIn foo build self assertNotIn bar build
[ controller2switch / aggregatestatsrequest ] - size 44 .,classmethod def setUpClass cls request AggregateStatsRequest table_id 1 out_port Port OFPP_NONE match _get_match super setUpClass super set_raw_dump_file v0x01 ofpt_aggregate_request super set_raw_dump_object StatsRequest xid 17 body_type StatsType OFPST_AGGREGATE flags 0 body request super set_minimum_size 12
"set current title to `` title `` and parse its content . unsaved changes to previous page will be lost . the content of the page should have been fetched by : py : meth:`fetch_pages ` , otherwise : py : exc:`valueerror ` will be raised .",def set_title self title if title not in self contents keys raise ValueError Content of page is not fetched format title self title title self wikicode mwparserfromhell parse self contents self title
returns a dictionary of all relevant flow blocks . if no list of flow block names is provided all flow blocks are returned . otherwise only flow blocks that are in the list or are children of flowblocks in the list are returned .,def discover_relevant_flowblock_models flow pad record alt flow_blocks flow flow_blocks all_blocks pad db flowblocks if flow_blocks is None return dict k v to_json pad record alt for k v in all_blocks iteritems wanted_blocks set to_process flow_blocks while to_process block_name to_process pop flowblock all_blocks get block_name if block_name in wanted_blocks or flowblock is None continue wanted_blocks add block_name for field in flowblock fields if isinstance field type FlowType if field type flow_blocks is None raise RuntimeError Nested flow blocks require explicit list of involved blocks to_process extend field type flow_blocks rv for block_name in wanted_blocks rv block_name all_blocks block_name to_json pad record alt return rv
highlight the road centre line the user has selected to associated with an aims feature,def setRcl self line rclLayer self _layers rclLayer self _rclMarker setToGeometry QgsGeometry fromPolyline line 0 None self _rclMarker show
register the default block chain instance .,staticmethod def RegisterBlockchain blockchain if Blockchain __instance is None Blockchain __instance blockchain
"returns the 32-bit part of the uuid string i.e. , given a uuid of the form ` zzzzyyyy - bbbb - bbbb - bbbb - vvvvvvvvvvvv ` it shall return ` zzzzyyyy `",property def uuid32 self u n Returns the 32 bit part of the UUID string i e given n a UUID of the form ZZZZYYYY BBBB BBBB BBBB VVVVVVVVVVVV n it shall return ZZZZYYYY n return self uuid 0 8
read content of a json file . : param path : path to read : type path : str : return : json content : rtype : str,def read_json path path fix_path path try with open path r as fil return json load fil except OSError return None
sets a year and loads the relevant dataset,def set_year self year self _year year self close_datasets self _load_datasets self _year
endpoint to map a tango device address to the sender 's ip address --- tags : - insert parameters : - name : tango_addr in : path type : string required : true responses : 200 : description : device address successfully inserted . type : string 500 : description : internal server error type : string,app route insert path tango_addr methods GET def insert tango_addr ip_addr request remote_addr existing_results DbHelper get quote tango_addr if len existing_results 0 if DbHelper add datetime datetime now quote tango_addr ip_addr 1 return Failed else return Device address exist return Successfully inserted device address
decorator to make a function native to a twinterpreter,def twinfunction twinterpreter_id def decorator func func __twin_id__ twinterpreter_id if state is_twinterpreter twinterpreter_id return func def function_runner_factory fargs fkwargs def function_runner args kwargs return function_runner dispatch_call function_dispatch_proxy args kwargs function_runner dispatch_call state get_kernel twinterpreter_id dispatch_call function_dispatch_proxy function_runner function_runner return function_runner fargs fkwargs def function_dispatch_proxy args kwargs return function_dispatch_proxy function_runner args kwargs function_dispatch_proxy function_runner function_runner_factory clone_function_meta func function_dispatch_proxy return function_dispatch_proxy return decorator
will clear the cancel and pause routing bits in firmware,def on_start_routing_clicked self widget self start_routing pass
merge sorted pairs / pairsam files .,cli command click argument pairsam_path nargs 1 type str click option o output type str default help output file If the path ends with gz lz4 the output is compressed by pbgzip lz4c By default the output is printed into stdout click option max nmerge type int default 8 show_default True help The maximal number of inputs merged at once For more store merged intermediates in temporary files click option tmpdir type str default help Custom temporary folder for merged intermediates click option memory type str default 2G show_default True help The amount of memory used by default click option compress program type str default show_default True help A binary to compress temporary merged chunks Must decompress input when the flag d is provided Suggested alternatives lz4c gzip lzop snzip NOTE fails silently if the command syntax is wrong click option nproc type int default 8 help Number of threads for merging show_default True click option nproc in type int default 1 show_default True help Number of processes used by the auto guessed input decompressing command click option nproc out type int default 8 show_default True help Number of processes used by the auto guessed output compressing command click option cmd in type str default None help A command to decompress the input If provided fully overrides the auto guessed command Does not work with stdin Must read input from stdin and print output into stdout EXAMPLE pbgzip dc n 3 click option cmd out type str default None help A command to compress the output If provided fully overrides the auto guessed command Does not work with stdout Must read input from stdin and print output into stdout EXAMPLE pbgzip c n 8 def merge pairsam_path output max_nmerge tmpdir memory compress_program nproc kwargs merge_py pairsam_path output max_nmerge tmpdir memory compress_program nproc kwargs
get frame number of last color frame : return : frame number,def getLastColorNum self return dsc getLastColorNum
decrypt a piece of data using a passphrase and * pbes2*.,def decrypt data passphrase encrypted_private_key_info decode_der DerSequence data encryption_algorithm decode_der DerSequence encrypted_private_key_info 0 encrypted_data decode_der DerOctetString encrypted_private_key_info 1 payload pbe_oid decode_der DerObjectId encryption_algorithm 0 value if pbe_oid 1 2 840 113549 1 5 13 raise ValueError Not a PBES2 object pbes2_params decode_der DerSequence encryption_algorithm 1 key_derivation_func decode_der DerSequence pbes2_params 0 key_derivation_oid decode_der DerObjectId key_derivation_func 0 value if key_derivation_oid 1 2 840 113549 1 5 12 raise ValueError Unknown KDF pbkdf2_params decode_der DerSequence key_derivation_func 1 salt decode_der DerOctetString pbkdf2_params 0 payload iteration_count pbkdf2_params 1 if len pbkdf2_params 2 pbkdf2_key_length pbkdf2_params 2 else pbkdf2_key_length None if len pbkdf2_params 3 raise ValueError Unsupported PRF for PBKDF2 encryption_scheme decode_der DerSequence pbes2_params 1 encryption_oid decode_der DerObjectId encryption_scheme 0 value if encryption_oid 1 2 840 113549 3 7 ciphermod DES3 key_size 24 elif encryption_oid 2 16 840 1 101 3 4 1 2 ciphermod AES key_size 16 elif encryption_oid 2 16 840 1 101 3 4 1 22 ciphermod AES key_size 24 elif encryption_oid 2 16 840 1 101 3 4 1 42 ciphermod AES key_size 32 else raise ValueError Unsupported cipher if pbkdf2_key_length and pbkdf2_key_length key_size raise ValueError Mismatch between PBKDF2 parameters and selected cipher IV decode_der DerOctetString encryption_scheme 1 payload key PBKDF2 passphrase salt key_size iteration_count cipher ciphermod new key ciphermod MODE_CBC IV pt cipher decrypt encrypted_data return unpad pt cipher block_size
guid for a particuar version ( < item><guid > ),def item_guid self version url absolutify reverse addons versions args version addon_id return s version s url version version
tests that the loader fails when the install.rdf is corrupt .,def test_load_irdf_unparsable _run_test install_rdf_unparsable xpi None
test that the magical behavior where 1 + = = 2pre is preserved .,def test_magical_plus_equals_plusone_pre_nonsense assert VersionPart 1 VersionPart 2pre
test that augmented concatenation happens even within referenced variable placeholders .,def test_ref_augconcat self self run_script var x xyz foo x xyz bar var y x xyz self assert_silent self assert_var_eq y foobar
this is just the django version of get_success_url https://github.com/django/django/blob/master/django/views/generic/edit.py#l51,def get_failure_url self if self failure_url url self failure_url else raise ImproperlyConfigured No URL to redirect to Provide a failure_url return url
"when a file is modified , thumbnails are built for all matching and project - wide aliases .",def test_changed self profile Profile avatar avatars test jpg profile avatar _committed False files self fake_save profile self assertEqual len files 6
"training score of the model , computed as the generalized matrix , rayleigh quotient , the sum of the first ` n_components ` eigenvalues",property def score_ self return np exp self eigenvalues_ sum
read and parse a filename or a list of filenames .,def read self filenames py26 check_python_version 2 6 0 2 6 99 False None False False False if isinstance filenames str filenames filenames read_ok for priority filename in enumerate filenames try out_file io StringIO for line in codecs open filename encoding utf 8 line line strip match_obj self OPTCRE match line if not self SECTCRE match line and match_obj optname delimiter optval match_obj group option vi value if optname and not optval and not delimiter out_file write line n else out_file write line n else out_file write line n out_file seek 0 self _read out_file filename except IOError continue try self _read out_file filename for group in self _sections keys try self _options_dict group except KeyError self _options_dict group for option value in self _sections group items if py26 self _options_dict group option str value priority else self _options_dict group option value priority self _sections self _dict except MissingSectionHeaderError self _read out_file filename out_file close read_ok append filename return read_ok
require a deb package to be uninstalled .,def nopackage pkg_name if is_installed pkg_name uninstall pkg_name
use the registered viewsets to generate a list of url patterns .,def get_urls self u n Use the registered viewsets to generate a list of URL patterns n ret for prefix viewset basename in self registry lookup self get_lookup_regex viewset routes self get_routes viewset for route in routes mapping self get_method_map viewset route mapping if not mapping continue regex route url format prefix prefix lookup lookup trailing_slash self trailing_slash if not prefix and regex 2 u regex u regex 2 view viewset as_view mapping route initkwargs name route name format basename basename ret append url regex view name name return ret
return a sub - directory of ` root_dir ` that is not specific to an os or processor architecture .,def noarch_dir root_dir _noarch noarch u n Return a sub directory of root_dir that is NOT specific to an OS or n processor architecture n return join root_dir _noarch
should handle a single js file name as string,def test_single_js_file self files js test libs jasmine djangojs js expected normpath js test libs jasmine djangojs js self assertEqual StorageGlobber glob files expected
"start a network , connect it to root ns , and run sshd on all hosts . ip : root - eth0 ip address in root namespace ( 10.123.123.1/32 ) routes : mininet host networks to route to ( 10.0/24 ) switch : mininet switch to connect to root namespace ( s1 )",def sshd network cmd usr sbin sshd opts D ip 10 123 123 1 32 routes None switch None if not switch switch network s1 if not routes routes 10 0 0 0 24 connectToRootNS network switch ip routes for host in network hosts host cmd cmd opts info Waiting for ssh daemons to start n for server in network hosts waitListening server server port 22 timeout 5 info n Hosts are running sshd at the following addresses n for host in network hosts info host name host IP n info n Type exit or control D to shut down network n CLI network for host in network hosts host cmd kill cmd network stop
reads a sequence of word characters,def read_word stream include_chars u n Reads a sequence of word characters n stream expect_input start stream ptr while stream ptr stream length ch stream text stream ptr if not ch isalnum or ch u _ or ch in include_chars break stream ptr 1 if start stream ptr stream raise_unexpected return stream text start stream ptr
"determine whether a file is under version control , and if so , obtain version information from this .",def find_versions_from_versioncontrol dependencies u Determine whether a file is under version control and if so n obtain version information from this for dependency in dependencies if dependency version u unknown try wc versioncontrol get_working_copy dependency path except versioncontrol VersionControlError pass else if wc has_changed dependency diff wc diff dependency version wc current_version dependency source wc repository url return dependencies
convenience method to call post ( ) on an arbitrary uri and parse the response into a json object . raises an error on non-200 response status .,def post_parse self uri params data return self _request_parse self post uri params data
catch - all errback which simply logs the failure . this is n't expected to be invoked in the normal case for this example .,def error why msg err why msg
parses sql statements from file - like object .,def parsestream stream encoding None stack engine FilterStack stack full_analyze return stack run stream encoding
called once after all tests are executed .,def stopTestRun self
associate current auth with a user with the same email address in the db .,def associate_by_email backend details user None args kwargs if user return None email details get email if email users list backend strategy storage user get_users_by_email email if len users 0 return None elif len users 1 raise AuthException backend The given email address is associated with another account else return user users 0
a function scheduled with l{ireactorthreads.callfromthread } invoked from a delayed call is run immediately in the next reactor iteration .,def test_delayedCallFromThread self reactor self buildReactor def threadCall reactor stop reactor callLater 0 reactor callFromThread threadCall before reactor seconds self runReactor reactor 60 after reactor seconds self assertTrue after before 30
return true if dependency is present and up - to - date on ' paths ',def is_current self paths None version self get_version paths if version is None return False return self version_ok version
create a pager with a reference to a remote collector and an optional callable to invoke upon completion .,def __init__ self collector callback None args kw if callable callback self callback callback self callbackArgs args self callbackKeyword kw else self callback None self _stillPaging 1 self collector collector collector broker registerPageProducer self
this returns the persistent state of this shell factory .,def __getstate__ self dict self __dict__ ns copy copy dict namespace dict namespace ns if ns has_key __builtins__ del ns __builtins__ return dict
"implement next as file does ( like readline , except raises stopiteration at eof )",def next self nextline self readline if nextline return nextline raise StopIteration
remove expired instances of `` registrationprofile `` and their associated `` user``s .,def delete_expired_users self for profile in self all if profile activation_key_expired user profile user if not user is_active user delete
get all the data files that should be included in this distutils project .,def getDataFiles dname ignore None parent None parent parent or ignore ignore or result for directory subdirectories filenames in os walk dname resultfiles for exname in EXCLUDE_NAMES if exname in subdirectories subdirectories remove exname for ig in ignore if ig in subdirectories subdirectories remove ig for filename in _filterNames filenames resultfiles append filename if resultfiles result append relativeTo parent directory relativeTo parent os path join directory filename for filename in resultfiles return result
testing variable - argument function signature .,def test_signature_variable self xplorer self pool getExplorer function_variable function_variable expected_names a kw signature xplorer signature self failUnlessEqual signature name expected_names self failUnless signature is_varlist 0 self failUnless signature is_keyword 1
"when we make a declaration for a class , we install a _ _ provides _ _ descriptors that provides a default for instances that do n't have instance - specific declarations :",def test_that_we_dont_inherit_provides_optimizations
microdom does not decode entities in text nodes .,def test_textEntitiesNotDecoded self doc5_xml x Souffl amp x doc5 self dom parseString doc5_xml actual domhelpers gatherTextNodes doc5 expected Souffl amp self assertEqual actual expected actual domhelpers gatherTextNodes doc5 documentElement self assertEqual actual expected
create a message receiver by launching a process .,def createMessageReceiver self p ProcessAliasProtocol m MessageWrapper p self program self reactor fd self spawnProcess p self program self path return m
test logging exception if stdout if not a correct json,mock patch u devops helpers exec_result logger autospec True def test_wrong_result self logger u cmd u ls la awk print 1 result Subprocess execute command cmd with self assertRaises error DevopsError result stdout_json logger assert_has_calls mock call exception u cmd stdout is not valid json n stdout_str r n format cmd cmd stdout_str u self assertIsNone result u stdout_yaml
filter and return hubs that match the given profile .,def filter_hubs_by_profile session hubs profile_id LOG debug Filtering hubs hubs s that match profile profile s hubs hubs profile profile_id pbm session pbm placement_solver pbm service_content placementSolver filtered_hubs session invoke_api pbm PbmQueryMatchingHub placement_solver hubsToSearch hubs profile profile_id LOG debug Filtered hubs s filtered_hubs return filtered_hubs
args : master_key ( bytearray ),def __init__ self master_key super MacCryptoMaterialCreator self __init__ master_key
set endpoint value on data source,staticmethod def _http_simple_set_value self uid location name value endp LagartoEndpoint endp_id uid location location name name value value status LagartoHttpServer data_server set_status endp dumps if status is not None if len status 1 if value in status 0 res str status 0 value if unit in status 0 res status 0 unit return res return None
plan to a desired end - effector offset with fixed orientation .,LockedPlanningMethod def PlanToEndEffectorOffset self robot direction distance kwargs chains self CreateTSRChains robot direction distance return self delegate_planner PlanToTSR robot chains kwargs
"should be run only if match_if , match_ifelse do n't match anything in acyclic graph . then any join node belong to abnormal selection pattern . we try to find the top - most and split it , after which normal structured matches should be tried again .",def match_abnormal_sel cfg for v _ in cfg iter_rev_postorder if cfg degree_in v 2 and cfg degree_out v 1 log info abnormal_sel s v split_node cfg v return True
get all binlogs that have been logged as uploaded,def get_logged_binlog_uploads instance conn mysql_lib connect_mysql instance dbascript cursor conn cursor sql SELECT binlog FROM metadata_db tbl WHERE hostname hostname s AND port port s format metadata_db mysql_lib METADATA_DB tbl environment_specific BINLOG_ARCHIVING_TABLE_NAME cursor execute sql hostname instance hostname port str instance port ret set for binlog in cursor fetchall ret add binlog binlog return ret
called when step function failed to execute .,def pytest_bdd_step_error request feature scenario step step_func step_func_args exception
patch ` jsonrpcclient.deploy_solidity_contract ( ) ` to not create a copy of the ` libraries ` dict parameter by removing the assignment in ` raiden.network.rpc.client.py:474 ` via ast manipulation .,def patch_deploy_solidity_contract import ast from inspect import getsource getsourcefile from textwrap import dedent class RemoveLibraryDeref ast NodeTransformer Removes the AST node representing the line libraries dict libraries def visit_Assign self node is_libraries len node targets 1 and node col_offset 4 and isinstance node targets 0 ast Name and node targets 0 id libraries if is_libraries return None return node ast_ ast parse dedent getsource JSONRPCClient deploy_solidity_contract ast_ RemoveLibraryDeref visit ast_ code compile ast_ getsourcefile JSONRPCClient deploy_solidity_contract exec ctx exec code in JSONRPCClient deploy_solidity_contract __globals__ ctx JSONRPCClient deploy_solidity_contract ctx deploy_solidity_contract
enforces that all the parameters are re - cast and updated in the meta dictionary,def refresh_parameters self for name parameter in self _parameters items value getattr self name parameter value value setattr self name parameter value
"return a tuple of numpy arrays theta and phi , each of size numsamples",abc abstractmethod def positions self tileID numSamples
play a note to the given specification . parameters are the same as those to ` note ` .,def play self args self note args play
initializes an instance of contentclassificationlens .,def __init__ self trace ad_rules tracking_rules self _trace trace self _requests trace request_track GetEvents self _requests_by_id r request_id r for r in self _requests self _main_frame_id trace page_track GetEvents 0 frame_id self _frame_to_requests collections defaultdict list self _ad_requests set self _tracking_requests set self _ad_matcher _RulesMatcher ad_rules True self _tracking_matcher _RulesMatcher tracking_rules True self _document_url self _GetDocumentUrl self _GroupRequestsByFrameId self _LabelRequests
atomically sets the mapping of keys to values in the object store . returns a |future| which is resolved once the new mapping has been stored .,def SetMulti self items raise NotImplementedError self __class__
creates a subprocess with command - line that is passed in .,def RunCommandInSubProcess command cmd_line command try try print Going to run n s command results subprocess check_output cmd_line stderr subprocess STDOUT shell True except subprocess CalledProcessError as e results e output finally print results return results
validates |profile| before assigning it as the source of user data .,def set_profile self profile if not isinstance profile dict raise ValueError profile must be a a valid dictionary self _profile profile
logs |msg| to stdout if --verbose/-v is passed when invoking this script .,def _log_debug self msg error False if self _verbose print INFO s msg
returns all the tests from a given test suite .,def GetTestsFromSuite suite tests for x in suite if isinstance x unittest TestSuite tests GetTestsFromSuite x else tests x return tests
initialize bindings to the linux gadgetfs interface .,def __init__ self hardware mountpoint dev gadget self _chip self _hw_eps HARDWARE hardware self _ep_dir mountpoint self _gadget None self _fd None self _ep_fds self _io_loop ioloop IOLoop current
"updates an existing image in gs , preserving permissions and metadata .",def UpdateImage self full_path image self cloud_bucket UpdateFile full_path image_tools EncodePNG image
"returns the element described by |selector| , if displayed .",def _ReturnElementIfDisplayed self selector try element self driver find_element_by_css_selector selector return element if element is_displayed else None except Exception return None
"parses a result line , and returns it .",def ParseResult result_line tokens result_line strip split assert len tokens 8 intent_sent_timestamp int tokens 4 return Result bool tokens 0 tokens 1 int tokens 2 int tokens 3 max _INVALID_VALUE int tokens 5 intent_sent_timestamp max _INVALID_VALUE int tokens 6 intent_sent_timestamp max _INVALID_VALUE int tokens 7 intent_sent_timestamp
args : threads : number of threads . run_time : total process uptime in seconds . cpu_usage : cpu usage [ 0 - 100 ] since the last getstats call . vm_rss_kb : resident memory set in kb . page_faults : number of vm page faults ( hard + soft ) .,def __init__ self threads run_time cpu_usage vm_rss page_faults self threads threads self run_time run_time self cpu_usage cpu_usage self vm_rss vm_rss self page_faults page_faults
print error records strings in the expected format .,def _PrintErrorRecords error_records current_path None for record in error_records if current_path record path current_path record path if not FLAGS unix_mode _PrintFileSeparator current_path print record error_string
generates all template configurations for gn .,def GenerateGnBuildRules gn_path root_dir out_dir settings for config in SUPPORTED_CONFIGS for target in SUPPORTED_TARGETS build_dir os path join out_dir s s config target generator GnGenerator settings config target generator CreateGnRules gn_path root_dir build_dir
base method to handle update requests . this view will render a update form to update items on ( get ) requests .,def update request callback None renderers None validators None values None if values is None values values _roles str r name for r in request user roles form get_item_form update request renderers validators values if request POST if handle_POST_request form request callback update renderers return handle_redirect_on_success request rvalues get_return_value request rvalues form render_item_form request form return rvalues
"this test checks if the new change to multinomialfromuniform is still compatible with old interface . here i will load a graph created ( using the old interface ) as follows : randomstreams = theano.sandbox.rng_mrg.mrg_randomstreams th_rng = randomstreams(12345 ) x = t.matrix('x ' ) pvals = t.exp(x ) pvals = pvals / pvals.sum(axis=1 , keepdims = true ) samples = th_rng.multinomial(pvals = pvals ) pickle.dump([x , samples ] , open(""multinomial_test_graph.pkl "" , "" w "" ) )",def test_n_samples_compatibility folder os path dirname os path abspath __file__ with open os path join folder multinomial_test_graph pkl rb as pkl_file if PY3 u CompatUnpickler pkl_file encoding latin1 else u CompatUnpickler pkl_file X samples u load f theano function X samples res f numpy random randn 20 10 assert numpy all res sum axis 1 1
this method can be called with information regarding an error . it creates a git issue about it and send the log files along . : param title : the title of the error : type title : string : param trace_back : the trace back resulting in the error : type trace_back : string : param labels : the labels to attach to the issue,def handle_error title trace_back labels bug settings plebnet_settings get_instance if not settings github_active return body An error occurred at a plebbot agent n r n rThe plebnet nick is _ s_ r nMore info can be added here later on n r n r n rThe track back of the error n r n r n r s n r n r n rThe log file can be found here s n r n rMore details regarding this post can be found here s n r n r n rGood luck fixing this full_link gist_link create_gist body body settings irc_nick trace_back gist_link full_link create_issue title body labels
return coefficients compatible with the [ biquad~ ] object in max / msp,def get_coefficients_MaxMSP self B A self get_coefficients return B 0 B 1 B 2 A 1 A 2
"return a list of url patterns , given the registered viewsets .",def get_urls self u n Return a list of URL patterns given the registered viewsets n raise NotImplementedError u get_urls must be overridden
get a unique layer name as an object within topojson,def getLayerObjectName self outIndex stub u l 0 return stub format str outIndex
"generic method to generate an infinite series of files with _ 1 , _ 2 , etc . in their names .",staticmethod def _openRolloverFiles base rollover_pattern None if rollover_pattern is None def rollover_pattern base_pattern number if in base_pattern return base_pattern base_pattern rindex _ str number base_pattern base_pattern rindex else return base_pattern _ str number if isinstance base file f base base f name elif isinstance base string_types f None else assert False base should be an open file or string filename n 0 while True if f is None name rollover_pattern base n f open name wb assert w in f mode yield f f None
compute algorithm errors and rankings using cross - validation .,def algorithm_cv_ranking algorithm_slugs None error_attr mean_error show_progress False if not algorithm_slugs algorithm_slugs list IntrinsicImagesAlgorithm objects filter active True order_by distinct slug values_list slug flat True if show_progress print Evaluating s algorithms s len algorithm_slugs algorithm_slugs if show_progress print Computing algorithm cross validation errors slug_to_photo_to_error slug algorithm_cv_errors slug error_attr for slug in progress_bar algorithm_slugs show_progress slug_to_errors slug photo_to_error values for slug photo_to_error in slug_to_photo_to_error iteritems slug_to_error slug np mean errors np std errors for slug errors in slug_to_errors iteritems if show_progress print Computing ranks photo_to_slug_error for slug photo_ids in slug_to_photo_to_error iteritems for p error in photo_ids iteritems if p in photo_to_slug_error photo_to_slug_error p append slug error else photo_to_slug_error p slug error slug_to_ranks slug for slug in algorithm_slugs for photo errors in photo_to_slug_error iteritems if len errors len algorithm_slugs continue ranks rankdata e 1 for e in errors method average for i v in enumerate errors slug_to_ranks v 0 append ranks i slug_to_rank slug np mean ranks np std ranks for slug ranks in slug_to_ranks iteritems if show_progress print Computing ranks done return slug_to_rank slug_to_rank slug_to_error slug_to_error
get driving signals per secondary source .,def driving_signals delays weights signal delays util asarray_1d delays weights util asarray_1d weights data samplerate signal_offset apply_delays signal delays return util DelayedSignal data weights samplerate signal_offset
write a few dummy audio clips to writer .,def WriteAudioSeries writer tag n_audio 1 step 0 session tf Session min_frequency_hz 440 max_frequency_hz 880 sample_rate 4000 duration_frames sample_rate 2 frequencies_per_run 1 num_channels 2 p tf placeholder float32 frequencies_per_run duration_frames num_channels s tf summary audio tag p sample_rate for _ in xrange n_audio frequencies np random random_integers min_frequency_hz max_frequency_hz size frequencies_per_run num_channels tiled_frequencies np tile frequencies 1 duration_frames tiled_increments np tile np arange 0 duration_frames num_channels 1 T reshape 1 duration_frames num_channels tones np sin 2 0 np pi tiled_frequencies tiled_increments sample_rate tones tones reshape frequencies_per_run duration_frames num_channels summ session run s feed_dict p tones writer add_summary summ step step 20 session close
request an updated set of data from casper.jxml .,def update self response self jss session post self url data self auth response_xml ElementTree fromstring response text encode utf_8 self clear for child in response_xml getchildren self append child
computes pose change based on odometry .,def computePoseChange self timestamp leftWheelOdometry rightWheelOdometry dxyMillimeters 0 dthetaDegrees 0 dtSeconds 0 timestampSecondsCurr leftWheelDegreesCurr rightWheelDegreesCurr self extractOdometry timestamp leftWheelOdometry rightWheelOdometry if self timestampSecondsPrev None leftDiffDegrees leftWheelDegreesCurr self leftWheelDegreesPrev rightDiffDegrees rightWheelDegreesCurr self rightWheelDegreesPrev dxyMillimeters self wheelRadiusMillimeters math radians leftDiffDegrees math radians rightDiffDegrees dthetaDegrees float self wheelRadiusMillimeters self halfAxleLengthMillimeters rightDiffDegrees leftDiffDegrees dtSeconds timestampSecondsCurr self timestampSecondsPrev self timestampSecondsPrev timestampSecondsCurr self leftWheelDegreesPrev leftWheelDegreesCurr self rightWheelDegreesPrev rightWheelDegreesCurr return dxyMillimeters dthetaDegrees dtSeconds
homepage and creation of code snippet,def home request if request method GET return render request app_code_share homepage html if request method POST code_share request POST get code_snippet file_name request POST get file_name language request POST get language chars abcdefghijklmnopqrstuvwxyz0123456789 hash_value get_random_string 8 chars CodeShare objects create code code_share hash_value hash_value file_name file_name language language return redirect code_share view_by_hash hash_id hash_value
"return a new ripemd160 object . an optional string argument may be provided ; if present , this string will be automatically hashed .",def new arg None return RIPEMD160 arg
login to the schoolism account and return the users account : param email : ( str ) email for account : param password : ( str ) password for account : return : ( str ) users email,def login self email password if self options get email and self options get password res self session http post self login_url data email email password password redirect None submit Login if res cookies get password and res cookies get email return res cookies get email else self logger error Failed to login to Schoolism incorrect email password combination else self logger error An email and password are required to access Schoolism streams
swap buffers around when the paused boolean changes state .,def _paused_changed self if self paused self _paused_buffer self unfiltered_list else self unfiltered_list self _paused_buffer self _log_level_filter_changed self _paused_buffer
validates one submission and copies it to target directory .,def validate_and_copy_one_submission self submission_path if os path exists self download_dir shutil rmtree self download_dir os makedirs self download_dir if os path exists self validate_dir shutil rmtree self validate_dir os makedirs self validate_dir logging info n 80 n Processing submission s n 80 submission_path local_path self copy_submission_locally submission_path metadata self base_validator validate_submission local_path if not metadata logging error Submission s is INVALID submission_path self stats add_failure return submission_type metadata type container_name metadata container_gpu logging info Submission s is VALID submission_path self list_of_containers add container_name self stats add_success submission_type if self do_copy submission_id 0 04 format self cur_submission_idx self cur_submission_idx 1 self copy_submission_to_destination submission_path TYPE_TO_DIR submission_type submission_id self id_to_path_mapping submission_id submission_path
gets the list of regularization losses .,tf_export losses get_regularization_losses def get_regularization_losses scope None return ops get_collection ops GraphKeys REGULARIZATION_LOSSES scope
gets the number of dimensions ( rank ) of the dataset .,property def ndim self return self data ndim
generate a product of n sets of combinations .,def times combined assert combined if len combined 1 return combined 0 first combined 0 rest_combined times combined 1 combined_results for a in first for b in rest_combined if set a keys intersection set b keys raise ValueError Keys need to not overlap vs format a keys b keys combined_results append OrderedDict list a items list b items return combined_results
load the configuration from the schema and config files .,def load self filename None u schema_file config_file None try schema_file resource_stream u mailman config u schema cfg schema ConfigSchema u schema cfg schema_file config_file resource_stream u mailman config u mailman cfg self _config schema loadFile config_file u mailman cfg if filename is not None self filename filename with open filename as user_config self _config push filename user_config read finally if schema_file schema_file close if config_file config_file close self _post_process
"compute the hidden layer activation probabilities , p(h=1|v = x ) .",def transform self X check_is_fitted self components_ X check_array X accept_sparse csr dtype np float return self _mean_hiddens X
wraps the ` runconfig ` uid check with ` experiment_fn ` .,def _wrapped_experiment_fn_with_uid_check experiment_fn require_hparams False def wrapped_experiment_fn run_config hparams Calls experiment_fn and checks the uid of RunConfig if not isinstance run_config run_config_lib RunConfig raise ValueError run_config must be tf contrib learn RunConfig instance if not run_config model_dir raise ValueError Must specify a model directory model_dir in run_config if hparams is not None and not isinstance hparams hparam_lib HParams raise ValueError hparams must be HParams instance if require_hparams and hparams is None raise ValueError hparams cannot be None expected_uid run_config uid experiment experiment_fn run_config hparams if not isinstance experiment Experiment raise TypeError Experiment builder did not return an Experiment instance got s instead type experiment config_from_estimator experiment estimator config if not hasattr config_from_estimator uid raise RuntimeError Pass run_config argument of the experiment_fn to the Estimator in Experiment It is likely a different RunConfig is passed to Estimator or the config constructor argument in Estimator is not set if config_from_estimator uid expected_uid raise RuntimeError RunConfig instance is expected to be used by the Estimator inside the Experiment expected but got format expected_uid experiment estimator config uid return experiment return wrapped_experiment_fn
implementation of the tensor value - carrying event proto callback .,def on_graph_def self graph_def device_name wall_time if self _dump_dir if self _grpc_path self _write_graph_def graph_def device_name wall_time else self _cached_graph_defs append graph_def self _cached_graph_def_device_names append device_name self _cached_graph_def_wall_times append wall_time else self _event_listener_servicer partition_graph_defs append graph_def
"return the bool value for ` pred ` , or none if ` pred ` had a dynamic value .",def constant_value pred if isinstance pred bool pred_value pred elif isinstance pred variables Variable pred_value None elif isinstance pred ops Tensor pred_value tensor_util constant_value pred else raise TypeError pred must be a Tensor a Variable or a Python bool return pred_value
javascript vendor libraries to be placed in the { % block global_scripts % } block,staticmethod def get_vendor_js return tethys_gizmos vendor select2_4 0 2 js select2 full min js
removes a script that has been passed into the container,def removeScript self script if script in self _scripts self _scripts remove script
get the triangle mesh for the slc file .,def getCarving fileName carving SLCCarving carving readFile fileName return carving
true divide each component of this vector3 .,def __itruediv__ self other self x operator truediv self x other self y operator truediv self y other self z operator truediv self z other return self
parse a gcode line and send the command to the extruder .,def parseLine self line self addToOutput line splitLine line split if len splitLine 1 return 0 firstWord splitLine 0 if firstWord G1 self linearMove splitLine if firstWord G2 self helicalMove False splitLine if firstWord G3 self helicalMove True splitLine if firstWord M101 self extruderActive 1 self evaluateCommand reprap extruder setMotor reprap CMD_REVERSE 150 if firstWord M103 self extruderActive 0 self evaluateCommand reprap extruder setMotor reprap CMD_REVERSE 0 self oldActiveLocation None
the arm lsr ( logical shift right ) operation .,def LSR value amount width if amount 0 return value result _ LSR_C value amount width return result
we have manually manipulated the sql property store by - passing the underlying implementation 's caching mechanism . we need to clear out the cache .,inlineCallbacks def cleanPropertyStore yield PropertyStore _cacher flushAll
dav header does not advertise caldav,def test_dav_header_caldav_disabled self def do_test response response IResponse response dav response headers getHeader dav if not dav self fail no DAV header s response headers self assertIn 1 dav no DAV level 1 header self assertNotIn calendar access dav DAV calendar access header self patch config EnableCalDAV False request SimpleRequest self site OPTIONS return self send request do_test
get a static child - when registered using l{putchild}.,def getChild self path return getattr self child_ s path None
undo monkey - patching by : func:`inject_into_urllib3 ` .,def extract_from_urllib3 connection ssl_wrap_socket orig_connection_ssl_wrap_socket util HAS_SNI orig_util_HAS_SNI
confirm that an old session from implicit grant is stale .,def test_old_implicit_grant_session_is_stale implicit_grant_session u implicit_grant_session oauth2credential expires_in_seconds 1 assert implicit_grant_session oauth2credential is_stale
sets the username and password after capturing them from the phishing page .,def set_creds self user password self user user self password password
"return a tuple of ( prop , valu ) tuples from the kvdict .",def items self return tuple self vals items
ack a sequence from this fifo .,def ack self seqn if seqn 1 self resync return False with self lock if seqn self nack return False qent None while self dequ and self dequ 0 0 seqn qent self dequ popleft if qent is not None self _set_nack qent 1 self fill return True
correct cross correlation ratio ( rhohv ) from noise . from the schuur et al . 2003 noaa report ( p7 eq 5 ),def correct_rhohv radar rhohv_name RHOHV snr_name SNR rhohv radar fields rhohv_name data copy snr radar fields snr_name data copy natural_snr 10 0 1 snr natural_snr natural_snr filled 9999 rho_corr rhohv 1 1 natural_snr rho_corr np isnan rho_corr rho_corr 0 rho_corr 1 1 try rho_corr rho_corr filled 1 except Exception pass return rho_corr
a convenience function for creating new messages .,def make_new self class_name args kwargs return getattr self MessageType class_name new_message args kwargs
parse a c source file and add its blocks to the processor 's list .,def parse_file self filename self reset self filename filename fileinput close self format None self lineno 0 self lines for line in fileinput input filename if line 1 n line line 0 1 if self format None self process_normal_line line elif self format end match line self lines append line self add_block_lines elif self format column match line self lines append line else self add_block_lines self process_normal_line line self add_block_lines
".. function : : tachy(average_hr_val , tachy_limit )",def tachy average_hr_val tachy_limit 100 if tachy_limit 0 print Your tachycardia limit must be greater than zero raise ValueError try tachy_limit complex tachy_limit tachy_limit tachy_limit real except ValueError print Your tachycardia threshold input is not a number please input a number if average_hr_val tachy_limit print Tachycardia was found return False else return True
converts a datetime to local time in a given time zone .,register filter timezone def do_timezone value arg if not isinstance value datetime return try if timezone is_naive value default_timezone timezone get_default_timezone value timezone make_aware value default_timezone except Exception return if isinstance arg tzinfo tz arg elif isinstance arg six string_types try tz pytz timezone arg except pytz UnknownTimeZoneError return else return result timezone localtime value tz result datetimeobject result year result month result day result hour result minute result second result microsecond result tzinfo result convert_to_local_time False return result
returns a short - hand string form of the ogr geometry type .,property def name self return self _types self num
add another list - like object,def __add__ self other return self __class__ list self list other
returns true if the element identified by ` selector ` has the css class ` klass ` .,def has_css_class self selector klass return self selenium find_element_by_css_selector selector get_attribute class find klass 1
returns true if the name looks like a url,def is_url self template if not in template return False scheme template split 1 0 lower return scheme in self url_schemes
look for a module with matching and non - matching sensitivity .,def sensitivity_test self sensitive_pkg sensitive 0 format self name insensitive_pkg insensitive 0 format self name lower context util create_modules insensitive_pkg sensitive_pkg with context as mapping sensitive_path os path join mapping root sensitive insensitive_path os path join mapping root insensitive sensitive_finder self finder sensitive_path insensitive_finder self finder insensitive_path return self find sensitive_finder self find insensitive_finder
transform for imports of specific module elements . replaces the module to be imported from with the appropriate new module .,def transform_member self node results mod_member results get mod_member pref mod_member prefix member results get member if member if isinstance member list member member 0 new_name None for change in MAPPING mod_member value if member value in change 1 new_name change 0 break if new_name mod_member replace Name new_name prefix pref else self cannot_convert node This is an invalid module element else modules mod_dict members results members for member in members if member type syms import_as_name as_name member children 2 value member_name member children 0 value else member_name member value as_name None if member_name for change in MAPPING mod_member value if member_name in change 1 if change 0 not in mod_dict modules append change 0 mod_dict setdefault change 0 append member new_nodes indentation find_indentation node first True def handle_name name prefix if name type syms import_as_name kids Name name children 0 value prefix prefix name children 1 clone name children 2 clone return Node syms import_as_name kids return Name name value prefix prefix for module in modules elts mod_dict module names for elt in elts 1 names extend handle_name elt pref names append Comma names extend handle_name elts 1 pref new FromImport module names if not first or node parent prefix endswith indentation new prefix indentation new_nodes append new first False if new_nodes nodes for new_node in new_nodes 1 nodes extend new_node Newline nodes append new_nodes 1 node replace nodes else self cannot_convert node All module elements are invalid
get transport for pipe with number fd .,def get_pipe_transport self fd raise NotImplementedError
collect all links in current page following given xpath values arguments : make_root - add / at beginning of url,def extract_links self xpaths None make_root False links xpaths xpaths or a for xpath in xpaths for element in self xpath xpath link get_link_info element make_root if link is None continue url link url strip rstrip split 1 0 scheme urlparse urlparse url scheme lower if scheme not in http https continue if url in links if link text and not links url text del links url else continue links url self complete_url link found_links links values found_links sort return found_links
return context manager for stream to send a ( incremental ) snapshot .,def send self targetPath parent diff showProgress True allowDryRun True if parent is not None cmd btrfs send p parent targetPath else cmd btrfs send targetPath if Store skipDryRun logger self dryrun and allowDryRun Command s cmd return None process subprocess Popen cmd stdout subprocess PIPE stderr subprocess PIPE stdin DEVNULL _makeNice process return _Reader process process stdout targetPath diff showProgress
returns true if task can be ignored .,def is_ignorable self return hasattr self ignorable and self ignorable True or hasattr self func ignorable and self func ignorable True
compute quotient metrics from csv data .,def compute_quotient_metrics filename index_col 0 resample_period 1M shift 0 quotient_metrics Volume max median Close max min data pd read_csv filename index_col index_col parse_dates True def compute_quotient_metric name num_metric den_metric series pd TimeSeries data name num_period series resample resample_period how num_metric den_period series resample resample_period how den_metric return num_period shift den_period len num_period shift values return compute_quotient_metric qm for qm in quotient_metrics
quadkey generation from tile coordinates .,def test_quadkey tiler assert tiler quadkey 0 0 1 0 assert tiler quadkey 1 0 1 1 assert tiler quadkey 0 0 2 00 assert tiler quadkey 1 0 2 01 assert tiler quadkey 0 1 2 02 assert tiler quadkey 1 1 2 03 assert tiler quadkey 2 0 2 10 assert tiler quadkey 3 0 2 11 assert tiler quadkey 2 1 2 12 assert tiler quadkey 3 1 2 13 assert tiler quadkey 20 35 9 000210122
checking the course already exists in db .,def clean self cleaned_data super CourseAccessRoleForm self clean if not self errors if CourseAccessRole objects filter user cleaned_data get email org cleaned_data get org course_id cleaned_data get course_id role cleaned_data get role exists raise forms ValidationError Duplicate Record return cleaned_data
get a list of all possible port types . @throw notimplementederror,def get_types self raise NotImplementedError
convert an event object triggered by the subscription into ordered lists for the sql insert string,def _format_event self event placeholders ev_variant_binaries ev_variant_dict event get_event_props_as_fields_dict names list ev_variant_dict keys names sort for name in names variant ev_variant_dict name placeholders append ev_variant_binaries append sqlite3 Binary variant_to_binary variant return self _list_to_sql_str names self _list_to_sql_str placeholders False tuple ev_variant_binaries
takes in no param as input to fetch realtime alarms from hp imc restful api,def get_realtime_alarm username auth url get_realtime_alarm_url imcrs fault faultRealTime operatorName username f_url url get_realtime_alarm_url r requests get f_url auth auth headers headers try realtime_alarm_list json loads r text return realtime_alarm_list faultRealTime faultRealTimeList except requests exceptions RequestException as e return Error n str e get_realtime_alarm An Error has occured
return all results as a list : return : the results : rtype : list[streaminstance ],def items self return list self iteritems
check if string matches any regex in list,def match_any string regexes if len regexes 100 return any re match regex string for regex in regexes else combined format join regex for regex in regexes return bool re match combined string
run the test with a chromium webdriver,def test_testrunner self with open TEST_FILE as file_pointer testrunner TestRunner from_file file_pointer results testrunner run WebDriver CHROMEDRIVER self assertFalse False in results results self assertTrue True in results results
find the version of mycroft - core,def get_version version None version_file os path join BASEDIR mycroft version __init__ py major minor build None None None with open version_file as f for line in f if CORE_VERSION_MAJOR in line major line split 1 strip elif CORE_VERSION_MINOR in line minor line split 1 strip elif CORE_VERSION_BUILD in line build line split 1 strip if major and minor and build or END_VERSION_BLOCK in line break version join major minor build return version
blueprint with implicit data and schema etag computation,def implicit_data_and_schema_etag_blueprint collection schemas DocSchema schemas DocSchema blp Blueprint test __name__ url_prefix test blp route class Resource MethodView blp response DocSchema many True blp paginate Page def get self return collection items blp arguments DocSchema blp response DocSchema def post self new_item return collection post new_item blp route int item_id class ResourceById MethodView def _get_item self item_id try return collection get_by_id item_id except ItemNotFound abort 404 blp response DocSchema def get self item_id return self _get_item item_id blp arguments DocSchema blp response DocSchema def put self new_item item_id item self _get_item item_id check_etag item DocSchema return collection put item_id new_item blp response code 204 def delete self item_id item self _get_item item_id check_etag item DocSchema collection delete item_id return blp
only return the username if the user has shared it with the project .,staticmethod def get_username obj if obj username_shared return obj member user username return None
`` connect < origin_port > < destination_port > ``,staticmethod def connect connection return ProtocolParser _connect_message ProtocolParser _get_out_name_of connection output ProtocolParser _get_in_name_of connection input
downloads the recent json files for short term metrics phyp args : http_object : http request object carrying the headers and url feedparser_stm : feedparser object containing the entries of stm object_list : available vios object list,def json_download_recent_files_phyp self HTTP_object feedparser_STM object_list timestamp_phyp for j in range 0 len feedparser_STM entries if feedparser_STM entries j category phyp timestamp_phyp append feedparser_STM entries j links 0 href 154 160 timestamp_phyp sort for k in range 0 len feedparser_STM entries if feedparser_STM entries k category phyp and feedparser_STM entries k links 0 href 154 160 timestamp_phyp len timestamp_phyp 1 HTTP_object HTTPGet url feedparser_STM entries k links 0 href log_object log_debug HTTP_object response print nThe recent json file of PowerHypervisor JsonFilesDownload json_file feedparser_STM entries k title HTTP_object response text break
called upon end of the context . does nothing : param exc_type : exception type : param exc_val : exception value : param exc_tb : exception traceback : return :,def __exit__ self exc_type exc_val exc_tb pass
transform a field value to lower case .,def _transform_to_lower value testcase return value lower
load and start the http server .,classmethod def start cls threading Thread target cls httpserver safe_start start while not cls httpserver ready time sleep 0 1
generates api path for unsubscribing an email from all campaigns args : email ( str ) : the email of the subscriber,def get_unsubscribe_email_query_path self email return subscribers remove format self endpoint self account_id email
general : test fuzzy search instance of easypeasy ( ) . specific : test easypeasy().normalize ( ) method .,def test_fuzzy_search self norm_CAD_to_USD ep normalize 100 region Canadian from_year 2005 to_year 2012 base_currency USD exchange_date 30 11 2012 self assertEqual norm_CAD_to_USD 114 46
try to solve an already solved cube,def test_solved_solution self c Cube solution self _test_solution c self _check_solution c solution
parses the xml data entry of the mainlist,def ParseXmlData self data items data UriHandler Open http www omroepflevoland nl Mobile FeedV3 programmas aspx t a wifi 1 v 14 proxy self proxy programs Regexer DoRegex item w W 0 5000 item data liveItem mediaitem MediaItem x07 Live TV http edge02 streamgate nl live omroepflevoland smil flevo_livestream smil playlist m3u8 liveItem icon self icon liveItem thumb self noImage liveItem type video liveItem dontGroup True now datetime datetime now liveItem SetDate now year now month now day now hour now minute now second items append liveItem for program in programs xmlData XmlHelper program name xmlData GetTagAttribute item title None Logger Debug Processing s name thumb xmlData GetTagAttribute thumb url None thumb http www omroepflevoland nl SiteFiles s thumb date xmlData GetTagAttribute item date None day month year date split showItem mediaitem MediaItem name None showItem thumb thumb showItem icon self icon showItem SetDate year month day items append showItem episodes Regexer DoRegex show w W 0 1000 show program for episode in episodes xmlData XmlHelper episode url xmlData GetTagAttribute show url None description xmlData GetSingleNodeContent content stripCData True name s s name date date xmlData GetTagAttribute show date None day month year date split time xmlData GetTagAttribute show time None hours minutes time split episodeItem mediaitem MediaItem name None episodeItem type video episodeItem thumb thumb episodeItem description description episodeItem icon self icon episodeItem SetDate year month day hours minutes 0 episodeItem complete True showItem items append episodeItem part episodeItem CreateNewEmptyMediaPart part AppendMediaStream url 1225 part AppendMediaStream url replace middel hoog 1825 part AppendMediaStream url replace middel laag 630 return data items
internal method called when the handler is going to be destroyed . you should add cleanup code here . remember to call the parent function .,def _shutdown self self close
returns current value of plugin specific option .,def get_plugin_option self plugin key if plugin in self plugins plugin self plugins plugin return plugin get_option key
test unsigned mdn generation and parsing,def test_unsigned_mdn self u self partner sign True self partner encrypt True self partner mdn_mode as2 SYNCHRONOUS_MDN self out_message as2 Message self org self partner self out_message build self test_data raw_out_message self out_message headers_str r n self out_message content in_message as2 Message _ _ mdn in_message parse raw_out_message find_org_cb self find_org find_partner_cb self find_partner out_mdn as2 Mdn status detailed_status out_mdn parse mdn headers_str r n mdn content find_message_cb self find_message self assertEqual status u processed
"adds an account . if one with the same number already exists , do nothing , unless edit is true , in which case , override the existing account . returns true if an action is taken , false otherwise .",def add_account number third_party name s3_name active notes edit False query Account query query query filter Account number number if query count if not edit return False else query delete account Account account name name account s3_name s3_name account number number account notes notes account active active account third_party third_party db session add account db session commit return True
"decorator that removes specific headers from the response . usage : @remove_headers(""vary "" ) def myview(request ) : ...",def remove_headers headers def _decorator func Decorates the given function wraps func def _inner args kwargs Alters the response response func args kwargs remove_headers_from_response response headers return response return _inner return _decorator
url to this page - override in subclass,def url self raise NotImplementedError
creates an article at /parent / slug and returns its urlpath,def create_urlpath self parent slug return URLPath create_article parent slug title slug
iterate through the list of lt * objects and capture the text data contained in each object,def parse_lt_objects lt_objects text_content for lt_object in lt_objects if isinstance lt_object LTTextBox or isinstance lt_object LTTextLine text_content append lt_object get_text encode utf 8 elif isinstance lt_object LTFigure text_content append parse_lt_objects lt_object _objs return n join text_content
notes view to handle list and search requests .,require_GET login_required def notes request course_id course_key CourseKey from_string course_id course get_course_with_access request user load course_key if not is_feature_enabled course raise Http404 page request GET get page or DEFAULT_PAGE page_size request GET get page_size or DEFAULT_PAGE_SIZE text request GET get text try notes_info get_notes request course page page page_size page_size text text except EdxNotesParseError EdxNotesServiceUnavailable as err return JsonResponseBadRequest error err message status 500 return HttpResponse json dumps notes_info cls NoteJSONEncoder content_type application json
verify that caching the due property works to limit queries,def test_ccx_due_caching self expected datetime now UTC self set_ccx_override due expected with check_mongo_calls 1 self ccx due with check_mongo_calls 0 self ccx due
"test staticcontentstream stream_data function , asserts that we get all the bytes",def test_static_content_stream_stream_data self data SAMPLE_STRING item FakeGridFsItem data static_content_stream StaticContentStream loc name type item length item length total_length 0 stream static_content_stream stream_data for chunck in stream total_length len chunck self assertEqual total_length static_content_stream length
scenario : ensure that the certificates can be created with signatories and edited correctly . given i have a course without certificates when i click button ' add your first certificate ' and i set new the course title override and signatory and click the button ' create ' then i see the new certificate is added and has one signatory inside it when i click ' edit ' button of signatory panel and i set the name and click the button ' save ' icon then i see the signatory name updated with newly set name when i refresh the certificates page then i can see course has one certificate with new signatory name when i click ' edit ' button of signatory panel and click on ' close ' button then i can see no change in signatory detail,skip_if_browser chrome def test_can_create_and_edit_signatories_of_certficate self self certificates_page visit certificate self create_and_verify_certificate Course Title Override 0 self make_signatory_data first self assertEqual len self certificates_page certificates 1 signatory certificate signatories 0 signatory edit signatory name Updated signatory name signatory title Update signatory title signatory organization Updated signatory organization signatory save self assertEqual len self certificates_page certificates 1 self certificates_page refresh self certificates_page wait_for_page signatory self certificates_page certificates 0 signatories 0 self assertIn Updated signatory name signatory name self assertIn Update signatory title signatory title self assertIn Updated signatory organization signatory organization signatory edit signatory close self assertIn Updated signatory name signatory name
"if diff - quality fails on pylint , the paver task should also fail",patch __builtin__ open mock_open def test_failure_on_diffquality_pylint self self _mock_paver_sh side_effect CustomShMock fail_on_pylint _mock_pep8_violations MagicMock return_value 0 with patch pavelib quality _get_pep8_violations _mock_pep8_violations with self assertRaises SystemExit pavelib quality run_quality self assertRaises BuildFailure self assertEqual _mock_pep8_violations call_count 1 self assertEqual self _mock_paver_sh call_count 2
updates the note with ` note_id(str ) ` by the ` note_info(dict ) ` to the stub edxnotes service .,def update_note self note_id note_info note self filter_by_id self notes note_id if note note 0 update note_info return note else return None
"pre - processes the image 's dockerfile . leaves the context with a dictionary of dockerfile lines by directive . e.g. context.data['dockerfile']['run ' ] = [ ' run apt - get update ' , ' run blah ' ] context.data['dockerfile']['volume ' ] = [ ' volume /tmp ' , ' volumn /var / log ' ]",def prepare_context self image_obj context return context
compute the error as 0.5 * ||x - y||^2 .,def forward self flag x y self err x y return tensor square self err 0 5
"if we 've previously locked a session for snapshot , unlock the session and remove the session file .",debug def unlock_snapshot self lock_filename tmp BACKUP_LOCK_KEY try with open BACKUP_LOCK_KEY r as f session_id f read self unlock BACKUP_LOCK_KEY session_id fcntl flock f fcntl LOCK_UN os remove lock_filename except IOError OSError pass
list all job boards for this project .,scoring_base ScoringProject cached jobboards def list_jobboards self project all_job_boards self _db get_collection project database return list scoring_base filter_using_score all_job_boards lambda j j filters project
set the nps score and redirect to end of survey .,def test_set_nps_and_redirect self response self app get api nps query_string redirect https typeform com abcde score 8 token self nps_auth_token user self user_id self assertEqual 302 response status_code self assertTrue response location startswith https typeform com abcde msg response location redirect_url parse urlparse response location redirect_args dict parse parse_qsl redirect_url query self assertEqual token self nps_auth_token user self user_id score 8 redirect_args user self get_user_info self user_id self auth_token self assertEqual 8 user get netPromoterScoreSurveyResponse get score
a chunk of html that shows the various login options,def login_box_raw request return_url auth_systems None default_auth_system_obj None if helios_auth DEFAULT_AUTH_SYSTEM default_auth_system_obj AUTH_SYSTEMS helios_auth DEFAULT_AUTH_SYSTEM if auth_systems None enabled_auth_systems set auth_systems intersection set helios_auth ENABLED_AUTH_SYSTEMS intersection set AUTH_SYSTEMS keys else enabled_auth_systems set helios_auth ENABLED_AUTH_SYSTEMS intersection set AUTH_SYSTEMS keys form password LoginForm return render_template_raw request login_box enabled_auth_systems enabled_auth_systems return_url return_url default_auth_system helios_auth DEFAULT_AUTH_SYSTEM default_auth_system_obj default_auth_system_obj form form
crossover two individuals to generate a child individual returns an ` individual ` object,def crossover self parent1 parent2 child Individual for i in range len Individual targetPhrase split random randint 0 len Individual targetPhrase child phrase parent1 phrase split parent2 phrase split return child
commented while waiting for marker 's swf mocks on moto,mock_s3 mock_swf def test_skip_step self self create_bucket self build_history args 2 kwargs skip_steps my_step decisions self replay self check_task_scheduled_decision decisions 0 task Activity GetStepsDoneTask self add_activity_task_from_decision decisions 0 task Activity GetStepsDoneTask result decisions self replay self assertEquals decisions 0 decisionType RecordMarker self assertEquals json loads decisions 0 recordMarkerDecisionAttributes details status skipped forced True step my_step reasons workflow_init
adds support for metric_name kwarg to session .,def request_wrapper func u functools wraps func def request method url kwargs try _local metric_api_name kwargs pop u metric_api_name None _local metric_host_name kwargs pop u metric_host_name None return func method url kwargs finally del _local metric_api_name del _local metric_host_name request _request_wrapper True return request
"run metasv if we have enough supported callers , adding output to the set of calls .",def run items assert len items 1 Expect one input to MetaSV ensemble calling data items 0 work_dir _sv_workdir data out_file os path join work_dir variants vcf gz cmd _get_cmd sample dd get_sample_name data reference dd get_ref_file data bam dd get_align_bam data outdir work_dir methods for call in data get sv vcf_file call get vcf_file call get vrn_file None if call variantcaller in SUPPORTED and call variantcaller not in methods and vcf_file is not None methods append call variantcaller cmd s_vcf call variantcaller vcf_file if len methods MIN_CALLERS if not utils file_exists out_file tx_work_dir utils safe_makedir os path join work_dir raw ins_stats shared calc_paired_insert_stats_save dd get_align_bam data os path join tx_work_dir insert stats yaml cmd workdir tx_work_dir num_threads str dd get_num_cores data cmd spades utils which spades py age utils which age_align cmd assembly_max_tools 1 assembly_pad 500 cmd boost_sc isize_mean ins_stats mean isize_sd ins_stats std do run cmd Combine variant calls with MetaSV filters NUM_SVTOOLS 1 ABS SVLEN 50000 NUM_SVTOOLS 1 ABS SVLEN 4000 BA_FLANK_PERCENT 80 NUM_SVTOOLS 1 ABS SVLEN 4000 BA_NUM_GOOD_REC 0 ABS SVLEN 4000 BA_NUM_GOOD_REC 2 filter_file vfilter cutoff_w_expression out_file filters data name ReassemblyStats limit_regions None effects_vcf _ effects add_to_vcf filter_file data snpeff data sv append variantcaller metasv vrn_file effects_vcf or filter_file return data
"perform running and check results , raising errors for issues .",def _do_run cmd checks log_stdout False env None cmd shell_arg executable_arg _normalize_cmd_args cmd s subprocess Popen cmd shell shell_arg executable executable_arg stdout subprocess PIPE stderr subprocess STDOUT close_fds True env env debug_stdout collections deque maxlen 100 while 1 line s stdout readline if line rstrip debug_stdout append line if log_stdout logger_stdout debug line rstrip else logger debug line rstrip exitcode s poll if exitcode is not None for line in s stdout debug_stdout append line if exitcode is not None and exitcode 0 error_msg join cmd if not isinstance cmd basestring else cmd error_msg n error_msg join debug_stdout s communicate s stdout close raise subprocess CalledProcessError exitcode error_msg else break s communicate s stdout close if checks for check in checks if not check raise IOError External command failed
"remove polyx stretches , contributing to long variant runtimes .",def remove_polyx_regions in_file items ex_bed tz get_in genome_resources variation polyx items 0 if ex_bed and os path exists ex_bed return _remove_regions in_file ex_bed nopolyx items 0 else return in_file
"check if s3 has an existing , up to date version of this file .",def s3_has_uptodate_file bucket transfer_file s3_key_name s3_key bucket get_key s3_key_name if s3_key s3_size s3_key size local_size os path getsize transfer_file s3_time rfc822 mktime_tz rfc822 parsedate_tz s3_key last_modified local_time os path getmtime transfer_file return s3_size local_size and s3_time local_time return False
returns a sorted lxc templates list,def get_templates_list templates try path os listdir usr share lxc templates except OSError path os listdir usr lib lxc templates if path for line in path templates append line replace lxc return sorted templates
"evaluates to true if this item contains an aggregate expression and does not contain an analytic expression . if an expression contains both an aggregate and an analytic , it is considered an analytic expression .",property def is_agg self return not self is_analytic and self val_expr contains_agg
view for the events home page,gzip_page def home request template events home html events Event objects all order_by start_time context events events return render request template context
return a dict of dicts indexed by ip address with whois results .,def lookup_ips self ip_list raw self _lookup ip_list records ip_index self field_names index ip if ip not in self field_names raise ValueError You need to include an ip field in the field_names array for line_num line in enumerate raw split self record_delim if line_num 0 and self has_result_header next fields line split self field_delim fields field strip for field in fields if len fields len self field_names pass else records setdefault fields ip_index dict zip self field_names fields return records
test to validate that dropping a keyspace with user defined types does n't kill the control connection .,def test_drop_keyspace self self session self cluster connect self session execute CREATE KEYSPACE keyspacetodrop WITH replication class SimpleStrategy replication_factor 1 self session set_keyspace keyspacetodrop self session execute CREATE TYPE user age int name text self session execute CREATE TABLE mytable a int PRIMARY KEY b frozen user cc_id_pre_drop id self cluster control_connection _connection self session execute DROP KEYSPACE keyspacetodrop cc_id_post_drop id self cluster control_connection _connection self assertEqual cc_id_post_drop cc_id_pre_drop
open read - only file descriptor for application of advisory locks .,def _open_fd_r self self fd os open self proxy os O_RDONLY
"this function accepts an office doc , converted into a python dictionary . it decides which files of the office document to be fuzzed , based on the file ( xml or binary file )",def Mutate self office_doc_dict file_name if self oxml fuzzed_office_file_dict fuzzed_office_file_dict copy office_doc_dict if len self FILES_TO_BE_FUZZED 0 for file_count in range 0 self NUMBER_OF_FILES_TO_MUTATE target_file choice office_doc_dict keys ext target_file split 1 if ext in self handler_obj_dict HandlerClass self handler_obj_dict ext fuzzed_office_file_dict target_file HandlerClass Fuzzit office_doc_dict target_file else fuzzed_office_file_dict target_file office_doc_dict target_file else for file_count in range 0 self NUMBER_OF_FILES_TO_MUTATE target_file choice self FILES_TO_BE_FUZZED ext target_file split 1 if ext in self handler_obj_dict HandlerClass self handler_obj_dict ext try fuzzed_office_file_dict target_file HandlerClass Fuzzit office_doc_dict target_file except print datetime now strftime Y m d H M S Error File not found in provided base openXML file target_file Please check config file parameter FILES_TO_BE_FUZZED You can Re Generate FILES_TO_BE_FUZZED list using OXDumper py exit else fuzzed_office_file_dict target_file office_doc_dict target_file return fuzzed_office_file_dict else ext file_name split 1 HandlerClass self handler_obj_dict ext return self handler_obj_dict ext Fuzzit office_doc_dict
same as : func:`.filter_tags_for_related_student ` but also filters on period .,def filter_tags_for_related_student_user_on_period self user period u n Same as func filter_tags_for_related_student but also filters on period n n Args n user class devilry account models User instance n period class devilry apps core models period Period instance n n Returns n QuerySet QuerySet of class PeriodTag n return self filter_tags_for_related_student_user user user filter period period
"return width , height , x center , and y center for an anchor ( window ) .",def _whctrs anchor w anchor 2 anchor 0 1 h anchor 3 anchor 1 1 x_ctr anchor 0 0 5 w 1 y_ctr anchor 1 0 5 h 1 return w h x_ctr y_ctr
start a connection with the time clock,def zksettime self t command CMD_SET_TIME command_string pack I encode_time t chksum 0 session_id self session_id reply_id unpack HHHH self data_recv 8 3 buf self createHeader command chksum session_id reply_id command_string self zkclient sendto buf self address try self data_recv addr self zkclient recvfrom 1024 self session_id unpack HHHH self data_recv 8 2 return self data_recv 8 except return False
returns the ascii decoded version of the given html string . this does not remove normal html tags like < p>.,def html_decode self s htmlCodes 39 quot gt lt amp for code in htmlCodes s s replace code 1 code 0 return s
returns a list of dc - terms author predicates,def get_dc_authors_list self dc_author_terms for dc_term_key dc_solr_key in self DC_AUTHOR_PREDICATES items dc_author_terms append dc_term_key return dc_author_terms
gets a list of the table field names,def get_table_fields self self field_name_row exfields ExpField objects filter table_id self table_id order_by field_num check_num 1 for exfield in exfields self field_count exfield field_num self field_name_row append exfield label if exfield field_num check_num raise Exception Expected field_num str check_num but got str exfield field_num check_num 1
bool : whether this is a multi - select node .,property def multiple self raise NotImplementedError
"remove the annotation . on success , returns a 204 no content response as per the annotator store api documentation .",def delete self request id note self get_object if not note user_can_delete self request user raise PermissionDenied note delete response HttpResponse response status_code 204 return response
"resizes the example image , and returns it as a string of png data",blueprint route resize example methods POST def resize_example try example_image_path os path join os path dirname digits __file__ static images mona_lisa jpg image utils image load_image example_image_path width int flask request form width height int flask request form height channels int flask request form channels resize_mode flask request form resize_mode backend flask request form backend encoding flask request form encoding image utils image resize_image image height width channels channels resize_mode resize_mode if backend lmdb or encoding none length len image tostring else s StringIO if encoding png PIL Image fromarray image save s format PNG elif encoding jpg PIL Image fromarray image save s format JPEG quality 90 else raise ValueError unrecognized encoding s encoding s seek 0 image PIL Image open s length len s getvalue data utils image embed_image_html image return img src data style width spx height spx br i Image size s i width height utils sizeof_fmt length except Exception as e return s s type e __name__ e
converts django 's ` language_code ` settings to a proper locale code .,def language_to_locale language tokens language split if len tokens 1 return tokens 0 return s_ s tokens 0 tokens 1 upper
connect second facebook account to logged in user .,def test_logged_social_connect_second_account social_config facebook_user db_session user db_session merge facebook_user profile accounts domain text_type facebook com userid text_type 2343 displayName text_type teddy preferredUsername text_type teddy emails value text_type aasd basd pl name text_type ted credentials oauthAccessToken 7897048593434 provider_name text_type facebook provider_type text_type facebook request testing DummyRequest request user user request registry social_config registry request remote_addr text_type 127 0 0 123 request context AuthenticationComplete profile credentials provider_name provider_type request _ mock_translate request login_perform MagicMock name login_perform request login_perform return_value status True view SocialLoginViews request out view assert out status is False assert out msg Your account is already connected to other provider account assert user provider_id text_type facebook is not profile accounts 0 userid
assume one - tree - per - line,def read_genia_file fh for line in fh line line strip line re sub S s 2 1 line line s line try yield tree LingTree from_str unicode line except KeyError sys stderr write skipping bad tree s n line
validates absence of table with zero patches .,def test_empty_patch_list self project create_project url reverse patch list kwargs project_id project linkname response self client get url self assertContains response No patches to display
"return a view into the current data , but only for the currently selected configurations",def current_view self cols None subconfigs self _running_data self _running_data configname isin self current_selection if cols is None cols subconfigs columns return subconfigs cols
add an instance of tableprocessor to blockparser .,def extendMarkdown self md md_globals u md parser blockprocessors add u table TableProcessor md parser u hashheader
verifies that the api functions are added to ee . image .,def testImageSignatures self self assertTrue hasattr ee Image 1 addBands
converts the snippet and its assets in place .,def _convert_default self snippet append_assets_to None template None assets self bundle assets_relative_to snippet root regexp x5_utils tokens_regexp_quoted assets keys match_func x5_utils match_function snippet assets template template snippet parsed_content regexp sub match_func snippet content if append_assets_to append_assets_to assets snippet assets else for asset_name in snippet assets asset self bundle assets asset_name if not asset inlineable or asset converted continue self _convert_default asset append_assets_to snippet
"return integer array of shape ( nedges,2 ) containing all edges of non - masked triangles .",property def edges self u n Return integer array of shape nedges 2 containing all edges of n non masked triangles n n Each edge is the start point index and end point index Each n edge start end and end start appears only once n if self _edges is None self _edges self get_cpp_triangulation get_edges return self _edges
parses the api responses for the : py : meth:`route53.connection . route53connection.list_hosted_zones ` method .,def list_hosted_zones_parser root connection zones root find HostedZones for zone in zones yield parse_hosted_zone zone connection
confirm new user 's account with provided token and prompt them to set a password .,account route join from invite int user_id token methods GET POST def join_from_invite user_id token if current_user is not None and current_user is_authenticated flash You are already logged in error return redirect url_for main index new_user User query get user_id if new_user is None return redirect 404 if new_user password_hash is not None flash You have already joined error return redirect url_for main index if new_user confirm_account token form CreatePasswordForm if form validate_on_submit new_user password form password data db session add new_user db session commit flash Your password has been set After you log in you can go to the Your Account page to review your account information and settings success return redirect url_for account login return render_template account join_invite html form form else flash The confirmation link is invalid or has expired Another invite email with a new link has been sent to you error token new_user generate_confirmation_token invite_link url_for account join_from_invite user_id user_id token token _external True get_queue enqueue send_email recipient new_user email subject You Are Invited To Join template account email invite user new_user invite_link invite_link return redirect url_for main index
generate a number of children by doing 1-point cross - over,def crossOver self parents nbChildren xdim self numParameters children for _ in range nbChildren p1 choice parents if xdim 2 children append p1 else p2 choice parents point choice range xdim 1 res zeros xdim res point p1 point res point p2 point children append res return children
"auxiliary access to just the cart position , to be used by balancetask",def getCartPosition self return self sensors 2
"decodes the huffman - encoded text stored in the bitbucket ' bb back into a plaintext string . if ' includes_eof ' is true , then it is assumed that the string was encoded with an eof . if bits_to_decode > 0 , then ' includes_eof ' is allowed to be false , and that many bits will be consumed from the bitbucket",def DecodeFromBB self bb includes_eof bits_to_decode output total_bits 0 if not includes_eof and bits_to_decode 0 raise StandardError if bits_to_decode 0 bits_to_decode 1 while bits_to_decode 0 or total_bits bits_to_decode root self code_tree while root 1 is None bit bb GetBits 1 0 0 7 root root 2 bit total_bits 1 if includes_eof and root 1 is not None and root 1 256 break elif root 1 is not None output append root 1 else raise StandardError if bits_to_decode 0 and total_bits bits_to_decode bb GetBits bits_to_decode total_bits return output
"returns a list with the passed network 's views or an empty list if there are no views . if a network is not specified , it assumes the current network .",def list self network None verbose False network check_network self network verbose verbose PARAMS set_param network network response api url self __url list PARAMS PARAMS method POST verbose verbose return response
sanity check files before and after update .,def verify_files self testname is_update qemu test cmd ls 1 usr bin modify_files_ status output qemu run_serial cmd test assertEqual 1 status Failed to run command s n s cmd output if not is_update test assertEqual output usr bin modify_files_remove_me r n usr bin modify_files_update_me else test assertEqual output usr bin modify_files_update_me r n usr bin modify_files_was_added cmd cat usr bin modify_files_update_me status output qemu run_serial cmd test assertEqual 1 status Failed to run command s n s cmd output test assertEqual output updated
"adds title page to header , using a format - string for header",def AddTitlePage self head self output append self header_text head Draft date head Title head Source head Author head Contact
"actual fitting , performing the search over parameters .",def fit self X y groups None results dict best_index None best_parameters None for bracket_idx in range self num_brackets 1 1 1 successive_halving_steps bracket_idx 1 estimator self estimator cv check_cv self cv y classifier is_classifier estimator self scorer_ check_scoring self estimator scoring self scoring X y groups indexable X y groups n_splits cv get_n_splits X y groups base_estimator clone self estimator arms_pulled 0 if mean_test_score in results arms_pulled len results mean_test_score res self _successive_halving X y groups cv self eta successive_halving_steps 1 self num_brackets 1 bracket_results bracket_best_index bracket_best_parameters res for key values in bracket_results items if key not in results results key values else results key np append results key values if best_index is None best_index bracket_best_index arms_pulled best_parameters bracket_best_parameters elif bracket_results mean_test_score bracket_best_index results mean_test_score best_index best_index bracket_best_index arms_pulled best_parameters bracket_best_parameters self cv_results_ results self best_index_ best_index self n_splits_ n_splits if self refit best_estimator clone base_estimator set_params best_parameters if y is not None best_estimator fit X y self fit_params else best_estimator fit X self fit_params self best_estimator_ best_estimator return self
close the ssh agent connection .,def close self self _close
create a temporary database and create the needed table,def setUp self messenger app config from_object settings self db_fd messenger app config DATABASE tempfile mkstemp messenger app config TESTING True self app messenger app test_client with sqlite3 connect messenger app config DATABASE as conn sql_path os path join messenger app config APP_ROOT db_init sql cmd open sql_path r read c conn cursor c execute cmd conn commit
traverse all faces of mesh breadth first and create an island ( does not check if edges are cut or fold ) need to figure out how to setup island so ready to do this function ...,def breadth_first_layout_face_version self island startMeshLoc startIslandLoc layoutPair startMeshLoc startIslandLoc queue collections deque layoutPair visited startMeshLoc face while True try meshLoc islandLoc queue popleft except IndexError break orientedEdges self myMesh get_edges_ccw_besides_base meshLoc edge meshLoc face newVerts newEdges islandFaceToBe island next_face_index for i orientedEdge in enumerate orientedEdges edge alignedWithFace orientedEdge face self myMesh getOtherFaceIdx edge meshLoc face if orientedEdge orientedEdges 1 tailPoint headPoint self myMesh get_aligned_points orientedEdge mapped_point self get_mapped_point headPoint meshLoc islandLoc island layout_add_vert_point mapped_point newEdge island layout_add_edge i 1 if face and face not in visited visited append face island update_edge_to_face edge newEdge toFace islandFaceToBe i 1 newMeshLoc MeshLoc face edge newIslandLoc IslandLoc islandFaceToBe newEdge queue append newMeshLoc newIslandLoc island layout_add_face baseEdge islandLoc edge
constructs a class ` consulhealthstruct < consulhealth > using a unpacked dictionary from /v1/health / node/<node>. will also associate tags from /v1/catalog / node/<node>.,def __init__ self kwargs self __dict__ update kwargs
"contour - plots a 2d density . if gaussian , plots 1.96 interval contour only",staticmethod def contour_plot_density distribution Xs None Ys None log_domain False if isinstance distribution Gaussian and log_domain False gca add_artist Visualise get_gaussian_ellipse_artist distribution gca plot distribution mu 0 distribution mu 1 r markersize 3 0 markeredgewidth 0 1 return assert distribution dimension 2 if Xs is None xmin xmax _ distribution get_plotting_bounds Xs linspace xmin xmax if Ys is None _ ymin ymax distribution get_plotting_bounds Ys linspace ymin ymax D zeros len Ys len Xs for i in range len Xs for j in range len Ys x array Xs i Ys j D j i distribution log_pdf x if log_domain False D exp D contour Xs Ys D origin lower
infer predicates from the tokens and graph . return a list of predicates .,def compute_predicates self tokens matches found_predicates set for matcher in self generators match_weights matcher get_predicates tokens matches append match_weights found_predicates update match_weights predicates fixed for fixed in FIXED_PREDICATES for name in found_predicates predicate WikiTablePredicate name original_string self get_original_string name match_weights self combine_match_weights matches name tokens predicates append predicate match_weights predicates sort key lambda x x 0 types x 0 name return predicates
: type path : str : rtype : str,staticmethod def read path data if os path isfile path with open path r as f data f read return data
replace the old value with the new value in the database .,def replace self old new count 1 return studiolibrary replaceJson self path old new count
init honeybee surface from an ep_string .,classmethod def from_ep_string cls ep_string types Wall 0 Roof 1 Floor 2 Ceiling 3 segments ep_string replace t replace replace split name segments 1 srf_type types segments 2 capitalize pts range len segments 11 3 for count i in enumerate xrange 11 len segments 3 try pts count float c for c in segments i i 3 except ValueError raise ValueError s is an invalid value for points segments i i 3 return cls name pts srf_type is_name_set_by_user True is_type_set_by_user True
uses cached client or create new one with specific token .,def _make_client_with_token self token cached_clients getattr self clients None hashed_token _hash_token self token if cached_clients and hashed_token in cached_clients return cached_clients hashed_token client self make_client token if cached_clients cached_clients hashed_token client return client
verify watch puts the pipeline in immediate execution mode .,def test_watch self with self redis pipeline as pipeline pipeline watch key1 key2 eq_ None pipeline get key1 eq_ None pipeline get key2 eq_ True pipeline set foo bar eq_ bar pipeline get foo
a transformation that applies optimizations .,def optimize optimizations None def _apply_fn dataset Function from Dataset to Dataset that applies the transformation return _OptimizeDataset dataset optimizations return _apply_fn
get homepage with ` url ` that triggers a dns resolution error,def test_invalid_hostname self with patch object urllib2 urlopen as mock_urlopen url http example com test_document odt message Name or service not known mock_urlopen side_effect urllib2 URLError message resp self testapp get params url url status 400 self assertTrue Name or service not known in resp body
lazy testing of the main function . checks the exitcode if the list is displayed .,def test_main_list self command usr bin env python3 cheat cheat py list dev null status os system command self assertEqual status self exit_0
othertrig1 and othertrig2 are two triggers like titletrigger and summarytrigger .,def __init__ self otherTrig1 otherTrig2 self otg1 otherTrig1 self otg2 otherTrig2
function to display 3d voxel .,def display_voxel points vis_size 128 try data visualize_voxel_spectral points vis_size except ValueError data visualize_voxel_scatter points vis_size return data
find the lnoverlaps given the parameters of a group,def calc_lnoverlaps group_pars star_pars nstars group_mn group_pars 0 6 group_cov utils generate_cov group_pars assert np min np linalg eigvalsh group_cov 0 age group_pars 13 interp_covs interp_mns gf interp_cov age star_pars lnols ol get_lnoverlaps group_cov group_mn interp_covs interp_mns nstars return lnols
make sure url is not touched by hook,def test_url self req _ self app op getUserByName username Tom req prepare self assertEqual req url http petstore swagger wordnik com api user Tom
"constructs example binary tree on page 156 of "" elements of programming interviews "" .",def example edges a b i b c f c d e f None g g h None i j o j None k k l n l None m o None p nodes for parent children in edges items l r children parent_node nodes setdefault parent Node parent if l is not None parent_node left nodes setdefault l Node l parent_node left parent parent_node if r is not None parent_node right nodes setdefault r Node r parent_node right parent parent_node return nodes
called by the coordinator when a receiver disconnects .,profile trackcpu def receiver_disconnect self receiver for k in list self clock_pairs keys if k 0 is receiver or k 1 is receiver del self clock_pairs k
"generate an iterable of endpoint objects given this input data , presumably from the result of performing the yadis protocol .",def applyFilter normalized_uri xrd_data flt None flt mkFilter flt et parseXRDS xrd_data endpoints for service_element in iterServices et endpoints extend flt getServiceEndpoints normalized_uri service_element return endpoints
return a list of weakrefs to each object in * objs . qobject instances are expanded to include all child objects .,def mkrefs objs allObjs for obj in objs if isinstance obj pg QtCore QObject obj qObjectTree obj else obj obj for o in obj allObjs id o o return map weakref ref allObjs values
load the input - hidden weight matrix from the original c word2vec - tool format .,def load_word2vec_format fname fvocab None binary False norm_only True encoding utf8 counts None if fvocab is not None logger info loading word counts from s fvocab counts with utils smart_open fvocab as fin for line in fin word count utils to_unicode line strip split counts word int count logger info loading projection weights from s fname with utils smart_open fname as fin header utils to_unicode fin readline encoding encoding vocab_size vector_size map int header split result Word2Vec size vector_size result syn0 zeros vocab_size vector_size dtype REAL if binary binary_len dtype REAL itemsize vector_size for line_no in xrange vocab_size word while True ch fin read 1 if ch break if ch n word append ch try word utils to_unicode join word encoding encoding except UnicodeDecodeError as e logger warning Couldn t convert whole word to unicode trying to convert first d bytes only e start word utils to_unicode join word e start encoding encoding logger warning first d bytes converted to s e start word if counts is None result vocab word Vocab index line_no count vocab_size line_no elif word in counts result vocab word Vocab index line_no count counts word else logger warning vocabulary file is incomplete result vocab word Vocab index line_no count None result index2word append word result syn0 line_no fromstring fin read binary_len dtype REAL else for line_no line in enumerate fin parts utils to_unicode line 1 encoding encoding split if len parts vector_size 1 raise ValueError invalid vector on line s is this really the text format line_no word weights parts 0 list map REAL parts 1 if counts is None result vocab word Vocab index line_no count vocab_size line_no elif word in counts result vocab word Vocab index line_no count counts word else logger warning vocabulary file is incomplete result vocab word Vocab index line_no count None result index2word append word result syn0 line_no weights logger info loaded s matrix from s result syn0 shape fname result init_sims norm_only return result
create a simple network to test the region .,def testNetworkCreate self rawParams outputWidth 8 2048 net Network rawSensor net addRegion raw py RawSensor json dumps rawParams l2c net addRegion L2 py ColumnPoolerRegion net link raw L2 UniformLink self assertEqual rawSensor getParameter outputWidth l2c getParameter inputWidth Incorrect outputWidth parameter rawSensorPy rawSensor getSelf rawSensorPy addDataToQueue 2 4 6 0 42 rawSensorPy addDataToQueue 2 42 1023 1 43 rawSensorPy addDataToQueue 18 19 20 0 44 net run 3
sets the weights of the lateral connections based on average pairwise activity of the sp 's columns . intuitively : the more two columns fire together on average the stronger the inhibitory connection gets .,def _updateLateralConnections self epsilon avgActivityPairs oldL self lateralConnections newL avgActivityPairs copy np fill_diagonal newL 0 0 newL newL np sum newL axis 1 keepdims True self lateralConnections 1 epsilon oldL epsilon newL
return the final component of a pathname,def basename path path _tostr path basename return asPyString File path getName
"determine if function ' func ' is available by constructing a source file that refers to ' func ' , and compiles and links it . if everything succeeds , returns true ; otherwise returns false .",def check_func self func headers None include_dirs None libraries None library_dirs None decl 0 call 0 self _check_compiler body if decl body append int s func body append int main if call body append s func else body append s func body append body string join body n n return self try_link body headers include_dirs libraries library_dirs
check if snmp yum dependencies are installed,def check_yum_snmp self pkg_module print Checking SNMP Packages yum_base pkg_module YumBase uninstalled for package in net snmp utils net snmp net snmp python if len yum_base rpmdb searchNevra name package 0 self messages append s Error s package is required for HDS self NAME package uninstalled append package if len uninstalled 0 self _set_status 0 s Info Uninstalled packages s self NAME join item for item in uninstalled return True
test the choices of an option .,def _choice_test self invalid_choice valid_choices opts option ignore_case True def _setup fx value fx load_raw_values group powervm option value fx register_opts opts group powervm def _build_list for val in valid_choices yield val yield val lower yield val upper if ignore_case valid_choices x for x in _build_list if invalid_choice with oslo_config fixture Config oslo_config cfg ConfigOpts as fx _setup fx invalid_choice self assertRaises oslo_config cfg ConfigFileValueError lambda fx conf powervm option for choice in valid_choices with oslo_config fixture Config oslo_config cfg ConfigOpts as fx _setup fx choice fx conf powervm option
"checks if a certain field is set for the message . note if the field_name is not defined in the message descriptor , valueerror will be raised .",def HasField self field_name u Checks if a certain field is set for the message Note if the n field_name is not defined in the message descriptor ValueError will be n raised raise NotImplementedError
search in the bulk edit form .,def _search self term self type_by_css self _SEARCH term self click_by_css self _SUBMIT_SEARCH
correctly generates a report for binary classification with linearsvc,def test_binary_class_report self _ ax plt subplots viz ClassificationReport LinearSVC random_state 42 ax ax viz fit self binary X train self binary y train viz score self binary X test self binary y test self assert_images_similar viz tol 40 assert viz scores_ precision 0 approx 0 7446808 1 approx 0 8490566 recall 0 approx 0 8139534 1 approx 0 7894736 f1 0 approx 0 7777777 1 approx 0 8181818
check that the target type is determined by a value y,def test_determine_target_color_type self manifold Manifold assert manifold target AUTO manifold _determine_target_color_type None assert manifold _target_color_type SINGLE y np random rand 100 manifold _determine_target_color_type y assert manifold _target_color_type CONTINUOUS y np random choice a b c d 100 manifold _determine_target_color_type y assert manifold _target_color_type DISCRETE manifold Manifold target CONTINUOUS y np random choice a b c d 100 manifold _determine_target_color_type y assert manifold _target_color_type CONTINUOUS manifold Manifold target DISCRETE y np random rand 100 manifold _determine_target_color_type y assert manifold _target_color_type DISCRETE manifold Manifold target CONTINUOUS manifold _determine_target_color_type None assert manifold _target_color_type SINGLE manifold Manifold target DISCRETE manifold _determine_target_color_type None assert manifold _target_color_type SINGLE manifold Manifold target foo msg could not determine target color type with pytest raises YellowbrickValueError match msg manifold _determine_target_color_type
return the field name on the : class:`follow ` model for `` model_or_obj_or_qs `` .,def fname self model_or_obj_or_qs if isinstance model_or_obj_or_qs QuerySet _ fname model_map model_or_obj_or_qs model else cls model_or_obj_or_qs if inspect isclass model_or_obj_or_qs else model_or_obj_or_qs __class__ _ fname model_map cls return fname
choose the next game to start .,def issue self if self to_reissue result min self to_reissue self to_reissue discard result else result self next_new self next_new 1 self outstanding add result self issued 1 return result
generate a query expression from data supplied .,def query self entitytype data queries for key value in data iteritems if not isinstance value basestring int if id in value keys queries append 0 id is 1 format key value id else queries append 0 is 1 format key value query select id from entitytype where and join queries self log debug query return query
test that the procedure throws out small imaginary components .,def test_approximately_real self for _ in range self num_test_repetitions v numpy random randn 2 1j 1e 14 G_left givens_matrix_elements v 0 v 1 which left G_right givens_matrix_elements v 0 v 1 which right self assertAlmostEqual G_left 0 0 G_left 1 1 self assertAlmostEqual G_right 0 0 G_right 1 1 self assertAlmostEqual G_left dot v 0 0 0 self assertAlmostEqual G_right dot v 1 0 0
reads the yaml file from input and generates the json for the es template in output . input and output are both file pointers .,def fields_to_es_template input output index docs yaml load input if docs is None print fields yml is empty Cannot generate template return if sections in docs keys del docs sections if defaults not in docs keys print No defaults are defined Each template needs at least defaults defined return defaults docs defaults template template index settings index refresh_interval 5s mappings _default_ _all norms False properties dynamic_templates template1 match_mapping_type string mapping type keyword index defaults index doc_values defaults doc_values ignore_above defaults ignore_above properties for doc section in docs items if doc not in version defaults prop fill_section_properties section defaults properties update prop template mappings _default_ properties properties json dump template output indent 2 separators sort_keys True
returns the current database table prefix .,def get_table_prefix self return self _table_prefix
keysym definition modules need no longer call xlib . xk._load_keysyms_into_xk ( ) . you should remove any calls to that function from your keysym modules .,def _load_keysyms_into_XK mod pass
generate a circuit to do bit reversal .,def bit_reversal qubits p pq Program n len qubits for i in range int n 2 p inst SWAP qubits i qubits i 1 return p
returns the local path of the file,def getlclPath self return self lclPath
open tcp socket and set it as datecs device,def open self self device socket socket socket AF_INET socket SOCK_STREAM self device connect self host self port if self device is None print Could not open socket for s self host
returns the percentage of the progress .,def percentage self return self currval 100 0 self maxval
: param w_vector : a global weight vector instance that stores the weight value ( float ) : return : none,def __init__ self w_vector None max_iter 1 PerceptronLearnerBase __init__ self w_vector self w_vector return
a few scatterers along the positive z - axis .,def create_simple_phantom from simple import create_phantom args Args args h5_file os path join out_dir simple h5 args num_scatterers 12 args z0 0 005 args z1 0 12 create_phantom args
push triggers a metric collection and pushes all collected metrics to the pushgateway specified by addr note that all previously pushed metrics with the same job and instance will be replaced with the metrics pushed by this call . ( it uses http method ' put ' to push to the pushgateway . ),def replace self registry payload self formatter marshall registry r requests put self path data payload headers self headers
"if auth fails , raise 401 with a basic authentication header .",def basic_auth realm users encrypt None debug False if check_auth users encrypt if debug cherrypy log Auth successful TOOLS BASIC_AUTH return cherrypy serving response headers www authenticate httpauth basicAuth realm raise cherrypy HTTPError 401 You are not authorized to access that resource
select dict - like class based on merge strategy and orderness of keys .,def _get_update_fn strategy if strategy is None strategy MS_DICTS try return _MERGE_FNS strategy except KeyError if callable strategy return strategy else raise ValueError Wrong merge strategy r strategy
convert a json string into an element .,def json2elem json_data factory ET Element return internal_to_elem json loads json_data factory
create a tensorflow op to group data into histogram buckets .,def _buckets data bucket_count None if bucket_count is None bucket_count DEFAULT_BUCKET_COUNT with tf name_scope buckets values data bucket_count with tf control_dependencies tf assert_scalar bucket_count tf assert_type bucket_count tf int32 data tf reshape data shape 1 data tf cast data tf float64 is_empty tf equal tf size data 0 def when_empty return tf constant shape 0 3 dtype tf float64 def when_nonempty min_ tf reduce_min data max_ tf reduce_max data range_ max_ min_ is_singular tf equal range_ 0 def when_nonsingular bucket_width range_ tf cast bucket_count tf float64 offsets data min_ bucket_indices tf cast tf floor offsets bucket_width dtype tf int32 clamped_indices tf minimum bucket_indices bucket_count 1 one_hots tf one_hot clamped_indices depth bucket_count bucket_counts tf cast tf reduce_sum one_hots axis 0 dtype tf float64 edges tf lin_space min_ max_ bucket_count 1 left_edges edges 1 right_edges edges 1 return tf transpose tf stack left_edges right_edges bucket_counts def when_singular center min_ bucket_starts tf stack center 0 5 bucket_ends tf stack center 0 5 bucket_counts tf stack tf cast tf size data tf float64 return tf transpose tf stack bucket_starts bucket_ends bucket_counts return tf cond is_singular when_singular when_nonsingular return tf cond is_empty when_empty when_nonempty
creates an entry for pr curve data . each entry corresponds to 1 step .,def _make_pr_entry self step wall_time data_array thresholds true_positives int v for v in data_array metadata TRUE_POSITIVES_INDEX false_positives int v for v in data_array metadata FALSE_POSITIVES_INDEX tp_index metadata TRUE_POSITIVES_INDEX fp_index metadata FALSE_POSITIVES_INDEX positives data_array tp_index fp_index astype int sum axis 0 end_index_inclusive len positives 1 while end_index_inclusive 0 and positives end_index_inclusive 0 end_index_inclusive 1 end_index end_index_inclusive 1 return wall_time wall_time step step precision data_array metadata PRECISION_INDEX end_index tolist recall data_array metadata RECALL_INDEX end_index tolist true_positives true_positives end_index false_positives false_positives end_index true_negatives int v for v in data_array metadata TRUE_NEGATIVES_INDEX end_index false_negatives int v for v in data_array metadata FALSE_NEGATIVES_INDEX end_index thresholds thresholds end_index
converts to dict compatible with vdom - as - json .,def to_dict self if callable self tag return self tag self attr to_dict node defaultdict dict node t NodeType Node node tn self tag upper callbacks if len self children 0 node c for c in self children if isinstance c str node c append t NodeType Text x c else child_node_dict c to_dict node c append child_node_dict dom if len child_node_dict callbacks 0 callbacks update child_node_dict callbacks if key in self attr node k self attr key del self attr key if namespace in self attr node n self attr namespace del self attr namespace event_attributes new_callbacks self get_dom_callbacks callbacks update new_callbacks self attr update event_attributes attributes properties self get_attributes_and_props if len attributes 0 properties attributes attributes if len properties 0 node p properties return dom node callbacks callbacks
"giving tree , return simple parsed information from the tree",def parse_pubmed_web_tree tree if len tree xpath articletitle 0 title join title text for title in tree xpath articletitle elif len tree xpath booktitle 0 title join title text for title in tree xpath booktitle else title abstract_tree tree xpath abstract abstracttext abstract join stringify_children a strip for a in abstract_tree if len tree xpath article title 0 journal join t text strip for t in tree xpath article title else journal pubdate tree xpath pubmeddata history pubmedpubdate pubstatus medline pubdatebook tree xpath pubmedbookdata history pubmedpubdate pubstatus medline if len pubdate 1 and pubdate 0 find year is not None year pubdate 0 find year text elif len pubdatebook 1 and pubdatebook 0 find year is not None year pubdatebook 0 find year text else year affiliations list if tree xpath affiliationinfo affiliation is not None for affil in tree xpath affiliationinfo affiliation affiliations append affil text affiliations_text join affiliations authors_tree tree xpath authorlist author authors list if authors_tree is not None for a in authors_tree firstname a find forename text if a find forename is not None else lastname a find lastname text if a find forename is not None else fullname firstname lastname strip if fullname fullname a find collectivename text if a find collectivename is not None else authors append fullname authors_text join authors else authors_text keywords keywords_mesh tree xpath meshheadinglist meshheading keywords_book tree xpath keywordlist keyword if len keywords_mesh 0 mesh_terms_list for m in keywords_mesh keyword m find descriptorname attrib get ui m find descriptorname text mesh_terms_list append keyword keywords join mesh_terms_list elif len keywords_book 0 keywords join m text or for m in keywords_book else keywords doi article_ids tree xpath articleidlist articleid if len article_ids 1 for article_id in article_ids if article_id attrib get idtype doi doi article_id text dict_out title title abstract abstract journal journal affiliation affiliations_text authors authors_text keywords keywords doi doi year year return dict_out
try to find the best local tileset based on tile dimensions,def findLocalImg x y fileList filePrefix 02dx 02d x y for file in os listdir tilesets if file endswith png if file startswith filePrefix fileList append int file 6 11 file fileList_sorted sorted fileList key lambda tup tup 0 reverse True if fileList print Didn t find appropriate existing tileset image Will create one return None else print Found tileset image s fileList_sorted 0 1 return fileList_sorted 0 1
there should be one blank line or less between a docstring and a function definition .,def foo def bar This is defined to far from previous block a 1
: param str name : name to convert from camelcase to underscore style . : return : underscores - style string from camelcase - style .,def camelcase_to_underscores name return _CC_TO_UND_REGEX sub _ 1 name lower
"return the last access time of a file , reported by os.stat ( ) .",def getatime filename return os stat filename st_atime
put an item into the queue without blocking .,def put_nowait self item return self put item False
"create a midi in and a midi out port on mido backend ` backend ` . if virtual is true , try to create two virtual ports .",def configure_ioports backend virtual True mido_in None mido_out None log debug Backend for midi is format backend midi_in None midi_out None if virtual try midi_in backend open_input VIRT_MIDI_PORT virtual True callback lambda x x midi_out backend open_output VIRT_MIDI_PORT virtual True except ImportError log error Cannot open virtual IOports Make sure rtmidi is availableor choose another backend raise ConfigurationError Cannot open virtual IOports Make sure rtmidiis available or choose anoter backend else if mido_in and mido_in isdigit mido_in backend get_input_names int mido_in if mido_out and mido_out isdigit mido_out backend get_output_names int mido_out midi_in backend open_input mido_in callback lambda x x midi_out backend open_output mido_out log debug Inport is format midi_in log debug Outport is format midi_out return midi_in midi_out
"listfiles(str git_repository_path , str baselevel= '' ) - > iterator",def listFiles self git_repositary_path baselevel for filepath in self runShell git ls files cached full name no empty directory filepath filepath decode string_escape strip fullpath path join baselevel filepath filename path basename filepath if self exclude and filename gitattributes self _excludes fh open filepath r for line in fh if not line break tokens line strip split if export ignore in tokens 1 self _excludes append tokens 0 fh close if not filename startswith git and path islink filepath or not path isdir filepath ignore False for pattern in self _excludes if fnmatch fullpath pattern or fnmatch filename pattern if self verbose print Exclude pattern matched s s pattern fullpath ignore True break if ignore continue yield filepath fullpath if self force_sub self runShell git submodule init self runShell git submodule update for submodule in self runShell git submodule quiet foreach pwd chdir submodule submodule submodule len git_repositary_path 1 for git_file in self listFiles git_repositary_path submodule yield git_file
"get the filename of the distutils , local , global , or per - user config",def config_file kind local if kind local return setup cfg if kind global return os path join os path dirname distutils __file__ distutils cfg if kind user dot os name posix and or return os path expanduser convert_path spydistutils cfg dot raise ValueError config_file type must be local global or user kind
"a single c { "" : "" } is not an ipv6 address literal .",def test_colon self self assertFalse isIPv6Address
"create an arbitrary new c{sshtransportaddress}. a new instance is created for each call , but always for the same address .",def buildAddress self return SSHTransportAddress IPv4Address TCP 127 0 0 1 22
sends one or more emailmessage objects and returns the number of email messages sent .,def send_messages self email_messages raise NotImplementedError subclasses of BaseEmailBackend must override send_messages method
add a host to this virtual host .,def addHost self name resrc self hosts name resrc
get the item(s ) at the specified index / slice .,def __getitem__ self index if isinstance index slice return self _get_single_external i for i in range index indices len self else index self _checkindex index return self _get_single_external index
"implements the actual traversal , using utils.delay to delay the move_to .",def at_traverse self traversing_object target_location move_delay 0 2 if traversing_object db stamina 0 traversing_object msg You are too tired to move any further return elif traversing_object db stamina traversing_object db last_move self key if traversing_object db moving traversing_object msg You are already moving return move_delay traversing_object db move_delay_default if time time traversing_object db balance_time move_delay move_delay 1 3 if traversing_object db stamina 10 move_delay_increase 10 0 traversing_object db stamina move_delay_increase move_delay_increase 10 0 move_delay move_delay move_delay_increase if not traversing_object location tags get city category corinth d19 randint 1 18 if d19 traversing_object db endurance traversing_object db stamina traversing_object db stamina 1 if not traversing_object location tags get trail_ends if not traversing_object location db trails traversing_object location db trails traversing_object location db trails str traversing_object name str traversing_object db last_move traversing_object db moving True traversing_object db stance no stance traversing_object db shielded False if traversing_object db stamina traversing_object db move_message walking if time time traversing_object db balance_time traversing_object db move_message maneuvering if traversing_object db stamina 4 traversing_object db move_message staggering def move_callback This callback will be called by utils delay after move_delay seconds traversing_object db moving False source_location traversing_object location if traversing_object move_to target_location self at_after_traverse traversing_object source_location elif self db err_traverse self caller msg self db err_traverse else self at_failed_traverse traversing_object if self db test_attr blocked traversing_object msg That exit was blocked traversing_object location msg_contents s is s sward traversing_object name traversing_object db move_message self key exclude traversing_object traversing_object msg You begin s sward traversing_object db move_message self key deferred utils delay move_delay callback move_callback traversing_object ndb currently_moving deferred
the name of this file ; a repr - style string giving information about its namespace .,property def name self return 0 1 2 format self __class__ __name__ self log namespace self level name
l{syslogobserver.emit } logs the value of the c{'message ' } key of the event dictionary it is passed to the syslog .,def test_emitMessage self self observer emit message hello world isError False system self assertEqual self events stdsyslog LOG_INFO hello world
calling c{login } on a portal with correct credentials and an interface that the portal 's realm supports works .,def test_basicLogin self login self successResultOf self portal login credentials UsernamePassword bob hello self ITestable iface impl logout login self assertEqual iface ITestable self assertTrue iface providedBy impl s does not implement s impl iface self assertTrue impl original loggedIn self assertTrue not impl original loggedOut logout self assertTrue impl original loggedOut
"returns the string associated with a windows error message , such as the ones found in socket.error .",def formatError self errorcode if self winError is not None return self winError errorcode strerror if self formatMessage is not None return self formatMessage errorcode if self errorTab is not None result self errorTab get errorcode if result is not None return result return os strerror errorcode
an implementation of l{ireactorsocket.adoptstreamconnection } raises l{unsupportedaddressfamily } if passed an address family it does not support .,def test_invalidAddressFamily self reactor self buildReactor connection socket socket self addCleanup connection close arbitrary 2 16 7 self assertRaises UnsupportedAddressFamily reactor adoptStreamConnection connection fileno arbitrary ServerFactory
supply a supplied credentials checker to the options class .,def addChecker self checker supported if self supportedInterfaces is None supported checker credentialInterfaces else for interface in checker credentialInterfaces if self supportsInterface interface supported append interface if not supported raise UnsupportedInterfaces checker credentialInterfaces if credInterfaces not in self self credInterfaces if credCheckers not in self self credCheckers self credCheckers append checker for interface in supported self credInterfaces setdefault interface append checker
l{newsshelf.notifymoderator } sends a moderation email to a single moderator .,def test_notifyModerator self shelf NewsShelf example com self mktemp alice example com shelf sendmail self sendmail shelf notifyModerator bob example org Article Foo bar Some text self assertEqual len self _email 1
test passing in a bogus log level to c{emit()}.,def test_logInvalidLogLevel self log TestLogger log emit bogus errors self flushLoggedErrors InvalidLogLevelError self assertEqual len errors 1
"construct a 2-tuple of c{(streamhandler , bytesio ) } for testing interaction with the ' logging ' module .",def handlerAndBytesIO output BytesIO stream output template py_logging BASIC_FORMAT if _PY3 stream TextIOWrapper output encoding utf 8 newline n formatter py_logging Formatter template handler py_logging StreamHandler stream handler setFormatter formatter return handler output
test that unspec does not return endpoint data for ipv6 connections .,def test_unspecProtoIpv6 self header _makeHeaderIPv6 famProto info _v2parser V2Parser parse header self assertFalse info source self assertFalse info destination
decode a banana - encoded string .,def decode st l _i expressionReceived l append try _i dataReceived st finally _i buffer del _i expressionReceived return l 0
mimic recognition of the given words and return the the extras parameter for the recognized rule .,def recognize_extras self words self _recognized_node self _NoRecognition self _recognized_extras self _NoRecognition def test_process_recognition node extras self _recognized_node node self _recognized_extras extras patched_rules for rule in self rules if hasattr rule _process_recognition original_method rule _process_recognition rule _process_recognition test_process_recognition patched_rules append rule original_method try self recognize words if self _recognized_extras self _NoRecognition msg Recognition hijacked Words s words self _log error msg raise TestError msg return self _recognized_extras finally for rule original_method in patched_rules rule _process_recognition original_method
make sure arguments can be passed correctly .,def testBasic self a constant_op constant 10 11 name a b constant_op constant 10 name b c math_ops add a b name c d math_ops add_n a c name d train_op ops get_collection_ref ops GraphKeys TRAIN_OP train_op append d mg meta_graph create_meta_graph_def graph ops get_default_graph report model_analyzer GenerateModelReport mg self assertTrue a Const in report self assertTrue a Const in report self assertTrue c Add in report self assertTrue d AddN in report print format report
the binomial cumulative distribution function .,def _bdtr k n p ones array_ops ones_like n k k_eq_n math_ops equal k n safe_dn array_ops where k_eq_n ones n k dk math_ops betainc a safe_dn b k 1 x 1 p return array_ops where k_eq_n ones dk
bottleneck residual unit variant with bn before convolutions .,add_arg_scope def bottleneck inputs depth depth_bottleneck stride rate 1 outputs_collections None scope None with variable_scope variable_scope scope bottleneck_v2 inputs as sc depth_in utils last_dimension inputs get_shape min_rank 4 preact layers batch_norm inputs activation_fn nn_ops relu scope preact if depth depth_in shortcut resnet_utils subsample inputs stride shortcut else shortcut layers_lib conv2d preact depth 1 1 stride stride normalizer_fn None activation_fn None scope shortcut residual layers_lib conv2d preact depth_bottleneck 1 1 stride 1 scope conv1 residual resnet_utils conv2d_same residual depth_bottleneck 3 stride rate rate scope conv2 residual layers_lib conv2d residual depth 1 1 stride 1 normalizer_fn None activation_fn None scope conv3 output shortcut residual return utils collect_named_outputs outputs_collections sc name output
"compute the exponential - moving mean , variance of a streaming value .",def exponential_moving_mean_variance value decay collections None name None if collections is None collections ops GraphKeys GLOBAL_VARIABLES with variable_scope variable_scope name exponential_moving_mean_variance value decay value ops convert_to_tensor value name value base_dtype value dtype base_dtype if not base_dtype is_floating raise TypeError value base_dtype is not a floating type format base_dtype name decay ops convert_to_tensor decay dtype base_dtype name decay variance_var variable_scope get_variable exponential_moving_variance shape value shape dtype value dtype initializer init_ops zeros_initializer trainable False collections collections mean_var variable_scope get_variable exponential_moving_mean shape value shape dtype value dtype initializer init_ops zeros_initializer trainable False collections collections return assign_exponential_moving_mean_variance mean_var variance_var value decay
returns full name of class and method calling report_benchmark .,def _get_name self overwrite_name None stack tf_inspect stack calling_class None name None for frame in stack 1 f_locals frame 0 f_locals f_self f_locals get self None if isinstance f_self Benchmark calling_class f_self name frame 3 break if calling_class is None raise ValueError Unable to determine calling Benchmark class name overwrite_name or name class_name type calling_class __name__ name s s class_name name return name
return either ` fn1 ( ) ` or ` fn2 ( ) ` based on the boolean predicate ` pred ` .,def smart_cond pred fn1 fn2 name None if not callable fn1 raise TypeError fn1 must be callable if not callable fn2 raise TypeError fn2 must be callable pred_value constant_value pred if pred_value is not None if pred_value return fn1 else return fn2 else return control_flow_ops cond pred fn1 fn2 name
"check counts for proper shape , values , then return tensor version .",def _maybe_assert_valid_sample self counts if not self validate_args return counts counts distribution_util embed_check_nonnegative_integer_form counts return control_flow_ops with_dependencies check_ops assert_equal self total_count math_ops reduce_sum counts 1 message counts must sum to self total_count counts
will return the message without the message type and the delimiter,def MessageString message try return message split DELIMITER 1 except return message
this component is optional and therefore the api will only work if it is installed,property def number_of_results self return six next six itervalues self zap _request self zap base ajaxSpider view numberOfResults
get detailed information of a stoage cluster health it is method for get /health / storageclusters/{storageclusterid },def ListStorageClusterHealth self storageclusterid headers None query_params None content_type application json uri self client base_url health storageclusters storageclusterid return self client get uri None headers query_params content_type
crops the image around the center . input is expected to be an np.ndarray,def crop image center scale resolution 256 0 ul transform 1 1 center scale resolution True br transform resolution resolution center scale resolution True if image ndim 2 newDim np array br 1 ul 1 br 0 ul 0 image shape 2 dtype np int32 newImg np zeros newDim dtype np uint8 else newDim np array br 1 ul 1 br 0 ul 0 dtype np int newImg np zeros newDim dtype np uint8 ht image shape 0 wd image shape 1 newX np array max 1 ul 0 1 min br 0 wd ul 0 dtype np int32 newY np array max 1 ul 1 1 min br 1 ht ul 1 dtype np int32 oldX np array max 1 ul 0 1 min br 0 wd dtype np int32 oldY np array max 1 ul 1 1 min br 1 ht dtype np int32 newImg newY 0 1 newY 1 newX 0 1 newX 1 image oldY 0 1 oldY 1 oldX 0 1 oldX 1 newImg cv2 resize newImg dsize int resolution int resolution interpolation cv2 INTER_LINEAR return newImg
stop recording multiple values in a log .,def stop_log self self mmio write iop_const MAILBOX_OFFSET iop_const MAILBOX_PY2IOP_CMD_OFFSET 1
evaluates l and lm as estimators of the exponential parameter .,def Estimate3 n 7 m 1000 lam 2 means medians for _ in range m xs np random exponential 1 lam n L 1 np mean xs Lm math log 2 np median xs means append L medians append Lm print Experiment 3 print rmse L RMSE means lam print rmse Lm RMSE medians lam print mean error L MeanError means lam print mean error Lm MeanError medians lam
can be used by subclasses to hook into the raw output stream .,def process_line self rawline pass
score a text by comparing its frequency distribution against another .,def ChiSquared target_frequency def inner text text join text return chi_squared frequency_analyze text target_frequency return inner
fetch the latest version of the map from phenotypes to genes,def fetch_hpo_to_genes file_name ALL_SOURCES_ALL_FREQUENCIES_phenotype_to_genes txt url HPO_URL format file_name return fetch_resource url file_name
you can either provid a client_id and client_secret to the constructor or set spotipy_client_id and spotipy_client_secret environment variables,def __init__ self client_id None client_secret None proxies None if not client_id client_id os getenv SPOTIPY_CLIENT_ID if not client_secret client_secret os getenv SPOTIPY_CLIENT_SECRET if not client_id raise SpotifyOauthError No client id if not client_secret raise SpotifyOauthError No client secret self client_id client_id self client_secret client_secret self token_info None self proxies proxies
this function compute the finite difference coefficients for the given derivative order and grid . the parameter * x * specifies where is computed the derivative on the grid . the grid is given as a list of integer offsets .,def compute_exact_finite_difference_coefficients derivative_order grid x0 0 N len grid d 0 for v in range N for n in range N for m in range derivative_order 1 d 0 0 0 fractions Fraction 1 1 c1 1 for n in range 1 N c2 1 for v in range n c3 grid n grid v c2 c3 if n derivative_order d n n 1 v 0 for m in range min n derivative_order 1 d m n v grid n x0 d m n 1 v m d m 1 n 1 v c3 for m in range min n derivative_order 1 d m n n fractions Fraction c1 c2 m d m 1 n 1 n 1 grid n 1 x0 d m n 1 n 1 c1 c2 return d 1 1
tests that post request with valid data to endpoint returns expected data .,def test_post_bulk_valid_data self data email ppueblo example com email ppueblo bulk example com response self client post api v1 auth signup_request data format json expected_response email ppueblo example com email ppueblo bulk example com signup_requests SignupRequest objects filter email__in ppueblo example com ppueblo bulk example com self assertEqual response status_code status HTTP_201_CREATED self assertEqual response data expected_response self assertEqual signup_requests count 2
"retrieve available controls from the camera ( exposure , binning etc ) .",property check_connection def controls self return self driver_protocol get_controls
gets a parameter with the given key,def get self key if key not in self values raise AttributeError Trying to get key but it doesn t exist If you re getting this message it s most likely it is not in the required list Use parms required parm1 parm2 to require parameters else return self values key
: type nums : list[int ] : rtype : int,def findMaxConsecutiveOnes self nums largest 0 temp 0 for n in nums if n 1 temp 1 largest max temp largest else temp 0 return largest
"find dynamicelement list under this context . note : 1 . if no condition is specified , the result will be returned immediately . 2 . if no elements is found , empty list will be returned .",def find_elements self locator identifier Identifier id condition None from dynamicelement import DynamicElement by value locator_to_by_value locator elements inner def _find_elements try try selenium_elements self _selenium_context find_elements by value elements inner DynamicElement self selenium_element locator identifier for selenium_element in selenium_elements return elements inner except exceptions NoSuchElementException StaleElementReferenceException self wait_for exists selenium_elements self _selenium_context find_elements by value elements inner DynamicElement self selenium_element locator identifier for selenium_element in selenium_elements return elements inner except InvalidSelectorException raise exceptions InvalidLocatorException The value s of locator s is not a valid expression value locator self except WebDriverException as wde raise exceptions EasyiumException wde msg self if condition try self waiter wait_for lambda condition _find_elements except exceptions TimeoutException as e if e __class__ exceptions ElementTimeoutException raise raise exceptions TimeoutException Timed out waiting for the found element list by s under s matches condition s locator self condition __name__ else _find_elements return elements inner
test test with t0 | t1 the response to select df_telecom .,def testcase_CardConnectionT0T1 self SELECT 160 164 0 0 2 DF_TELECOM 127 16 for reader in readers cc reader createConnection if expectedATRinReader str reader cc connect CardConnection T0_protocol CardConnection T1_protocol response sw1 sw2 cc transmit SELECT DF_TELECOM expectedSWs 9f 1a 1 6e 0 2 9f 20 3 9f 22 4 self assertEqual response self assertTrue x x sw1 sw2 in expectedSWs or 9f x sw1 else self assertRaises NoCardException cc connect cc disconnect
check if the repository contains the known - good commit .,def HasCommit self return 0 subprocess call git rev parse verify quiet self commit commit cwd self subdir
"yields the cummulative sums of the values in a iterable , starting with the specified initial value .",def cumsum lst initial 0 for item in lst initial item yield initial
returns a set of http handlers that the plugin implements .,abstractmethod def get_plugin_handlers self run_paths raise NotImplementedError
gradients for an enter are calculated using an exit op .,ops RegisterGradient Enter def _EnterGrad op grad graph ops get_default_graph grad_ctxt graph _get_control_flow_context if not grad_ctxt back_prop return grad if grad_ctxt grad_state is None return grad if op get_attr is_constant if isinstance grad ops Tensor result grad_ctxt AddBackPropAccumulator op grad elif isinstance grad ops IndexedSlices result grad_ctxt AddBackPropIndexedSlicesAccumulator op grad else raise TypeError Type s not supported type grad else result exit grad grad_ctxt ExitResult result return result
connect to office 365 using specified open authentication protocol,staticmethod def oauth2 client_id client_secret store_token True token_path None connection Connection connection api_version 2 0 connection client_id client_id connection client_secret client_secret if not store_token delete_token token_path token load_token token_path if not token connection oauth OAuth2Session client_id client_id redirect_uri https outlook office365 com owa scope https graph microsoft com Mail ReadWrite https graph microsoft com Mail Send offline_access oauth connection oauth auth_url state oauth authorization_url url Connection _oauth2_authorize_url access_type offline print Please open and authorize the application format auth_url auth_resp input Enter the full result url os environ OAUTHLIB_RELAX_TOKEN_SCOPE Y token oauth fetch_token token_url Connection _oauth2_token_url authorization_response auth_resp client_secret client_secret save_token token token_path else connection oauth OAuth2Session client_id client_id token token return connection
.. http : get : : /api/1/accountpatternauditscores/<int : id >,def get self id app logger info ID str id result AccountPatternAuditScore query filter AccountPatternAuditScore id id first if not result return status Override Account Pattern Audit Score with the given ID not found 404 app logger info RESULT DICT str result __dict__ accountpatternauditscore_marshaled marshal result __dict__ ACCOUNT_PATTERN_AUDIT_SCORE_FIELDS accountpatternauditscore_marshaled auth self auth_dict app logger info RETURN str accountpatternauditscore_marshaled return accountpatternauditscore_marshaled 200
od.__eq__(y ) < = = > od==y . comparison to another od is order - sensitive while comparison to a regular mapping is order - insensitive .,def __eq__ self other if isinstance other OrderedDict return len self len other and self items other items return dict __eq__ self other
' skip ' statement def for ast . interpret - runtime function for evaluator ( empty function ) .,def skip_statement env pass
this method is employed instead of _ tap ( ) if the pykeyboardevent is initialized with diagnostic = true . this makes some basic testing quickly and easily available . it will print out information regarding the event instead of passing information along to self.tap ( ),def _diagnostic self event logger info n Keyboard Event Diagnostic logger info MessageName event MessageName logger info Message event Message logger info Time event Time logger info Window event Window logger info WindowName event WindowName logger info Ascii event Ascii chr event Ascii logger info Key event Key logger info KeyID event KeyID logger info ScanCode event ScanCode logger info Extended event Extended logger info Injected event Injected logger info Alt event Alt logger info Transition event Transition logger info
: type trigger : dart.model.trigger.trigger : type trigger_service : dart.service.trigger.triggerservice,abstractmethod def teardown_trigger self trigger trigger_service raise NotImplementedError
adds a description to the `` short_descriptions `` collection .,def add_short_description self description self short_descriptions add description
get the phenotypes for the sub - selection .,def get_phenotype self phenotype kwargs return self __filter self __phenotyper get_phenotype phenotype kwargs
get playlist metadata value from a given key .,def get self key if key in self metadata return self metadata key return None
a decorator that requires a logged in user to be an admin .,def admin_required original_function wraps original_function def wrapper args kwargs user _get_user_from_request required True if not user is_admin raise Forbidden This request requires administrator privileges g user user return original_function args kwargs return wrapper
returns a mapping from channel ids to absolute file paths of their history entries,def get_history_files for dirpath _ filenames in os walk CHAT_HISTORY_DIRECTORY result for history_file in filenames channel_id extension os path splitext os path basename history_file if extension json continue result channel_id os path join dirpath history_file return result return
"load memory setting for each zoomdat service , prepares memory map : param available_memory : memory amount available for distribution : param app_options : options passed to application : return :",def prepare_memory_map available_memory app_options installed_services lookup_installed_services app_options services if installed_services print Error No installed Zoomdata services found Aborting return services for service in installed_services services update service load_service_memory_defaults service app_options all_requested_memory sum services srv max if max in services srv keys else 0 for srv in services keys if app_options verbose print All memory requested by Zoomdata services is Mb format len installed_services all_requested_memory if all_requested_memory available_memory print Error Physical available memory Mb is less then requested by Zoomdata components Mb Aborting format available_memory all_requested_memory return services else for service in services keys if max in services service keys services service adj max int available_memory services service max float all_requested_memory return services
"usually , go left then right , unless dominated .",def maybePrune m lvl west east goLeft goRight True True if The prune and lvl The what depthMin sw scores m west se scores m east if abs sw se The wriggle if se sw goLeft False if sw se goRight False return goLeft goRight
tag to render the tour nav node,register simple_tag takes_context True def tour_navigation context kwargs return TourNavNode always_show kwargs get always_show False render context
callback executed when message delivery either succeeds or fails .,def delivery_callback err msg if not hasattr delivery_callback pkts_out delivery_callback pkts_out 0 if err logging error message delivery failed error s err elif msg is not None delivery_callback pkts_out 1 pretty_print 0 pretty_print producer_args pretty_print if pretty_print 0 and delivery_callback pkts_out pretty_print 0 print Packet delivered s date s topic s partition s offset s len s delivery_callback pkts_out to_date unpack_ts msg key msg topic msg partition msg offset len msg value
navigate to courseware using resume course button in the header .,def resume_course_from_header self self q css self HEADER_RESUME_COURSE_SELECTOR first click courseware_page CoursewarePage self browser self course_id courseware_page wait_for_page
contacts the backend to have a badge assertion created for this badge class for this user .,def award self user evidence_url None return self backend award self user evidence_url evidence_url
test exception handling of ` undo_override_subsection_grade ` when persistentsubsectiongrade does not exist .,freeze_time 2018 01 01 def test_undo_override_subsection_grade_without_grade self self grade delete try self service undo_override_subsection_grade user_id self user id course_key_or_id self course id usage_key_or_id self subsection location except PersistentSubsectionGrade DoesNotExist assert False Exception raised unexpectedly self assertFalse self mock_signal called
"this function attempts to fit as many characters as possible into the available space , cutting "" like a knife "" between characters . this would do for chinese . it returns a list of ( text , extraspace ) items where text is a unicode string , and extraspace is the points of unused space available on the line . this is a structure which is fairly easy to display , and supports ' backtracking ' approaches after the fact .",def dumbSplit word widths maxWidths _more dumbSplit u Hello 10 5 4 less than one character u u Hello this says Nihongo wa muzukashii desu ne Japanese is difficult isn t it in 12 characters jtext u u65e5 u672c u8a9e u306f u96e3 u3057 u3044 u3067 u3059 u306d uff01 dumbSplit jtext 10 11 30 u u65e5 u672c u8a9e u u306f u96e3 u3057 u3044 u3067 u3059 u306d uff01 if not isinstance maxWidths list tuple maxWidths maxWidths assert isUnicode word lines i widthUsed lineStartPos 0 maxWidth maxWidths 0 nW len word while i nW w widths i c word i widthUsed w i 1 if widthUsed maxWidth _FUZZ and widthUsed 0 extraSpace maxWidth widthUsed if ord c 12288 limitCheck lineStartPos i 1 for j in range i 1 limitCheck 1 cj word j if category cj Zs or ord cj 12288 k j 1 if k i j k 1 extraSpace sum widths j i w widths k c word k i j break if c not in ALL_CANNOT_START and i lineStartPos 1 i 1 extraSpace w lines append extraSpace word lineStartPos i strip try maxWidth maxWidths len lines except IndexError maxWidth maxWidths 1 lineStartPos i widthUsed 0 if widthUsed 0 lines append maxWidth widthUsed word lineStartPos return lines
"calculate attack success and average confidence based w.r.t . true labels , originally predicted labels and correctly classified labels , respectively",def acc_calc_all X_adv y_test X_test_mod i_c validator indexer predictor confidence o_list c_w conf_w acc_calc X_adv y_test validator indexer confidence o_list extend c_w conf_w c_a conf_a acc_calc X_adv predictor X_test_mod validator indexer confidence o_list extend c_a conf_a c_p conf_p acc_calc X_adv i_c y_test i_c validator indexer confidence o_list extend c_p conf_p return o_list
displays basic show info on the terminal,def printShowInfo obj drawline 80 print Series name obj seriesname print Overview obj overview c 1 try obj 0 except tvdb_api tvdb_seasonnotfound c 0 print Number of seasons len obj c drawline 80
returns a query object for this message .,def query self model return MessageQuery model dict self payload models Operation self operations
return the kullback - leibler divergence between two distributions .,def analytical_KLDiv p q func lambda x p pdf x np log p pdf x q pdf x a 1e 05 return integrate quad func max p ppf a q ppf a min p isf a q isf a 0
creates a ` failedpreconditionerror ` .,def __init__ self node_def op message super FailedPreconditionError self __init__ node_def op message FAILED_PRECONDITION
check that there are no tabs in python files .,def test_no_tabs self tabs for fname line_no line in self _iter_source_files_lines if t in line self _push_file tabs fname line_no if tabs self fail self _format_message tabs Tab characters were found in the following source files They should either be replaced by t or by spaces
shortcut to create a time sheet url with optional date parameters .,register simple_tag def project_timesheet_url project_id date None return _timesheet_url view_project_timesheet project_id date
returns the gradient of the cross - entropy error function with ( optional ) sum - of - squares regularization term .,def grad w X y c 0 outputs expit X dot w return X transpose dot outputs y c w
retrieve the parent dag path .,def bnGetParent self if self length 1 return None dagPath OpenMaya MDagPath self dagPath pop 1 return dagPath
return the number of items in `` iterable `` .,def ilen iterable return sum 1 for _ in iterable
"checks all connections in the pool for their age if too old and idle , gets closed immediatly if too old and in use , gets closed on next disconnect",def _old_connection_reaper self now time time close_connections for connection in self _connections age now connection _created_time if age self _max_connection_age close_connections append connection for connection in close_connections if connection in self _pool self log debug s closing idle connection with old age self self _close connection else self log debug s will close busy connection with old age on next disconnect self connection __close__ True
run all tests against a running redcap instance,task def test warn_only False return utility_redcap test warn_only
get a database connection from the gremlin server .,def _create_connection url graph timeout None username password loop None session None force_close False future_class None return graph connect force_close force_close
tests if a parent tab knows it 's children .,def test_children self request self rf get response ParentTab as_view request context response context_data self assertIsInstance context child_tabs list self assertEqual len context child_tabs 2 self assertIsInstance context child_tabs 0 FirstChildTab self assertIsInstance context child_tabs 1 SecondChildTab
"ensures that whenever the specified context is active , all vocabularies with the specified tag(s ) will not be active in the global dynamic vocabulary .",def inhibit_global_dynamic_vocabulary grammar_name tag context None global _vocabulary_inhibitions if isinstance tag basestring _vocabulary_inhibitions setdefault tag _vocabulary_inhibitions tag append context grammar_name _rebuild_lists dynamic else for t in tag inhibit_global_dynamic_vocabulary grammar_name t context
tetragonal heusler structure with formula x2yz space group i4/mmm ( 139 ),def HeuslerTetragonal139 X Y Z a c biso 0 0 0 occ 1 1 1 x y z check_elements X Y Z return Crystal s2 s s x basename y basename z basename SGLattice 139 a c atoms x y z pos 4d 2b 2a b biso occ occ
make sure that apps only appear in the related database .,def allow_syncdb self db model if model _meta app_label south return True elif db in settings DATABASE_APPS_MAPPING values return settings DATABASE_APPS_MAPPING get model _meta app_label db elif settings DATABASE_APPS_MAPPING has_key model _meta app_label return False elif db default return False return True
"if an attribute has no value , it is given non - legal character as a value , to prevent ' collisions '",def ReplaceNone attr_value if attr_value is None return else return attr_value
"given an easyinstancefield object , returns a list of urls for this plugin 's views of this object . these urls should be absolute .",def urls self plugin_name easy_instance_field return None
"returns the total number of objects , across all pages .",def _get_count self if self _count is None try self _count self object_list count except AttributeError TypeError self _count len self object_list return self _count
generate the initial security hash from self.content_object and a ( unix ) timestamp .,def initial_security_hash self timestamp initial_security_dict content_type str self target_object _meta object_pk str self target_object _get_pk_val timestamp str timestamp return self generate_security_hash initial_security_dict
returns a list of string names corresponding to each of the fields available in this layer .,property def fields self return capi get_field_name capi get_field_defn self _ldefn i for i in xrange self num_fields
"time zone offset in seconds ( i.e. ' -43200 ' to ' 43200 ' ) . the offset for timezones west of utc is always negative , and for those east of utc is always positive .",def Z self if not self timezone return 0 offset self timezone utcoffset self data return offset days 86400 offset seconds
appends genotypes from a phased file,def appendPhasedGT GTblo coord pGT pFile stat block GTblo append coord pGT pL readPhasedLine pFile stat pChr pL 0 pPos pL 1 pGT pL 2 stat pL 3 return GTblo pChr pPos pGT stat
this function will output an error message formatted in json to display on the dashboard,def output_message message detail statusbar_output graph title GRAPH_TITLE error message message detail detail output json dumps statusbar_output return output
render the scene with povray for publication .,def render_povray scene filename ipython width 600 height 600 antialiasing 0 01 extra_opts if not vapory_available raise Exception To render with povray you need to have the vapory package installed scene normalize_scene scene scene update extra_opts aspect scene camera aspect up np dot rmatrixquaternion scene camera quaternion 0 1 0 v_fov scene camera vfov 180 0 np pi h_fov 2 0 np arctan np tan v_fov 2 0 aspect np pi 180 camera vp Camera location scene camera location direction 0 0 1 sky up look_at scene camera target angle h_fov global_settings if scene get radiosity False radiosity vp Radiosity brightness 2 0 count 100 error_bound 0 15 gray_threshold 0 0 low_error_factor 0 2 minimum_reuse 0 015 nearest_count 10 recursion_limit 1 adc_bailout 0 01 max_sample 0 5 media off normal off always_sample 1 pretrace_start 0 08 pretrace_end 0 01 light_sources global_settings append radiosity else light_sources vp LightSource np array 2 4 3 1000 color 1 1 1 vp LightSource np array 2 4 3 1000 color 1 1 1 vp LightSource np array 1 2 3 1000 color 1 1 1 vp LightSource np array 1 2 3 1000 color 1 1 1 background vp Background 1 1 1 stuff _generate_objects scene representations scene vp Scene camera objects light_sources stuff background global_settings global_settings return scene render filename width width height height antialiasing antialiasing
returns the hash id of the leaf .,def identity self return self hid
test that a dict with only data raises,def test_dict_with_only_data self with self assertRaises KeyError process_endpoint data format self PARENT self FULL_ID
"parse missing end block , check for exception",def test_nonclosed_block self data begin b1 0 31 0 21 block_file io StringIO data parser BlockParser with self assertRaises err NonClosedBlockError parser parse block_file
returns a representation for the dataset for showing in the notebook .,def __repr__ self u Returns a representation for the dataset for showing in the notebook n if self _is_temporary return u QueryResultsTable s self job_id else return super QueryResultsTable self __repr__
"expand a sqlstatement , query string or sqlmodule with a set of arguments .",staticmethod def expand sql args None u Expand a SqlStatement query string or SqlModule with a set of arguments n n Args n sql a SqlStatement sql module or string containing a query n args a string of command line arguments or a dictionary of values If a string it is n passed to the argument parser for the SqlModule associated with the SqlStatement or n SqlModule If a dictionary it is used to override any default arguments from the n argument parser If the sql argument is a string then args must be None or a dictionary n as in this case there is no associated argument parser n Returns n The expanded SQL list of referenced scripts and list of referenced external tables n sql args SqlModule get_sql_statement_with_environment sql args return _sql_statement SqlStatement format sql _sql args
persist datapoints in the database for metric .,def write self metric datapoints raise NotImplementedError
centroid position from cartesian or polar shapelet coefficients [ manual eq . 1.15 and 1.24 ] coeffs : shapelet coefficients beta : two element beta nmax : coefficient limit mode : hermite or lageurre,def centroid coeffs beta nmax mode f flux coeffs beta nmax mode if mode startswith hermite c0 np reshape coeffs nmax xc np array 0 0 0 0 for ny in range nmax 0 for nx in range nmax 1 if ny 2 1 and nx 2 0 xc 0 np sqrt ny 1 2 0 5 2 ny nx np sqrt scipy special binom ny 1 ny 1 2 np sqrt scipy special binom nx nx 2 c0 ny nx elif ny 2 0 and nx 2 1 xc 1 np sqrt nx 1 2 0 5 2 ny nx np sqrt scipy special binom ny ny 2 np sqrt scipy special binom nx 1 nx 1 2 c0 ny nx return 1 0 f np sqrt np pi beta 0 beta 1 xc elif mode startswith lageurre ids polarIDs nmax xc 0 for cnt i in enumerate ids if i 0 2 1 and i 1 1 xc np sqrt i 0 1 coeffs cnt xc np sqrt 8 np pi beta 0 beta 1 f xc return np array xc real xc imag else print Error Unknown mode return np nan
this function produces a side effect mocking the behaviour of open ( ) when used to read the lines of the ' config ' or ' head ' file of a github repository 's ' .git ' directory .,def dot_git_open_side_effect repo repo org org branch branch url True def open_side_effect args kwargs path args 0 if path not in git config git HEAD raise Exception Cannot open s path github_url turl https github com s s n org repo github_url github_url int url if path git config lines core n trepositoryformatversion 0 n tfilemode true n tbare false n logallrefupdates true tignorecase true n tprecomposeunicode true n remote origin n github_url fetch refs heads refs remotes origin branch master n tremote origin n tmerge refs heads master n elif path git HEAD lines ref refs heads s n branch file_object mock MagicMock readlines lambda lines return file_object return open_side_effect
"the type of drive , values are :",property def type self t winproxy GetDriveTypeA self name return self DRIVE_TYPE get t t
generate a silicon pw.x input file for the self consistent cycle,def test_pw_input_scf self if not os path isdir scf os mkdir scf qe self get_inputfile qe control calculation scf qe write scf si scf self assertEqual filecmp cmp scf si scf reference_si scf_si scf True
get the list of current reservations .,def get self with self lock logging debug Returning reservations array 0 format self reservations return self reservations
return the name of the default display mode . it must be defined in getdisplaymodes .,def getDefaultDisplayMode self return Flat Lines
a hack to get around the deprecation errors in 2.6 .,property def message self return self _message
this essentially replicates what 's done when awslimitchecker is called from the command line with `` -l `` . this replicates some of the internal logic of : py : class:`~awslimitchecker.runner . runner ` .,pytest mark integration skip_if_pr def test_verify_limits self checker_args creds_type service_name use_ta expect_api_source allow_endpoint_error boto3 DEFAULT_SESSION None if creds_type normal creds self normal_creds elif creds_type sts creds self sts_creds elif creds_type sts_mfa creds self sts_mfa_creds checker_args mfa_serial_number creds 2 else raise RuntimeError unknown creds type s creds_type os environ AWS_ACCESS_KEY_ID creds 0 os environ AWS_SECRET_ACCESS_KEY creds 1 if mfa_token in checker_args checker_args mfa_token self totp_code creds 3 with LogCapture as l checker AwsLimitChecker checker_args limits checker get_limits use_ta use_ta service service_name logs LogRecordHelper l have_api_source False data for svc in sorted limits keys for lim in sorted limits svc keys src_str if limits svc lim get_limit_source SOURCE_API have_api_source True src_str API if limits svc lim get_limit_source SOURCE_TA src_str TA data s l format s svc l lim v t format v limits svc lim get_limit t src_str logs verify_region checker_args get region REGION print dict2cols data if expect_api_source assert have_api_source is True records logs unexpected_logs allow_endpoint_error allow_endpoint_error assert len records 0 awslimitchecker emitted unexpected log messages at WARN or higher s n join records polls logs num_ta_polls assert polls 1 awslimitchecker should have polled Trusted Advisor once but polled s times polls
see coprocessor.c for an explanation of this test,test_harness test emulator def shared_memory unused test_harness build_program coprocessor c memory_file tempfile NamedTemporaryFile args test_harness EMULATOR_PATH s memory_file name test_harness HEX_FILE process subprocess Popen args stdout subprocess PIPE stderr subprocess STDOUT try time sleep 1 0 memory mmap mmap memory_file fileno 0 testvalues random randint 0 4294967295 for __ in range 10 for value in testvalues computed sharedmem_transact memory value if computed value 4294967295 raise test_harness TestException Incorrect value from coprocessor expected hex value 4294967295 got hex computed finally test_harness kill_gently process
a generic method for adding / updating data to / in vault .,def vault_update vault path None args if path is None path input path entries if len args 0 while True entry input entry key value if entry is None or entry break key val entry split entries key strip val strip else for arg in args key val arg split entries key strip val strip vault update path entries
"for any command line , if we have an error message , there was a problem . subsequent commands will not be executed , that message will be ' command not ran due to previous failures ' so once you find and error , return the message of the first error .",def check_for_errors self rc response for cmd in response try response s on line s cmd error message cmd id rc 1 break except KeyError pass return rc response
substract a number of days from a given date and then get then first day of that month,def timedelta_months date nmonths first_day datetime date year date month 1 for i in range 0 nmonths first_day datetime first_day year first_day month 1 first_day first_day timedelta days 1 first_day datetime first_day year first_day month 1 return first_day
the two args are the value and tick position,def millions x pos return 1 1fM x 1e 06
"given a slot name , returns a filename .",def filename self slotname return os path join self directory slotname renpy savegame_suffix
get a link to a detail view that can be shown for an object with this type,register filter def detail_link thing name thing __class__ __name__ nameLower name lower if nameLower in MODEL_DETAILS return MODEL_DETAILS nameLower thing elif MapFeature has_subclass name return MODEL_DETAILS mapfeature thing else return None
"compares matched reference ( truth ) to test ( prediction ) ref_obj , test_obj -- reference , test single_tractorcat ( ) return 5x5 confusion matrix and colum / row names",def create_confusion_matrix ref_obj test_obj cm np zeros 5 5 1 types PSF SIMP EXP DEV COMP for i_ref ref_type in enumerate types cut_ref np where ref_obj t type ref_type 0 for i_test test_type in enumerate types n_test np where test_obj t type cut_ref test_type 0 size if cut_ref size 0 cm i_ref i_test float n_test cut_ref size else cm i_ref i_test np nan return cm types
"< h4>return</h4>get value of key of ' meta_json ' field < p><h4>syntax</h4>getvaluefrommetadata('list_keys')</p > < p><h4>argument</h4>list_keys - > string with a sequence of keys names - ' "" key1"",""key2"", ... '</p > < p><h4>example</h4>getvaluefrommetadata ( ' "" item_type "" ' ) < /p><p > return : item type</p >",qgsfunction args 1 group Planet Labs def getValueFromMetadata values feature parent if values 0 count 2 0 raise Exception Catalog Planet Error Key need double quotes s values 0 if len values 0 1 raise Exception Catalog Planet Error Field is empty name_metadata_json meta_json id_metadata_json feature fieldNameIndex name_metadata_json if id_metadata_json 1 raise Exception Catalog Planet Error Need have s field name_metadata_json lstKey map lambda item item strip values 0 split lstKey map lambda item item strip lstKey metadata_json feature attributes id_metadata_json try success valueKey API_PlanetLabs getValue metadata_json lstKey if not success raise Exception valueKey except Exception as e raise Exception e message return valueKey
gets location information about the current toolchain ( must have been previously updated by ' update ' ) . this is used for the gn build .,def GetToolchainDir runtime_dll_dirs SetEnvironmentAndGetRuntimeDllDirs if not WINDOWSSDKDIR in os environ default_sdk_path C Program Files x86 Windows Kits 10 if os path isdir default_sdk_path os environ WINDOWSSDKDIR default_sdk_path print vs_path s sdk_path s vs_version s wdk_dir s runtime_dirs s NormalizePath os environ GYP_MSVS_OVERRIDE_PATH NormalizePath os environ WINDOWSSDKDIR GetVisualStudioVersion NormalizePath os environ get WDK_DIR os path pathsep join runtime_dll_dirs or None
save exif data to photo file on disk .,def write self if self altitude is not None self exif GPS Altitude float_to_rational self altitude self exif GPS AltitudeRef 0 if self altitude 0 else 1 self exif GPS Latitude decimal_to_dms self latitude self exif GPS LatitudeRef N if self latitude 0 else S self exif GPS Longitude decimal_to_dms self longitude self exif GPS LongitudeRef E if self longitude 0 else W self exif GPS MapDatum WGS 84 self exif write
"generates the hdf file with the data for testing arguments : fn ( str ) : filename lshape ( tuple / list ) : shape of the input data n ( int ) : number of data points ( input / output pairs ) mean ( optional , tuple / list or ndarray ) : mean values",def gen_hdf fn lshape N mean None autoencode False multidimout False C H W lshape dat np arange N C H W reshape N C H W h5f h5py File fn w inp h5f create_dataset input dat shape inp dat copy inp attrs lshape C H W if mean is not None mean_ h5f create_dataset mean mean shape mean_ mean if not autoencode if multidimout out h5f create_dataset output dat shape out dat 1 copy else out h5f create_dataset output N 1 dtype i8 out 0 np arange N out attrs nclass N h5f close return
test setting an invalid collective attribute .,def test0 self t TPC PH try t c 42 except AttributeError pass
"returns python string versions ( '' and "" "") of original substring",def stringify sub check_str_s sub check_str_d sub return check_str_s check_str_d
make document dict of instance to store to db,def to_document self return url self url name self name username self username last_latest_hash self last_latest_hash date datetime datetime now analysis_results self analysis_results
removes a contributor from a channel,def test_remove_contributor client staff_jwt_header contributor UserFactory create username 01BTN6G82RKTS3WF61Q33AA0ND url reverse contributor detail kwargs channel_name admin_channel contributor_name contributor username resp client delete url staff_jwt_header assert resp status_code status HTTP_204_NO_CONTENT
"dump the grammar tables to standard output , for debugging .",def report self from pprint import pprint print s2n pprint self symbol2number print n2s pprint self number2symbol print states pprint self states print dfas pprint self dfas print labels pprint self labels print start self start
get short description for recommender .,def get_description self return self config_dict desc
return one of the following responses : - 204 with the bundle is empty - 302 to a bundle url after generating it if not cached .,cache_control public True max_age SNIPPET_BUNDLE_TIMEOUT access_control max_age SNIPPET_BUNDLE_TIMEOUT def fetch_snippets request kwargs statsd incr serve snippets client Client kwargs bundle SnippetBundle client if bundle empty statsd incr bundle empty return HttpResponse status 200 content elif bundle cached statsd incr bundle cached else statsd incr bundle generate bundle generate return HttpResponseRedirect bundle url
subtracts the mean of each image in x and renormalizes them to unit norm .,def per_image_whiten X num_examples height width depth X shape X_flat X reshape num_examples 1 X_mean X_flat mean axis 1 X_cent X_flat X_mean None X_norm np sqrt np sum X_cent X_cent axis 1 X_out X_cent X_norm None X_out X_out reshape X shape return X_out
datepicker should change the date on entry on response ok .,def test_popup_response_ok self self _entry set_date datetime datetime 2015 1 2 10 20 with mock patch datagrid_gtk3 ui popupcal Gtk Dialog as dialog fake_dialog FakeDialog Gtk ResponseType OK dialog return_value fake_dialog with mock patch object self _entry get_date as get_date get_date return_value datetime datetime 2010 2 3 self _entry _popup_picker self assertEqual self _entry get_date datetime datetime 2010 2 3
return human readable size for n bytes,def human n global Divisors for nm sz in Divisors if n sz s 8 2f s float n sz nm return s return lu n
"guess the labels , and apply the guess on the document",def label_guess dst_dsearch src_doc dst_doc guessed_labels dst_dsearch guess_labels dst_doc guessed_labels label for label scores in guessed_labels for label in guessed_labels dst_dsearch add_label dst_doc label update_index False upd_index dst_dsearch dst_doc new True
property to provide reference to bios boot instance,property def boot_settings self if self _boot_settings is None self _boot_settings BIOSBootSettings self _conn utils get_subresource_path_by self Oem Hpe Links Boot redfish_version self redfish_version self _boot_settings refresh force False return self _boot_settings
"find a zero using the bisection method : param funct : function the function whose zero is wanted . it must be a function of a single variable of the form f(x , a , b , c ... ) , where a , b , c ... are extra arguments that can be passed in the ` args ` parameter . : param left_x : : param right_x : : param args : tuple , optional extra arguments to be used in the function call . : param tol : : float , optional the allowable error of the zero value . : param maxiter : int , optional maximum number of iterations . : return : : float estimated location where function is zero .",def bisection funct args left_x 0 99999 right_x 100 tol 1e 05 maxiter 1000 func_left funct left_x args func_right funct right_x args if func_left 0 and func_right 0 or func_left 0 and func_right 0 if func_left 0 warnings warn exceeded upper threshold format right_x return right_x else warnings warn exceeded the lower threshold format left_x return left_x mid_x left_x right_x 2 0 for iter in range maxiter func_left funct left_x args func_mid funct mid_x args if func_mid 0 return mid_x elif func_left 0 and func_mid 0 or func_left 0 and func_mid 0 right_x mid_x else left_x mid_x mid_x left_x right_x 2 0 if right_x left_x 2 0 tol return mid_x print Failed to converge after iterations format maxiter return mid_x
doc on scopes available at https://developer.microsoft.com/en-us/graph/docs/concepts/permissions_reference,def get_default_scope self u n Doc on scopes available at n https developer microsoft com en us graph docs concepts permissions_reference n return u User Read
returns a queryset of recent tweets favorited by the account associated with the twitter user with screen_name .,register simple_tag def recent_favorites screen_name None limit 10 if screen_name is None tweets Tweet public_favorite_objects all else user User objects get screen_name screen_name if user is_private tweets Tweet objects none else tweets Tweet public_favorite_objects filter favoriting_users user return tweets prefetch_related user limit
return true if an invite can be sent .,def can_send self if self invites_allocated 1 return True return self invites_allocated self invites_sent
move the veth into the namespace .,def move_veth_into_ns namespace veth_name_ns_temp veth_name_ns with NamedNamespace namespace as ns _log debug Moving temp interface s into ns s veth_name_ns_temp ns name check_output ip link set veth_name_ns_temp netns ns name timeout IP_CMD_TIMEOUT ns check_output ip link set dev veth_name_ns_temp name veth_name_ns ns check_output ip link set veth_name_ns up
plot ( ) [ public ] purpose : plots the station on an image . parameters : layout [ type = dict ] dictionary that specifies where to put each value in the station plot returns : [ nothing ],def plot self layout print Plotting station plot for s self _station_id for location in hootpyStationPlot _layout_keys try value getattr self _ s layout location except AttributeError continue return
called before each test from this class,def setUp self self o make_tree tree
whether the game is over .,def game_over self for action in range 4 if self is_action_available action return False return True
testing normalize_text_for_edit with plain text and user defaults to rich text,def test_normalize_text_for_edit_plain_text_default_rich_text self u Testing normalize_text_for_edit with plain text and n user defaults to rich text n user User objects create_user u test u test example com Profile objects create user user default_use_rich_text True text normalize_text_for_edit user text u lt test foo rich_text False self assertEqual text u amp lt quot test quot foo self assertTrue isinstance text SafeText
testing the get /review - requests/<id>/status - updates/?change= api,def test_get_with_change_id self u review_request self create_review_request submitter self user publish True change ChangeDescription objects create review_request changedescs add change self create_status_update review_request update self create_status_update review_request change_description change with override_feature_checks self override_features rsp self api_get get_status_update_list_url review_request u change change pk expected_mimetype status_update_list_mimetype self assertEqual rsp u stat u ok self assertEqual len rsp u status_updates 1 self assertEqual rsp u status_updates 0 u id update pk
returns whether there 's a next page available .,property def has_next self u return self next_url is not None
testing the post < url > api with an invalid review_id,webapi_test_template def test_post_with_invalid_review_id self u review_request self create_review_request publish True with override_feature_checks self override_features rsp self api_post get_status_update_list_url review_request u service_id u Service u summary u Summary u review_id u 123456 expected_status 400 self assertEqual rsp u stat u fail self assertEqual rsp u err u code INVALID_FORM_DATA code self assertTrue u review_id in rsp u fields
verify that checking ndctl tool availability works as expected,def test_check_no_ndctl self self assertTrue BlockDev reinit True None with fake_path all_but ndctl with self assertRaises GLib GError BlockDev reinit self requested_plugins True None self assertNotIn nvdimm BlockDev get_available_plugin_names self assertTrue BlockDev reinit self requested_plugins True None self assertIn nvdimm BlockDev get_available_plugin_names
convert a bytestring to a long,def _bytes_to_long bytestring byteorder result if byteorder little result v i 8 for i v in enumerate bytestring else result v i 8 for i v in enumerate reversed bytestring return sum result
a failed read due to tombstones at v4 should result in a readfailure,since 2 2 def test_tombstone_failure_v4 self self protocol_version 4 session self _prepare_cluster self _insert_tombstones session 600 self _perform_cql_statement session SELECT value FROM tombstonefailure
"a simple factory function for compatibility with the standard shleve.py module . it can be used like this , where key is a string and data is a pickleable object :",def open filename flags db DB_CREATE mode 432 filetype db DB_HASH dbenv None dbname None if type flags type sflag flags if sflag r flags db DB_RDONLY elif sflag rw flags 0 elif sflag w flags db DB_CREATE elif sflag c flags db DB_CREATE elif sflag n flags db DB_TRUNCATE db DB_CREATE else raise db DBError flags should be one of r w c or n or use the bsddb db DB_ flags d DBShelf dbenv d open filename dbname filetype flags mode return d
maps a word to its corresponding index in the vocabulary .,def word2id self word u Maps a word to its corresponding index in the vocabulary n n Args n word Word to lookup n if word in self _word2id return self _word2id word else return len self _word2id
return field value if it 's set : param name : field name : return : field value or none,def field self name return self _data data get name None
print all the dbus info we can get our hands on .,def print_all dbus_client try metadata dbus_client get_property Metadata d_keys list metadata keys d_keys sort for k in d_keys d k split 1 if d artist print 0 t t 1 format d metadata k 0 elif len d 7 print 0 t t 1 format d metadata k else print 0 t 1 format d metadata k except AttributeError as e log error Could not get properties format e
"parse a point from a log line and return it , or none if no data point .",def parse line match re match INFO METRIC line if match json_str match group 1 try raw json loads json_str return Point metric_type raw get type metric raw get metric value raw get value tags raw get tags except Exception as exc get_logger warning Error parsing metric s exc return None
create a dummy login response payload,staticmethod def _login_response payload seto Payload payload eto_payload seq 1 payload eto_payload type eto PAYLOAD_LOGIN_RESPONSE payload eto_payload login_response session session payload eto_payload login_response reset 2 return payload
test saving an envi formatted image from a spyfile object .,def test_save_image_spyfile self u import os import spectral r b c 3 8 23 fname os path join testdir u test_save_image_spyfile hdr src spectral open_image u 92AV3C lan spectral envi save_image fname src img spectral open_image fname assert_almost_equal src r b c img r b c
returns path to location where plugin file is installed,def get_fm_source_path plugin u n tReturns path to location where plugin file is installed n t filename u s py plugin paths u scripts u usr share syncthing gtk u usr local share syncthing gtk for path in paths fn os path abspath os path join path filename if os path exists fn return fn return None
searches for an abbreviation and returns possible expansions for that abbreviation,def abr_lookup string try c execute SELECT str FROM LRABR WHERE abr string return c fetchall except sqlite3 ProgrammingError as e return
"represents external information , typically original obs data and metadata .",def Reference uri meaning None attrib uri uri if meaning is not None attrib meaning meaning return objectify Element Reference attrib
"returns true is the topods_shape is a cylinder , false otherwise",def shape_is_cylinder face hs BRep_Tool_Surface face downcast_result Handle_Geom_CylindricalSurface DownCast hs if downcast_result IsNull return False else return True
copy contents of theme directory skipping all jinja template files .,def copy_static_data theme_dir output_dir def ignored_files src names return name for name in names if name endswith jinja2 shutil copytree theme_dir output_dir ignore ignored_files
returns a list of filenames from the local object store which emulates the sorting order of keys returned from an aws s3 file store .,def GetS3CompatibleFileList root prefix None def _ListFiles dir for obj in os listdir dir objpath os path join dir obj if os path isfile objpath yield os path relpath objpath root elif os path isdir objpath for f in _ListFiles objpath yield f filelist x for x in _ListFiles root if not prefix or x startswith prefix return sorted filelist
gathers pre - mutation information : 1 . queries for existing followers and comment . 2 . checkpoints list of followers that need to be revived .,gen coroutine def _Check self message_byte_size len escape utf8 self _cm_dict message if message_byte_size Comment COMMENT_SIZE_LIMIT_BYTES logging warning User d attempted to exceed message size limit d d on comment s viewpoint s self _user_id message_byte_size Comment COMMENT_SIZE_LIMIT_BYTES self _comment_id self _viewpoint_id raise LimitExceededError Comment s is too long self _comment_id self _followers _ yield gen Task Viewpoint QueryFollowers self _client self _viewpoint_id limit Viewpoint MAX_FOLLOWERS owner_follower follower for follower in self _followers if follower user_id self _user_id if not owner_follower or not owner_follower 0 CanContribute raise PermissionError User d does not have permission to add comments to viewpoint s self _user_id self _viewpoint_id if self _op checkpoint is None comment yield gen Task Comment Query self _client self _viewpoint_id self _comment_id None must_exist False if comment is not None logging warning comment s already exists self _comment_id raise gen Return False self _revive_follower_ids self _GetRevivableFollowers self _followers checkpoint revive self _revive_follower_ids yield self _op SetCheckpoint self _client checkpoint else self _revive_follower_ids self _op checkpoint revive raise gen Return True
send an arbitrary service request to the viewfinder service from this client . the request is a json request consisting of any additional keyword arguments to sendrequest .,def SendRequest self service_path callback method POST kwargs if self _user_cookie is None raise ScenarioLoginError Client s can not be used until it is has a valid authorization cookie self name http_client httpclient AsyncHTTPClient url self _GetUrl service_path headers Cookie user s _xsrf watchdog self _user_cookie X Xsrftoken watchdog if method GET if len kwargs 0 url urllib urlencode kwargs http_client fetch url method method callback callback validate_cert False headers headers elif method POST headers Content Type application json request_body json dumps kwargs http_client fetch url method method body request_body callback callback validate_cert False headers headers else raise ValueError Invalid method s must be one of GET or POST method
makes accounting changes : 1 . for revived followers . 2 . for new followers .,gen coroutine def _Account self photo_ids photo_id for new_ep_dict in self _new_ep_dicts for photo_id in new_ep_dict photo_ids acc_accum AccountingAccumulator yield acc_accum SharePhotos self _client self _user_id self _viewpoint_id photo_ids follower user_id for follower in self _followers yield acc_accum Apply self _client
quantify the rhythmicity of an oscillator using the lagged coherence measure .,def lagged_coherence x f_range Fs N_cycles 3 f_step 1 return_spectrum False freqs np arange f_range 0 f_range 1 f_step f_step F len freqs lcs np zeros F for i f in enumerate freqs lcs i _lagged_coherence_1freq x f Fs N_cycles N_cycles f_step f_step if return_spectrum lc lcs return lc freqs else lc np mean lcs return lc
free all the resources regarding to this module : param self : a roguehostapdinfo object . : type self : roguehostapdinfo : return : none : rtype : none,def on_exit self pass
the super - helical axis .,property def axis self return Axis start self helix_start end self helix_end
downloads cifar10 and uncompresses it locally .,def _download_and_uncompress_dataset dataset_dir filename _DATA_URL split 1 filepath os path join dataset_dir filename if not os path exists filepath def _progress count block_size total_size sys stdout write r Downloading s 1f filename float count block_size float total_size 100 0 sys stdout flush filepath _ urllib request urlretrieve _DATA_URL filepath _progress print statinfo os stat filepath print Successfully downloaded filename statinfo st_size bytes tarfile open filepath r gz extractall dataset_dir
make sure that the default fetcher instance wraps exceptions by default,def test_wrappedByDefault self default_fetcher fetchers getDefaultFetcher self failUnless isinstance default_fetcher fetchers ExceptionWrappingFetcher default_fetcher self failUnlessRaises fetchers HTTPFetchingError fetchers fetch http invalid janrain com
just check the first inner product layer,def gradiant_check self linearList epsilon 1e 06 self input_layer setValue self train_x 2 self output_layer setY self train_y 2 index 0 n np size self convolution_pooling_layer index filters 0 m np size self convolution_pooling_layer index filters 1 grad_list for i in range n for j in range m self convolution_pooling_layer index filters i j epsilon self forward_compute Ju self costFunction self convolution_pooling_layer index filters i j epsilon 2 self forward_compute Jd self costFunction grad_list append Ju Jd 2 epsilon self convolution_pooling_layer index filters i j epsilon grad_list np array grad_list self forward_compute self backward_compute bp_grad_list self convolution_pooling_layer index grad_filters ravel distance np sum grad_list bp_grad_list 2 len bp_grad_list print distance if distance 1e 05 print Conv Layer filter Gradiant check pass else print Conv Layer Gradiant check failed return False index 0 n np size self convolution_pooling_layer index bias 0 m np size self convolution_pooling_layer index bias 1 grad_list for i in range n for j in range m self convolution_pooling_layer index bias i j epsilon self forward_compute Ju self costFunction self convolution_pooling_layer index bias i j epsilon 2 self forward_compute Jd self costFunction grad_list append Ju Jd 2 epsilon self convolution_pooling_layer index bias i j epsilon grad_list np array grad_list self forward_compute self backward_compute bp_grad_list self convolution_pooling_layer index grad_bias ravel distance np sum grad_list bp_grad_list 2 len bp_grad_list print distance if distance 1e 05 print Conv Layer bias Gradiant check pass else print Conv Layer bias Gradiant check failed return False
"get nws alert feed , and cache it",def _get_nws_feed self url http alerts weather gov cap s php x 0 str self _state lower xml requests get url content return xml
"returns the index , key , and value of a slot found in a bucket . returns -1 , key , and default ( none if not set ) when not found .",def get_slot aMap key default None bucket get_bucket aMap key for i kv in enumerate bucket k v kv if key k return i k v return 1 key default
get embedded exif data from image file .,def exif fname ret try img Image open fname if hasattr img _getexif exifinfo img _getexif if exifinfo None for tag value in exifinfo items decoded TAGS get tag tag ret decoded value except IOError print IOERROR fname return ret
create a new fermentable type suggestion .,def create self validated_data new_type_data validated_data pop new_type new_type models FermentableType objects create new_type_data old_type_id None if old_type_id in validated_data old_type_id validated_data pop old_type_id suggestion models Suggestion objects create content_type ContentType objects get model fermentabletype suggested_object_id new_type id replaced_object_id old_type_id return suggestion
! @brief apply an equation on input values @param equation < equation > : an equation object @param input_values < [ numpy 1d - array ] > : the values of the input variables @return < numpy 1d - array > : the values of the output variable,def do_calculation equation input_values operation OPERATIONS equation operator nb_operands len input_values if nb_operands 1 with np errstate divide ignore invalid ignore return operation input_values 0 elif nb_operands 2 with np errstate divide ignore invalid ignore return operation input_values 0 input_values 1 with np errstate divide ignore invalid ignore return operation input_values 0 input_values 1 input_values 2
"returns a copy of |schema| with "" description "" fields removed .",def _RemoveDescriptions node if isinstance node dict result for key value in node items if key description and isinstance value basestring continue result key _RemoveDescriptions value return result if isinstance node list return _RemoveDescriptions v for v in node return node
load files during a cron run .,def Cron self futures for root dirs files in self _file_system Walk if redirects json in files futures append self _cache GetFromFile posixpath join root redirects json return Future delegate Gettable lambda f Get for f in futures
finds a matching component name which a given |bucket| belongs to .,def find_malloc self bucket assert not bucket or bucket allocator_type malloc if not bucket return no bucket if bucket component_cache return bucket component_cache stackfunction bucket symbolized_joined_stackfunction stacksourcefile bucket symbolized_joined_stacksourcefile typeinfo bucket symbolized_typeinfo if typeinfo startswith 0x typeinfo bucket typeinfo_name for rule in self _rules if rule allocator_type malloc and not rule stackfunction_pattern or rule stackfunction_pattern match stackfunction and not rule stacksourcefile_pattern or rule stacksourcefile_pattern match stacksourcefile and not rule typeinfo_pattern or rule typeinfo_pattern match typeinfo bucket component_cache rule name return rule name assert False
run a perf test on the device .,def RunTest self test_name output result_type self _LaunchPerfTest test_name results base_test_result TestRunResults results AddResult base_test_result BaseTestResult test_name result_type retry None if not results DidRunPass retry test_name return results retry
adict.one in dict lookup in a loop,def test30 self for i in range 10 self check aDict one
change directory to the top of the git repository .,def move_to_topdir try toplevel subprocess check_output git rev parse show toplevel except subprocess CalledProcessError sys exit Please run in a git repository toplevel toplevel rstrip os chdir toplevel
using /getupdates to poll updates from telegram .,def get_updates self offset 0 limit 100 timeout 0 return self send_request getUpdates offset offset limit limit timeout timeout
returns a c++ function which will create a controller object .,def DumpController self num_states self A shape 0 num_inputs self B shape 1 num_outputs self C shape 0 ans StateFeedbackController d d d s n num_states num_inputs num_outputs self ControllerFunction ans append self _DumpMatrix L self L ans append self _DumpMatrix K self K if not hasattr self Kff self Kff numpy matrix numpy zeros self K shape ans append self _DumpMatrix Kff self Kff ans append self _DumpMatrix A_inv numpy linalg inv self A ans append return StateFeedbackController d d d L K Kff A_inv Make sPlantCoefficients num_states num_inputs num_outputs self _name ans append n return join ans
"[ * optional * ] i d of the source entity of this spike , if any . for example the spike waveform of the action potential corresponding to this spike might have been recorded in a segment entity .",property def source_entity_id self return self _info SourceEntityID
the dsapublickey associated with this private key .,abc abstractmethod def public_key self
"import a keytab file , i d is the name of the keytab file ( they should be the same )",def import_keytab isamAppliance id file check_mode False force False if force is True or _check isamAppliance id is False if check_mode is True return isamAppliance create_return_object changed True else return isamAppliance invoke_post_files description Import a keytab file uri 0 format uri fileinfo file_formfield keytab_file filename file mimetype application octet stream data requires_modules requires_modules requires_version requires_version json_response False return isamAppliance create_return_object
rollback the current pending changes .,def rollback isamAppliance check_mode False force False if force is True or _changes_available isamAppliance is True if check_mode is True return isamAppliance create_return_object changed True else return isamAppliance invoke_delete Rollback the changes isam pending_changes return isamAppliance create_return_object
runs a speed benchmark on hascollided ( ) using a tank and shell and prints the results : param iterations : the number of times to repeat each test,def perfTest iterations import datetime from dataModels import tank shell from serverLogic logging import round def runTrials maxDist None Runs the number of trials set by iterations return The time taken in seconds aTank tank aTank x 200 aTank y 100 aShell shell 0 aTank 0 start datetime datetime now for count in range 0 iterations aShell x 100 while not hasCollided aTank toPoly aShell toPoly maxDist maxDist aShell move 1 return datetime datetime now start total_seconds print Benchmarking hasCollided using a shell and tank print Using str iterations iterations n timeWith runTrials maxDist maxDistValues tankShell timeWithout runTrials print Time with maxDist str round timeWith 5 secs print Time without str round timeWithout 5 secs n print maxDist is str round timeWithout timeWith 2 times faster
execute a request against the labkey security controller group membership apis : param server_context : a labkey server context . see utils.create_server_context . : param api : action to execute : param user_ids : user ids to apply action to : param group_id : group i d to apply action to : param container_path : additional container context path : return : request json object,def __make_security_group_api_request server_context api user_ids group_id container_path u n Execute a request against the LabKey Security Controller Group Membership apis n param server_context A LabKey server context See utils create_server_context n param api Action to execute n param user_ids user ids to apply action to n param group_id group id to apply action to n param container_path Additional container context path n return Request json object n url server_context build_url security_controller api container_path if not hasattr user_ids u __iter__ user_ids user_ids return server_context make_request url u groupId group_id u principalIds user_ids
algorithm is controlled by a exploration parameter epsilon .,def __init__ self epsilon 0 1 counts values self epsilon epsilon self arms DataFrame Iteration counts Reward values self arms index name Arm return
bar and pub are the same thing and they should be treated similiarly at least to a general drinker . this is doing just that . : param : data - restructured and verified node data and way data,def mergeBARnPUB data searchMatchValue pub for each in data if searchMatchTag in each k and searchMatchValue in each v and each get removed true each v each k index searchMatchTag bar yield each
returns file path to given zk node .,def _dpath fsroot zkpath u if zkpath u return fsroot path zkpath lstrip u split u return os path join fsroot u join u _ d for d in path
construct a watcher for the manifest directory .,def get_dir_watch self u watch dirwatch DirWatcher self paths manifest_dir watch on_created self _on_created return watch
test the ` exit_on_unhandled ` decorator on python ` exception ` .,mock patch u treadmill utils sys_exit mock Mock def test_decorator_py_exc self u utils exit_on_unhandled def test_fun u raise Exception test raise Exception u test test_fun utils sys_exit assert_called_with 1
"the bold formatting attribute , l{a.bold } , emits the vt102 control sequence to enable bold when flattened .",def test_bold self self assertEqual text assembleFormattedText A bold Hello world x1b 1mHello world
"l{streamserverendpointservice.startservice } sets the c{running } flag , but nothing else , if the service has already been started .",def test_startServiceStarted self self test_privilegedStartService self svc startService self assertEqual self fakeServer listenAttempts 1 self assertEqual self svc running True
use the redshift copy command to copy event data from s3,def copy_from_s3 network s3_prefix table_name rawdata host user password database parsely port 5439 access_key_id secret_access_key debug False query COPY table_name FROM s3 parsely dw network s3_prefix CREDENTIALS aws_access_key_id aws_access_key_id aws_secret_access_key aws_secret_access_key JSON AS auto GZIP TRUNCATECOLUMNS format table_name table_name network utils clean_network network s3_prefix s3_prefix aws_access_key_id access_key_id aws_secret_access_key secret_access_key if debug print Running the following Redshift COPY command print query connection psycopg2 connect host host port port user user password password database database connection cursor execute query connection commit
sets up a protocol to be opened after the broker initializes .,def open_protocol protocol_name kwargs result log_stack_on_error Deferred def do_open_protocol Actually do the opening of the protocol once the broker is running return d maybeDeferred Broker get_instance open_protocol protocol_name kwargs d chainDeferred result Broker call_on_start do_open_protocol return result
"given an origin and a list of destinations ( in lat / lon form ) , returns a list of 3-tuples in the form "" [ ( distance , duration , stop ) ] "" . distance and duration are dicts in the form { "" value"" : n , "" text"" : s}. distance is in meters , duration in seconds . the stop is a dictionary like : { ' stpid ' : ' 2564 ' , ' stpnm ' : ' 5th ave at meyran ave ' , ' lon ' : -79.959239533731 , ' lat ' : 40.441172012068 }",def distance_points self origin destinations l len destinations if l self window_size return self __distance_points origin destinations else return list self __distance_points origin destinations self window_size list self distance_points origin destinations self window_size
renames entry in preview models system if it exists,def rename old_name new_name _cache rename_entry old_name new_name
set uv layer to given texture type in material .,def set_uv material tex_type uv_layer tex_coord is_valid_input True if truckpaint in material scs_props mat_effect_name and tex_type in paintjob base if tex_type paintjob if altuv in material scs_props mat_effect_name if tex_coord 2 is_valid_input False elif tex_coord 1 is_valid_input False elif tex_type base if tex_coord 0 is_valid_input False if is_valid_input __setup_nodes__ material material scs_props mat_effect_name tex_type uv_layer False
the schema is a python dict which maps the config name to a validator .,def __init__ self schema u n The schema is a Python dict which maps the config name to a validator n self _schema schema self _schema_keys set dict schema keys self data self user_configs self set_defaults
clear the graph database of all nodes and edges .,def clear_db self self graph_db clear
type query with no criteria .,def test_000_unset self alltypes sorted self p types q TypeQuery self p qtypes sorted q results self assertListEqual alltypes qtypes
constraint query with type match .,def test_040_type_match_single self q ConstraintQuery self p type_ test40t constraint sorted c tclass for c in q results self assertListEqual test40 constraint
return source or target based on index .,def _index_to_item self index if index 0 return self source elif index 1 return self target else raise IndexError Invalid index edges only have 2 items 0 format index
the name of the file ( read / write ),property def filename self return core BNGetFilename self handle
load aead from a file .,def load self filename aead_f open filename rb buf aead_f read 1024 if buf startswith YHSM_AEAD_CRLF_File_Marker buf YHSM_AEAD_File_Marker buf len YHSM_AEAD_CRLF_File_Marker if buf startswith YHSM_AEAD_File_Marker if buf len YHSM_AEAD_File_Marker chr 1 fmt I is pyhsm defines YSM_AEAD_NONCE_SIZE self key_handle self nonce struct unpack_from fmt buf len YHSM_AEAD_File_Marker 1 self data buf len YHSM_AEAD_File_Marker 1 struct calcsize fmt else raise pyhsm exception YHSM_Error Unknown AEAD file format else self data buf pyhsm defines YSM_MAX_KEY_SIZE pyhsm defines YSM_BLOCK_SIZE aead_f close
"given a language english name , returns corresponding language",def name_to_language given_name try return name_to_language_ given_name except KeyError return None
counts the unique substrings of p in the infinite wraparound string .,def findSubstringInWraproundString self p n len p if n 0 or n 1 return n chars set p dp c 0 for c in chars i 0 count 0 while i n j i 1 while j n and self alpha p j self alpha p j 1 1 26 j 1 for k in xrange i j c p k length j k endpoints max 0 length dp c count endpoints dp c max dp c length i j return count
"returns a chainablelist [ [ self1 , other1 ] , [ self2 , other2 ] , ... ]",def zip self other if len self len other raise ValueError self and other lists must be the same length res ChainableList for i in xrange 0 len self res append self i other i return res
add element key represented by hashes to the heavyhitters object ( hence the different signature on the function ! ),def add_alt self key hashes num_els 1 res super HeavyHitters self add_alt hashes num_els if self __top_x_size self __num_hitters tmp self __top_x get key None self __top_x key res if tmp is None self __top_x_size len self __top_x return res if key in self __top_x self __top_x key res return res if res self __smallest self __top_x key res tmp_key min self __top_x key self __top_x get self __top_x pop tmp_key None new_min min self __top_x key self __top_x get self __smallest self __top_x new_min return res return res
return the average of the elements of a sequence .,def mean seq return float sum seq len seq if len seq 0 else float nan
returns the menu items to display when no file / folder is selected ( i.e. when right - clicking the background ) .,def get_background_items self window file if os geteuid ROOT_UID return items self _setup_gettext self window window if file is_directory and file get_uri_scheme file if os path exists NAUTILUS_PATH items self _create_nautilus_item file return items
"validate ` payload ` against ` schema ` , returning an error list .",def validate payload schema u Validate payload against schema returning an error list n n jsonschema provides lots of information in it s errors but it can be a bit n of work to extract all the information n v jsonschema Draft4Validator schema format_checker jsonschema FormatChecker error_list for error in v iter_errors payload message error message location u u join str c for c in error absolute_path error_list append message u at location return error_list
@return : the socket 's own address @rtype :,def getsockname self return self __ssl_conn getsockname
"grant the permission level specified to the generic group of users specified . if level is level_none , any existing assignment is removed .",def set_gen_level self gen_role level my_ct ContentType objects get_for_model self if level self LEVEL_NONE GenericObjectRoleMapping objects filter subject gen_role object_id self id object_ct my_ct delete else try role ObjectRole objects get codename level content_type my_ct except ObjectRole DoesNotExist raise PermissionLevelError Invalid Permission Level s level GenericObjectRoleMapping objects filter subject gen_role object_id self id object_ct my_ct delete GenericObjectRoleMapping objects create subject gen_role object self role role
depth first pre - order traversal of tree .,def pre_order self node root if node is root node self root if not node return yield node val for n in self pre_order node node left yield n for n in self pre_order node node right yield n
return an iterator which yields the paths matching a pathname pattern .,def iglob pathname if not has_magic pathname if os path lexists pathname yield pathname return dirname basename os path split pathname if not dirname for name in glob1 None basename yield name return if dirname pathname and has_magic dirname dirs iglob dirname else dirs dirname if has_magic basename glob_in_dir glob1 else glob_in_dir glob0 for dirname in dirs for name in glob_in_dir dirname basename yield os path join dirname name
return a helpful list of instructions ( commands ) for receipt printing,def terminal_print_help self return self get v1 terminal preview print command_spec
a smoke test of the integrated workflow,def test_basic_mosiac image pool pm basic_mosaic image pool 5 5
return optimal collocation nodes for some orthogonal polynomial .,classmethod def roots cls degree domain kind basis_coefs cls _basis_monomial_coefs degree basis_poly cls functions_factory basis_coefs domain kind return basis_poly roots
set and add to the pre - up commands for an interface . takes a list of shell commands .,def setPreUp self pre self _ifAttributes pre up pre
login or register a facebook user .,patch social_auth backends facebook FacebookAuth enabled patch social_auth utils urlopen def login self user mock_urlopen mock_facebook_enabled backend facebook token dummyToken backends facebook urllib urlencode access_token token expires 3600 simplejson dumps user google simplejson dumps access_token token token_type Bearer expires_in 3600 simplejson dumps user linkedin urllib urlencode oauth_token token oauth_token_secret token oauth_callback_confirmed true xoauth_request_auth_url https api linkedin com uas oauth authorize oauth_expires_in 3600 urllib urlencode oauth_token token oauth_token_secret token oauth_expires_in 3600 oauth_authorization_expires_in 3600 xml version 1 0 encoding UTF 8 standalone yes person id id id email address email email address first name first_name first name last name last_name last name person format user if backend not in backends raise NoBackendError s is not supported backend mock out urlopen mock_urlopen side_effect DumbResponse r for r in backends backend mock_facebook_enabled return_value True factory RequestFactory request factory post code dummy redirect_state dummy engine import_module settings SESSION_ENGINE if self session request session self session else request session engine SessionStore request user AnonymousUser request session facebook_state dummy redirect complete request backend request session save session_cookie settings SESSION_COOKIE_NAME self cookies session_cookie request session session_key cookie_data max age None path domain settings SESSION_COOKIE_DOMAIN secure settings SESSION_COOKIE_SECURE or None expires None self cookies session_cookie update cookie_data return True
returns a long representation of the stream codec .,def codecDescription self codec_d None if self __dict__ codec_long_name codec_d self __dict__ codec_long_name return codec_d
generate one use number and return * if * it was created,def useNonce self server_url timestamp salt if abs timestamp time time SKEW return False return self nonce use server_url timestamp salt
returns whether the feature flag to enable microsite has been set,def is_feature_enabled return settings FEATURES get USE_MICROSITES False
create the output directory recursively if it does n't already exist .,def create_directory dname if not os path exists dname os makedirs dname return os path exists dname
we should not find a citation if it does n't exist in the tree,def test_process_unknown self self assertIsNone self ic process Node XXX section I B
"when notices are corrected , the xml for notices does n't follow the normal syntax . namely , pargraphs are n't inside section tags . we fix that here , by finding the preceding section tag and appending paragraphs to it .",def fix_section_node paragraphs amdpar_xml sections s for s in amdpar_xml itersiblings preceding True if s tag SECTION if len sections 1 section copy deepcopy sections 0 for paragraph in paragraphs section append copy deepcopy paragraph return section
"read the bitcoin.conf file from dbdir , returns dictionary of settings",def read_bitcoin_config dbdir from ConfigParser import SafeConfigParser class FakeSecHead object def __init__ self fp self fp fp self sechead all n def readline self if self sechead try return self sechead finally self sechead None else s self fp readline if s find 1 s s 0 s find strip n return s config_parser SafeConfigParser config_parser readfp FakeSecHead open os path join dbdir bitcoin conf return dict config_parser items all
initialize your data structure here .,def __init__ self self stack self minStack
create database objects and superuser account,task cmdopts email e email username u username password p password def create options args username options get username None password options get password None email options get email None if all username password email args s s s username password email sh python GeoHealthCheck models py create s args
"produce a "" docker save "" compatible tarball from the dockerimage .",def tarball name image tar def add_file filename contents info tarfile TarInfo filename info size len contents tar addfile tarinfo info fileobj io BytesIO contents multi_image_tarball name image tar add_file top image top encode utf8
"read in a csv containing samples generated by r and transform it into a set of argument dictionaries . expects the following fields : ' mw_0 ' , ' mw_1 ' , ' mw_2 ' , ' women_0 ' , ' women_1 ' , ' women_2 ' value between 0 & 1 ' mw_share_prob ' , ' women_share_prob ' , ' responder_share_weight ' , ' signaller_share_weight ' between 0 & 1",def lhs_sampling samples chunksize None kwargs results with open samples rb as csvfile samples_reader csv DictReader csvfile delimiter for row in samples_reader row dict k float v for k v in row iteritems bias row honesty_bias type_weights bias 1 0 1 0 1 0 bias 1 0 1 0 1 0 bias referral_cost row payoff_distinction baby_payoff 1 row payoff_distinction kwarg game_args mw_share_prob row mw_share_prob women_share_prob row women_share_prob type_weights type_weights baby_payoff baby_payoff referral_cost referral_cost signaller_args share_weight row signaller_share_weight responder_args share_weight row responder_share_weight mw_weights row mw_0 row mw_1 row mw_2 women_weights row women_0 row women_1 row women_2 kwargs append kwarg if chunksize is not None and len kwargs chunksize results append kwargs kwargs results append kwargs return results
"test cycle on dir with devices , changing uid / gid , etc .",def test_basic_cycle self self total_sequence testfiles root1 testfiles root2
"overwrite old context.json , use context.json from target_zip : param target_zip : : return :",tasks register_helper def import_context target_zip u n Overwrite old context json use context json from target_zip n param target_zip n return n context_path tasks get_context_path with zipfile ZipFile target_zip as unzipped_data with open context_path u w as context context write unzipped_data read u context json
indicate that a test has been fully handled .,def test_completed self with self _lock self _tests_in_progress 1 if self _tests_in_progress 0 self _item_avaliable_or_all_done set
calculate the center of a polygon,def calc_center points assert len points 0 need at least 1 points to calculate the center area calc_area points p1 points 0 cx cy 0 for p2 in points 1 points 0 tmp p1 X p2 Y p2 X p1 Y cx p1 X p2 X tmp cy p1 Y p2 Y tmp p1 p2 c 1 6 0 area cx 1 6 0 area cy return c
goal : slicing data goal : using zip to transpose data,def ping_rtt from notebooks course import sh import sys cmd ping c10 www google it if win in sys platform cmd ping n10 www google it ping_output sh cmd if win in sys platform ping_output ping_output 6 2 for x in ping_output else ping_output ping_output 4 1 2 for x in ping_output ttl rtt zip ping_output return map float rtt
render html for using the package 's output file .,def render_compressed_output self package package_name package_type u Render HTML for using the package s output file n n Subclasses can override this method to provide custom behavior for n rendering the output file n method getattr self u render_ 0 format package_type return method package package output_filename
represent as a string - usefull for printing,def __repr__ self output s with outputs self name for op in self outputs output s op name output return output
return an uncompressed revision of a given,def revision self node if node nullid return text None chain iter_node node rev self rev iter_node while self bundle rev if self _cache and self _cache 0 iter_node text self _cache 2 break chain append rev iter_node self bundlebase rev rev self rev iter_node if text is None text revlog revlog revision self iter_node while chain delta self _chunk chain pop text mdiff patches text delta p1 p2 self parents node if node revlog hash text p1 p2 raise error RevlogError _ integrity check failed on s d self datafile self rev node self _cache node self rev node text return text
create an argparse . argumentparser from an input list . does not support subparsers ( yet ) .,def argparseFactory argspec parser_spec argspec 0 if not default parser_spec get type raise ValueError default arg dict not found args kwargs parser_spec get args parser_spec get kwargs parser ArgumentParser args kwargs group parser_spec get group if group for argument in group args kwargs argument get args argument get kwargs parser add_argument args kwargs for i in xrange 1 len argspec spec argspec i typ spec get type group spec get group if not typ or not group raise ValueError Invalid type or group in argspec d i if typ exclusive fun ArgumentParser add_mutually_exclusive_group elif typ group fun ArgumentParser add_argument_group else raise ValueError Unsupported group type s typ args kwargs spec get args spec get kwargs group_parser fun parser args kwargs for argument in group args kwargs argument get args argument get kwargs group_parser add_argument args kwargs return parser
create an empty blockchain and num_nodes wallets . useful if a test case wants complete control over initialization .,def initialize_chain_clean test_dir num_nodes for i in range num_nodes datadir initialize_datadir test_dir i
"creates a secure ( `` ssl `` ) socket connection to the given host and port , authenticating with the given certfile and ca file .",def ssl_connect host port DEFAULT_SERVER_SSL_PORT keyfile None certfile None ca_certs None cert_reqs None ssl_version None ciphers None ipv6 False return factory ssl_connect host port keyfile keyfile certfile certfile ssl_version ssl_version ca_certs ca_certs service SlaveService ipv6 ipv6
"fetch a integer type from the json file , but use default if it returns the incorrect type or does n't exist .",def getInt self type attribute default 0 value self getOption type attribute default if isinstance value int long return int value else return default
apply porter stemming algorithm then double metaphone algorithm to the passed in string to obtain normalized and misspelling tolerant hash values / tokens,def fuzz text processed_tokens doublemetaphone stemmer stem word for word in text split return token for token in sum processed_tokens if token
edit domain xml description and insert < cpu > element,def add_cpu_xml domobj guestname sockets cores threads logger guestxml domobj XMLDesc 0 logger debug original guest s xml n s guestname guestxml doc minidom parseString guestxml cpu doc createElement cpu topology doc createElement topology topology setAttribute sockets sockets topology setAttribute cores cores topology setAttribute threads threads cpu appendChild topology vcpuval int sockets int cores int threads newvcpu doc createElement vcpu newvcpuval doc createTextNode str vcpuval newvcpu appendChild newvcpuval oldvcpu doc getElementsByTagName vcpu 0 domain doc getElementsByTagName domain 0 domain appendChild cpu domain replaceChild newvcpu oldvcpu return doc toxml
get any new instrument samples that have arrived on the network .,def get_stream_data self n 0 timeout None if timeout and timeout 0 raise ValueOutOfRangeException Timeout must be positive or None if n 1 raise ValueOutOfRangeException Invalid number of samples Expected n 1 if not self _stream_net_is_running raise InvalidOperationException No network streaming session is running if self _no_data log debug No more samples to get return if type n is not int raise TypeError Sample number n must be an integer processed_samples self _stream_get_processed_samples if n 0 num_processed_samples len x for x in processed_samples else num_processed_samples 1 1 while n 1 or self ch1 and num_processed_samples 0 n or num_processed_samples 0 0 or self ch2 and num_processed_samples 1 n or num_processed_samples 1 0 try self _stream_receive_samples timeout except NoDataException log debug No more data available for current stream self _no_data True processed_samples self _stream_get_processed_samples if n 1 num_processed_samples len x for x in processed_samples if self _no_data break active_channels self ch1 self ch2 to_return min len p for c p in zip active_channels processed_samples if c if n 0 to_return min n to_return dout_ch1 processed_samples 0 0 to_return if self ch1 else dout_ch2 processed_samples 1 0 to_return if self ch2 else self _stream_clear_processed_samples to_return return dout_ch1 dout_ch2
translate a protein sequence from 3 to 1 letter code,def three2one prot code GLY G ALA A LEU L ILE I ARG R LYS K MET M CYS C TYR Y THR T PRO P SER S TRP W ASP D GLU E ASN N GLN Q PHE F HIS H VAL V newprot for a in prot newprot code get a return newprot
create galactose model . : return :,def test_galactose model_dict Preprocess dict_from_modules sbmlutils examples models hepatocyte sbmlutils examples models galactose cell_model CoreModel from_dict model_dict cell_model create_sbml
tests if the authentication was successful,def _test_authentication conn page url http_code requests get_ui_return_html_status conn conn baseurl if re search conn host url is not None and re search userlogin url is None return True else return False
"returns the size of the grid as a tuple ( row , col )",property def size self return self rows self cols
tell luigi that the useritemrecs task needs to be completed before running this task .,def requires self return UserItemRecs output_base_path self output_base_path
returns domname for given cssname e.g. for cssname ' font - style ' returns ' fontstyle ' .,def _toDOMname CSSname def _doCSStoDOMname2 m return m group 0 1 capitalize return _reCSStoDOMname sub _doCSStoDOMname2 CSSname
add new notification to registration message,def add_notification self name enabled True notice notice Notification Name u s name notice Notification Enabled u s enabled self notifications append notice self add_header Notifications Count len self notifications
create or update the changelog txt file . prompt for update description . : return none :,def update_changelog description Placeholder for description here with open changelog txt a as f f write str datetime datetime now strftime d B Y I M p nDescription description return
loads input and computes the sparse code for it .,def ForwardPropagate self train False method iter input_layer self input_layer code_layer self code_layer input_layer GetData inputs input_layer state we self encoder params weight be code_layer params bias scale code_layer params scale hyp code_layer hyperparams code_approx code_layer approximator cm dot we T inputs target code_approx code_approx add_col_vec be code_layer ApplyActivation code_approx code_approx mult_by_col scale if hyp dropout and train code_layer mask fill_with_rand code_layer mask greater_than hyp dropout_prob code_approx mult code_layer mask if train if method iter self IterateForZ train train elif method exact self SolveForZ elif method iter self IterateForZ train train
the down arrow was pressed .,def keyPressDown self event pass
move circle into an open spot .,def moveCircle self derivation otherCircles overlapArealRatio angle abs self center self radius euclidean globalTau movedCenter self center searchRadius derivation searchRadiusOverRadius self radius distanceIncrement searchRadius float derivation searchAttempts distance 0 0 greatestRadius self radius searchCircles searchCircleDistance searchRadius searchRadius self radius derivation wallThickness for otherCircle in otherCircles if abs self center otherCircle center searchCircleDistance otherCircle radius searchCircles append otherCircle for attemptIndex in xrange derivation searchAttempts angle euclidean globalGoldenAngle distance distanceIncrement offset distance euclidean getWiddershinsUnitPolar angle attemptCenter self center Vector3 offset real offset imag radius self getRadius attemptCenter derivation searchCircles overlapArealRatio if radius greatestRadius greatestRadius radius movedCenter attemptCenter self center movedCenter self radius greatestRadius
parse a gcode line and add it to the limit skein .,def parseLine self lineIndex line self lines lineIndex lstrip splitLine gcodec getSplitLineBeforeBracketSemicolon line if len splitLine 1 return firstWord gcodec getFirstWord splitLine if firstWord G1 location gcodec getLocationFromSplitLine self oldLocation splitLine line self getLimitedInitialMovement line splitLine line self getZLimitedLineLinear line location splitLine self oldLocation location elif firstWord G2 or firstWord G3 line self getZLimitedLineArc line splitLine elif firstWord M101 self maximumZCurrentFeedRatePerSecond self maximumZDrillFeedRatePerSecond elif firstWord M103 self maximumZCurrentFeedRatePerSecond self maximumZFeedRatePerSecond self distanceFeedRate addLine line
"given a list of parsers and a media type , return the appropriate parser to handle the incoming request .",def select_parser self request parsers u n Given a list of parsers and a media type return the appropriate n parser to handle the incoming request n for parser in parsers if media_type_matches parser media_type request content_type return parser return None
converts any urls in text into clickable links .,register filter def urlize_quoted_links text trim_url_limit None nofollow True autoescape True u n Converts any URLs in text into clickable links n n Works on http https www links and also on links ending in one of n the original seven gTLDs com edu gov int mil net and org n Links can have trailing punctuation periods commas close parens and n leading punctuation opening parens and it ll still do the right thing n n If trim_url_limit is not None the URLs in link text longer than this limit n will truncated to trim_url_limit 3 characters and appended with an elipsis n n If nofollow is True the URLs in link text will get a rel nofollow n attribute n n If autoescape is True the link text and URLs will get autoescaped n def trim_url x limit trim_url_limit return limit is not None and len x limit and u s x max 0 limit 3 or x safe_input isinstance text SafeData words word_split_re split force_text text for i word in enumerate words if u in word or u in word or u in word lead middle trail u word u for punctuation in TRAILING_PUNCTUATION if middle endswith punctuation middle middle len punctuation trail punctuation trail for opening closing in WRAPPING_PUNCTUATION if middle startswith opening middle middle len opening lead lead opening if middle endswith closing and middle count closing middle count opening 1 middle middle len closing trail closing trail url None nofollow_attr u rel nofollow if nofollow else u if simple_url_re match middle url smart_urlquote_wrapper middle elif simple_url_2_re match middle url smart_urlquote_wrapper u http s middle elif u not in middle and simple_email_re match middle local domain middle rsplit u 1 try domain domain encode u idna decode u ascii except UnicodeError continue url u mailto s s local domain nofollow_attr u if url trimmed trim_url middle if autoescape and not safe_input lead trail escape lead escape trail url trimmed escape url escape trimmed middle u a href s s s a url nofollow_attr trimmed words i mark_safe u s s s lead middle trail elif safe_input words i mark_safe word elif autoescape words i escape word elif safe_input words i mark_safe word elif autoescape words i escape word return u join words
return the button event text .,property def eventText self return self _events get self event None
: param node : the object to use to create subprocesses .,def __init__ self node args kwargs self node node self _pid_gen 0 self _processes super ProcessHelper self __init__ args kwargs
destroy the application 's database on the server machine .,task roles db def drop_db require db_name provided_by staging production fastprint Dropping database db_name s env show_prefix True if not console confirm Are you sure abort Deployment aborted with hide commands warnings with settings warn_only True run dropdb db_name s env fastprint Dropped database db_name s env end n
test that a node is reregistered after handling a request .,def test_static_request_handled self configfile self setup_config static basic yaml pool self useNodepool configfile watermark_sleep 1 pool start nodes self waitForNodes fake label self assertEqual len nodes 1 req zk NodeRequest req state zk REQUESTED req node_types append fake label self zk storeNodeRequest req self log debug Waiting for request s req id req self waitForNodeRequest req self assertEqual req state zk FULFILLED self assertEqual len req nodes 1 self assertEqual req nodes 0 nodes 0 id nodes 0 state zk USED self zk storeNode nodes 0 new_nodes self waitForNodes fake label self assertEqual len new_nodes 1 self assertEqual nodes 0 hostname new_nodes 0 hostname
this rule is intended to permit inbound ping6,classmethod def create_v6_pingable_secgroup_rule cls secgroup_id None client None rule_list protocol ipv6 icmp direction ingress port_range_min 128 port_range_max 0 ethertype IPv6 remote_ip_prefix 0 client client or cls os_primary network_client cls create_secgroup_rules rule_list client client secgroup_id secgroup_id
objective function for the maximin design optimization .,def _maximin_design_obj y vert None Ny n vert shape N y size n Y y reshape N n D0 distance_matrix Y Y 100000 0 np eye N d0 np power D0 flatten 2 d0star np amin d0 D1 distance_matrix Y vert d1 np power D1 flatten 2 d1star np amin d1 dstar np amin d0star d1star return dstar
": ivar function : the function to be called : ivar list args : an optional list of arguments to be passed to the function : ivar dict kwargs : an optional dictionary of keyword arguments to be passed to the function : ivar return_value : the value returned by the function , none if it has n't been called yet .",def __init__ self text function args None kwargs None menu None should_exit False super FunctionItem self __init__ text text menu menu should_exit should_exit self function function if args is not None self args args else self args if kwargs is not None self kwargs kwargs else self kwargs self return_value None
"add item / s to one of the lists . ' side ' - > str ( ' left ' or ' right ' ( no case sensitive ) ) ' item ' - > list , tuple or str",def append_to self side item if self _is_side_correct side if type item type str tempList list tempList append item item tempList if side lower left self _storeLeft append item else self _storeRight append item elif type item type list or type item type tuple if side lower left for element in item tempList list tempList append element element tempList self _storeLeft append element else for element in item tempList list tempList append element element tempList self _storeRight append element else pass
decode string if it is a bytes instance .,def decode string encoding utf 8 if isinstance string bytes return string decode encoding return string
contextmanager to suppress stderr messages http://stackoverflow.com/a/1810086/882918,contextmanager def nostderr savestderr sys stderr class Devnull object dev null incarnation as output stream like object def write self _ Write method just does nothing pass sys stderr Devnull try yield finally sys stderr savestderr
returns a dict representation of the object,def to_dict self return key getattr self key for key in self FEATURES
check if bookmarks results are present,def results_present self return self q css self BOOKMARKS_ELEMENT_SELECTOR present
set the value of input field by selector .,def set_input_field_value self selector value self q css selector 0 send_keys value
handle a response from the payment processor .,def process_postpay_callback params kwargs return PROCESSOR_MODULE process_postpay_callback params kwargs
test returns proper value when have proper access,patch class_dashboard views has_instructor_access_for_class def test_all_sequential_open_distribution_has_access self has_access has_access return_value True response views all_sequential_open_distrib self request test test test self assertEqual json dumps self simple_data response content
creates course action state entries with different states for the given action model class . creates both displayable ( should_display = true ) and non - displayable ( should_display = false ) entries .,def init_course_action_states self action_class def create_course_states starting_course_num ending_course_num state should_display True Creates a list of course state tuples by creating unique course locators with course numbers from starting_course_num to ending_course_num CourseState namedtuple CourseState course_key state should_display return CourseState CourseLocator org course run str num state should_display for num in range starting_course_num ending_course_num NUM_COURSES_WITH_STATE1 3 NUM_COURSES_WITH_STATE2 3 NUM_COURSES_WITH_STATE3 3 NUM_COURSES_NON_DISPLAYABLE 3 self courses_with_state1 create_course_states 0 NUM_COURSES_WITH_STATE1 state1 self courses_with_state2 create_course_states NUM_COURSES_WITH_STATE1 NUM_COURSES_WITH_STATE1 NUM_COURSES_WITH_STATE2 state2 self courses_with_state3 create_course_states NUM_COURSES_WITH_STATE1 NUM_COURSES_WITH_STATE2 NUM_COURSES_WITH_STATE1 NUM_COURSES_WITH_STATE2 NUM_COURSES_WITH_STATE3 state3 self course_actions_displayable_states self courses_with_state1 self courses_with_state2 self courses_with_state3 self courses_with_state3_non_displayable create_course_states NUM_COURSES_WITH_STATE1 NUM_COURSES_WITH_STATE2 NUM_COURSES_WITH_STATE3 NUM_COURSES_WITH_STATE1 NUM_COURSES_WITH_STATE2 NUM_COURSES_WITH_STATE3 NUM_COURSES_NON_DISPLAYABLE state3 should_display False for CourseState in self course_actions_displayable_states self courses_with_state3_non_displayable action_class objects update_state CourseState course_key CourseState state should_display CourseState should_display allow_not_found True
returns true if the specified xblock is a vertical that is treated as a unit . a unit is a vertical that is a direct child of a sequential ( aka a subsection ) .,def is_unit xblock parent_xblock None if xblock category vertical if parent_xblock is None parent_xblock get_parent_xblock xblock parent_category parent_xblock category if parent_xblock else None return parent_category sequential return False
"flatten a dict from cls - > [ fields , ... ] and yields values of the form ( cls , fields ) for each entry in the dictionary value .",def flatten class_dict for cls fields_list in class_dict items for fields in fields_list yield cls fields
test if a backend can be remove by setting it to none .,override_settings TRACKING_BACKENDS MULTI_SETTINGS copy def test_django_remove_settings self settings TRACKING_BACKENDS update second None backends self _reload_backends self assertEqual len backends 1
enable verified track cohorting for the default course .,def _enable_verified_track_cohorting self cohort_name None if cohort_name config VerifiedTrackCohortedCourse objects create course_key self course id enabled True verified_cohort_name cohort_name else config VerifiedTrackCohortedCourse objects create course_key self course id enabled True config save
to be called when a new rerun is initiated for the given course by the given user .,def initiated self source_course_key destination_course_key user display_name self update_state course_key destination_course_key new_state self State IN_PROGRESS user user allow_not_found True source_course_key source_course_key display_name display_name
test that a named outer_atomic raises an error only if nested in enable_named_outer_atomic and inside another atomic .,def test_named_outer_atomic_nesting self if connection vendor mysql raise unittest SkipTest Only works on MySQL outer_atomic name abc do_nothing with atomic outer_atomic name abc do_nothing with enable_named_outer_atomic abc outer_atomic name abc do_nothing with atomic outer_atomic name pqr do_nothing with self assertRaisesRegexp TransactionManagementError Cannot be inside an atomic block with atomic outer_atomic name abc do_nothing with enable_named_outer_atomic abc def outer_atomic name def do_nothing with atomic outer_atomic name pqr do_nothing with self assertRaisesRegexp TransactionManagementError Cannot be inside an atomic block with atomic outer_atomic name def do_nothing with self assertRaisesRegexp TransactionManagementError Cannot be inside an atomic block with outer_atomic outer_atomic name def do_nothing with self assertRaisesRegexp TransactionManagementError Cannot be inside an atomic block with atomic outer_atomic name abc do_nothing with self assertRaisesRegexp TransactionManagementError Cannot be inside an atomic block with outer_atomic outer_atomic name abc do_nothing
owners always have permission to make get actions .,def test_has_permission_as_owner_with_get self user UserFactory request RequestFactory get username format user username request user user self assertTrue self permission has_permission request None
"test that the "" no groups "" messages does n't reference enrollment tracks if they are disabled .",override_settings FEATURES FEATURES_WITH_ENROLLMENT_TRACK_DISABLED def test_enrollment_tracks_disabled self self verify_visibility_view_contains self video_location self NO_CONTENT_OR_ENROLLMENT_GROUPS self NO_CONTENT_ENROLLMENT_TRACK_DISABLED self verify_visibility_view_does_not_contain self video_location self NO_CONTENT_ENROLLMENT_TRACK_ENABLED
calls the course api as the specified user and checks the output against a specified set of expected blocks .,def get_blocks_and_check_against_expected self user expected_blocks block_structure get_course_blocks user self course location self transformers self assertEqual set block_structure get_block_keys set self get_block_key_set self blocks expected_blocks
"tests that if we provide mismatched passwords , user is not marked as active .",def test_password_reset_fail self self assertFalse self user is_active url reverse password_reset_confirm kwargs uidb36 self uidb36 token self token request_params new_password1 password1 new_password2 password2 confirm_request self request_factory post url data request_params resp password_reset_confirm_wrapper confirm_request self uidb36 self token self assertEqual resp status_code 200 self assertFalse User objects get pk self user pk is_active
returns the usage key for the given key parameters using the default modulestore,def create_location org course run block_type block_id return modulestore make_course_key org course run make_usage_key block_type block_id
register method to all exporters .,def _export_method self method for exporter in self _exporters args method export_params 0 kwargs method export_params 1 exporter export method args kwargs
authenticate the given username / password against the radius server described by ` server ` .,def _radius_auth self server username password client self _get_client server packet self _get_auth_packet username password client return self _perform_radius_auth client packet
funcg : func changetolocalscope func1 changetoglobalscope,def p_funcg p
time encoding a p - data - tf pdu .,def time_encode_pdata_tf_pdu self for ii in range 1000 self pdata_tf encode
read group options data using my_print_defaults tool .,def _read_group_data self group assert self _tool_path First the required MySQL tool must be found E g use method search_my_print_defaults_tool out_file tempfile TemporaryFile if self _verbosity 0 subprocess call self _tool_path group stdout out_file else null_file open os devnull w b subprocess call self _tool_path group stdout out_file stderr null_file out_file seek 0 results for line in out_file key_value line 2 split 1 if len key_value 2 results append key_value 0 key_value 1 strip elif len key_value 1 results append key_value 0 True else raise UtilError Invalid option value format for group s s group line out_file close if len results self _config_data group dict results else self _config_data group None return self _config_data group
"key < langcode>:<version>:page:<pageid>:categories value list ( category , category , ... )",def page_categories self pageid return self sep join self lc self version page pageid categories
"get a list of quotas , refer to api docs for other key value pairs accepted as params",def quota self kwargs options resolve_names True return self api_call_resumeable GET 1 quota quotas params self _override options kwargs
return train and val iterators for mnist,def mnist_iterator batch_size input_shape get_data GetMNIST_ubyte flat False if len input_shape 3 else True train_dataiter mx io MNISTIter image data train images idx3 ubyte label data train labels idx1 ubyte input_shape input_shape batch_size batch_size shuffle True flat flat val_dataiter mx io MNISTIter image data t10k images idx3 ubyte label data t10k labels idx1 ubyte input_shape input_shape batch_size batch_size flat flat return train_dataiter val_dataiter
split string into 2 or 3 numerical segments,def splitVersion s if not s or type s not in str unicode return None l unicode s split for c in l if not c isnumeric return None if int c 99 return None if len l not in 2 3 return None return l
stop the stratisd simulator and daemon .,def tearDown self self _service tearDown
"returns an object implementing the port interface . if port_name is none , this routine attempts to guess at the most appropriate port on this platform .",def get self port_name None options None kwargs port_name port_name or self _default_port options for port_class in self PORT_CLASSES module_name class_name port_class rsplit 1 module __import__ module_name globals locals 1 cls module __dict__ class_name if port_name startswith cls port_name port_name cls determine_full_port_name self _host options port_name return cls self _host port_name options options kwargs raise NotImplementedError unsupported platform s port_name
make sure we can parse the raises section .,def test_can_parse_raises self docstring n join This has a problem Raises Exception An exception for generic reasons doc Docstring docstring self assertTrue Exception in doc raises_description
header_unit _ : header_unit ' ; ' | header_unit,def p_header_unit_ self p u header_unit_ header_unit n header_unit p 0 p 1
return the state items for the given state name .,def get_state_items self state_name if not state_name in self theme return return self theme state_name
generates lines to add to a cmake file which will set variables,def generate_cmake_file package_name version scripts package_dir pkgs prefix s_SETUP_PY package_name result result append set s_VERSION s prefix version result append set s_SCRIPTS s prefix join scripts locations _get_locations pkgs package_dir for pkgname location in locations items if not in pkgname continue splits pkgname split if splits 1 in msg srv continue parent_name join splits 1 if location locations parent_name raise RuntimeError catkin_export_python does not support setup py files that combine across multiple directories s in s s in s pkgname location parent_name locations parent_name pkgs p for p in pkgs if not in p resolved_pkgs for pkg in pkgs resolved_pkgs os path join locations pkg pkg result append set s_PACKAGES s prefix join pkgs result append set s_PACKAGE_DIRS s prefix join resolved_pkgs replace return result
build ( and cache ) a map { gene_name - > annotation } : return a dictionary { gene_name - > { annotation } },def gene_dict self if self _gene_dict is None cursor connections self _db cursor request SELECT gene chrom transcript_min_start transcript_max_end FROM gene_summary cursor execute request self _gene_dict for r in cursor fetchall symbol r 0 if symbol is None continue symbol symbol lower self _gene_dict setdefault symbol location self _gene_dict symbol location append GenomicRange r 1 int r 2 int r 3 return self _gene_dict
"replace symbolic intervals with hard - wired constants . normally this kind of operations have no intersect to fix , but the method is here so that we can invoke it on any kind of operation .",def fixIntersects self
create a pool key of type `` key_class `` for a request .,def _default_key_normalizer key_class request_context context for key in key_class _fields context key request_context get key context scheme context scheme lower context host context host lower return key_class context
"tries to make passive an active item . returns false if the item is already passive , true otherwise .",def make_passive self item waiting self _passive item next item dot n len waiting waiting add item return len waiting n
use to derive a number that allows to easily recover the public key from the signature,def recoverPubkeyParameter message digest signature pubkey if not isinstance message bytes message bytes message utf 8 for i in range 0 4 if SECP256K1_MODULE secp256k1 sig pubkey ecdsa_recoverable_deserialize signature i p secp256k1 PublicKey pubkey ecdsa_recover message sig if p serialize pubkey serialize return i elif SECP256K1_MODULE cryptography and not isinstance pubkey PublicKey p recover_public_key digest signature i message p_comp hexlify compressedPubkey p pubkey_comp hexlify compressedPubkey pubkey if p_comp pubkey_comp return i else p recover_public_key digest signature i p_comp hexlify compressedPubkey p p_string hexlify p to_string if isinstance pubkey PublicKey pubkey_string bytes repr pubkey latin else pubkey_string hexlify pubkey to_string if p_string pubkey_string or p_comp pubkey_string return i return None
returns words in specified fileids .,_parse_args def raw self fileids None kwargs return concat self _view self add_root fileid mode NKJPCorpusReader RAW_MODE kwargs handle_query for fileid in fileids
wrapper for scipy.stats.skew that returns nan instead of raising error,def _skew a try res stats skew a except ValueError res np nan return res
helper method to get clip_lower from kwds or attribute,def _get_clip_lower self kwds if not clip_lower in kwds clip_lower self clip_lower else clip_lower kwds pop clip_lower return clip_lower kwds
test the user can only put activities as a publisher of which he is in the admin group,def test_update_activity_success self admin_group OrganisationAdminGroupFactory create user OrganisationUserFactory create user__username test1 admin_group organisationuser_set add user self c force_authenticate user user activity iati_factory ActivityFactory create publisher admin_group publisher data iati_identifier WOPA publisher_id activity publisher id res self c put api publishers activities format json format activity publisher id activity id data format json self assertEquals res status_code 200
this is used for navigating concordance results and highlighting hits,def byte_query hit_bytes return join byte d int byte for byte in hit_bytes
return boolean array indicating which elements as binary have a 1 in a specified bit position . input is numpy array .,def binmask arr bit return arr 1 bit 1 1 bit 1
make the hardware make an ok sound,def send_ok_sound self log debug ok sound self send_data comms CMD_SEND_OK
compress frames to the ftp - compatible array and extract sums of intensities per every field .,def compress self frames ftp_array fieldsum compressFrames frames self config deinterlace_order return ftp_array fieldsum
finds sentences that matches the regex_name : param regex_name : name of the regex ex : landlord_money_cover_rent : param nb_of_files : number of files to search through : return : list of sentences that matched this regex,def sentence_finder regex_name nb_of_files regexes get_regexes regex_name count 0 sentences_matched for i in os listdir Path raw_data_directory if count nb_of_files break count 1 file open Path raw_data_directory i r encoding ISO 8859 1 for line in file for reg in regexes if reg search line sentences_matched append line file close return sentences_matched
generate a directory with a file structure for tests,def setup_module module module temp_dir tempfile mkdtemp for i in xrange 0 10 open temp_dir file_ str i a close open temp_dir log_1 log a close open temp_dir log_2 log a close os makedirs str temp_dir subfolder for i in xrange 0 5 open temp_dir subfolder file_ str i a close
"api endpoint that allows category to be viewed . --- response example : return a list of : `` ` { "" i d "" : "" integer "" , "" category_name "" : "" string "" , "" father_category "" : "" string "" } `` `",def list self request response super ProductCategoryViewSet self list request return response
callback function which displays status during initialisation,def initStatus status if status 0 print Supported controller connected blkt set_all 0 0 255 elif status 0 print No supported controller detected for i in range 1 7 blkt set_all 255 0 0 blkt show sleep 0 25 blkt clear blkt show sleep 0 25 else print Waiting for controller format status if status 9 blkt set_pixel status 1 96 0 96 elif status 17 blkt set_pixel status 9 96 96 0 elif status 25 blkt set_pixel status 17 192 40 0 elif status 33 blkt set_pixel status 25 164 2 2 blkt show
should be used to create all remoteversioncontrolservice objects .,def make_remote_vcs self args kwargs kwargs _titan_client self titan_client return RemoteVersionControlService args kwargs
writes an analog value to a pin .,def analogWrite self pin value return request_from url analogWrite self api_key pin value self device_id
"installs the latest updates , updates the kernel and reboots , the instance / host / vm . this function blocks until ssh is available after reboot",retry stop_max_attempt_number 3 wait_fixed 10000 def install_patches self with settings hide running stdout host_string self host_string private_key_filename self private_key log_green self host_string install_os_updates distribution ubuntu14 04 upgrade_kernel_and_grub do_reboot False
"if moren than 1 line or 0 line error will be raised @param includes are include patters ( regular expressions ) @param excludes @return [ linenr , line ]",def find1Line self includes excludes j logger log try to find 1 line which matches the specified includes s excludes s includes excludes 8 result linenr 0 if includes includes if excludes excludes for line in self content split n if j tools code regex matchMultiple includes line and not j tools code regex matchMultiple excludes line result append line linenrfound linenr linefound line linenr 1 if len result 0 raise j exceptions RuntimeError Could not find a line matching s and not matching s in file s includes excludes self filepath if len result 1 raise j exceptions RuntimeError Found more than 1 line matching s includes self filepath return linenrfound linefound
this function uses the http api to get information from racktivity devices .,def getData self addr guid index None count None log None t1 None t2 None fmt None var None url self get_url addr addr guid guid if index is not None url INDEX s str index if count is not None url COUNT s str count if log is not None url LOG s str log if t1 is not None url T1 s str t1 if t2 is not None url T2 s str t2 if fmt is not None url FORMAT s str fmt if var is not None url VAR s str var data self _send_data url return data
retrun ip of this instance of the machine if started .,property def ip self tries 7 if not self _ip for i in range tries for nic in self nics ip nic ip if ip self _ip ip return ip if i tries 1 sleep 5 return self _ip
* * protected * * callback to automatically reload the output spatial object .,def loadTREFileCallback self cliNode unused if cliNode GetStatusString Completed and self currentOutputNode spatialObjectLogic slicer modules spatialobjects logic spatialObjectLogic SetSpatialObject self currentOutputNode cliNode GetParameterAsString outputTubeFile
"return a dictionary of e neuron parameters , using ` no ` : neuron options object .",def getENeuronParams no return V_m no EL_e C_m no taum_e no gL_e t_ref no t_ref_e V_peak no V_peak_e V_reset no Vr_e E_L no EL_e g_L no gL_e Delta_T no deltaT_e V_th no Vt_e E_AMPA no E_AMPA E_GABA_A no E_GABA_A tau_AMPA_fall no tau_AMPA tau_NMDA_fall no tau_NMDA_fall tau_GABA_A_fall no tau_GABA_A_fall tau_AHP no tau_AHP_e E_AHP no E_AHP_e g_AHP_max no g_AHP_e_max g_AHP_ad False I_const no Iext_e_const I_ac_amp no Iext_e_theta I_ac_freq no theta_freq I_ac_phase np pi 2 I_ac_start_t no theta_start_t I_noise_std no noise_sigma V_clamp no Vclamp C_Mg no C_Mg rat_pos_x rat_pos_y
"takes a iterable of iterables ( list of sets from here on ; but any iterable works . ) , and returns the smallest list of sets such that each set , is either a subset , or is disjoint from , each of the input sets .",def classify list_of_sets sort True classifier Classifier sort sort classifier update list_of_sets return classifier getClasses classifier getMapping
set up a localcluster for distributed,def start_cluster diagnostics_port 0 hostname socket gethostname n_workers os cpu_count 2 cluster LocalCluster ip localhost n_workers n_workers diagnostics_port diagnostics_port memory_limit 6000000000 0 client Client cluster params bokeh_port cluster scheduler services bokeh port user getpass getuser scheduler_ip cluster scheduler ip hostname hostname print If the link to the dashboard below doesn t work run this command on a local terminal to set up a SSH tunnel print print ssh N L bokeh_port scheduler_ip bokeh_port hostname nci org au l user format params return client
agarifies a string . source : https://gist.github.com/papyrustheplant/e6a8790dbfce5a8c74193044bbecc5a1,def agarify line add_clan False ulist agar_replace line upper ulist generate_symbols ulist ulist ulist generate_symbols if add_clan ulist agar_clan ulist ulist agar_clan if random randint 1 100 15 else return join chr u for u in ulist
check whether the given path references an xattrs file .,def _is_attr_path self path _ name pathsplit path if name startswith xattrs return True return False
check valueerror raised for an incorectly parameterised request sent to server .,def test_value_error self with pytest raises ValueError response self _client generate_integers 10001 0 10
we are mocking the request so every second call is rate limited .,def runTest self with requests_mock Mocker as m m register_uri GET https api hipchat com v2 user john status_code 200 json self hipchat_callback for i in xrange 3 self hipchat get_user john
create all directories we may need .,def createAllDirs createDirIfNeeded DIR_OUTPUT_BLOCKSTATES createDirIfNeeded DIR_OUTPUT_BLOCKS createDirIfNeeded DIR_OUTPUT_ITEMS
test that io methods raise key error when wrong format is provided .,def test_io_with_wrong_format self ev EventList with pytest raises KeyError ev write ev pickle format_ unsupported with pytest raises KeyError ev read ev pickle format_ unsupported
check if a file exists and its size is > 0,def output_file_exists filename if not file_exists filename util_logger info did not exist s filename return False st stat filename if st stat_module ST_SIZE 0 util_logger info stat size 0 s s os path abspath filename st return False return True
create request string for inverter .,staticmethod def generate_string serial_no response h x02 0 double_hex hex serial_no 2 2 hex_list double_hex i i 2 decode hex for i in reversed range 0 len double_hex 2 cs_count 115 sum ord c for c in hex_list checksum hex cs_count 2 decode hex response join hex_list x01 x00 checksum x16 return response
"program chip with provided list of hex and/or bin files . hex_files is a list of paths to .hex files , and bin_files is a list of tuples with the first value being the path to the .bin file and the second value being the integer starting address for the bin file .",def program self hex_files bin_files commands init reset init halt for f in hex_files f self escape_path os path abspath f commands append flash write_image 0 0 ihex format f for f addr in bin_files f self escape_path os path abspath f commands append flash write_image 0 0x 1 08X bin format f addr commands append reset run commands append exit self run_commands commands
"use python to download the file , even though it can not authenticate the connection .",def download_file_insecure url target src urlopen url try data src read finally src close with open target wb as dst dst write data
make a new param from nested data .,def __init__ self block n base_key n find base_key if base_key and base_key in block get_param_keys n_expanded block get_param base_key _n copy n_expanded update n n n_expanded self _n n self _name n find name self _key n find key value n find value or self _type n find type or raw self _hide n find hide or self _tab_label n find tab or block get_param_tab_labels 0 if not self _tab_label in block get_param_tab_labels block get_param_tab_labels append self _tab_label Element __init__ self block self _options list for option in map lambda o Option param self n o n findall option key option get_key if key in self get_option_keys raise Exception Key s already exists in options key self get_options append option if self is_enum if len set self get_option_keys len self get_options raise Exception Options keys s are not unique self get_option_keys opt_keys self get_options 0 get_opt_keys for option in self get_options if set opt_keys set option get_opt_keys raise Exception Opt keys s are not identical across all options opt_keys self _value value if value or value in self get_option_keys else self get_option_keys 0 if self get_value not in self get_option_keys raise Exception The value s is not in the possible values of s self get_value self get_option_keys else self _value value or self _default value
handle a drag and drop by setting the key to the selection object . this will call the destination handler for drag and drop . only call set when the key is valid to ignore dnd from categories .,def _handle_drag_get_data self widget drag_context selection_data info time key self _get_selected_block_key if key selection_data set selection_data target 8 key
makes a java parm pair .,def _make_java_param_pair self param value sc SparkContext _active_spark_context param self _resolveParam param java_param self _java_obj getParam param name java_value _py2java sc value return java_param w java_value
this function initialise swan model .,def swan_init self input z wID sl distances indices self tree query self xyi k self searchpts z_vals z indices with numpy errstate invalid ignore nz numpy average z_vals weights 1 0 distances axis 1 onIDs numpy where distances 0 0 0 if len onIDs 0 nz onIDs z indices onIDs 0 rZ numpy reshape nz self wnx self wny order F wl input wavelist wID cl input climlist wID wD1 0 wD2 0 if self rank 0 wD1 input waveWd wl cl 2 0 input waveWs wl cl numpy random rand 0 5 wD2 input waveWdd wl cl 2 0 input waveWs wl cl numpy random rand 0 5 wD1 self comm bcast wD1 root 0 wD2 self comm bcast wD2 root 0 swan model init self fcomm input swanFile input swanInfo input swanBot input swanOut rZ input waveWh wl cl input waveWp wl cl wD1 input waveWu wl cl wD2 input waveSide wl cl self res input waveBase sl return
the initialization methods assumes that it will receive two points,def __init__ self start end self points start end
"execute a command , return stdout and stderr in tuple",def cmd cmd logging debug Execute Command s cmd process None try process subprocess Popen cmd shell True stdout subprocess PIPE stderr subprocess PIPE close_fds True return process communicate finally if process is not None process stdout close process stderr close
: parameters : ` display ` : ` ~pyglet.canvas . display ` : attr:`display ` ` x ` : int left edge : attr:`x ` ` y ` : int top edge : attr:`y ` ` width ` : int : attr:`width ` ` height ` : int : attr:`height `,def __init__ self display x y width height self display display Display this screen belongs to self x x Left edge of the screen on the virtual desktop self y y Top edge of the screen on the virtual desktop self width width Width of the screen in pixels self height height Height of the screen in pixels
manage your vagrant libcloud environment .,def main formatter_class argparse RawDescriptionHelpFormatter p argparse ArgumentParser prog libcloud vagrant description main __doc__ strip epilog format_help formatter_class formatter_class p add_argument command metavar cmd type str choices COMMANDS help command to execute args p parse_args logging basicConfig level logging INFO format asctime s name s message s driver get_driver VAGRANT return COMMANDS args command driver
returns a chrome user agent based on a user agent type . this is derived from : https://developers.google.com/chrome/mobile/docs/user-agent,def GetChromeUserAgentArgumentFromType user_agent_type if user_agent_type return user agent s UA_TYPE_MAPPING user_agent_type return
creates an instance of the inputreader for the given state .,classmethod def from_json cls state raise NotImplementedError from_json not implemented in s cls
nicely format a list of line numbers .,def format_lines statements lines pairs i 0 j 0 start None statements sorted statements lines sorted lines while i len statements and j len lines if statements i lines j if start is None start lines j end lines j j 1 elif start pairs append start end start None i 1 if start pairs append start end ret join map nice_pair pairs return ret
returns the package names of all supported browsers .,def get_supported_browsers supported_browsers stable chrome PACKAGE_INFO chrome_stable beta chrome PACKAGE_INFO chrome_beta dev chrome PACKAGE_INFO chrome_dev build chrome PACKAGE_INFO chrome supported_browsers update chrome PACKAGE_INFO return supported_browsers
returns true since limited seek support exists .,def seekable self return True
fetch a valid access token and display it .,def RunWithArgs self scopes credentials FetchCredentials scopes print _Format FLAGS credentials_format lower credentials
"retrieve input ids for collections , normalizing to a list .",def _get_input_ids config ref_uuid config get reference or config get ref out ref_uuid if ref_uuid else input_id config get input or config get inputs if not input_id return out elif isinstance input_id basestring return sorted list set out input_id else assert isinstance input_id list tuple input_id return sorted list set out input_id
"configobject includeurl(configincludecontext context , url what ) ;",def include_url self context what raise NotImplementedError
skip nodes that have already been attempted .,def host_passes self host_state filter_properties retry filter_properties get retry None if not retry LOG debug Re scheduling is disabled return True hosts retry get hosts host host_state host host_state nodename passes host not in hosts if not passes LOG debug Host host s fails Previously tried hosts hosts s host host hosts hosts return passes
logs out storage target through its session i d .,def logout_storage_target self target_iqn targets self _conn_storage MSFT_iSCSITarget NodeAddress target_iqn if targets target targets 0 if target IsConnected sessions self _conn_storage MSFT_iSCSISession TargetNodeAddress target_iqn for session in sessions if session IsPersistent session Unregister target Disconnect
get the devices allocated to one or all requests for an instance .,def get_instance_pci_devs inst request_id None pci_devices inst pci_devices return device for device in pci_devices if device request_id request_id or request_id all
calculate the angular dispersion according to m / sigma / cos beta,def calc_angdisp self beta A calc_angdisp self grating sigma self grating order beta return A
"runs the command list , returning its output .",def GetCommandOutput command devnull open os devnull w proc subprocess Popen command stdout subprocess PIPE stderr devnull bufsize 1 output proc communicate 0 return output
merges a string with a diff in the format that diff_string ( ) produces,def diff_string_merge self first diff result_list prev_marker 0 matches re findall d d diff for match in matches result_list append first prev_marker int match 1 result_list append match 3 prev_marker int match 2 return join result_list
get the activity by matching a string with a similar name .,def get_activity_name self cname dir_class Diving Side diving Kicking Front kicking Run Side running Walk Front walking Golf Swing Back golf_swing Kicking Side kicking SkateBoarding Front skateboarding Golf Swing Front golf_swing Lifting lifting Swing Bench swing_bench Golf Swing Side golf_swing Riding Horse riding_horse Swing SideAngle swing_side return dir_class cname
"returns group name , if used with group start lines",def _getgroupname line return line strip split GRPSTART 1
write blog posts to their permalink locations,def write_permapages site_re re compile bf config site url re IGNORECASE num_posts len blog posts for i post in enumerate blog posts if post permalink path site_re sub post permalink blog logger info u Writing permapage for post 0 format path else blog logger info u Post has no permalink 0 format post title continue env post post posts blog posts if i num_posts 1 env prev_post blog posts i 1 if i 0 env next_post blog posts i 1 bf writer materialize_template permapage mako bf util path_join path index html env
test /info / package with a package,def test_info_packages_with_package self rid self _create_release self _create_package rid name packageOne response self client get info packages packageOne self assert200 response self assertIn packageOne response json
this regression score is the sum of itself + neighbors .,def score_nbr G sum_score 0 for n d in G nodes data True sum_score n for nbr in G neighbors n sum_score nbr return sum_score
push podspecs to cpdc - internal .,def PushPodspecs version_data pods version_data keys pods insert 0 pods pop pods index FirebaseCore tmp_dir tempfile mkdtemp for pod in pods LogOrRun pod cache clean all format pod if pod FirebaseFirestore warnings_ok allow warnings else warnings_ok podspec podspec format pod json os path join tmp_dir json format podspec os system pod ipc spec format podspec json LogOrRun pod repo push format GetCpdcInternal json warnings_ok os system rm rf format tmp_dir
make sure the currently running kernel is specific grsec kernel .,pytest mark skipif os environ get FPF_GRSEC true false reason Need to skip in environment w o grsec def test_grsecurity_kernel_is_running Command c Command uname r assert c stdout endswith grsec assert c stdout 4 4 135 grsec
start a database connection using the connection string : args : connectionstr - this is a rfc 3986 uri ( postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1 & ... ] ) : returns : a connection object - this class also stores it as an instance variable for your convenience .,def connectToDatabase self connectionStr self conn psycopg2 connect connectionStr return self conn
generates a gravatar url for the given email address .,register simple_tag def gravatar_for_email email size None rating None img_url None if img_url and img_url or email return img_url gravatar_url savatar s GRAVATAR_URL_PREFIX _get_gravatar_id email parameters p for p in d img_url or GRAVATAR_DEFAULT_IMAGE s size or GRAVATAR_DEFAULT_SIZE r rating or GRAVATAR_DEFAULT_RATING if p 1 if parameters gravatar_url urllib urlencode parameters doseq True return escape gravatar_url
calls the analytics_data_excel module to create the workbook,def create_excel_workbook data result_info_key identifier_keys workbook analytics_data_excel get_excel_workbook data result_info_key identifier_keys adjust_column_width_workbook workbook return workbook
"checking the environment variable , if found then return it 's value , else raise error",def check_environment_variable var try value os environ var except Exception raise CCPluginError s not defined Please define it in your environment var return value
"reads a ( w)arc record from the stream , returns a tuple ( record , errors ) . either records is null or errors is null . any record - specific errors are contained in the record - errors is only used when * nothing * could be parsed",classmethod def make_parser self raise Exception
try to find * fname * in the dataset directory and return a absolute path .,def datapath fname candidates path abspath path join path dirname __file__ data path abspath path abspath data if DATASET_PATH in os environ candidates append os environ DATASET_PATH for c in candidates c path join c fname if path exists c return c raise IOError Could not find s fname
method to compute the file path for the indicated tile,def process self x_index y_index z_index t_index None return
shuts down single global instance of application .,def close_example_application global _application if _application is not None _application close _application None
return matching serverdescriptions from a list .,def __call__ self server_descriptions secondaries secondary_with_tags_server_selector self tag_sets server_descriptions if secondaries return secondaries else return writable_server_selector server_descriptions
: return : the data for the includeimport,def get_data self return self data
checking that parameters have correct values .,def test_checkParameters self self failUnlessEqual self nice opts long Alpha self failUnlessEqual self nice opts another Beta self failUnlessEqual self nice opts longonly noshort self failUnlessEqual self nice opts shortless Gamma
( internal ) method called by broker .,def sendNextPage self self collector callRemote gotPage self nextPage
configure the twisted mainloop to be run inside the gtk mainloop .,def install reactor GtkReactor from twisted internet main import installReactor installReactor reactor return reactor
return token header to access vault,staticmethod def _get_headers token return X Vault Token token
set the number of error lines .,errors_count setter def errors_count self value self _errors_count value
returns the vector at vector i d ' vec_id ' . raises keyerror if key ' vec_id ' is unknown .,def get_vector self vec_id pass
"get value from config or env , if the value is not in the config , prompt the user for it .",def get_required_value_from_usersettings key env_name if os getenv env_name return os getenv env_name try return config get user_settings key except configparser Error value click prompt 0 format env_name print Adding key and value to config at 0 format config_file_path with open config_file_path a as file file write n 0 1 format key value return value
general pattern reading on an input string,def read_pattern text_str patterns terminate_on_match False postprocess str General pattern reading on an input string Args text_str str the input string to search for patterns patterns dict A dict of patterns e g energy r energy sigma 0 s s d terminate_on_match bool Whether to terminate when there is at least one match in each key in pattern postprocess callable A post processing function to convert all matches Defaults to str i e no change Renders accessible Any attribute in patterns For example energy r energy sigma 0 s s d will set the value of matches energy 1234 3453 to the results from regex and postprocess Note that the returned values are lists of lists because you can grep multiple items on one line compiled key re compile pattern re MULTILINE re DOTALL for key pattern in patterns items matches defaultdict list for key pattern in compiled items for match in pattern finditer text_str matches key append postprocess i for i in match groups if terminate_on_match break return matches
transmit a chosen code string using the gpio transmitter,def transmit_code code GPIO setmode GPIO BCM GPIO setup TRANSMIT_PIN GPIO OUT for t in range NUM_ATTEMPTS for i in code if i 1 GPIO output TRANSMIT_PIN 1 time sleep short_delay GPIO output TRANSMIT_PIN 0 time sleep long_delay elif i 0 GPIO output TRANSMIT_PIN 1 time sleep long_delay GPIO output TRANSMIT_PIN 0 time sleep short_delay else continue GPIO output TRANSMIT_PIN 0 time sleep extended_delay GPIO cleanup
"takes a string query , an httprequest , and an optional application name . returns a list of results . results are dictionaries with keys having the meanings given in the documentation at ref / apps / search .",def perform_search self request query application None raise NotImplementedException
register observer with the global logpublisher,def begin_or_register observer redirectStandardIO False kwargs global began_logging if not began_logging globalLogBeginner beginLoggingTo observer redirectStandardIO redirectStandardIO kwargs began_logging True else globalLogPublisher addObserver observer
minimize ( x - x0)**2 / 2 with respect to x.,def _minimize self initial_val loss_grad_func step_callback optimizer_kwargs unused_kwargs for _ in range self NUM_LOSS_CALLS loss_grad_func initial_val for _ in range self NUM_STEP_CALLS step_callback initial_val _ grad loss_grad_func initial_val return initial_val grad
rnn decoder that creates training and sampling sub - graphs .,def rnn_decoder decoder_inputs initial_state cell scope None with vs variable_scope scope or dnn_decoder states sampling_states initial_state initial_state outputs sampling_outputs with ops op_scope decoder_inputs initial_state training for i inp in enumerate decoder_inputs if i 0 vs get_variable_scope reuse_variables output new_state cell inp states 1 outputs append output states append new_state with ops op_scope initial_state sampling for i _ in enumerate decoder_inputs if i 0 sampling_outputs append outputs i sampling_states append states i else sampling_output sampling_state cell sampling_outputs 1 sampling_states 1 sampling_outputs append sampling_output sampling_states append sampling_state return outputs states sampling_outputs sampling_states
writes a mapping file between archive file to associated objc source files .,def WriteArchiveSourceMappingFile compiled_archive_file_path output_archive_source_mapping_file translated_source_files objc_file_path file_open open with file_open output_archive_source_mapping_file w as f for translated_source_file in translated_source_files split file_path os path relpath translated_source_file objc_file_path f write compiled_archive_file_path file_path n
log cdf of observations ` x ` under these gamma distribution(s ) .,def log_cdf self x name log_cdf with ops name_scope self name with ops op_scope self _alpha self _beta x name x ops convert_to_tensor x x control_flow_ops with_dependencies check_ops assert_positive x if self validate_args else x contrib_tensor_util assert_same_float_dtype tensors x dtype self dtype return math_ops log math_ops igamma self _alpha self _beta x
main function of vectorization for neural network,def prepare_problem vectorizer task_type train_table test_table etalon_table message_settings features_settings utils load_embeddings features Features TwitterMessageParser message_settings task_type features_settings term_vocabulary TermVocabulary doc_vocabulary DocVocabulary train_problem utils create_problem task_type train train_table vectorizer features term_vocabulary doc_vocabulary message_settings test_problem utils create_problem task_type test test_table vectorizer features term_vocabulary doc_vocabulary message_settings return train_problem test_problem
some fields are optional and may not exist ; parsing should not crash if / when they are not available .,def test_parsing_may_encounter_field_which_does_not_exist self data x97A x00 x13 xa2 x00 oG xe4v x1aIS x01 info self zigbee _split_response data expected_info id remote_at_response frame_id A source_addr_long x00 x13 xa2 x00 oG xe4 source_addr v x1a command IS status x01 self assertEqual info expected_info
take an irc message already decoded from utf-8/latin1 etc and replace typical binary irc color code formatting with pango markup .,def formatting_to_pango_markup msg msg decode msg msg re sub amp msg msg re sub lt msg msg re sub gt msg class MarkupFunctor object def __init__ self self match_found False self bold False self underline False self fg_color 1 self bg_color 1 self italic False def __call__ self match function call operator called by regex replace upon the finding of a match in msg sring if match groupdict reset is not None self bold False self underline False self fg_color 1 self bg_color 1 self italic False if match groupdict reverse is not None c self bg_color self bg_color self fg_color self fg_color c if match groupdict bold is not None self bold not self bold if match groupdict underline is not None self underline not self underline if match groupdict italic is not None self italic not self italic if match groupdict color is not None if match groupdict fg is not None self fg_color int match groupdict fg if match groupdict bg is not None self bg_color int match groupdict bg if match groupdict fg is None and match groupdict bg is None self fg_color 1 self bg_color 1 output if not self match_found self match_found True output span else output span span if self bold output weight bold if self underline output underline single if self italic output style italic if self fg_color 0 output color color_code_to_X11 self fg_color if self bg_color 0 output background color_code_to_X11 self bg_color output return output regex P reset x0f P underline x1f P bold x02 P italic x1d P reverse x12 P color x03 P fg d 1 2 P bg d 1 2 markup_transform MarkupFunctor msg re sub regex markup_transform msg if markup_transform match_found msg span return msg
install a container and exit the module .,def do_install module container image values_list rc out err changed _install module container image values_list if rc 0 module fail_json rc rc msg err else module exit_json msg out changed changed
return from_literal in a string ready for cli,def from_literal_to_params self return from literal format key value for key value in self from_literal items
explicitly kill the running ssh - agent,def kill self self cleanup
gathers the docker storage disk usage stats and puts them in a dto .,def get_disk_usage self dds DockerDiskStats if not self is_devicemapper and not self is_loopback return dds dds data_space_used DockerUtil convert_to_size_in_gb self _get_driver_status_attr Data Space Used dds data_space_available DockerUtil convert_to_size_in_gb self _get_driver_status_attr Data Space Available dds data_space_total DockerUtil convert_to_size_in_gb self _get_driver_status_attr Data Space Total dds metadata_space_used DockerUtil convert_to_size_in_gb self _get_driver_status_attr Metadata Space Used dds metadata_space_available DockerUtil convert_to_size_in_gb self _get_driver_status_attr Metadata Space Available dds metadata_space_total DockerUtil convert_to_size_in_gb self _get_driver_status_attr Metadata Space Total if not self is_loopback dds data_space_total dds data_space_used dds data_space_available dds metadata_space_total dds metadata_space_used dds metadata_space_available dds data_space_percent_available dds data_space_available dds data_space_total 100 dds metadata_space_percent_available dds metadata_space_available dds metadata_space_total 100 return dds
return only heartbeat metrics from the list,staticmethod def filter_heartbeat_metrics metrics return m for m in metrics if m key heartbeat
generator yields parsed json for each item passed in config_data .,def parse_configs config_data for input_data input_path in config_data try yield json loads input_data except ValueError raise exc ConfigException Could not parse metadata file s input_path
: param name : next scene to invoke . defaults to next in the list .,def __init__ self name None u n param name Next Scene to invoke Defaults to next in the list n super NextScene self __init__ self _name name
"verifying the _ e. coli_-ness of the genome files : param fasta_files : [ ] of all fasta files : param ofiles : [ ] of all non - fasta files : param args : command line arguments : param temp_dir : ectyper run temp_dir : return : ( [ ecoli_genomes ] , { file : species } )",def verify_ecoli fasta_files ofiles args temp_dir ecoli_files other_files for f in fasta_files if args verify if is_ecoli f temp_dir ecoli_files append f elif args refseq other_files f get_species f args else other_files f Failed E coli species confirmation else ecoli_files append f for bf in ofiles other_files bf Non fasta fastq file return ecoli_files other_files
save a notebook to an os_path .,def _save_notebook self os_path nb with self atomic_writing os_path encoding utf 8 as f if file_type os_path notebook nbformat write nb f version nbformat NO_CONVERT elif file_type os_path yaml yml nb_to_yaml nb f write yml
existing role handles are not allowed,def test_existing_handle_fails self role self create_role validator validators UniqueRoleHandle error validator validate role handle self assertTrue error
utility function for the zeromqlogrecord .,def _getCallingContext frames inspect stack if len frames 4 context frames 5 else context frames 0 modname context 1 lineno context 2 if context 3 funcname context 3 else funcname del context del frames return modname funcname lineno
check if ( in given protein ) there is given residue on given position .,def is_sequence_broken protein test_pos test_res test_alt None if len protein sequence int test_pos return protein refseq test_res str test_pos test_alt else ref_in_db protein sequence int test_pos 1 if test_res ref_in_db return False return protein refseq ref_in_db test_res str test_pos test_alt
"robust exponential volatility calculation , assuming daily series of prices we apply an absolute minimum level of vol ( absmin ) ; and a volfloor based on lowest vol over recent history",def robust_vol_calc x days 35 min_periods 10 vol_abs_min 1e 10 vol_floor True floor_min_quant 0 05 floor_min_periods 100 floor_days 500 vol x ewm adjust True span days min_periods min_periods std vol vol vol_abs_min vol_abs_min if vol_floor vol_min vol rolling min_periods floor_min_periods window floor_days quantile quantile floor_min_quant vol_min at vol_min index 0 0 0 vol_min vol_min ffill vol_with_min pd concat vol vol_min axis 1 vol_floored vol_with_min max axis 1 skipna False else vol_floored vol return vol_floored
read and extract data from a file : param filepath file ot read,def readFile self filepath abspath filepath if not path isabs filepath abspath path join path dirname path abspath __file__ filepath f open abspath r lines f readlines f close data for l in lines 1 l l strip l l replace t while l find 1 l l replace fields l split try data append map float fields except continue return map list zip data
visit the whole module and add all import at the top level .,def visit_Module self node node body k for k in self visit n for n in node body if k imports ast Import ast alias i mangle i for i in self imports node body imports node body ast fix_missing_locations node return node
"creates a ( python ) generator for bayesian network evidence for households that yields ( serial number , evidence , segment , tract , count )",staticmethod def _extract_household_evidence allocated_rows fields segmenter _ u Creates a python generator for bayesian network evidence for households that yields n serial number evidence segment tract count n for _ row in allocated_rows iterrows serialno row inputs SERIAL_NUMBER name evidence tuple field row field for field in fields segment segmenter row yield serialno evidence segment row inputs TRACT name row u count
called by the group object so it can see the updated_at from the group,def _get_group_data self return self _block_for_response pkt_type protocol TYPE_GETGROUP
"return the program name and argv of the process that would be executed by run_program(program_string , command_template ) .",def get_run_program program_string command_template None env bld env if command_template in None s argv shlex split program_string program_name argv 0 try program_obj find_program program_name env except ValueError as ex raise WafError str ex program_node program_obj path find_or_declare program_obj target execvec program_node abspath argv 1 else program_name program_string try program_obj find_program program_name env except ValueError as ex raise WafError str ex program_node program_obj path find_or_declare program_obj target tmpl command_template program_node abspath execvec shlex split tmpl replace return program_name execvec
retrieve a cell bucket from the index .,def get_cell self cell raise NotImplementedError
main information to built the regions .,def __init__ self polygons regions_id None self multiple None self _initialization self borders polygons if regions_id is None self regions_id np arange len polygons else self regions_id regions_id self regionlocs self map_regionid2regionlocs self limits self compute_limits
construct a new oauth 2 authorization object .,def __init__ self client_id None client None token None u Construct a new OAuth 2 authorization object n n param client_id Client id obtained during registration n param client class oauthlib oauth2 Client to be used Default is n WebApplicationClient which is useful for any n hosted application but not mobile or desktop n param token Token dictionary must include access_token n and token_type n self _client client or WebApplicationClient client_id token token if token for k v in token items setattr self _client k v
get current playlist i d from user data,def get_current_playlist_id self userdata self get_user_storage if current_playlist not in userdata return None return int userdata current_playlist
return true if the video stream is in good condition .,def _is_video_ok self try return self _axis _api is_video_ok except IOError as e rospy logerr repr e return False
make sure that the request looks good before processing .,def IsValidLocalRequest self host self request headers Host try caller_host _ host split except caller_host host if caller_host localhost or caller_host 127 0 0 1 self ShowUri host return True return False
test globe file is same as gold standard .,def TestGlcFiles unpacker if unpacker ReadFile earth info txt ReadGoldStandard gold_glc_info txt print Did not match earth info txt return False if unpacker ReadFile earth layer_info txt ReadGoldStandard gold_glc_layer_info txt print Did not match earth info txt return False return True
test that a logged in user can view the edit evidence form .,def test_can_show_edit_form self self evidence Evidence objects create board self board creator self user evidence_desc Evidence 1 event_date None self login response self client get reverse openach edit_evidence args self evidence id self assertEqual response status_code 200 self assertTemplateUsed response boards edit_evidence html
test that the given model_class actually reads from the given database,pytest mark parametrize model_class database EXPORT_TEST_MODEL_CLASS default SIERRA_TEST_MODEL_CLASS sierra def test_db_read_routing model_class database queryset model_class objects all assert queryset db database
create a model with the values according to the values dictionary,abstractmethod def create self values args kwargs u n Create a model with the values according to the values dictionary n n param dict values A dictionary of values to create the model according to n return The dictionary of arguments that should be returned by the serializer n rtype dict n pass
save the current memory into a file in numpy format : param out_file : file storage path : return :,def save self out_file np savez_compressed out_file states self _states actions self _actions rewards self _rewards terminals self _terminals
"read 32-bits from the specified ` offset ` in bytes , relative to the base physical address of the mmio region .",def read32 self offset if not isinstance offset int long raise TypeError Invalid offset type should be integer offset self _adjust_offset offset self _validate_offset offset 4 return struct unpack L self mapping offset offset 4 0
test add scalar single - fp values,def test_addss self self feed addss xmm13 xmm9 self feed addss xmm6 r11 1000 self check f3450f58e9 f3410f58b3e8030000
lexing and parsing stage ( phase 1 ),def do_parse self src context tokens self lexer lex src self parser parse_source tokens context
renders the headers for this request field .,def render_headers self lines sort_keys Content Disposition Content Type Content Location for sort_key in sort_keys if self headers get sort_key False lines append s s sort_key self headers sort_key for header_name header_value in self headers items if header_name not in sort_keys if header_value lines append s s header_name header_value lines append r n return r n join lines
: param repo_name : github repo url : param author : the author of the commit : param mail : the mail of the author of the commit : return : none,def github_plugin repo_name author mail tmp_dir tempfile mkdtemp print a temp dir has been created tmp_dir if not tmp_dir print Error occurred in creating temp dir for cloning the repository return repo git Repo clone_from repo_name tmp_dir dir_walk tmp_dir if repo is_dirty repo git add update True index repo index author git Actor author mail index commit since author adding author author committer author origin repo remote try origin push print Git pushed successfully to github repo except Exception as e print str e shutil rmtree tmp_dir ignore_errors True
provides the reply portion of email .,staticmethod def parse_reply text return EmailReplyParser read text reply
set amsdu_aggregation without sending out anything .,def set_amsdu_aggregation self amsdu_aggregation self _amsdu_aggregation bool amsdu_aggregation
"verify that ` handle_result ` can modify the return values of the worker , such that other dependencies see the updated values .",def test_handle_result container_factory rabbit_manager rabbit_config rpc_proxy container container_factory ExampleService rabbit_config container start assert rpc_proxy echo hello hello with entrypoint_waiter container unserializable with pytest raises RemoteError as exc rpc_proxy unserializable assert is not JSON serializable in str exc value assert worker_result_called hello None something went wrong TypeError ANY ANY
returns true if challenge vault supports message protection,def supports_message_protection self return self supports_pop and self server_encryption_key and self server_signature_key
"! @brief add us , tau and dmax and eventually frotp variable objects to the list @param available_vars < [ variable ] > : the target list @param known_vars < [ str ] > : known variables ids",def new_variables_from_US known_vars new_vars US TAU DMAX if MU in known_vars new_vars append FROTP return new_vars
add a hex value type to a signature with a specific name . the name is used in the condition but also to provide conext to how / what the value is,def add_named_hex self name value count 0 ex False for i in self __signature _named_hex if i value value ex True if not ex self __signature _named_hex append name str name value self __cleanup_value value count count
get ancestor elements of a doctype with a tree structure,def get_ancestors_of doctype name u lft rgt frappe db get_value doctype name u lft u rgt result frappe db sql_list u select name from tab s n t twhere lft s and rgt s order by lft desc doctype u s u s lft rgt return result or
": param name : a friendly name to call this plugin . example : "" gedcom import "" : type name : string : param description : a short description of the plugin . example : "" this plugin will import a gedcom file into a database "" : type description : string : param module_name : the name of the module that contains this plugin . example : "" gedcom "" : type module_name : string : return : nothing",def __init__ self name description module_name self __name name self __desc description self __mod_name module_name
"returns a list of temple codes , temple name tuples",def name_code_data self return sorted code name for name code in self __temple_codes items key lambda v v 1
make the default output style for the custom text report .,def make_default_style self default_style font FontStyle font set face FONT_SANS_SERIF size 12 bold 0 italic 0 para ParagraphStyle para set_font font para set_alignment PARA_ALIGN_CENTER para set pad 0 5 para set_description _ The style used for the first portion of the custom text default_style add_paragraph_style CBT Initial para font FontStyle font set face FONT_SANS_SERIF size 12 bold 0 italic 0 para ParagraphStyle para set_font font para set pad 0 5 para set_alignment PARA_ALIGN_CENTER para set_description _ The style used for the middle portion of the custom text default_style add_paragraph_style CBT Middle para font FontStyle font set face FONT_SANS_SERIF size 12 bold 0 italic 0 para ParagraphStyle para set_font font para set_alignment PARA_ALIGN_CENTER para set pad 0 5 para set_description _ The style used for the last portion of the custom text default_style add_paragraph_style CBT Final para
"return the list of ( classname , handle ) tuples for all directly referenced primary objects .",def get_referenced_handles self return self get_referenced_note_handles self get_referenced_citation_handles
"od.iteritems - > an iterator over the ( key , value ) items in od",def iteritems self for k in self yield k self k
"create a neuron with three levels of branching , each level getting "" bushier "" . each final branch synapses onto another neuron .",def example2 import random neuronX network createNeuron name X leaves neuronX for branchLevel in range 3 oldLeaves list leaves leaves for leaf in oldLeaves for branch in range 2 branchLevel 1 leaves leaf extendNeurite for leaf in leaves if random choice True False leaf synapseOn network createNeuron else network createNeuron synapseOn leaf
initializes a * * base * * api object . primarily acts as an interface for all child object to use .,def __init__ self object_type if not object_type raise ValueError API Object requires object_type to be passed for s format self __class__ __name__ self session None self object_type object_type self base_url GuildWars2Client BASE_URL self version GuildWars2Client VERSION
test italic and bold text .,def test_bold_and_italic self expected bold and italic text self assertEqual expected md gen_italic md gen_bold bold and italic text self assertEqual expected md gen_bold md gen_italic bold and italic text expected asterisks and _underscores_ self assertEqual expected md gen_bold asterisks and md gen_italic underscores True
tests data integrity of containers / images / services number in projects dashboard 's status boxes . steps : * go to projects / dashboard view * compare the data in the status boxes to api data forz containers / images / services numbers,pytest mark polarion CMP 10805 def test_projects_dashboard_icons provider appliance soft_assert container_project_instance api_values get_api_object_counts appliance PROJECT_NAME provider view navigate_to container_project_instance Dashboard for containers_cls in api_values keys statusbox_value getattr view containers_cls PLURAL split 1 lower value soft_assert api_values containers_cls statusbox_value There is a mismatch between API and UI values API UI format containers_cls __name__ api_values containers_cls statusbox_value
test date is converted to a good human format,def test_date_filter self template load mfl_none_filter attribute mfl_bool_none_date_filter context Context attribute 2015 11 09 tpl Template template val tpl render context self assertEqual val 2015 11 9
object / edit mode update the object .,def bmesh_to_object obj bm me obj data is_editmode obj mode EDIT if is_editmode bmesh update_edit_mesh me True else bm to_mesh me if me vertices me vertices 0 co 0 me vertices 0 co 0
"test the "" in "" operator for safe references ( cmp )",def testIn self for t in self ts 50 self assert_ safeRef t x in self ss
returns the number of items left in iteration .,property def remaining self return len self _iter
"get the item , but also makes it most recent .",def __getitem__ self key u Get the item but also makes it most recent n _super typing cast OrderedDict super LRUCache self value _super __getitem__ key _super __delitem__ key _super __setitem__ key value return value
returns a list of strings describing all available navigator items,def list_all_items self return self _navigator_io list_signal_names
returns `` true `` if the input filename ` fn ` ends with an xml extension .,def is_xml fn return os path isfile fn and fn lower endswith xml
get the eval rule from the global context and create a partial method from it and the specified argument from the configuration .,def preprocess self ruleset super EvalRule self preprocess ruleset try method ruleset ctxt eval_rules self eval_rule_name except KeyError raise oa errors InvalidRule self name Undefined eval rule referenced s self eval_rule_name self eval_rule EvalMethod method self eval_args self target
test converting postgresql dbi to alchemy,def test_sqlite self expected sqlite path spamassassin db dsn DBI SQLite dbname path spamassassin db user password result oa plugins base dbi_to_alchemy dsn user password self assertEqual result expected
derive selectable with a postgis point in 4326 projection derived from either the latitude and longitude columns or single location column,def _geom_col self t self staging d self dataset if d lat and d lon geom_col func ST_SetSRID func ST_Point t c d lon t c d lat 4326 label geom elif d loc geom_col func point_from_loc t c d loc label geom else msg Staging table does not have geometry information raise PlenarioETLError msg return geom_col
test that the header written to a file,def test_write_header self writer RecordModelWriter self csv_columns writer write_header self outfile self assertEqual self outfile getvalue test1 test2 r n
translates a timedelta object to exact days,def _getFloatDays self delta days seconds delta days delta seconds hours seconds 3600 minutes seconds 3600 60 seconds seconds 60 return days hours 24 0 minutes 60 0 24 0 seconds 60 0 60 0 24 0
a wrapper for posting things . it will also json encode your ' data ' parameter,def _post self args kwargs if data in kwargs kwargs data json dumps kwargs data response requests post args kwargs response raise_for_status
"solve a system of linear equations , using lu decomposition .",def solve_lu A P B options MATPROP NONE X Array safe_call backend get af_solve_lu c_pointer X arr A arr P arr B arr options value return X
check if the number is a valid bsn .,def is_valid number try return bool validate number except ValidationError return False
find a single html element using jquery - style selectors .,def find_element_by_jquery step browser selector elements find_elements_by_jquery browser selector assert_true step len elements 0 return elements 0
load points from multiple files to a feature class .,def load_points_from_multiple_files workspace in_point_files out_points_name spatial_reference in_x_field in_y_field in_z_field decimal_separator logger debug Split the input point files in_point_files in_point_files split logger info Splitting input files finished successfully count_files 1 point_feature_classes for in_file in in_point_files logger info Start function load_points to load the points from the input files The current input file is in_file try in_points load_points workspace in_file out_points_name str count_files spatial_reference in_x_field in_y_field in_z_field decimal_separator except arcpy ExecuteError logger warning out_points_name str count_files already exists Change name to out_points_name m_in_file_ str count_files and delete a same named file if necessary if arcpy Exists out_points_name m_in_file_ str count_files arcpy Delete_management out_points_name m_in_file_ str count_files in_points load_points workspace in_file out_points_name m_in_file_ str count_files spatial_reference in_x_field in_y_field in_z_field decimal_separator point_feature_classes append in_points count_files count_files 1 logger info Load_points finished successfully logger debug Merge point files try out_points workspace out_points_name arcpy Merge_management point_feature_classes out_points except arcpy ExecuteError logger warning out_points already exists Change output name out_points time strftime d m y_ H M S out_points out_points time strftime d m y_ H M S arcpy Merge_management point_feature_classes out_points logger info Merging point files finished successfully logger debug Delete the input files for feature_class in point_feature_classes arcpy Delete_management feature_class logger info Deleting the input files finished successfully return out_points
admin emails should not be hijacked .,def test_send_to_admins self u emails EmailMessage u Subject u Content u from example com u admin example com num_sent self get_connection send_messages emails self assertEqual len emails num_sent messages self get_mailbox_content self assertEqual len messages num_sent message messages 0 self assertEqual message get_all u to u admin example com
save a book from a data source to another one,append_doc docs ISAVE_BOOK_AS def isave_book_as keywords dest_keywords source_keywords _split_keywords keywords book sources get_book_stream on_demand True source_keywords return sources save_book book dest_keywords
calculate the cost of exchanging two arcs in a tour .,def exchange_cost tour i j D n len tour a b tour i tour i 1 n c d tour j tour j 1 n return D a c D b d D a b D c d
validate a combination of parameters .,def test_basic_parameters self click group click option param envvar PARAM help A sample option click argument ARG envvar ARG def cli A sample command group pass ctx click Context cli info_name cli output list ext _format_command ctx show_nested False self assertEqual textwrap dedent A sample command group program cli code block shell cli OPTIONS ARG COMMAND ARGS rubric Options option param param A sample option rubric Arguments option ARG Required argument rubric Environment variables envvar PARAM Provide a default for option param envvar ARG Provide a default for option ARG lstrip n join output
takes the returned dictionary from get_data ( ) and convert the information into csv file and then save the csv file in housing - insights / data / processed / zoneunitcount as zoneunitcount_2017 - 05 - 30.csv .,def get_csv self if not os path exists data processed zoneUnitCount os makedirs data processed zoneUnitCount data_processed_zoneUnitCount os path join PYTHON_PATH os pardir data processed zoneUnitCount zone_data self get_data toCSV date datetime date today strftime Y m d filename os path join data_processed_zoneUnitCount zoneUnitCount_ date csv for key value in zone_data items toCSV extend value keys toCSV 0 keys with open filename w as output_file dict_writer csv DictWriter output_file keys dict_writer writeheader dict_writer writerows toCSV
returns a list of populated apps,def get_data self include_static_builds True include_dynamic_builds True app_include_list None include_sandboxes False apps self _get_apps if app_include_list apps app for app in apps if app name in app_include_list for app in apps app_info self _get_app_info app id app business_unit app_info business_unit builds self _get_builds app id include_static_builds include_dynamic_builds app builds build for build in builds if self build_tools build_should_be_processed app id build id build policy_updated_date for build in app builds analysis_unit_attrib self _get_build_info app id build id find analysis_unit attrib if published_date in analysis_unit_attrib published_date_string analysis_unit_attrib published_date 22 analysis_unit_attrib published_date 23 build published_date parser parse published_date_string astimezone pytz utc build policy_updated_date build published_date if build type static build flaws build analysis_size_bytes self _get_flaws build id build type else build flaws self _get_flaws build id build type if include_sandboxes app sandboxes self _get_sandboxes app id for sandbox in app sandboxes sandbox builds self _get_builds app id include_static_builds include_dynamic_builds sandbox id for build in sandbox builds analysis_unit_attrib self _get_build_info app id build id sandbox id find analysis_unit attrib if published_date in analysis_unit_attrib published_date_string analysis_unit_attrib published_date 22 analysis_unit_attrib published_date 23 build published_date parser parse published_date_string astimezone pytz utc build flaws build analysis_size_bytes self _get_flaws build id build type return apps
challenge report uses the same template as challenge only without submission form .,require_GET user_id_staff_required def challenge_report request user slug challenge get_object_or_404 Challenge slug slug if not challenge has_view_report_permission request for_user user return HttpResponseForbidden contest challenge contest submission score challenge get_submission_score user public_submissions Submission objects filter challenge challenge is_public True return render_to_response onlinejudge challenge_report html user user contest contest challenge challenge score score submission submission public_submissions public_submissions RequestContext request
"given a model name as `` app_label . modelname `` , returns the django model .",def get_model model try if isinstance model str app_label model_name model split 1 m loading get_model app_label model_name if not m raise LookupError return m elif issubclass model models Model return model except LookupError ValueError pass raise ValueError model
tries to connect to the http server at /status path and specified port to see if it responds successfully .,def is_url_connectable port try from urllib import request as url_request except ImportError import urllib2 as url_request try res url_request urlopen http 127 0 0 1 s status port if res getcode 200 return True else return False except return False
processing on i{node } has ended . @param content : the current content being unmarshalled . @type content : l{content },def end self content pass
parse data form a text file,def parseData file_name delimiter None header_size 0 col_types None ret_array False with open file_name as f for i in range header_size next f data_list for line in f line line replace n replace r if delimiter is None line line split else line line split delimiter if col_types is not None if not isinstance col_types list col_types col_types len line if len line len col_types for i tp entry in enumerate zip col_types line line i tp entry data_list append line if ret_array data_list np array data_list return data_list
decorator that allows access roles to be registered within the roles module and referenced by their string values .,def register_access_role cls try role_name cls ROLE REGISTERED_ACCESS_ROLES role_name cls except AttributeError log exception u Unable to register Access Role with attribute ROLE return cls
update the settings for the twitter third party auth provider / backend,classmethod def configure_twitter_provider cls kwargs kwargs setdefault name Twitter kwargs setdefault backend_name twitter kwargs setdefault icon_class fa twitter kwargs setdefault key test kwargs setdefault secret test return cls configure_oauth_provider kwargs
"parameters to pass in to the query . each element of the tuple will be substituted in to the corresponding ? parameter locator in the query . the first element will replace the first question mark , the second will replace the second etc .",property def query_parameters self return tuple
"can be set , to change the preferred quality of image smoothing . unknown values are ignored .",imageSmoothingQuality setter def imageSmoothingQuality self val if val in low medium high self _imageSmoothingQuality val
"the sum of all coordinates adds up to zero . by taking the absolute value and summing them , you get twice the total distance between two coords .",def distance_to self sector return int sum abs x for x in tuple map operator sub self coordinates sector 2
validates that the code has not expired yet . returns bool,def is_code_valid timestamp exp_window CODE_EXPIRATION now arrow utcnow entry_time arrow get timestamp exp_time entry_time replace seconds exp_window if now exp_time return True else return False
: param instmt : instrument : param raw : raw data in json : return :,classmethod def parse_trade cls instmt raw trade Trade keys list raw keys if cls get_trades_timestamp_field_name in keys and cls get_trade_id_field_name in keys and cls get_trade_side_field_name in keys and cls get_trade_price_field_name in keys and cls get_trade_volume_field_name in keys timestamp raw cls get_trades_timestamp_field_name timestamp timestamp replace T replace Z replace trade date_time timestamp trade trade_side Trade parse_side raw cls get_trade_side_field_name trade trade_id raw cls get_trade_id_field_name trade trade_price raw cls get_trade_price_field_name trade trade_volume raw cls get_trade_volume_field_name else raise Exception Does not contain trade keys in instmt s s nOriginal n s instmt get_exchange_name instmt get_instmt_name raw return trade
test of partial matching in logging test harness .,def test_partial self self logger debug This won t show up self logger info Neither will this self logger warning But this will h self handler self assertTrue h matches msg ut th self assertTrue h matches message ut th self assertFalse h matches message either self assertFalse h matches message won t
"returns ( value , error_msg ) , where error_msg is not none if there was problem",def get_value_with_check self try return self get_value None except return None self _error_msg
builds input columns for use with tensorflow estimator .,def build_input_columns embedding_dim embedding_vocab_file categorical tf feature_column categorical_column_with_vocabulary_file key cpc4 vocabulary_file embedding_vocab_file num_oov_buckets 1 cpc_embedding tf feature_column embedding_column categorical_column categorical dimension embedding_dim numeric_columns tf feature_column numeric_column k for k in FEATURE_NAMES return cpc_embedding numeric_columns
initialize this instance with the root and a git command,def __init__ self root_path git super GitCmdObjectDB self __init__ root_path self _git git
: return : read - only contents of the file represented by the file descriptor fd,def file_contents_ro fd stream False allow_mmap True try if allow_mmap try return mmap mmap fd 0 access mmap ACCESS_READ except EnvironmentError return mmap mmap fd os fstat fd st_size access mmap ACCESS_READ except OSError pass contents os read fd os fstat fd st_size if stream return _RandomAccessBytesIO contents return contents
takes a base64 string and saves it out as an .ovpn file,def write_openvpn_file self b64ovpndata vpnname openvpnconfigpath vpnconfigs vpnconfig_ 0 ovpn format vpnname decoded_ovpndata b64ovpndata decode base64 Utils create_directory_path openvpnconfigpath fh open openvpnconfigpath wb fh write decoded_ovpndata fh write script security 2 up etc openvpn update resolv conf down etc openvpn update resolv conf fh close return self grab_ovpn_values openvpnconfigpath
"abstract class for learning agents , such as running reinforcement learning neural nets against pygame games .",def __init__ self force_game_fps 10 run_real_time False pass_quit_event True self force_game_fps force_game_fps Fixes the pygame timer functions so the ai will get input as if it were running at this fps self run_real_time run_real_time If True the game will actually run at the force_game_fps speed self pass_quit_event pass_quit_event Decides whether the quit event should be passed on to the game self _keys_pressed self _last_keys_pressed self _playing False self _default_flip pygame display flip self _default_update pygame display update self _default_event_get pygame event get self _default_time_clock pygame time Clock self _default_get_ticks pygame time get_ticks self _game_time 0 0
helper to get and a proper dict iterator with py2k and py3k,def _iterator self d try return d iteritems except AttributeError return d items
process a stackexchange posts.xml into a dictionary of objects .,click option ifile help StackExchange posts file click option ofile help Output pickle file def main ifile ofile if ifile is None or ofile is None print Make sure you have used the command line arguments print t ifile for the input file location print t ofile for the output file location sys exit 1 with open ofile wb as output_handle database parse_xml ifile pickle dump database output_handle 2
"we ignore max_pages , because you ca n't regex - search that under batoto .",def downloadChapter self downloadThread max_pages url manga_chapter_prefix current_chapter s getSourceCode url self proxy soup BeautifulSoup s ol soup find select id page_select option n 1 for i in ol if self verbose_FLAG print i value self downloadImage downloadThread n i value manga_chapter_prefix n 1
"qmult pre - multiply by random orthogonal matrix . qmult(a ) is q*a where q is a random real orthogonal matrix from the haar distribution , of dimension the number of rows in a. special case : if a is a scalar then qmult(a ) is the same as qmult(eye(a ) ) .",def qmult b try n _ b shape a b copy except AttributeError n b a np eye n d np zeros n for k in range n 2 1 1 x nrnd randn n k s nl norm x sgn np sign x 0 float x 0 0 s sgn s d k sgn x 0 x 0 s beta s x 0 y np dot x a k n a k n a k n np outer x y beta for i in range n 1 a i d i a i a n 1 a n 1 np sign nrnd randn return a
calculate the area of the vertices described by the sequence of vertices .,def polygon_area vertices area 0 0 X float vertex 0 for vertex in vertices Y float vertex 1 for vertex in vertices j len vertices 1 for i in range len vertices area X j X i Y j Y i j i return abs area 2
create a user on the local system,def create_user self user self run useradd m s user usr getpwnam user return usr
"populates a creature object with values that are normally found in the header section of a d20pfsrd.com bestiary entry : name , cr , mr",def _populate_from_header_values root creature info_element root cssselect td sites layout tile tr info_text info_element 0 text_content info_text info_text strip info_text re sub s info_text creature_name info_text info_text index CR 1 creature_cr info_text info_text index CR creature name _format_creature_name creature_name _populate_cr_and_mr creature_cr creature
set the font used to render this label .,def set_font self font self font font self chsize
stub to replace urlopen for testing .,def urlopen_stub url data None if url valid_httpurl tmpfile NamedTemporaryFile prefix urltmp_ return tmpfile else raise URLError Name or service not known
"given the output from mount , determine the currently active and passive partitions , returning them as a pair in that order .",def determine_active_passive_part bitbake_variables mount_output run mount a bitbake_variables MENDER_ROOTFS_PART_A b bitbake_variables MENDER_ROOTFS_PART_B if mount_output find a 0 return a b elif mount_output find b 0 return b a else raise Exception Could not determine active partition Mount output was looking for format mount_output a b
generic response generation for endpoints that return a single serialized object .,def object_response self status 200 self response self get_response_handler self response process self obj return self _response self response get_response_data status status
"this task takes the output of the wordrank task as its input , so we list wordrank as a dependency .",def requires self return WordRank output_path self output_path
check that a given word does not feature repeating characters .,def _uniqueChars self word condition if condition wordChars for c in word if c in wordChars return False wordChars append c return True else return True
this plugin is always enabled .,def enabled self return True
raise missinghookerror with comma - separated list of missing hooks,def missing_entrypoints_callback names error _ The following hook s are missing or failed to load s raise RuntimeError error join names
simple wrapper function . it has almost no features .,def make_rest_client service_key options None app_name None app_version None version None kwargs cloud get_config service_key service_key options options app_name app_name app_version app_version kwargs return cloud get_session_client service_key version version
return completion and status information about an asynchronous job,def query_progress request_ctx id request_kwargs path v1 progress id url request_ctx base_api_url path format id id response client get request_ctx url request_kwargs return response
@type d : dict @param d : value store @type k : str @param k : key to get value for @param default : return this value if key l{k } can not be found @rtype : str @return : value corresponding to key l{k } or l{default },def get_val d k default None if not d has_key k return default return d k
turns argparser 's namespace into something manageable by an external library .,def object_from_args args return dict args _get_kwargs args _get_args
changes the value of cell in this row under the desired column name .,def set_value self column_name value values self get_elements column_name GSX_NAMESPACE if len values 0 values 0 text value else new_value ListRow text value new_value _qname new_value _qname column_name self _other_elements append new_value
similar to gradient for the sum op ( i.e. tf.reduce_sum ( ) ) .,ops RegisterGradient SparseReduceSum def _SparseReduceSumGrad op out_grad sp_indices op inputs 0 sp_shape op inputs 2 output_shape_kept_dims math_ops reduced_shape sp_shape op inputs 3 out_grad_reshaped array_ops reshape out_grad output_shape_kept_dims scale sp_shape math_ops to_int64 output_shape_kept_dims return None array_ops gather_nd out_grad_reshaped sp_indices scale None None
decode v into a string of len bytes .,def b58decode v length long_value 0L for i c in enumerate v 1 long_value __b58chars find c __b58base i result while long_value 256 div mod divmod long_value 256 result chr mod result long_value div result chr long_value result nPad 0 for c in v if c __b58chars 0 nPad 1 else break result chr 0 nPad result if length is not None and len result length return None return result
"> > > syntax.escape(""select ' abcdefgh ' from foobar "" ) "" select ' abcdefgh ' from foobar """,staticmethod def escape expression quote True return expression
parses the directory specified for crashlog files and adds them to a class list,def parse_directory self directory self directory directory dirList os listdir directory for fname in dirList if fname find crashlog 1 self crash_files append CrashFile fname
name of test database to be created .,pytest fixture scope session def mysql_database_name return pytest_services_test
construct a new oauth 2 authorization object .,def __init__ self client_id None client None token None u Construct a new OAuth 2 authorization object n n param client_id Client id obtained during registration n param client class oauthlib oauth2 Client to be used Default is n WebApplicationClient which is useful for any n hosted application but not mobile or desktop n param token Token dictionary must include access_token n and token_type n self _client client or WebApplicationClient client_id token token if token for k v in token items setattr self _client k v
"used from within templates to decide what functionality to allow for a specific object . for typical models , we just return the model - wide permission .",def can_edit_object self user obj return self has_edit_permission user
"in the end , ensure that the tested app has its latest migration .",def tearDown self call_command migrate self app verbosity 0
test that the template name of the view is as expected,def test_template_name self request self factory get reverse sales search latitude 0 longitude 1 request user AnonymousUser response SearchPageView as_view request self assertIn homes for sale search html response template_name
xor an input string with a given character key .,def xor input key output join chr ord c key for c in input return output
create a zone for the specified zone .,def create_zone self zone serial None return self service createObject name zone serial serial or time strftime Y m d01 resourceRecords
verify that config loads a list as a list,def testConfigList self cfg config initUp2dateConfig test_up2date assert type cfg disallowConfChanges type
verify that config.has_key ( ) is correct for runtime keys,def testConfigHasKeyRuntime self cfg config initUp2dateConfig test_up2date cfg runtimekey blippy assert cfg has_key runtimekey 1
upwind differencing scheme for advection .,def advec self bwd fwd self _derivs_bwd_fwd neg pos self _flow_neg_pos advec_arr pos bwd neg fwd if not self fill_edge slice_middle self dim slice self order self order advec_arr advec_arr slice_middle return advec_arr
add the aggregate to the nominated query .,def add_to_query self query alias col source is_summary klass getattr query aggregates_module self name aggregate klass col source source is_summary is_summary self extra query aggregates alias aggregate
"returns a dictionary of { field_index : ( field_index_other_table , other_table ) } representing all relationships to the given table . indexes are 0-based .",def get_relations self cursor table_name u n Returns a dictionary of field_index field_index_other_table other_table n representing all relationships to the given table Indexes are 0 based n cursor execute u n SELECT con conkey con confkey c2 relname n FROM pg_constraint con pg_class c1 pg_class c2 n WHERE c1 oid con conrelid n AND c2 oid con confrelid n AND c1 relname s n AND con contype f table_name relations for row in cursor fetchall relations row 0 0 1 row 1 0 1 row 2 return relations
the priority value should not be localized ( refs # 14164 ),skipUnless settings USE_I18N u Internationalization is not enabled override_settings USE_L10N True def test_localized_priority self u activate u fr self assertEqual u 0 3 localize 0 3 response self client get u simple sitemap xml self assertContains response u priority 0 5 priority self assertContains response u lastmod s lastmod date today deactivate
restores settings to avoid breaking other tests .,def tearDown self settings MIDDLEWARE_CLASSES self curr_middleware settings AUTHENTICATION_BACKENDS self curr_auth
reorders a test suite by test type .,def reorder_suite suite classes class_count len classes bins unittest TestSuite for i in range class_count 1 partition_suite suite classes bins for i in range class_count bins 0 addTests bins i 1 return bins 0
test if title attribute is set .,def test_with_title self u input_props u linkType u external u url u http test test u title u Test title output DOM render DOM create_element Link input_props self assertEqual output u a href http test test title Test title a
io access to the yaml file .,def __get_completions self try section_content self _get_yaml_content completion section yaml section yaml load section_content return section except yaml YAMLError as error logger error error return
a simple handler that prints the exception message .,def exception_handler exception_type exception traceback u A simple handler that prints the exception message n n print_err u Chromecast s s exception_type __name__ exception print_exception exception_type exception traceback
returns boolean if client username has client,def is_client_user_inuse self client_username vpn_name result try data self api manage self SOLACE_USER_PLUGIN get client_username client_username vpn_name vpn_name detail True response data 0 rpc reply rpc show client username client usernames client username num clients except KeyError as e logging debug Key does not exist this normally means there was no user matching the filter logging debug data return False except Exception as e logging warn Error decoding response keys in s data logging warn e message raise if int response 0 logging info User s is in use s sessions open client_username response return True else logging info User s is NOT in use s sessions open client_username response return False
"one or more application origins , white space delimited",property def application_origins self return self _redirect_uris
return the gnr digraph with n nodes and redirection probability p.,def gnr_graph n p create_using None seed None if create_using is None create_using nx DiGraph elif not create_using is_directed raise nx NetworkXError Directed Graph required in create_using if not seed is None random seed seed G empty_graph 1 create_using G name gnr_graph s s n p if n 1 return G for source in range 1 n target random randrange 0 source if random random p and target 0 target G successors target 0 G add_edge source target return G
execute the given recipe from the recipe model,def run_recipe self recipe reversion create_revision def apply_recipe modeladmin request queryset for zone in queryset all r recipe zone r save zone_fully_saved_signal send sender self __class__ instance zone created False return apply_recipe
"test that , if an event has a location associated with it , it gets set when popover_helper ( ) is called ( the event location only appears in the popover on the month calendar view page ) .",def test_location self u n Test that if an event has a location associated with it it gets n set when popover_helper is called the event location only appears n in the popover on the month calendar view page n yr 2014 mo 5 count defaultdict list event create_event start_date 2014 5 15 end_date 2014 5 15 created_by self user title u Big Event description u Wow An event repeat u WEEKLY events event day 15 count_dict day event title event pk cal EventCalendar yr mo count events cal count count_dict render_result cal formatday day 0 self assertNotIn u Where render_result self assertNotIn u Heck render_result event location create name u Heck events event cal2 EventCalendar yr mo count events cal2 count count_dict render_result cal2 formatday day 0 self assertIn u Where render_result self assertIn u Heck render_result
tests for the : class:`configloader ` class .,def test_config_loader self loader ConfigLoader program_name update dotdee filename_extension conf assert etc update dotdee conf in loader filename_patterns with MockedHomeDirectory as directory main_file os path join directory update dotdee ini write_file main_file dedent main section main option value config_directory os path join directory config update dotdee d os makedirs config_directory modular_file_1 os path join config_directory 1 ini modular_file_2 os path join config_directory 2 ini modular_file_11 os path join config_directory 11 ini write_file modular_file_1 dedent modular section 1 my option name value write_file modular_file_2 dedent modular section 2 my option name value main section modular option value write_file modular_file_11 dedent modular section 11 my option name value loader ConfigLoader program_name update dotdee assert len loader available_files 4 assert loader available_files 0 main_file assert loader available_files 1 modular_file_1 assert loader available_files 2 modular_file_2 assert loader available_files 3 modular_file_11 assert set loader section_names set main section modular section 1 modular section 2 modular section 11 assert loader get_options main section main option value modular option value
get whether to convert to invoice .,def get_convert_to_invoice self return self convert_to_invoice
set whether shipping charge is required or not .,def set_is_shipping_charge_required self is_shipping_charge_required self is_shipping_charge_required is_shipping_charge_required
parse all uvision specific setttings .,def _parse_specific_options self data data compiler_options for dic in data misc for k v in dic items self _libraries k v data self _compiler_options k v data self _optimization k v data self _cc_standard k v data self _c_standard k v data data linker_options for dic in data misc for k v in dic items self _linker_options k v data
"given a file path , indicate whether the file is either valid javascript , malformed javascript or no javascript . on a system error -1 is returned .",def is_js_file given_file syntactical_units False tolerance false with open os path join SRC_PATH is_js log w as my_log try result subprocess check_output nodejs os path join SRC_PATH features parsing parser js given_file tolerance stderr my_log shell True if syntactical_units syntax_part str result split b 1 split n del syntax_part len syntax_part 1 return syntax_part return 0 except subprocess CalledProcessError as err if err returncode 1 or err returncode 8 if str err output b return 1 return 2 elif err returncode 0 logging exception Something went wrong with the file given_file str err except OSError logging exception System related error return 1
bringi et al . ( 2004 ) eqs . a.15-a.17,def dsd_sband_method2 dz kdp zdr d0 power_law zdr 1 81 0 486 Nw calc_Nw_mult_methods dz d0 mu 0 0 dz DEFAULT_MU return d0 Nw mu
overrides default behavior during external_account deactivation .,def revoke_remote_oauth_access self external_account client Dropbox external_account oauth_key try client auth_token_revoke except DropboxException pass
fully connected layer : from https://github.com/lisa-lab/deeplearningtutorials/blob/master/code/mlp.py,def __init__ self rng input n_in n_out W None b None activation T tanh self input input if W is None W_values np asarray rng uniform low np sqrt 6 0 n_in n_out high np sqrt 6 0 n_in n_out size n_in n_out dtype theano config floatX if activation theano tensor nnet sigmoid W_values 4 W theano shared value W_values name W borrow True if b is None b_values np zeros n_out dtype theano config floatX b theano shared value b_values name b borrow True self W W self b b lin_output T dot input self W self b self output lin_output if activation is None else activation lin_output self params self W self b
runs basic evolution strategies using the provided arguments .,def run_es args sol SOLUTIONS args sol_index w np random randn sol size for i in range args num_iters if i args print_every 0 print iter w solution reward 5f format str i zfill 4 str w sol f w sol N np random randn args npop sol size R np zeros args npop for j in range args npop R j f w args sigma N j sol A R np mean R np std R 1e 06 w w args lrate args npop args sigma np dot N T A
": type path : str : rtype : tuple[requests . response , int ]",retry ZoeAPIException def _rest_get_stream self path url self url api ZOE_API_VERSION path try req requests get url auth self user self password stream True except requests exceptions Timeout raise ZoeAPIException HTTP connection timeout except requests exceptions HTTPError raise ZoeAPIException Invalid HTTP response except requests exceptions ConnectionError as e raise ZoeAPIException Connection error format e return req req status_code
"return a generator which generate a pair wise list from an iterable . s - > ( s[0],s[1 ] ) , ( s[1],s[2 ] ) , ... ( s[n-1],s[n ] )",def pairwise iterable prev iterable 0 for x in iterable 1 yield prev x prev x
initializes a model and returns the object of the model class .,def create_and_initialize_model session params train_dir data_dir model None if FLAGS model_name cnn_model model cnn_model CNNModel params else raise ValueError Invalid model format FLAGS model_name ckpt tf train get_checkpoint_state train_dir if ckpt and ckpt model_checkpoint_path print Reading model parameters from format ckpt model_checkpoint_path model saver restore session ckpt model_checkpoint_path else print Created model with fresh parameters session run tf global_variables_initializer session run tf assign model word_embedding_table get_embeds data_dir return model
remove a client from the connected list .,def remove self client try l threading Lock l acquire self clients remove client l release except Exception as e pass
search after parsing unicode properties and set flag to unicode,def search pattern string flags 0 re search parse_unicode_properties pattern string flags re UNICODE
install an exception handler that formats tracebacks as html .,def enable display 1 logdir None context 5 format html sys excepthook Hook display display logdir logdir context context format format
unregisters the given model(s ) .,def unregister self model_or_iterable from xadmin views base import BaseAdminView if isinstance model_or_iterable ModelBase BaseAdminView model_or_iterable model_or_iterable for model in model_or_iterable if isinstance model ModelBase if model not in self _registry raise NotRegistered The model s is not registered model __name__ del self _registry model else if model not in self _registry_avs raise NotRegistered The admin_view_class s is not registered model __name__ del self _registry_avs model
returns the different layers of a finite structure,def get_onion_layers structure assert not structure is_periodic layers cur_st structure copy morelayers True while morelayers pos cur_st positions if len pos 4 core range cur_st natom layers append core break st pychemia Structure positions pos symbols len pos H periodicity False st canonical_form if st volume 0 1 core range cur_st natom layers append core break try voro scipy spatial Voronoi pos surface i for i in range cur_st natom if 1 in voro regions voro point_region i except qhull QhullError surface range cur_st natom morelayers False layers append surface if not morelayers break core i for i in range cur_st natom if i not in surface if len core 0 break symbols list np array cur_st symbols np array core positions cur_st positions np array core cur_st pychemia Structure symbols symbols positions positions periodicity False new_layers layers 0 included list layers 0 acumulator 0 for i in range 1 len layers noincluded j for j in range structure natom if j not in included acumulator len included relabel noincluded j for j in layers i included relabel new_layers append relabel return new_layers
@name : _ _ sendgetreqtocs @desc : sends the get request to cs @input : url : url to send post req payload : payload information as part of request @output : returns response from get output else failed,def __sendGetReqToCS self url payload try return requests get url params payload cert self certPath verify self httpsFlag except Exception as e self __lastError e self logger exception __sendGetReqToCS Exception Occurred s str self __lastError return FAILED
this registers the signal handler function and timeout,def register_signal_handler global registered_signal_status registered_signal_status True signal signal signal SIGALRM signal_handler
coerces a value using str ( ) unless that value is none : param value : any value that can be coerced using str ( ) or none : return : str(value ) or none if value is none,def _coerce_str_unless_none value return str value if value is not None else None
< for debugging purposes > gives information relevant to the motor state,def __str__ self return position degrees str self deg_pos nzeros position degrees str self deg_zeros
reset the mapping parameters so the next circuit can be mapped .,def _reset self self _cmds self _interactions dict
return the server url for the image . you can use this url in an img html tag .,def get_url self plantuml_text return self url deflate_and_encode plantuml_text
adds a new leaf node at the given index with the given data_object,def add_leaf self index data_object assert self type data_object type data type mismatch if self _get_child_by_index index is not None raise NodeAlreadyExistsError Leaf data node already exists at this index else data_node DataNode parent self index index data_object data_object type self type data_node full_clean data_node save return data_node
sets all value in the dictionary to none if empty : param row : the dictionary to process : type row : dict,def null_empty_cells row for k in row keys if row k row k None
returns an array of ` size ` random integers representing bytes : param size : the size of the array : return : the array of random integers,def getRandomBytes size random seed a for i in range 0 size a append random randint 0 255 return a
test the listing of the agoras in which an specific user is a member,def test_specific_user_agoras self self get user 10 agoras code HTTP_NOT_FOUND data self getAndParse user 0 agoras self assertEqual len data objects 2 data self getAndParse user 1 agoras self assertEqual len data objects 0 self login user1 123 data self getAndParse user 0 agoras self assertEqual len data objects 2
get listing visit counts for a profile_id and listing_id,def get_listing_visit_counts_for_profile current_request_username profile_id listing_id None if profile_id self profile_instance models Profile objects get user__username current_request_username else profile_instance models Profile objects get id profile_id visit_counts models ListingVisitCount objects for_user current_request_username filter profile profile_instance if listing_id visit_counts visit_counts filter listing_id listing_id return visit_counts order_by count
here fetched the catagory squash to speed up the scraping,def start_requests self urls https www liveyoursport com squash rackets page 1 https www liveyoursport com squash rackets page 2 https www liveyoursport com squash rackets page 3 https www liveyoursport com squash shoes page 1 https www liveyoursport com squash shoes page 2 https www liveyoursport com squash shoes page 3 https www liveyoursport com squash shoes page 4 https www liveyoursport com squash shoes page 5 https www liveyoursport com squash shoes page 6 https www liveyoursport com Squash strings https www liveyoursport com squash racket grips page 1 https www liveyoursport com squash racket grips page 2 https www liveyoursport com squash racket grips page 3 https www liveyoursport com squash racket grips page 4 https www liveyoursport com squash racket grips page 5 https www liveyoursport com squash balls https www liveyoursport com squash racket bags https www liveyoursport com Squash eye wear https www liveyoursport com Squash dampners https www liveyoursport com squash wrist bands https www liveyoursport com squash accessories page 1 https www liveyoursport com squash accessories page 2 https www liveyoursport com squash accessories page 3 https www liveyoursport com squash accessories page 4 https www liveyoursport com squash accessories page 5 for url in urls yield scrapy Request url url callback self parse
clear all 2d data objects .,def clear return d clear
updates a bucket type on a node,bucket_type command update click argument node click argument bucket type click argument props pass_context def bucket_type_update ctx bucket_type props kwargs ctx init_args kwargs r ctx api_request get clusters ctx cluster nodes ctx node types if r status_code 200 click echo Failed to get bucket types status_code str r status_code return if not is_bucket_type_exists bucket_type r click echo Bucket with such type bucket_type does not exist return r ctx api_request post clusters ctx cluster nodes ctx node types bucket_type data props click echo r text
"return a factory function for collection.namedtuple objects which uses the supplied ' required ' , ' defaults ' and ' ignored ' parameters to determine what the attributes of the namedtuple should be .",def make_named_tuple name required defaults ignored required_attr set required default_attr dict defaults default_attr_keys default_attr viewkeys ignored_attr set ignored expected_attr required_attr default_attr_keys assert not default_attr_keys required_attr assert not default_attr_keys ignored_attr assert not ignored_attr required_attr NamedTuple collections namedtuple name required defaults keys def make_instance kwargs keys kwargs viewkeys ignored_keys keys ignored_attr for key in ignored_keys del kwargs key unexpected keys expected_attr if unexpected warnings warn ignoring unexpected args str unexpected for key in unexpected del kwargs key missing_attr required_attr keys if missing_attr raise Error missing attributes str missing_attr auto_attr default_attr_keys keys for a in auto_attr kwargs a default_attr a return NamedTuple kwargs return make_instance
generator which returns all test cases in the suite,property def testcases self for table in self tables if isinstance table TestcaseTable for testcase in table testcases yield testcase
run python script and return output .,def runpy self py_file stdin None cmd sys executable cmd shlex split py_file stdin_val subprocess PIPE if stdin else None p subprocess Popen cmd stdout subprocess PIPE stderr subprocess STDOUT stdin stdin_val output _ p communicate input stdin return output
wait for the instance to finish up booting .,abc abstractmethod def wait_for_boot_completion self
updates the old access token with the new one . : param access_token : : return :,def update_access_token self access_token unix_timestamp None refresh_token None self _json self _jstore get_data self _json access_manager self _user access_token access_token if unix_timestamp is not None self _json access_manager self _user token_expires int unix_timestamp if refresh_token is not None self _json access_manager self _user refresh_token refresh_token self _jstore save self _json
"processing color pairs through the imagehash hasher should return "" same "" results",def test_imagehash_pairs_color imgs ALL_IMAGES color h1 imagehash imgs 0 imgs 0 h2 imagehash imgs 1 imgs 1 dist h1 h2 assert dist THRESHOLD_IDENTITY
returns the set of all webviews belonging to all processes of the app .,def GetWebViews self return self _app_backend GetWebViews
test mulitple headers with the same name .,def test__ToTuplesMultipleHeadersWithSameName self real_http_fetch httpclient RealHttpFetch headers self CONTENT_TYPE self COOKIE_1 self COOKIE_2 self FIRST_LINE result real_http_fetch _ToTuples headers expected content type image x icon set cookie self COOKIE_1 12 set cookie self COOKIE_2 12 fake header first line self assertEqual result expected
recompute the archive_hosts from the http_archive .,def InitializeArchiveHosts self self archive_hosts set s req host split 0 for req in self http_archive
add mock clients to the membership list of the master .,def set_membership_list self for ip in self ips self master register ip client_cls mock_client self
tests the successful path of the module under test .,def test_success self batch gtf_file fasta_file init_objects batch platform_accession_code TEST batch save gtf_file internal_location TEST TRANSCRIPTOME_INDEX gtf_file save fasta_file internal_location TEST TRANSCRIPTOME_INDEX fasta_file save processor_job ProcessorJob create_job_and_relationships batches batch processor_job save job_context utils start_job job processor_job job_id processor_job id job_context transcriptome_index _set_job_prefix job_context temp_dir gtf_file get_temp_dir job_context job_dir_prefix shutil rmtree temp_dir ignore_errors True job_context transcriptome_index _prepare_files job_context gtf_file_path job_context gtf_file_path self assertIsInstance gtf_file_path str self assertTrue os path isfile gtf_file_path fasta_file_path job_context fasta_file_path self assertIsInstance fasta_file_path str self assertTrue os path isfile fasta_file_path self assertIsInstance job_context gtf_file File self assertIsInstance job_context fasta_file File job_context transcriptome_index _process_gtf job_context self assertTrue job_context success self assertNotEqual job_context gtf_file_path gtf_file_path self assertTrue os path isfile job_context gtf_file_path self assertTrue genes_to_transcripts_path in job_context self assertTrue os path isfile job_context genes_to_transcripts_path job_context transcriptome_index _create_index job_context self assertTrue job_context success self assertTrue output_dir in job_context self assertTrue os path isdir job_context output_dir self assertEqual 9 len os listdir job_context output_dir job_context transcriptome_index _zip_index job_context self assertTrue files_to_upload in job_context self assertEqual job_context gtf_file id gtf_file id self assertEqual job_context files_to_upload 0 id gtf_file id zipped_path gtf_file get_temp_post_path job_context job_dir_prefix self assertTrue os path isfile zipped_path utils end_job job_context
"helper routine for _ _ getitem _ _ that constructs a feature from the given feature id . if the ogr layer does not support random - access reading , then each feature of the layer will be incremented through until the a feature is found matching the given feature id .",def _make_feature self feat_id if self _random_read try return Feature get_feature self _ptr feat_id self _ldefn except OGRException pass else for feat in self if feat fid feat_id return feat raise OGRIndexError Invalid feature id s feat_id
deleting an instance of a concrete model should also delete objects referencing its proxy subclass .,def test_delete_concrete_parent self u n Deleting an instance of a concrete model should also delete objects n referencing its proxy subclass n self create_image File objects all delete self assertEqual len File objects all 0 self assertEqual len Image objects all 0 self assertEqual len FooFile objects all 0 self assertEqual len FooImage objects all 0
"querydicts must be able to handle invalid input encoding ( in this case , bad utf-8 encoding ) .",def test_invalid_input_encoding self q QueryDict foo bar foo xff self assertEqual q foo u ufffd self assertEqual q getlist foo u bar u ufffd
the worst implementation of fibonacci numbers calculation using multithreading complexity : tinfinity(n ) = o(n ),def fib_parallel num if num 2 return num thread gevent spawn fib_parallel num 1 val2 fib_parallel num 2 val1 thread get return val1 val2
outputs / console - size based flush,def test_console_output_size_flush self self render_config_template console pretty false bulk_max_size 1 flush_interval 1h proc self start_beat logging_args e self wait_until lambda self log_contains Mockbeat is alive max_timeout 2 proc check_kill_and_wait
handle http errors returned by the api server,def contrail_error_handler f u Handle HTTP errors returned by the API server n wraps f def wrapper args kwargs try return f args kwargs except HttpError as e if e details e message e details e details e message e args u s HTTP s e message e http_status raise return wrapper
returns a list of indexes corresponding to events that pass the gate .,def _identify self dataframe raise NotImplementedError
returns the yet non deserialized chunk in the input,def get_undeserialized self u n Returns the yet non deserialized chunk in the input n return self _binary_buffer self _deserialized_pos
returns list of face objects decoded from the inference result .,def get_faces result assert len result tensors 3 bboxes _reshape result tensors bounding_boxes data 4 face_scores result tensors face_scores data joy_scores result tensors joy_scores data assert len bboxes len joy_scores assert len bboxes len face_scores return Face tuple bbox face_score joy_score for bbox face_score joy_score in zip bboxes face_scores joy_scores
the model should not submit if all fields are left blank,def test_blank self with self assertRaises ValidationError bird_extended BirdExtended bird_extended full_clean bird_extended save
""" check if files exist in the same folder as this program . filenames must be passed as comma seperated parameters",def check_files filenames txt for filename in filenames ok True if os path isfile filename txt n exist format filename else txt n not found ok False return ok txt
context manager that allows to execute send wrapped in before_send ( ) and after_send ( ) .,contextmanager def before_after_send_handling self self _init_delivery_statuses_dict self before_send try yield finally self after_send self _update_dispatches
: type date : datetime : type publickey : string_types : type signature : string_types : type signedby : string_types : rtype : signature,staticmethod def create kwargs return Signature kwargs
"encode v , which is a string of bytes , to base58 .",def b58encode v long_value 0L for i c in enumerate v 1 long_value 256 i ord c result while long_value __b58base div mod divmod long_value __b58base result __b58chars mod result long_value div result __b58chars long_value result nPad 0 for c in v if c x00 nPad 1 else break return __b58chars 0 nPad result
"parse the username & ip from the request , and see if it 's already locked .",def is_already_locked request get_username get_username_from_request username None user_blocked is_user_already_locked username or get_username request ip_blocked is_source_ip_already_locked get_ip request if config LOCKOUT_BY_IP_USERNAME return ip_blocked and user_blocked return ip_blocked or user_blocked
"set break : controls txd . when active , to transmitting is possible .",def setBreak self level True if not self _port_handle raise portNotOpenError self _port_handle BreakState bool level
"function _ move_select changes the ' selected ' field of a minefield depending on the direction provided . ' direction ' must be a curses . key _ * instance , either up , down , left , or right . if moving the selected cell would move to an out of bounds position , we do nothing .",def move_select direction field startloc field selected delta 0 0 if direction game Keys UP delta 0 1 elif direction game Keys DOWN delta 0 1 elif direction game Keys RIGHT delta 1 0 elif direction game Keys LEFT delta 1 0 x y startloc nx ny x delta 0 y delta 1 if nx 0 or nx field width nx x if ny 0 or ny field height ny y field selected nx ny
does n't do much .... just loads the keyboard config from the ini,def main msikeys get_keyboard
called when the user launches the skill without specifying what they want,def on_launch launch_request session return get_welcome_response
replica set name or none .,property def replica_set_name self return self _doc get setName
"test adding random floating point numbers from the range [ 0.0 , 1.0 )",def test_add_random_floats self for _ in range 20 a b random random random random out self encrypt_a_and_add_b a b self assertAlmostEqual float a b float out
determines if two submissions are original,def original submission1 submission2 threshold 0 05 score originality_score submission1 submission2 return score threshold
"update scenes with latest status of their containers , and possibly shift scene phase",def _update_scene_phases self for scene in Scene objects all order_by date_started id scene update_and_phase_shift
run command and check the return code .,def run_cmd args kwargs preexec_fn None if chdir in kwargs def preexec_fn return os chdir kwargs chdir try os environ EDITOR bin cat proc subprocess Popen args stdin subprocess PIPE stdout subprocess PIPE stderr subprocess STDOUT env os environ preexec_fn preexec_fn if confirm in kwargs and kwargs confirm proc stdin write yes encode proc stdin flush out err proc communicate out out decode utf 8 except Exception raise Exception Exception while processing the command n s n s join args traceback format_exc if proc returncode 0 raise Exception Error occurred while processing the command s Stdout s Stderr s join args out strip err return out strip
get irmc firmware version of the node .,def get_irmc_firmware_version snmp_client try bmc_name snmp_client get BMC_NAME_OID irmc_firm_ver snmp_client get IRMC_FW_VERSION_OID return bmc s sep s firm_ver s bmc bmc_name if bmc_name else firm_ver irmc_firm_ver if irmc_firm_ver else sep if bmc_name and irmc_firm_ver else except SNMPFailure as e raise SNMPIRMCFirmwareFailure SNMP_FAILURE_MSG GET IRMC FIRMWARE VERSION e
return whether the interface supports ap mode .,def has_ap_mode self return self _support_ap_mode
verify that the browser is on the page and it is not still loading .,def is_browser_on_page self return all self q css body view group configurations present self q css div ui loading is hidden present
represent the country as a 2-character unicode identifier .,def to_representation self obj return unicode obj
checking course - id format and course exists in module store . this field can be null .,def clean_course_id self if self cleaned_data course_id course_id self cleaned_data course_id try course_key CourseKey from_string course_id except InvalidKeyError raise forms ValidationError u Invalid CourseID Please check the format and re try if not modulestore has_course course_key raise forms ValidationError u Cannot find course with id in the modulestore format course_id return course_key return None
return the set of fields that the requester can initialize for a comment,def get_initializable_comment_fields context ret get_editable_fields Comment user_id context cc_requester id type comment context ret NON_UPDATABLE_COMMENT_FIELDS return ret
generates a one - use only link for resetting password and sends to the user .,def save self subject_template_name registration password_reset_subject txt email_template_name registration password_reset_email html use_https False token_generator default_token_generator from_email configuration_helpers get_value email_from_address settings DEFAULT_FROM_EMAIL request None from django core mail import send_mail for user in self users_cache site_name configuration_helpers get_value SITE_NAME settings SITE_NAME context email user email site_name site_name uid int_to_base36 user id user user token token_generator make_token user protocol https if use_https else http platform_name configuration_helpers get_value platform_name settings PLATFORM_NAME password_reset_link protocol site_name reset_link format protocol context protocol site_name site_name reset_link reverse student views password_reset_confirm_wrapper kwargs uidb36 int_to_base36 user id token context token MandrillClient send_mail MandrillClient PASSWORD_RESET_TEMPLATE user email first_name user first_name reset_link password_reset_link
verify that certificate_info_for_user works as expect in scenario when grading of problems changes after certificates already generated . in such scenario ` certificate delivered ` should not depend on student 's eligibility to get certificates since in above scenario eligibility can change over period of time .,unpack data allow_certificate False whitelisted False grade None output N Y honor allow_certificate True whitelisted True grade None output Y Y honor allow_certificate True whitelisted False grade 0 9 output Y Y honor allow_certificate False whitelisted True grade 0 8 output N Y honor allow_certificate False whitelisted None grade 0 8 output N Y honor def test_certificate_info_for_user_when_grade_changes self allow_certificate whitelisted grade output student UserFactory course CourseFactory create org edx number verified display_name Verified Course student profile allow_certificate allow_certificate student profile save GeneratedCertificateFactory create user student course_id course id status CertificateStatuses downloadable mode honor certificate_info certificate_info_for_user student course id grade whitelisted self assertEqual certificate_info output
return true if the ccx start date is in the past,def has_started self u return datetime now utc self start
generates a course - identifying unicode string for use in a file name .,def course_filename_prefix_generator course_id separator _ return get_valid_filename unicode separator join course_id org course_id course course_id run
verify the status is set to failure if a passing grade is received past the submission deadline .,def test_min_grade_requirement_with_valid_grade_and_expired_deadline self self assert_requirement_status 0 7 self EXPIRED_DUE_DATE failed
find the section and unit urls for a block .,def find_urls course_id block child_to_parent request block_path while block in child_to_parent block child_to_parent block block_path append block block_list list reversed block_path block_count len block_list chapter_id block_list 1 location block_id if block_count 1 else None section block_list 2 if block_count 2 else None position None if block_count 3 position 1 for block in section children if block name block_list 3 url_name break position 1 kwargs course_id unicode course_id if chapter_id is None course_url reverse courseware kwargs kwargs request request return course_url course_url kwargs chapter chapter_id if section is None chapter_url reverse courseware_chapter kwargs kwargs request request return chapter_url chapter_url kwargs section section url_name section_url reverse courseware_section kwargs kwargs request request if position is None return section_url section_url kwargs position position unit_url reverse courseware_position kwargs kwargs request request return unit_url section_url
enables cohorting for the current course .,def enable_cohorting self course_fixture url LMS_BASE_URL courses course_fixture _course_key cohorts settings data json dumps is_cohorted True response course_fixture session patch url data data headers course_fixture headers self assertTrue response ok Failed to enable cohorts
"verify a badge has been created for this badge class , and create it if not .",def _ensure_badge_created self badge_class slug self _slugify badge_class if slug in BadgrBackend badges return response requests get self _badge_url slug headers self _get_headers timeout settings BADGR_TIMEOUT if response status_code 200 self _create_badge badge_class BadgrBackend badges append slug
returns the url for textbook detail handler .,def get_details_url self textbook_id return reverse_course_url textbooks_detail_handler self course id kwargs textbook_id textbook_id
is this package in the output of ' pip freeze ' ?,def package_in_frozen package_name frozen_output pattern mi pkg egg pkg_under format pkg re escape package_name pkg_under re escape package_name replace _ return bool re search pattern frozen_output
"delete /api / bookmarks / v1/bookmarks/{username},{usage_id }",def delete self request username None usage_id None usage_key_or_response self get_usage_key_or_error_response usage_id usage_id if isinstance usage_key_or_response Response return usage_key_or_response try api delete_bookmark user request user usage_key usage_key_or_response except ObjectDoesNotExist error_message ugettext_noop u Bookmark with usage_id usage_id does not exist format usage_id usage_id log error error_message return self error_response error_message error_status status HTTP_404_NOT_FOUND return Response status status HTTP_204_NO_CONTENT
this function sets the xmove or ymove variables that will then move the snake when update ( ) function is called . the xmove and ymove values will be returned to normal when this keys movekeyup function is called .,def MoveKeyDown self key ladder_group block_group if key K_d self __xMove self x_dist self _last_direction 1 elif key K_a self __xMove self x_dist self _last_direction 1 elif key K_w self __yMove self y_dist elif key K_s self __yMove self y_dist
provide a convenient object hook to our hamster - dbus service .,pytest fixture def activity_manager request live_service u daemon bus live_service object_ bus get_object u org projecthamster HamsterDBus u org projecthamster HamsterDBus ActivityManager interface dbus Interface object_ dbus_interface u org projecthamster HamsterDBus ActivityManager1 return interface
print a string to stdout when debug is set to true .,def debug_print string if DEBUG print DEBUG string
"parse an nmea sentence , returning an nmeasentence class of the appropriate type",staticmethod def Parse sentence if not sentence startswith NmeaParser __NmeaStart raise InvalidNmeaSentence NMEA sentence does not start with if not sentence endswith NmeaParser __NmeaEnd raise InvalidNmeaSentence NMEA sentence does not end with r n sentence sentence 1 2 if sentence 3 raise InvalidNmeaSentence NMEA checksum is not preceeded by checksum int sentence 2 16 sentence sentence 3 if checksum NmeaParser __ComputeXorChecksum sentence raise InvalidNmeaSentence Invalid checksum fields sentence split NmeaParser __Delimiter if fields 0 GPGGA return NmeaSentences GpggaSentence fields else pass
converges all the dbs to a single master db,def converge_droplets_dbs t1 tm master_con sql connect master_db_file timeout 10 master_cur master_con cursor for root directories files in os walk droplet_dbs_folder for filename in files splitted filename split if len splitted 1 and splitted 1 db if not r_master hget dbs_done filename r_master hset dbs_done filename True print filename ingest_ filename master_cur master_con master_con close t2 tm print total time taken for converging d int t2 t1 return
same as calling `` add_parameter `` with `` overload = true ``,def set_parameter self parameter self add_parameter parameter overload True
set the base uri for site resources .,def set_base_uri self base_uri uri sites format base_uri self uri uri
the ` args ` / ` kwargs ` params are the same as in ` api . script ` . : param operation : the refactoring operation to execute . : type operation : str : type source : str : return : list of changed lines / changed files,def extract script new_name new_lines split_lines python_bytes_to_unicode script source old_lines new_lines user_stmt script _parser user_stmt dct if user_stmt pos script _pos line_index pos 0 1 arr index helpers array_for_pos user_stmt pos if arr is not None start_pos arr index start_pos end_pos arr index end_pos e end_pos 1 if end_pos 0 start_pos 0 else None start_line new_lines start_pos 0 1 text start_line start_pos 1 e for l in range start_pos 0 end_pos 0 1 text n l if e is None end_line new_lines end_pos 0 1 text n end_line end_pos 1 t text lstrip del_start start_pos 1 len text len t text t rstrip del_end len t len text if e is None new_lines end_pos 0 1 end_line end_pos 1 del_end e len start_line else e e del_end start_line start_line del_start new_name start_line e new_lines start_pos 0 1 start_line new_lines start_pos 0 end_pos 0 1 open_brackets close_brackets if n in text and not text 0 in open_brackets and text 1 close_brackets open_brackets index text 0 text s text indent user_stmt start_pos 1 new s s s indent new_name text new_lines insert line_index new dct script path script path old_lines new_lines return Refactoring dct
"defines a decorator to be attached to tests of this package . this decorator passes a unique ycmd application as a parameter . it should be used on tests that change the server state in a irreversible way ( ex : a semantic subserver is stopped or restarted ) or expect a clean state ( ex : no semantic subserver started , no .ycm_extra_conf.py loaded , etc ) .",def IsolatedYcmd test u Defines a decorator to be attached to tests of this package This decorator n passes a unique ycmd application as a parameter It should be used on tests n that change the server state in a irreversible way ex a semantic subserver n is stopped or restarted or expect a clean state ex no semantic subserver n started no ycm_extra_conf py loaded etc n n Do NOT attach it to test generators but directly to the yielded tests functools wraps test def Wrapper args kwargs old_server_state handlers _server_state app SetUpApp try test app args kwargs finally StopCompleterServer app u rust handlers _server_state old_server_state return Wrapper
make sure that calling the same method on two different instances of the same class does resolv to different signatures .,def test_bound_methods a Klass b Klass nose tools assert_not_equal filter_args a f 1 filter_args b f 1
this function remove all iptables rules,def iptables_clean subprocess call iptables F subprocess call iptables X subprocess call iptables t nat F subprocess call iptables t nat X
"extract the images into a 4d uint8 numpy array [ index , y , x , depth ] .",def extract_images filename print Extracting filename with gzip open filename as bytestream magic _read32 bytestream if magic 2051 raise ValueError Invalid magic number d in MNIST image file s magic filename num_images _read32 bytestream rows _read32 bytestream cols _read32 bytestream buf bytestream read rows cols num_images data numpy frombuffer buf dtype numpy uint8 data data reshape num_images rows cols 1 return data
set the username of an account in gerrit .,def set_username self account_id username data username username request_path api_path account_id username format api_path self api_path account_id account_id return self connection put_request request_path json_data data
remove all temporary test files : return :,def tearDown self shutil rmtree test_output_directory
computes the specified essentia features from the audio array .,def compute_features self audio features for frame in ES FrameGenerator audio frameSize self frame_size hopSize self hop_size if self feature name MFCC bands coeffs self feature self spectrum self w frame elif self feature name HPCP spectral_peaks ES SpectralPeaks freqs mags spectral_peaks self spectrum self w frame coeffs self feature freqs mags features append coeffs features essentia array features if self beats framerate self sample_rate float self hop_size tframes np arange features shape 0 float framerate features utils resample_mx features T tframes self beats T return features
sleep between retry attempts using an exponential backoff .,def sleep self backoff self get_backoff_time if backoff 0 return time sleep backoff
args : record ( evtx . record ) : indent ( int ) :,def describe_root record root indent 0 suppress_values False def format_node n extra None indent 0 Depends on closure over record and suppress_values Args n Evtx Nodes BXmlNode extra str Returns str ret indent_s indent name n __class__ __name__ offset n offset record offset if extra is not None ret s s offset s s indent_s name hex offset extra else ret s s offset s indent_s name hex offset if not suppress_values and isinstance n VariantTypeNode ret s n string if isinstance n BXmlTypeNode ret n ret describe_root record n _root indent indent 1 return ret def rec node indent 0 Args node Evtx Nodes BXmlNode indent int Returns str ret if isinstance node TemplateInstanceNode if node is_resident_template extra resident True length s hex node template data_length ret s n format_node node extra extra indent indent ret rec node template indent indent 1 else ret s n format_node node extra resident False indent indent else ret s n format_node node indent indent for child in node children ret rec child indent indent 1 if isinstance node RootNode ofs node tag_and_children_length indent_s indent 1 offset node offset record offset ofs ret sSubstitutions offset s n indent_s hex offset for sub in node substitutions ret s n format_node sub indent indent 2 return ret ret ret rec root indent indent return ret
this gets called for each topic . print as per specified content .,def _onTopic self topicObj self __wrapper width self __width indent self __indent if topicObj isAll topicName self ALL_TOPICS_NAME else topicName topicObj getNodeName head s Topic s self __topicsBullet topicName self __output append self __formatDefn indent head indent self __indentStep for item in self __content function self __contentMeth item function indent topicObj
"https://recalll.co/ask/v/topic/d-bus-d-feet-send-dictionary-of-string%2cvariants-in-python-syntax/5565e1372bd273d7108b7b82 _ _ import__('gi.repository . glib ' , globals ( ) , locals ( ) , [ ' variant']).variant(""s "" , "" value "" )",dbus service method dbus PROPERTIES_IFACE in_signature ssv def Set self interface_name property_name new_value if interface_name in self properties if property_name in self properties interface_name func self properties function get property_name new_value func interface_name new_value self PropertiesChanged interface_name property_name new_value interval self interval else raise dbus exceptions DBusException at xundeenergie mkbackup UnknownInterface The Foo object does not implement the s interface interface_name
lookup < field > in < cfg > map and convert it to a boolean ; take < dflt > when this < field > does not exist,def param_bool cfg field dflt None value cfg get field dflt strvalue str value lower if strvalue in yes y true t 1 return True elif strvalue in no n false f 0 return False raise ValueError invalid value for boolean parameter s s field value
override panels creation to add custom buttons,def override_panels custom_hs_cmd None custom_ne_cmd None from mttOverridePanels import override_panels override_panels custom_hs_cmd custom_hs_cmd custom_ne_cmd custom_ne_cmd
make api call to github to retrieve user data .,def github_api_call profile_str print api call client_id os environ get GITHUB_APP_ID client_secret os environ get GITHUB_API_SECRET github_api_string https api github com users profile_str client_id client_id client_secret client_secret req requests get github_api_string content req content decode utf 8 return content
the op responsible for initializing this variable .,property def create self return self _initialize_op
the main function / pipeline for duplication filter .,def run o_options options opt_validate o_options info options info warn options warn debug options debug error options error assert options format BAMPE Pair end data with BAMPE option currently doesn t work with pileup command You can pretend your data to be single end with f BAM Please try again outfile os path join options outdir options outputfile if os path isfile outfile info Existing file s will be replaced outfile os unlink outfile info read alignment files tsize treat load_tag_files_options options info tag size d tsize t0 treat total info total tags in alignment file d t0 if options bothdirection info Pileup alignment file extend each read towards up downstream direction with d bps options extsize pileup_and_write treat outfile options extsize 2 1 directional False halfextension False else info Pileup alignment file extend each read towards downstream direction with d bps options extsize pileup_and_write treat outfile options extsize 1 directional True halfextension False info Done Check s options outputfile
check if dir cache mode is enabled in dostype,def is_dircache dos_type return dos_type DOS4 or dos_type DOS5
parameters : a1 ( : class:`myclass ` ) : used to call : def:`my_function ` and access : attr:`my_attr `,def func a1
finalize parse details . call at end of ` self.parse ( ) ` .,def finish_parse self self document reporter detach_observer self document note_parse_message
mark tests as needing all of the specified fixtures .,def usefixtures self fixturenames
checks whether the transaction manager is in manual or in auto state .,def is_managed using None if using is None using DEFAULT_DB_ALIAS thread_ident thread get_ident if thread_ident in state and using in state thread_ident if state thread_ident using return state thread_ident using 1 return settings TRANSACTIONS_MANAGED
"split the pathname path into a pair ( drive , tail ) .",def splitdrive path return path path
determine the maximum frame height of an animation,def animation_height animation height 0 for frame in animation if len frame height height len frame return height
"retrieves trashed documents , as an iterator .",def iter self page_size None view None sort None order None modified_since None deleted_since None return super Trash self iter page_size view sort order modified_since deleted_since
"> > > q.user.tags[0].name = = ' my tag ' < q : ( and : ( ' user__tags__0__name ' , ' my tag ' ) ) >",def __getitem__ self item if isinstance item slice return QFactory _ format item start item stop self else return QFactory str item self
"remainder of ` a ` and ` b ` , implies nothing .",def rem self a b return self zero
expand the density operator into an outer product format .,def doit self hints terms for state prob in self args state state expand if isinstance state Add for arg in product state args repeat 2 terms append prob self _generate_outer_prod arg 0 arg 1 else terms append prob self _generate_outer_prod state state return Add terms
returns the number of independent generators of e_n,def basis self n self n if n 6 return 78 if n 7 return 133 if n 8 return 248
: param parsed_sents : the list of parsed_sents as the output of parser : type parsed_sents : list(dependencygraph ),def __init__ self parsed_sents gold_sents self _parsed_sents parsed_sents self _gold_sents gold_sents
return repositories in path . can search in inner folders as depth .,def get_addons path depth 1 if not os path exists path or depth 0 return res if is_addons path res append path else new_paths os path join path x for x in sorted os listdir path if os path isdir os path join path x for new_path in new_paths res extend get_addons new_path depth 1 return res
"return `` true `` if we are using a database , `` false `` otherwise .",property def has_db self return self db_filename is not None
"calculate a "" continuous "" prediction .",def cts_predict self start_time None end_time None kernel self _kernel start_time end_time return _predictors KernelRiskPredictor kernel
"indicate whether the named node is present in the configuration . return true if the given node name is present , and false if not present .",def has_node self node return nodes in self data and node in self data nodes
run : func:`beaker_jobid_to_system_info ` and print the response .,def main pprint pprint beaker_jobid_to_system_info open a xml
test memory with a function with keyword arguments .,def test_memory_kwarg accumulator list def g l None m 1 accumulator append 1 return l for test in check_identity_lazy g accumulator yield test memory Memory cachedir env dir verbose 0 g memory cache g nose tools assert_equal g l 30 m 2 30
returns a link to the extrainfo detail page for users with one,def extrainfo_link self obj u n Returns a link to the ExtraInfo detail page for users with one n return format_html u a href admin register_cme extrainfo extrainfo_id ExtraInfo a extrainfo_id obj extrainfo id
returns the uplink queue : implementation of link.if.spacelink.getuplinkqueue,def getUplinkQueue self return self uplinkQueue
"geting the author friends w/o any auth will result in a 401 , even if the author i d does n't exist yet",def test_authoridfriends_get_unauth_401 self url reverse authorIdFriend args 1 response self client get url self assertEqual response status_code status HTTP_401_UNAUTHORIZED
store the information from the inverter in a mysql database .,def process_message self msg import mysql connector self logger debug Connect to database con mysql connector connect host self config get mysql host user self config get mysql user password self config get mysql pass database self config get mysql database cur con cursor self logger debug Executing SQL statement on database cur execute INSERT INTO minutes InvID timestamp ETotal EToday Temp HTotal VPV1 VPV2 VPV3 IPV1 IPV2 IPV3 VAC1 VAC2 VAC3 IAC1 IAC2 IAC3 FAC1 FAC2 FAC3 PAC1 PAC2 PAC3 VALUES s s s s s s s s s s s s s s s s s s s s s s s s msg id datetime datetime now msg e_today 10 int msg e_today 10 10 msg e_total msg e_today msg temp msg h_total msg v_pv 1 msg v_pv 2 msg v_pv 3 msg i_pv 1 msg i_pv 2 msg i_pv 3 msg v_ac 1 msg v_ac 2 msg v_ac 3 msg i_ac 1 msg i_ac 2 msg i_ac 3 msg f_ac 1 msg f_ac 2 msg f_ac 3 msg p_ac 1 msg p_ac 2 msg p_ac 3 con commit cur close con close
get data for training an sklearn model,def get_sklearn_data df load_arxiv_and_tweets sort_values published max_date df df tweeted 1 published max return get_features_matrix df df published max_date
"gets the list of availids in a standard group ( pmcs , services , podlings )",def getStandardGroup group logging info Fetching LDAP group list for s group ldap_base cn s ou project ou groups dc apache dc org group if CONFIG has_section group s group and CONFIG has_option group s group members logging warning Found hardcoded member list for s group return CONFIG get group s group members split if CONFIG has_section group s group and CONFIG has_option group s group ldap ldap_base CONFIG get group s group ldap ldap_key member if CONFIG has_section group s group and CONFIG has_option group s group ldapkey ldap_key CONFIG get group s group ldapkey groupmembers try ldapClient ldap initialize LDAP_URI ldapClient set_option ldap OPT_REFERRALS 0 ldapClient bind LDAP_USER LDAP_PASSWORD results ldapClient search_s ldap_base ldap SCOPE_BASE for result in results result_dn result 0 result_attrs result 1 if ldap_key in result_attrs for member in result_attrs ldap_key m UID_RE match member if m groupmembers append m group 1 ldapClient unbind_s groupmembers sorted groupmembers except Exception as err logging error Could not fetch LDAP data s err groupmembers None return groupmembers
return a new attr instance and set properties from dargs,def new_attr self dargs new_one self Attr virsh_instance self virsh for key value in list dargs items setattr new_one key value return new_one
attempts to find the qemu fs proxy binary at the installation prefix,def _qemu_fs_proxy_bin_exists_at_prefix self qemu_fs_proxy_bin_name os path join self install_prefix bin self QEMU_FS_PROXY_BIN if os path isfile qemu_fs_proxy_bin_name logging debug Found qemu fs proxy binary at s qemu_fs_proxy_bin_name return qemu_fs_proxy_bin_name else logging debug Could not find qemu fs proxy binary at prefix s self install_prefix return None
compile and benchmark a kernel instance based on kernel strings and parameters,def compile_and_benchmark self gpu_args params kernel_options tuning_options instance_string util get_instance_string params logging debug compile_and_benchmark instance_string mem_usage round resource getrusage resource RUSAGE_SELF ru_maxrss 1024 0 1 logging debug Memory usage 2 2f MB mem_usage verbose tuning_options verbose instance self create_kernel_instance kernel_options params verbose if instance is None return None try func self compile_kernel instance verbose if func is None return None if kernel_options cmem_args is not None self dev copy_constant_memory_args kernel_options cmem_args if tuning_options answer is not None self check_kernel_correctness func gpu_args instance tuning_options answer tuning_options atol tuning_options verify verbose time self benchmark func gpu_args instance tuning_options times verbose except Exception as e temp_filename util get_temp_filename suffix c util write_file temp_filename instance kernel_string print Error while compiling or benchmarking see source files temp_filename join instance temp_files values raise e for v in instance temp_files values util delete_temp_file v return time
atualiza a wiki com o status selecionado,def muda_status status wiki atualiza_pagina status status
login as the given user and booking flights . set retflightid = none if booking one way .,def book_flights self user toFlightId retFlightId r requests Session url format self _app_host self _api_context_root bookings bookflights headers Content Type self FORM_CONTENT_TYPE payload userid user toFlightId toFlightId if retFlightId is None payload oneWayFlight true else payload oneWayFlight false payload retFlightId retFlightId sessionId self login user cookies sessionid sessionId loggedinuser user print Book flight s str payload response r post url headers headers data payload cookies cookies if response status_code 200 print nFlight s booked n format response text else raise RuntimeError response text
@:return true if the channel pass the filter validation,def verifyFilters filters name country group lang if filters is None return True filterCountry filters get country None if filterCountry is not None if country is None or country lower not in filterCountry return False filterGroup filters get group None if filterGroup is not None if group is None or group lower not in filterGroup return False filterLang filters get lang None if filterLang is not None if lang is None or lang lower not in filterLang return False filterName filters get names None if filterName if include in filterName if not filterByName filterName include name return False if exclude in filterName if filterByName filterName exclude name return False return True
convert exception info into a string suitable for display .,def exception_format return join traceback format_exception sys exc_info 0 sys exc_info 1 sys exc_info 2
mkdir -p < name > if it does n't exist .,def make_dir name u n mkdir p name if it doesn t exist n if not os path exists name os makedirs name
": param look_for : "" icode "" or "" uuid """,login_required def Get_ID Look_for UUID Find_with if Find_with return looking_for if Look_for upper ICODE looking_for ICODE else looking_for UUID lu luv result if looking_for ICODE try luv Crosswalk objects get guid Find_with result luv hicn except Crosswalk DoesNotExist result else try luv Crosswalk objects get hicn Find_with result luv except Crosswalk DoesNotExist result lu looking_for result if settings DEBUG print lu returned lu return lu
saves this asset to the given storage .,def save self storage name meta u with closing self open as handle storage save name handle
creates a copy of the clusterer .,classmethod def make_copy cls associator return Associator jobject javabridge static_call weka associations AbstractAssociator makeCopy Lweka associations Associator Lweka associations Associator associator jobject
given an email return a capitalized name . ex . john.smith@example.com would return john smith .,def _get_name_from_email email name email rsplit 1 0 name join n_part capitalize for n_part in name split return name
log in an existing user .,account route login methods GET POST def login form LoginForm if form validate_on_submit user User query filter_by email form email data first if user is not None and user password_hash is not None and user verify_password form password data login_user user form remember_me data flash You are now logged in Welcome back success return redirect request args get next or url_for admin index else flash Invalid email or password form error return render_template account login html form form
"determine full module name from given easyconfig , according to the thematic module naming scheme .",def det_full_module_name self ec return os path join ec moduleclass ec name det_full_ec_version ec
clean up git working copy .,def cleanup self try self wc os path dirname self wc rmtree2 self wc except IOError as err raise EasyBuildError Can t remove working copy s s self wc err
"create(self , int width , int height , int bits_per_pixel , int image_origin=0 ) - > bool create(self , int width , int height , int bits_per_pixel ) - > bool",def Create args return _highgui CvvImage_Create args
"adds a wrapper around the documents pk field . the wrapper object gets the attributes django expects on the pk field , like name and attname .",def _init_pk self if id_field in self _meta self pk_name self _meta id_field pk_field getattr self document self pk_name else pk_field None self pk PkWrapper pk_field def _get_pk_val obj return obj pk patch_document _get_pk_val self document False if pk_field is not None self pk name self pk_name self pk attname self pk_name else self pk fake True self pk editable True
add an i / o handler to the loop .,def _add_io_handler self handler self _handlers append handler
get the hash function of the user object .,def GetHashFunction self return self _GetProperty USER_HASH_FUNCTION
gets domain single sign - on signing key,def GetSSOKey self return self genericGet sso signingkey
"return the string obtained by replacing the leftmost non - overlapping occurrences of the pattern in string by the replacement repl . repl can be either a string or a callable ; if a string , backslash escapes in it are processed . if it is a callable , it 's passed the match object and must return a replacement string to be used .",def sub pattern repl string count 0 flags 0 return _compile pattern flags sub repl string count
verifies the presence of all necessary arguments and returns the data dir,def handle_arguments if len sys argv 1 stderr no arguments provided show_help try keys values getopt getopt sys argv 1 hi f v except getopt GetoptError stderr invalid arguments provided show_help args args verbose 0 for key value in keys if key f args in fasta value if key i args in ids value if key v args verbose 1 if not args has_key in fasta stderr in fasta file missing show_help if not args has_key in ids stderr in ids file missing show_help if not file_exists args get in fasta stderr in fasta file does not exist show_help if not file_exists args get in ids stderr in ids file does not exist show_help return args
build a blueprint containing a flask route that is the hub endpoint .,def build_blueprint hub url_prefix return build_blueprint hub url_prefix
verifies the output values of the glimpse extraction kernel .,def _VerifyValues self tensor_in_sizes glimpse_sizes offsets expected_rows expected_cols rows tensor_in_sizes 0 cols tensor_in_sizes 1 t_rows tf tile 1 0 r for r in range 1 rows 1 1 cols name tile_rows t_rows_4d tf transpose tf expand_dims tf expand_dims t_rows 0 3 0 2 1 3 t_cols tf tile 1 0 r for r in range 1 cols 1 rows 1 name tile_cols t_cols_4d tf transpose tf expand_dims tf expand_dims t_cols 0 3 0 2 1 3 t1 tf constant glimpse_sizes 1 glimpse_sizes 0 shape 2 t2 tf constant offsets 1 offsets 0 shape 1 2 glimpse_rows tf transpose tf image extract_glimpse t_rows_4d t1 t2 0 2 1 3 glimpse_cols tf transpose tf image extract_glimpse t_cols_4d t1 t2 0 2 1 3 with self test_session as sess value_rows value_cols sess run glimpse_rows glimpse_cols self assertEqual value_rows shape 1 glimpse_sizes 0 self assertEqual value_rows shape 2 glimpse_sizes 1 self assertEqual value_cols shape 1 glimpse_sizes 0 self assertEqual value_cols shape 2 glimpse_sizes 1 min_random_val 0 max_random_val max rows cols for i in range glimpse_sizes 0 for j in range glimpse_sizes 1 if expected_rows i is None or expected_cols j is None self assertGreaterEqual value_rows 0 i j 0 min_random_val self assertLessEqual value_rows 0 i j 0 max_random_val self assertGreaterEqual value_cols 0 i j 0 min_random_val self assertLessEqual value_cols 0 i j 0 max_random_val else self assertEqual value_rows 0 i j 0 expected_rows i self assertEqual value_cols 0 i j 0 expected_cols j
perform a o(1 ) memory hash of an iterable of arbitrary length .,def hash_iterable it hash_value hash type it for value in it hash_value hash hash_value value return hash_value
convert the partitioned data for a word to a tuple containing the word and the number of occurances .,def estimate_pi item key occurances item return sum occurances NBR_POINTS 4
raise a valueerror if the input matrix does not satisfy the property .,def check_mat mat prop if prop square if mat ndim 2 or mat shape 0 mat shape 1 raise ValueError Expected a square matrix got array of shape 0 format mat shape if prop symmetric if not np allclose mat mat T raise ValueError Expected a symmetric matrix if prop spd if not is_spd mat raise ValueError Expected a symmetric positive definite matrix
returns the sgconnection the factory belongs to .,def connection self return self __connection
set the colour for the id,api expect IntColourModel api response 204 Colour successfully updated def put self int_id log debug Got parameter r int_id log debug Got body r request data COLOUR_DATA_DICT int_id Colour request json intcolour return None 204
call all extension drivers to extend prs dictionary .,def extend_policy_rule_set_dict self session result for driver in self ordered_ext_drivers driver obj extend_policy_rule_set_dict session result
stubs out the vmwareapisession 's get_vim_object method .,def fake_get_vim_object arg return fake_vmware_api FakeVim
upgrades a cluster to a new datastore version .,def upgrade self cluster datastore_version body upgrade datastore_version datastore_version return self _action cluster body
connect a callback to a signal . returns an callback handle that can be passed into disconnect ( ) .,def connect self name func extra_args self _check_already_connected name func id_ self id_generator next callbacks self get_callbacks name callbacks id_ Callback func extra_args return name id_
enable macro keys on the keyboard,def marco_keys self enable if enable print Daemon Marco Keys Enabled self dbus_daemon_controls enable_macro_keys else print DBUS Restart the razer_bcd service to disable marco keys
"the fixture returned by the `` pytest_clean_fixture ( ) `` method should yield a started container , and afterwards stop and remove the container .",def test_clean_fixtures self request docker_helper raw_fixture fixture ContainerDefinition name test image IMG pytest_clean_fixtures test fixture_gen raw_fixture request docker_helper container next fixture_gen assert isinstance container ContainerDefinition assert container inner status running with pytest raises StopIteration next fixture_gen assert not container created
passing `` success_url `` to the `` activate `` view and successfully activating will result in that url being used for the redirect .,def test_activation_success_url self success_redirect http testserver s reverse registration_test_custom_success_url self client post reverse registration_register data username alice email alice example com password1 swordfish first_name First last_name Last password2 swordfish profile RegistrationProfile objects get user__username alice response self client get reverse registration_test_activate_success_url kwargs activation_key profile activation_key self assertRedirects response success_redirect
the full glib functionality is available if needed . here 's a timer function which will be called periodically returning true restarts the timer returning false makes it a one - shot,def _on_timer_tick self userdata None self ticks 1 self halcomp value self ticks return True
"given a list of reference values and a corresponding list of test values , return the percentage of corresponding values that are equal . in particular , return the percentage of indices c{0<i<=len(test ) } such that c{test[i ] = = reference[i]}.",def accuracy reference test assert chktype 1 reference assert chktype 2 test if len reference len test raise ValueError Lists must have the same length num_correct 1 for x y in zip reference test if x y return float len num_correct len reference
"wait for calls , answer , peer hangup",def test_ip2ip_recv_peer_hungup self self sflphone onIncomingCall_cb acceptOnIncomingCall self sflphone start
generates the instructions according to a set level of strength . 1 : minimum strength ; 9 : maxmimum strength,def create_instructions n try n int n except ValueError n 9 if n 1 n 1 if n 9 n 9 hexseeds list generate_hexseed n random randint 1 1 n addvalpos list generate_addvalpos n random randint 1 1 n 2 rgbscramble list generate_rgbscrambling n random randint 1 1 n 2 return hexseeds addvalpos rgbscramble
returns base64 version of data .,def _b64 data if data is None return None try return b64encode bytes data utf 8 decode utf 8 except Exception return b64encode data
"return base path . override to customize behavior ( per - user directories , etc )",def get_base_path self return op normpath self base_path
return balance of the wallet and the wallet itself .,def get_balance owner_id currency cached True wallet_obj get_wallet owner_id currency if not cached return wallet_obj wallet_obj transactions balance return wallet_obj wallet_obj balance
create a from node and register it in the locals of the given node with the specified name,def attach_import_node node modname membername from_node From modname membername None _attach_local_node node from_node membername
"open the file , parses it and return the values",def parse fname retdict defaultdict list if show_output print Parsing file format __name__ inspect currentframe f_code co_name fname with open fname as f lines f readlines for lno l in enumerate lines if Distance to Nearest Neighbour Shells in l for l2 in lines lno 4 match near_neigh_re search l2 if not match or in l2 break _ dist mult match groups retdict near_neigh_dist append float dist retdict near_neigh_mult append int mult continue if Completeness relation is fully satisfied in l for l2 in lines lno 6 match completeness_re search l2 if not match or in l2 break _ bkx bky bkz bkw match groups retdict completeness_x append float bkx retdict completeness_y append float bky retdict completeness_z append float bkz retdict completeness_weight append float bkw continue if Final State in l for l2 in lines lno 1 match spread_re search l2 if not match break _ x y z s match groups retdict final_centres_x append float x retdict final_centres_y append float y retdict final_centres_z append float z retdict final_spreads append float s continue match omegaI_re search l if match retdict omegaI append float match groups 0 continue match omegaD_re search l if match retdict omegaD append float match groups 0 continue match omegaOD_re search l if match retdict omegaOD append float match groups 0 continue match omegaTotal_re search l if match retdict omegaTotal append float match groups 0 continue retdict dict retdict if show_output for k in sorted retdict print format k retdict k print 72 return retdict
url - > full target url method - > method from requests data - > request body kwargs - > url formatting args,def _http_response self url method data None kwargs header content type application json if data data json dumps data path url format kwargs logger debug s s method __name__ upper path response method self host path data data headers header self method_kwargs logger debug s s response status_code response reason response raise_for_status return response
return priority for a give object .,def priority s if type s in list tuple set frozenset return 6 if type s is dict return 5 if hasattr s validate return 4 if type s is type return 3 if callable s return 2 else return 1
return flowcell run object with updated fields .,def get_flowcell_run self self _update_flowcellrun logger debug returning flowcell run object info format self flowcellrun to_json return self flowcellrun
the c{--flush - interval } command line option can be used to specify the flush interval .,def test_flush_interval self self config load flush interval 123 self assertEqual self config flush_interval 123
invalid values raise an errors .,def test_unicode_bad_value self self assertRaises InvalidError Unicode coerce 32
dicts which are applied to a keydict must have all the keys specified in the keydict .,def test_key_dict_must_have_all_keys self schema KeyDict foo Int self assertRaises InvalidError schema coerce
check whether the given request ( http or drf ) is allowed to comment on this commentable .,def check_commenting self request is_authenticated request user is_authenticated if self commenting Commenting NONE raise ValidationError _ s does not allow commenting self code commenting_none elif self commenting Commenting REGISTERED if not is_authenticated raise ValidationError _ s does not allow anonymous commenting self code commenting_registered elif self commenting Commenting OPEN return else raise NotImplementedError Not implemented
calculate the volume of an object .,def calc_volume obj bm bmesh_copy_from_object obj apply_modifiers True volume bm calc_volume signed True bm free return abs volume
retrieve the category by his path .,def get_object self request path return get_category_or_404 path
"drops the database table of the given model class , if it exists .",def drop_table self model_class u n Drops the database table of the given model class if it exists n if model_class is_system_model raise DatabaseException u You can t drop system table self _send model_class drop_table_sql self
spawns contrail vm on openstack managed esxi server ( non vcenter env ),def create_esxi_compute_vm esxi_host vcenter_info power_on mode get_mode esxi_host contrail_vm host datastore esxi_host datastore with settings host_string esxi_host username esxi_host ip password esxi_host password warn_only True shell bin sh l c src_vmdk var tmp ContrailVM disk1 vmdk if vmdk_download_path in esxi_host contrail_vm keys vmdk_download_path esxi_host contrail_vm vmdk_download_path run wget O s s src_vmdk vmdk_download_path else vmdk esxi_host contrail_vm vmdk if vmdk is None assert vmdk Contrail VM vmdk image or download path should be specified in testbed file put vmdk src_vmdk if mode is openstack vm_name esxi_host contrail_vm name if mode is vcenter name ContrailVM vm_name name esxi_host datacenter esxi_host ip vm_store datastore vm_name vmx_file create_vmx esxi_host vm_name vmid run vim cmd vmsvc getallvms grep s awk print 1 vm_name if vmid run vim cmd vmsvc power off s vmid run vim cmd vmsvc unregister s vmid run rm rf s vm_store out run mkdir p s vm_store if out failed raise Exception Unable create s on esxi host s s vm_store esxi_host ip out dst_vmx vm_store vm_name vmx out put vmx_file dst_vmx os remove vmx_file if out failed raise Exception Unable to copy s to s on s s vmx_file vm_store esxi_host ip out dst_vmdk vm_store vm_name vmdk out run vmkfstools i s d zeroedthick s src_vmdk dst_vmdk if out failed raise Exception Unable to create vmdk on s s esxi_host ip out run rm src_vmdk out run vim cmd solo registervm dst_vmx if out failed raise Exception Unable to register VM s on s s vm_name esxi_host ip out if power_on False return out run vim cmd vmsvc power on s out if out failed raise Exception Unable to power on s on s s vm_name esxi_host ip out
"get an xmlrpc handle to the master . it is recommended to use the ` rosgraph.masterapi ` library instead , as it provides many conveniences .",def get_master try import xmlrpc client as xmlrpcclient except ImportError import xmlrpclib as xmlrpcclient uri rosgraph get_master_uri return xmlrpcclient ServerProxy uri
: param machine : machine instance . must be fully configured . machine.env_loader is required to be set .,def __init__ self run_id name server_uri machine master_uri None if not machine env_loader raise ValueError machine env_loader must have been assigned before creating ssh child instance args machine env_loader roslaunch c name u server_uri run_id run_id super SSHChildROSLaunchProcess self __init__ name args self machine machine self master_uri master_uri self ssh self sshin self sshout self ssherr None self started False self uri None self is_dead False
straightforward wrapper around ` requests . session.request < http://docs.python - requests.org / en / master / api/#requests . session.request>`__.,def request self args kwargs response self session request args kwargs Browser add_soup response self soup_config return response
qimage not created from bgr ndarray,patch object QImage isNull return_value True def test_qimage_of_bgr_null_qimage self mock_is_null self assertRaises ValueError qimage_of_bgr cv2 imread str TESTDATA joinpath shapes png mock_is_null assert_called_once_with
function that maps the given function to items in the given iterable keeping the type of the iterable .,def keep_type_map func iterable if isinstance iterable dict return dict func key iterable key for key in iterable items_gen func item for item in iterable if isinstance iterable list return list items_gen elif isinstance iterable tuple if iterable __class__ is tuple return tuple items_gen else return iterable __class__ items_gen elif isinstance iterable set return set items_gen elif isinstance iterable str return join items_gen else return items_gen
returns trace of shape with intensity as radial extension,def genShape vizMTX V sph2cartMTX vizMTX trace go Surface x V xs y V ys z V zs surfacecolor _np abs vizMTX reshape 181 1 T colorscale Viridis showscale False hoverinfo none return trace
: type input _ : theano.tensor.tensortype : param input _ : symbolic variable that describes the input ( one minibatch ),def __init__ self input_ n_in n_out self input input_ self W theano shared value numpy zeros n_in n_out dtype theano config floatX name W borrow True self b theano shared value numpy zeros n_out dtype theano config floatX name b borrow True self p_y_given_x T nnet softmax T dot input_ self W self b self params self W self b
"set the current rotation to * matrix*. after decorating the evaluation function , this function will be available directly from the function object . : : # create a random orthogonal matrix a = numpy.random.random((n,n ) ) q , _ = numpy.linalg.qr(a ) @rotate(q ) def evaluate(individual ) : return sum(individual ) , # this will reset rotation to identity evaluate.rotate(numpy.identity(n ) )",def rotate self matrix self matrix numpy linalg inv matrix
initiates a reaction based on being delayed ( consuming or nonconsuming ) or not,def InitiateReaction self if self reaction_index in self reactions_Consuming self X_matrix self N_matrix_transpose_reactants self reaction_index self species_to_update self parse reactant_indices self reaction_index self add_delay elif self reaction_index in self reactions_NonConsuming self add_delay self species_to_update else self X_matrix self N_matrix_transpose self reaction_index self species_to_update self parse reaction_affects self reaction_index
returns true if the argument is not none,def not_none x return x is not None
write an 8-bit value to the specified register .,def write8 self register value value value 255 self _bus write_byte_data self _address register value self _logger debug Wrote 0x 02X to register 0x 02X value register
read a length code string from a buffer ( < = 2 ^ 16 bytes ),def test_read_lc_string_2 self exp a 2 16 1 expsize len exp lcs xfc utils int2store expsize exp rest result utils read_lc_string lcs if result exp or len result expsize self fail Wrong result Expected d got d expsize len result
"runs a function of the db session and attempts to commit . if we encounter a dropped connection , we retry the operation . the retries are spaced out using exponential backoff with full jitter . all other errors are propagated .",backoff on_exception backoff expo DBAPIError max_tries RETRY_CONNECTION_LIMIT giveup lambda err not getattr err connection_invalidated False def autoretry self func with self session as session return func session
this function selects a matcher from a given list of matchers based on a given metric .,def select_matcher matchers x None y None table None exclude_attrs None target_attr None metric_to_select_matcher precision metrics_to_display precision recall f1 k 5 n_jobs 1 random_state None if not isinstance metrics_to_display list metrics_to_display metrics_to_display for met in metrics_to_display if met not in precision recall f1 logger error Metrics must be either precision recall or f1 raise AssertionError Metrics must be either precision recall or f1 if metric_to_select_matcher not in precision recall f1 logger error Metric must be either precision recall or f1 raise AssertionError Metric must be either precision recall or f1 x y _get_xy_data x y table exclude_attrs target_attr max_score 0 sel_matcher matchers 0 header Name Matcher Num folds fold_header Fold str i 1 for i in range k header extend fold_header header append Mean score drill_down_cv_stats OrderedDict cv_stats_dict OrderedDict matcher_names for m in matchers matcher_names append m get_name cv_stats_dict Matcher matcher_names for met in metrics_to_display dict_list mean_score_list for m in matchers matcher scores cross_validation m x y met k random_state n_jobs val_list matcher get_name matcher k val_list extend scores val_list append pd np mean scores d OrderedDict zip header val_list dict_list append d mean_score_list append pd np mean scores if met metric_to_select_matcher and pd np mean scores max_score sel_matcher m max_score pd np mean scores stats pd DataFrame dict_list stats stats header drill_down_cv_stats met stats cv_stats_dict Average met mean_score_list res OrderedDict res selected_matcher sel_matcher res cv_stats pd DataFrame cv_stats_dict res drill_down_cv_stats drill_down_cv_stats return res
"construct a geopoint from a formatted latitude , longitude string @param point_string - latitude , longitude @type point_string string @return geopoint",classmethod def from_string cls point_string try lat_lon point_string split lat float lat_lon 0 lon float lat_lon 1 g GeoPoint g latitude lat g longitude lon return g except ValueError IndexError as e raise Exception GeoPoint Invalid point string specified format point_string e
"log a value of some diagnostic call this once for each diagnostic quantity , each iteration",def log_tabular key val if G first_row G log_headers append key else assert key in G log_headers Trying to introduce a new key s that you didn t include in the first iteration key assert key not in G log_current_row You already set s this iteration Maybe you forgot to call dump_tabular key G log_current_row key val
unregister any listeners for the view that was just closed .,def on_close self view set_timeout_async lambda mediator remove view 1
if i 'm not logged in i can not post to the writeit instance delete url,def test_post_if_not_logged_in self url reverse delete_an_instance subdomain self writeitinstance slug c self client response c post url self assertEquals response status_code 404
"' 1.2.3 ' = > ( 1 , 2 , 3 )",def caseIdtoIdTuple self id return tuple int x for x in id split
create a website using the new_website cookie .,def bake_the_website self host port website_path cookie_jar None self cookielog warn Creating directories from the Website Cookie template if cookie_jar self cookie_jar cookie_jar e_c website_name self website website_path os path join str website_path website_host host website_port port cookiecutter str self Recipes website_cookie no_input True extra_context e_c output_dir str self cookie_jar os chmod str self cookie_jar Path self website mode 511 script_path website_path Path hooks Path post_gen_project sh run_script script_path str script_path cwd str website_path self cookielog info Directories have been created for the Flask Web Server s xe2 x9c x94 self website self cookielog warn The s Flask Server should now be running on http s s self website host port
get the file that represent the value of this pin .,def _sysfs_gpio_value_path self return SYSFS_GPIO_VALUE_PATH self number
input : p : : predictions g : : groundtruth w : : corresponding words f : : original input gold standard file,def save_to_disfeval_file p g w f filename incremental False out if incremental False for sl sp sw in zip g p w out BOS O O n for wl wp w in zip sl sp sw out w wl wp n out EOS O O n n else for sl sp sw in zip g p w prefix sw append EOS sl append O sp 1 append O for wl pp w in zip sl sp sw prefix append w wl assert len prefix len pp str prefix str pp out BOS O O n for my_prefix my_prediction in zip prefix pp out my_prefix my_prediction n out n f open filename w f writelines out f close return filename
return the name of a message given the message i d .,def getMIDName mid name getName MID mid if name return name if mid 1 name getName MID mid 1 if name return name Ack return unknown MID
"tests calling the "" tokenize "" method .",def test_tokenize self tokenizer Tokenizer classname weka core tokenizers WordTokenizer self assertIsNotNone tokenizer msg Tokenizer should not be None sentence The quick brown fox jumps over the lazy dog words list tokenizer tokenize sentence self assertEqual u The u quick u brown u fox u jumps u over u the u lazy u dog words msg Tokens differ
"plot spikes as frames , exported as png images .",def plot_spikes spikes output_dir data output image_naming timestamps resolution 240 180 offsets 0 0 frame_length 1000 pivots None color_range 0 10 if pivots is not None if isinstance pivots str and pivots endswith npy pivots np load pivots 1000 0 frames timestamps generate_frames_from_spikes resolution resolution xs spikes xs offsets 0 ys spikes ys offsets 1 ts spikes ts zs spikes zs time_interval frame_length pivots pivots non_pixel_value 1 for i ts img in enumerate zip timestamps frames plt imshow img interpolation none vmin color_range 0 vmax color_range 1 plt colorbar plt savefig os path join output_dir 04d png format i if image_naming enumerate else png format ts plt gcf clear
"output : [ ' < stream > < event stanza=""test_scheme://test "" unbroken=""1 "" > < time>1459919070.994</time > < index > main</index > < host > localhost</host > < source > test</source > < sourcetype > test</sourcetype > < data>{""kk "" : [ 1 , 2 , 3]}</data > < done / > < /event > < event stanza=""test_scheme://test "" unbroken=""1 "" > < time>1459919082.961</time > < index > main</index > < host > localhost</host > < source > test</source > < sourcetype > test</sourcetype > < data>{""kk "" : [ 3 , 2 , 3]}</data > < done / > < /event > < /stream > ' ]",classmethod def format_events cls events stream ET Element stream for event in events stream append event _to_xml return ET tostring stream encoding utf 8 method xml
compares predicted and golden lexica .,def CompareLexica golden_lex predicted_lex writer golden_cutoff None predicted_cutoff None u Compares predicted and golden lexica n n Compares the predicted pronunciations against the golden n reference dictionary Outputs statistics to writer in n tab separated value format with headers to facility further n analysis with R n n Args n golden_lex golden lexicon to compare against n predicted_lex lexicon containing predicted pronunciations n writer writer to which output will be sent n golden_cutoff only consider top n golden pronunciations n predicted_cutoff only consider top n predicted pronunciations n stats Stats for word prons in predicted_lex items if word not in golden_lex _stderr write u Warning Word s not found in golden lexicon n word stats not_found 1 continue else stats words_total 1 assert prons stats prons len prons assert len golden_lex word 1 argvals for predicted in prons predicted_cutoff predicted_pron predicted 0 inner_argmin None inner_valmin _INF for golden in golden_lex word golden_cutoff golden_pron golden 0 ed edist EditDistance golden_pron predicted_pron edist LevenshteinCost val fdiv ed Valmin len golden_pron if val inner_valmin inner_argmin golden predicted ed inner_valmin val assert inner_argmin is not None if FLAGS output_word_stats writer write u PRON_PhE t s t s t s t f t s n word u join inner_argmin 0 0 u join predicted_pron inner_valmin u t join predicted 2 argvals append inner_argmin inner_valmin assert argvals argvals sort key lambda x x 1 if FLAGS predicted_oracle_type u best index 0 elif FLAGS predicted_oracle_type u worst index 1 elif FLAGS predicted_oracle_type u median index len argvals 1 else assert False u This cannot happen golden predicted ed pherr argvals index golden_pron golden 0 edits ed Valmin assert fdiv edits len golden_pron pherr if FLAGS output_word_stats writer write u WORD_PhE t s t s t s t f t s n word u join golden_pron u join predicted 0 pherr u t join predicted 2 if edits 0 stats word_error 1 stats phone_edits edits stats reference_length len golden_pron stats phone_error pherr stats squared_phone_error pherr pherr if pherr stats max_phone_error stats max_phone_error pherr if FLAGS output_edit_stats alignment ed Argmin u eps u eps for edit in alignment if edit not in stats edit_stats stats edit_stats edit 0 stats edit_stats edit 1 rr 0 found False for i predicted in enumerate prons predicted_cutoff predicted_pron predicted 0 for golden in golden_lex word golden_cutoff golden_pron golden 0 if predicted_pron golden_pron rr fdiv 1 1 i found True break if found break assert found rr 0 stats reciprocal_rank rr if FLAGS output_word_stats writer write u WORD_RR t s t f n word rr if FLAGS output_edit_stats for i o c in stats edit_stats items writer write u EDIT t s t s t d n i o c if FLAGS output_summary_stats writer write u MISSING d words without reference pronunciation n stats not_found writer write u TOTAL d words with reference pronunciation n stats words_total writer write u PRONS d pronunciations n stats prons writer write u PPW 6f pronunciations per word average n fdiv stats prons stats words_total writer write u ORACLE s n FLAGS predicted_oracle_type writer write u WER 4f word error rate n 100 fdiv stats word_error stats words_total writer write u PhER 4f phone error rate n 100 fdiv stats phone_edits stats reference_length writer write u AVG_PhE 4f mean phone error per word n 100 fdiv stats phone_error stats words_total writer write u RMS_PhE 4f root mean square phone error per word n 100 math sqrt fdiv stats squared_phone_error stats words_total writer write u MAX_PhE 4f maximum phone error per word n 100 0 stats max_phone_error writer write u MRR 6f mean reciprocal rank n fdiv stats reciprocal_rank stats words_total return
"@brief import pip . will install pip if necessary , and restarts the program after installment .",def ImportPip self try globals pip importlib import_module pip except ImportError restart_cmd sys argv sys argv sys argv 0 get_pip_main os execv sys executable python restart_cmd sys exit
@brief load calibration parameters from dictionary or list,def LoadParams self parameters load_from_json False ok False dictionary if len parameters 0 ok True if load_from_json for key in parameters dictionary key self ListToNumpyArray parameters key else dictionary parameters return ok dictionary
create a set of wrappers based on a list determined by the easyconfig file,staticmethod def extra_options extra_vars host_compilers None Host compilers for which a wrapper will be generated CUSTOM return Binary extra_options extra_vars
custom sanity check for samcef .,def sanity_check_step self custom_paths files samcef dirs super EB_Samcef self sanity_check_step custom_paths custom_paths
"create module file , before copy of original environment that was tampered with is restored .",def make_module_step self fake False modpath super EB_EasyBuildMeta self make_module_step fake fake if not fake self initial_environ copy deepcopy self real_initial_environ self log debug Restored copy of original environment return modpath
send a password reset to the user 's email address .,def send_password_reset self site Site objects get_current self password_reset_notification user self site site notify
return width of available window area . autodetection works for windows and posix platforms . returns 80 for others,def get_console_width if os name nt STD_INPUT_HANDLE 10 STD_OUTPUT_HANDLE 11 STD_ERROR_HANDLE 12 from ctypes import windll Structure byref try from ctypes wintypes import SHORT WORD DWORD except ImportError from ctypes import c_short as SHORT c_ushort as WORD c_ulong as DWORD console_handle windll kernel32 GetStdHandle STD_OUTPUT_HANDLE class COORD Structure _fields_ X SHORT Y SHORT class SMALL_RECT Structure _fields_ Left SHORT Top SHORT Right SHORT Bottom SHORT class CONSOLE_SCREEN_BUFFER_INFO Structure _fields_ dwSize COORD dwCursorPosition COORD wAttributes WORD srWindow SMALL_RECT dwMaximumWindowSize DWORD sbi CONSOLE_SCREEN_BUFFER_INFO ret windll kernel32 GetConsoleScreenBufferInfo console_handle byref sbi if ret 0 return 0 return sbi srWindow Right 1 elif os name posix from fcntl import ioctl from termios import TIOCGWINSZ from array import array winsize array H 0 4 try ioctl sys stdout fileno TIOCGWINSZ winsize except IOError pass return winsize 1 winsize 0 0 return 80
perform data manipulation and datadump without affecting the database,def handle self args options try with transaction atomic self manipulate_data self create_fixture raise FakeException Trigger rollback except FakeException pass
generate placeholder variables to represent the input tensors .,def placeholder_inputs images_placeholder tf placeholder tf float32 shape None mnist IMAGE_PIXELS labels_placeholder tf placeholder tf int32 shape None return images_placeholder labels_placeholder
decorator for marking specific function argument values as deprecated .,def deprecated_arg_values date instructions deprecated_kwargs _validate_deprecation_args date instructions if not deprecated_kwargs raise ValueError Specify which argument values are deprecated def deprecated_wrapper func Deprecation decorator decorator_utils validate_callable func deprecated_arg_values functools wraps func def new_func args kwargs Deprecation wrapper named_args inspect getcallargs func args kwargs for arg_name arg_value in deprecated_kwargs items if arg_name in named_args and named_args arg_name arg_value logging warning From s calling s from s with s s is deprecated and will be removed after s Instructions for updating s _call_location decorator_utils get_qualified_name func func __module__ arg_name arg_value date instructions return func args kwargs new_func __doc__ _add_deprecated_arg_notice_to_docstring func __doc__ date instructions return new_func return deprecated_wrapper
"subscription process stage 3 : verfies contact details for the subscriber id specified in the url . if no sms number is provided , then just landing on this page is enough to verify the users email address ( assuming the id is not guessable ) . in this case we do a redirect to stage 4 . if the user has already been verified , then we also redirect to stage four with a flash message to remind them that they have already verified . in all other cases we show the sms verification form .",messaging route subscribe verify string subscriber_id def verify subscriber_id subscriber libs hermes subscribe subscriber_id GET if subscriber Item verified is True flash gettext You have already verified your account return redirect g get language messaging subscribe verified subscriber_id code 302 elif sms not in subscriber Item current_app logger warning str subscriber Item libs hermes verify subscriber_id GET return redirect g get language messaging subscribe verified subscriber_id else return render_template messaging verify html content g config MESSAGING_CONFIG week c api epi_week data subscriber Item
function writes out dataframes as tsv files,def DF_to_TSV dataframe NewFileName path Users mmacgilvray18 Desktop dataframe to_csv path NewFileName sep t
"{ "" title"":""turn off"",""desc"":""turns this computer off."",""group"":""power "" }",def local_action_TurnOff arg None print Action TurnOff requested shutdown
returns a string representation of the instance,def __str__ self params self address self count return WriteMultipleRegisterRequest d d params
test function to check admin queue add,def test_admin_queue_view_add self response self client get admin callcenter queue add self assertEqual response status_code 200
write the given list of lines to a text file and return the absolute path to it .,def makeSourceFile self sourceLines script self mktemp scriptFile file script wt scriptFile write os linesep join sourceLines os linesep scriptFile close return os path abspath script
return the mp version of ( x**y)%z,def _MPpow x y z return MP pow x y z
classes representing constants containers are not intended to be instantiated .,def __new__ cls raise TypeError s may not be instantiated cls __name__
specify an extension to ignore . these will be processed in order .,def opt_ignore_ext self ext if not isinstance self root static File raise usage UsageError You can only use ignore_ext after path self root ignoreExt ext
"read and return the next record from c{self._users } , filtering out any records with previously seen uid values ( as these can not be found with c{getpwuid } and only cause trouble ) .",def getExistingUserInfo self while True entry next self _users uid entry pw_uid if uid not in self _uids self _uids add uid return entry
l{loopback.loopbackasync } does not call a protocol 's c{datareceived } method while that protocol 's transport 's c{write } method is higher up on the stack .,def test_writeNotReentrant self class Server Protocol def dataReceived self bytes self transport write bytes class Client Protocol ready False def connectionMade self reactor callLater 0 self go def go self self transport write foo self ready True def dataReceived self bytes self wasReady self ready self transport loseConnection server Server client Client d loopback loopbackAsync client server def cbFinished ignored self assertTrue client wasReady d addCallback cbFinished return d
sends get request to blazar .,def get self url return self request url GET
add options that are common for several plugins .,classmethod def add_common_opts cls parser for opt in cls common_opt_names cls _parser_add_opt parser opt
gets property or calls method of related config object without rasing an exception if config is not set,def _get_config_attr self attr if not self _has_config return None attr getattr self config attr return attr if callable attr else attr
state space system with state space feedback block .,def testSSSS1 self ans1 feedback self sys2 self sys2 ans2 feedback self sys2 self sys2 1 0 np testing assert_array_almost_equal ans1 A 1 0 4 0 1 0 0 0 3 0 2 0 4 0 0 0 1 0 0 0 1 0 4 0 4 0 0 0 3 0 2 np testing assert_array_almost_equal ans1 B 1 0 4 0 0 0 0 0 np testing assert_array_almost_equal ans1 C 1 0 0 0 0 0 0 0 np testing assert_array_almost_equal ans1 D 0 0 np testing assert_array_almost_equal ans2 A 1 0 4 0 1 0 0 0 3 0 2 0 4 0 0 0 1 0 0 0 1 0 4 0 4 0 0 0 3 0 2 0 np testing assert_array_almost_equal ans2 B 1 0 4 0 0 0 0 0 np testing assert_array_almost_equal ans2 C 1 0 0 0 0 0 0 0 np testing assert_array_almost_equal ans2 D 0 0
test validationerror class ' transaction_error_code ' property,def test_transaction_error_code_property self transaction Transaction amount_in_cents 1000 currency USD account Account account_code transactionmock with self mock_request transaction declined transaction xml try transaction save except ValidationError as e error e self assertEqual error transaction_error_code insufficient_funds
set the values for a cell range .,def set_cell_range self sheet cell_ref data self __check_for_lock r self __cell_range_to_index cell_ref sheet self spreadsheet sheets sheet if r row_start r row_end data self __check_1D_list data sheet r row_start r column_start r column_end 1 values data elif r column_start r column_end data self __check_1D_list data sheet r row_start r row_end 1 r column_start values data else self __check_list data for x row in enumerate data if not isinstance row list raise ValueError Expected a list of cells for y cell in enumerate row data x y self __convert_to_float_if_numeric cell sheet r row_start r row_end 1 r column_start r column_end 1 values data
get a cassandra stress cmd string suitable for grow cluster purposes .,def get_stress_cmd self mode write duration None ip self db_cluster get_node_private_ips 0 population_size self params get cassandra_stress_population_size default 1000000 if not duration duration self params get test_duration default 60 threads self params get cassandra_stress_threads default 1000 return cassandra stress s cl QUORUM duration sm schema replication factor 3 port jmx 6868 col size FIXED 2 n FIXED 1 mode cql3 native rate threads s pop seq 1 s node s mode duration threads population_size ip
"return the timecode corresponding to the given frame , for the given fps .",def timecode_from_frame frame_duration fps 24 0 seconds frame_duration fps remainder seconds int seconds frames int round remainder fps minutes int seconds 60 remainder minutes int minutes seconds int round remainder 60 hours int minutes 60 remainder hours int hours minutes int round remainder 60 hours int hours timecode 02d 02d 02d 02d hours minutes seconds frames return timecode
returns list of data we have for this probe from wolfram alpha url = /<probe_name > ie < /cassini >,app route probes probe support_jsonp json def detail probe return get_detail probe 200
command : generates catalog_metadata from readme data .,def generate_metadata_files self for project in self get_projects_from_readme metadata_file os path join self collection_root project relative_path catalog_metadata print Generating format metadata_file with open metadata_file w as f json dump project f indent 4
returns the quality ' q ' of a mime - type when compared against the media - ranges in ranges . for example :,def quality mime_type ranges parsed_ranges parse_media_range r for r in ranges split return quality_parsed mime_type parsed_ranges
parses and initializes the echorequest object from the echo_request_data .,def ParseAndInitialize self echo_request_data EchoHeader ParseAndInitialize self echo_request_data if len echo_request_data EchoRequest PAYLOAD_START raise ValueError Invalid data s echo_request_data self payload echo_request_data EchoRequest PAYLOAD_START
logarithm of elbo on posterior probabilities : log q(weights|learned mu and rho ) aka log q(theta|x ),def log_posterior_approx self weights mean rho std T log1p T exp rho return self log_normal weights mean std
""" extract mbap header from request adu and return it . the dict has 4 keys : transaction_id , protocol_id , length and unit_id .",def get_meta_data self request_adu return unit_id struct unpack B request_adu 1 0
register a new path to handle in tuio provider,staticmethod def register oscpath classname TuioMotionEventProvider __handlers__ oscpath classname
"no unicode can get into the http request , otherwise unicode decode errors may be raised . use this function to find and fix the issues .",classmethod def _to_data cls data data_type if isinstance data unicode logging warning s is in unicode converting to str data_type data data encode utf8 if not isinstance data str logging error s not returning str s data_type type data return data
results : learning rate of 0.1 still nans .,def exp_a name e91d but learning rate 0 01 and smaller inits to try to capture smaller changes and larger first layer And e96 centres input data And I ve fixed a problem where only the last instance of an appliance if multiple appliances occured within a batch would be shown in the targets source RealApplianceSource filename data dk3810 ukdale h5 appliances fridge freezer fridge freezer hair straighteners television dish washer washer dryer washing machine max_appliance_powers 300 500 200 2500 2400 on_power_thresholds 20 20 20 20 20 min_on_durations 60 60 60 1800 1800 window 2013 06 01 2014 07 01 seq_length 1500 output_one_appliance False boolean_targets False min_off_duration 60 subsample_target 5 train_buildings 1 validation_buildings 1 skip_probability 0 7 X_processing_func partial standardise how std 1 mean 0 06 std 0 18 net Net experiment_name name a source source save_plot_interval SAVE_PLOT_INTERVAL loss_function crossentropy updates partial nesterov_momentum learning_rate 0 01 layers_config type DenseLayer num_units 200 nonlinearity sigmoid W Uniform 10 b Uniform 10 type DenseLayer num_units 50 nonlinearity sigmoid W Uniform 5 b Uniform 5 type BLSTMLayer num_units 40 W_in_to_cell Uniform 5 gradient_steps GRADIENT_STEPS type DimshuffleLayer pattern 0 2 1 type Conv1DLayer num_filters 60 filter_length 5 stride 5 nonlinearity sigmoid type DimshuffleLayer pattern 0 2 1 type BLSTMLayer num_units 80 W_in_to_cell Uniform 5 gradient_steps GRADIENT_STEPS type DenseLayer num_units source n_outputs nonlinearity sigmoid return net
fetches an entry from the database and displays it in a view . the entry is retrieved from the database and the id is a primary key for the entry .,utilities cache cached timeout 60 5 scoreboard route result rid methods GET def result rid entry_name Result query filter_by id rid first if entry_name progress_bar_data dict progress_bar_data value utilities get_progress_bar_score entry_name score progress_bar_data class utilities get_progress_bar_class entry_name score return flask render_template result html name entry_name progress_bar progress_bar_data else flask abort 404
class to hold information about a single video downloaded as content from a reddit submission,def __init__ self userOrSubName submissionID defaultPath URL redditSubmissionURL numInSeq specialString None specialCount None specialPath None super __init__ userOrSubName submissionID defaultPath URL redditSubmissionURL numInSeq specialString specialCount specialPath ydlOpts outtmpl str self savePath _ autonumber s ext s quiet True restrictfilenames True no_warnings True ignoreerrors True logtostderr False nooverwrites False logger MockLogger bidi_workaround False self _ydl youtube_dl YoutubeDL ydlOpts self _ydl add_default_info_extractors self _ydl to_stderr lambda 1
fetch all private channels in which the user participates .,def get_private_channels self return self client api_call groups list
it is tracking the bunch through the space charge calculator .,def track self paramsDict if self switcher True return bunch paramsDict bunch self sc_calculator trackBunch bunch self sc_length self pipe_radius
set the center frequency we 're interested in .,def set_freq self target_freq self u_snk set_freq target_freq self u_src set_freq target_freq
exports the event as a zip on the server and return its path,def export_event_json event_id settings exports_dir app config BASE_DIR static uploads exports if not os path isdir exports_dir os mkdir exports_dir dir_path exports_dir event d event_id if os path isdir dir_path shutil rmtree dir_path ignore_errors True os mkdir dir_path for e in EXPORTS if e 0 event data _order_json marshal e 1 get event_id e 2 e _download_media data event dir_path settings else data marshal e 1 list event_id e 2 for count in range len data data count _order_json data count e _download_media data count e 0 dir_path settings data_str json dumps data indent 4 ensure_ascii False encode utf 8 fp open dir_path e 0 w fp write data_str fp close data_str json dumps _generate_meta sort_keys True indent 4 ensure_ascii False encode utf 8 fp open dir_path meta w fp write data_str fp close shutil make_archive dir_path zip dir_path dir_path dir_path zip storage_path UPLOAD_PATHS exports zip format event_id event_id uploaded_file UploadedFile dir_path dir_path rsplit 1 1 storage_url upload uploaded_file storage_path if get_settings storage_place s3 and get_settings storage_place gs storage_url app config BASE_DIR storage_url replace serve_ return storage_url
make the eyes look to the given side args : side ( str ) : ' r ' for right ' l ' for left ' u ' for up 'd ' for down ' c ' for crossed,def eyes_look self side self ws emit Message enclosure eyes look side side
registers the expected requests along their reponses .,def expected_requests self requests requests requests for request in requests self assertEqual tuple request __class__ self assertIn len request 3 4 with self _lock self assertEqual self _requests self _requests requests
returns the list of all the files in a tree .,def list_files_tree directory actual for root _dirs files in os walk directory actual extend os path join root f len directory 1 for f in files return sorted actual
expands pattern replacing ' % ' with sequential integers starting with start .,def Gen pattern n start it string hexdigits start n start return join ExpandPattern pattern it
sets away mode value for the climate.entityid device,def SetAwayMode self entityId awayMode if awayMode is None return urlServices self url services climate set_away_mode try jsonMsg json dumps entity_id entityId away_mode awayMode header Content Type application json requests post urlServices data jsonMsg headers header self on_publish_topic except requests exceptions RequestException as e print e
: return : bitarray object containing the compressed data,def compress sourcefile start_offs end_offs debuggy False lookup_table vecbuild_path bitarray bitarray endian big out_bitstream bitarray bitarray endian big def build_lookup_table node path search if not node isleaf lefty path copy lefty append False righty path copy righty append True build_lookup_table node childzero lefty search build_lookup_table node childone righty search elif node value search lookup_table search path def build_vector_tree node if node isleaf vecbuild_path append False out_bitstream extend vecbuild_path for i in range len vecbuild_path vecbuild_path pop val bitarray bitarray endian big val frombytes node value out_bitstream extend val else vecbuild_path append True build_vector_tree node childzero build_vector_tree node childone tree buildHuffmanTree sourcefile start_offs end_offs sourcefile seek start_offs if debuggy tree2dot tree optimumtree dot build_vector_tree tree datum sourcefile read 1 target_read 0 while datum and target_read end_offs start_offs if datum not in lookup_table keys build_lookup_table tree bitarray bitarray endian big datum out_bitstream extend lookup_table datum datum sourcefile read 1 target_read 1 return out_bitstream
"> > > allure_report = getfixture('allure_report ' ) > > > assert_that(allure_report , ... has_test_case('test_with_links_cases_and_issues ' , ... has_link(link , name = link_name , link_type = link_type ) , ... has_test_case_link(test_case , name = test_case_name ) , ... has_issue_link(issue , name = issue_name ) ... ) )",pytest allure link LINK name LINK_NAME link_type LINK_TYPE pytest allure testcase TEST_CASE name TEST_CASE_NAME pytest allure issue ISSUE name ISSUE_NAME def test_with_links_cases_and_issues pass
testing 5th order butcher ode solver,def butcher5_ode_solver_test self C0 C 1 coef k 2 rates R k C dcdt C R dt 0 0001 T 0 01 time np linspace 0 T T dt 1 num_sol np array C0 C for i in range 1 len time C_new _ OdeSolver ode_integrate C0 dcdt rates coef dt solver 0 C0 C C_new C num_sol np append num_sol C_new C assert max num_sol np exp coef k time 1e 05
add a remote section to config file based on a ostreeremote .,def set_remote self ostree_remote section_name remote s ostree_remote name baseurl conf rhsm baseurl ca_cert conf rhsm repo_ca_cert full_url utils url_base_join baseurl ostree_remote url self set section_name url full_url gpg_verify_string true if ostree_remote gpg_verify else false self set section_name gpg verify gpg_verify_string if ostree_remote tls_client_cert_path self set section_name tls client cert path ostree_remote tls_client_cert_path if ostree_remote tls_client_key_path self set section_name tls client key path ostree_remote tls_client_key_path self set section_name tls ca path ca_cert proxy_uri self get_proxy if proxy_uri self set section_name proxy proxy_uri
this is called after the child processes are initialized,def post_init_children self return
return a dataframe of companies from the given list of cnpjs,def load_companies_dataset cnpjs u_cols cnpj trade_name zip_code latitude longitude all_companies pd read_csv COMPANIES_DATASET_PATH low_memory False usecols u_cols dtype trade_name np str all_companies all_companies dropna subset cnpj trade_name all_companies clean_cnpj all_companies cnpj map only_numbers return all_companies all_companies clean_cnpj isin cnpjs
when a plugin is created or edited,def record_plugin_history self sender instance kwargs from cms models import CMSPlugin Page from models import EditHistory if not isinstance instance CMSPlugin return user_id cache get cms user id comment cache get cms comment content generate_content instance if content is None return history EditHistory objects filter plugin_id instance id if history count 0 this EditHistory content content latest history latest if latest content content or this uuid latest uuid return EditHistory objects record instance user_id comment content
retrieve a ` message ` instance from ` user ` 's inbox .,def inbox_get self user msg_id
performs a pid computation and returns a control value based on the elapsed time ( dt ) and the error signal from a summing junction ( the error parameter ) .,def compute self inputValue dt currentTime time time dt currentTime self lastTime error self setpoint inputValue de error self lastError self _Cp error self _Ci error dt if self _Ci WINDUP_GUARD self _Ci WINDUP_GUARD elif self _Ci WINDUP_GUARD self _Ci WINDUP_GUARD self _Cd 0 if dt 0 self _Cd de dt self lastError error self lastTime currentTime pTerm self _Cp self Kp iTerm self _Ci self Ki dTerm self _Cd self Kd output pTerm iTerm dTerm if self debug MODULE_MOTION_PID logging debug PID s output 0 2f input 0 2f error 0 2f pTerm 0 2f iTerm 0 2f dTerm 0 2f self name output inputValue error pTerm iTerm dTerm return output
: param subject : the target resource ( or resource name ) of this namespace : param object _ : the subject resource ( or resource name ) of this namespace ( e.g. for relations ) : param path : the path prefix for this namespace : param controller : the object responsible for implementations associated with this namespace . : param version : the version of this namespace : param enable_basic_auth : enable basic auth for this namespace if it 's not enabled globally : param identifier_type : the flask data type to use for identifiers ; usually ` uuid ` or ` string `,def __init__ self subject object_ None prefix None controller None version None qualifier None enable_basic_auth False enable_metrics False identifier_key None identifier_type uuid self subject subject self object_ object_ self prefix prefix or self qualifier qualifier self controller controller self version version self enable_basic_auth enable_basic_auth self enable_metrics enable_metrics self identifier_key identifier_key self identifier_type identifier_type
creates a showcase add for the given adgroup with the given images .,def CreateShowcaseAd client adgroup expanded_image_filepath collapsed_image_filepath ad_group_ad_service client GetService AdGroupAdService v201806 showcase_ad adGroupId adgroup id ad xsi_type ShowcaseAd Ad Type ShowcaseAd name Showcase ad s uuid uuid4 finalUrls http example com showcase displayUrl example com expandedImage mediaId UploadImage client expanded_image_filepath mediaId collapsedImage mediaId UploadImage client collapsed_image_filepath mediaId ad_operation operator ADD operand showcase_ad showcase_ad ad_group_ad_service mutate ad_operation value 0 print ShowcaseAd with ID s was added showcase_ad ad id return showcase_ad
get a tweepy api object configured using oauth .,def get_oauth_api config auth OAuthHandler config get twitter consumer_key config get twitter consumer_secret auth set_access_token config get twitter access_token_key config get twitter access_token_secret return API auth wait_on_rate_limit True wait_on_rate_limit_notify True
"x is a vector giving the time step , and y is the total number of international airline passengers , in thousands . each element corresponds to one month , and it goes from jan. 1949 through dec. 1960 .",def load_X_y values load_data data_file return np arange values size astype float values astype float
a quadratic b - spline .,def quadratic x ax abs asarray x res zeros_like ax cond1 less ax 0 5 if cond1 any ax1 ax cond1 res cond1 0 75 ax1 2 cond2 cond1 less ax 1 5 if cond2 any ax2 ax cond2 res cond2 ax2 1 5 2 2 0 return res
alias for : func:`~charms.reactive.decorators.when_all ` .,def when desired_flags return when_all desired_flags
parse a stream and return the syntax tree .,def parse_stream_raw self stream debug False tokens tokenize generate_tokens stream readline return self parse_tokens tokens debug
display an array as an image .,staticmethod def clean imagedata if asarray imagedata ndim not in set 2 3 raise Exception Input must be two or three dimensional outdict array_to_im imagedata return images outdict
print a menu with all the functionalities .,def menu print 33 nMENU n 33 descriptions Load host from external file Add a new host Print selected hosts Check active hosts Select only active hosts Select bots Execute command locally Execute command on bots Run external script Open shell in a host Exit for num func in enumerate descriptions print str num func choice raw_input return choice
"checks how parameters passed to test_flags interact with parameters from yaml files . expected behavior is that any params in test_flags will override those from files , but that all values from file will be used if not explicitly passed to test_flags .",def test_merge_params self config io_utils parse_config flags TEST_FLAGS config update_config config model ChatBot self assertEqual config model ChatBot config update_config config model DynamicBot self assertEqual config model DynamicBot config update_config config dataset TestData self assertEqual config dataset TestData config update_config config batch_size 123 dropout_prob 0 8 logging info config self assertEqual config model self test_config model self assertEqual config dataset self test_config dataset self assertNotEqual config model_params self test_config model_params
testing with non - existent file . must return no such file error .,def test_check_map_not_exist self check_file no_such_file result links_map_checker check_file expected error no_such_file_error no_such_file self assertItemsEqual result expected
return the weights and biases already trained by vgg,def _weights vgg_layers layer expected_layer_name W vgg_layers 0 layer 0 0 2 0 0 b vgg_layers 0 layer 0 0 2 0 1 layer_name vgg_layers 0 layer 0 0 0 0 assert layer_name expected_layer_name return W b reshape b size
initialise the : class:`callbackmanager ` .,def __init__ self shell available_events self shell shell self callbacks n for n in available_events
simplistic converter of strings from repr to float numpy arrays .,def str_to_array s import numpy as np from numpy import inf nan if s startswith u array s s 6 1 if s startswith u a np array eval s dtype float else a np atleast_1d float s return a
"yield ' ( op , arg ) ' pair for each operation in code object ' code '",def _iter_code code from array import array from dis import HAVE_ARGUMENT EXTENDED_ARG bytes array b code co_code eof len code co_code ptr 0 extended_arg 0 while ptr eof op bytes ptr if op HAVE_ARGUMENT arg bytes ptr 1 bytes ptr 2 256 extended_arg ptr 3 if op EXTENDED_ARG long_type six integer_types 1 extended_arg arg long_type 65536 continue else arg None ptr 1 yield op arg
"run nbconvert as a shell command , listening for both errors and non - zero return codes . returns the tuple ( stdout , stderr ) of output produced during the nbconvert run .",def nbconvert self parameters ignore_return_code False stdin None if isinstance parameters string_types parameters shlex split parameters cmd sys executable m nbconvert parameters p Popen cmd stdout PIPE stderr PIPE stdin PIPE stdout stderr p communicate input stdin if not p returncode 0 or ignore_return_code raise OSError bytes_to_str stderr return stdout decode utf8 replace stderr decode utf8 replace
"change the selection index , and make sure it stays in the right range",def _select_index self row col nr nc self _size nr nr 1 nc nc 1 if row nr and col nc or row nr and col nc self _select_index 0 0 elif row 0 and col 0 or row 0 and col 0 self _select_index nr nc elif row nr self _select_index 0 col 1 elif row 0 self _select_index nr col 1 elif col nc self _select_index row 1 0 elif col 0 self _select_index row 1 nc elif 0 row and row nr and 0 col and col nc self _index row col else raise NotImplementedError you r trying to go where no completion have gone before d d d d row col nr nc
create address_scope : foo - address - scope with minimum option .,def test_create_address_scope_with_minimum_option_ipv6 self resource address_scope cmd address_scope CreateAddressScope test_cli20 MyApp sys stdout None name foo address scope myid myid args name 6 position_names name ip_version position_values name 6 self _test_create_resource resource cmd name myid args position_names position_values
ensure the given argument is in filesystem encoding ( not unicode ),def fsencoding s encoding sys getfilesystemencoding if isinstance s unicode s s encode encoding return s
"generate "" logout "" url .",property def logout_url self return url_for dropbox logout
l{runner.run } calls the expected methods in order .,def test_runInOrder self runner DummyRunner runner run self assertEqual runner calledMethods killIfRequested startLogging startReactor reactorExited
returns true if the backend supports the named elliptic curve .,abc abstractmethod def elliptic_curve_supported self curve
: return : json file with function definitions,property def function_definitions self return self _function_definitions
style loss is the mse between gram matrices computed using activation maps .,def style_loss x target norm_by_channels False x_gram gram_matrix x norm_by_channels norm_by_channels return K mean K square target x_gram axis 1 2
similar to fail_unless_raises but also checks the exception message .,def fail_unless_raises_with_msg exc_class expected_msg callable_obj args kwargs try callable_obj args kwargs except exc_class as err assert_equal expected_msg unic err Correct exception but wrong message else if hasattr exc_class __name__ exc_name exc_class __name__ else exc_name str exc_class _report_failure s not raised exc_name
"given a list of khashmir instances , finds min , max , and average number of nodes in tables",def bucket_stats l max avg 0 min None def count buckets c 0 for bucket in buckets c c len bucket l return c for node in l c count node table buckets if min None min c elif c min min c if c max max c avg avg c avg avg len l return min min max max avg avg
"serialise a message , including framing information inferred from the `` meta `` inner class of the packet . `` self . meta.endpoint `` must be defined to call this method .",def serialise_packet self if not hasattr self _Meta raise ReferenceError Can t serialise a packet that doesn t have an endpoint ID serialised self serialise return struct pack HH len serialised self _Meta endpoint serialised
this function will produce and save a set of data sets to test the scalability with features . in order to do so the function takes a vector with the number of features that the the user wishes to get tested .,def generate_data_for_features n_samples feature_sizes_vector noise filename seed for n_features in feature_sizes_vector name filename str n_features create_data_set n_samples n_features noise name seed
record index records for a single document .,def index self si if not si body clean_visible logger warn stream item s has no clean_visible part skipping keyword indexing si stream_id return hash_counts defaultdict int hash_counts DOCUMENT_HASH_KEY 1 hash_kw defaultdict int words self collect_words si for tok count in words iteritems tok tok_hash self make_hash_kw tok hash_counts tok_hash count hash_kw tok tok_hash if self hash_docs k1 k2 key_for_stream_item si kvps h k1 k2 n for h n in hash_counts iteritems if h DOCUMENT_HASH_KEY self client put HASH_TF_INDEX_TABLE kvps if self hash_frequencies kvps h 1 for h in hash_counts iterkeys self client increment HASH_FREQUENCY_TABLE kvps if self hash_keywords kvps h t 1 for t h in hash_kw iteritems self client increment HASH_KEYWORD_INDEX_TABLE kvps
tell if the lock is currently held .,def locked self by_self False has_lock self _rlock acquire False if by_self and not has_lock return False try return super ThreadRLock self locked by_self by_self finally if has_lock self _rlock release
assigns a list of found users to the given role .,expose my_queries def my_queries self return redirect savedqueryview list _flt_0_user format g user id
test the minimum input size calculator .,def testCalcMinSize self net snt nets AlexNet mode snt nets AlexNet MINI self assertEqual net _calc_min_size None 3 1 None 3 self assertEqual net _calc_min_size None 3 1 3 2 5 self assertEqual net _calc_min_size None 3 1 3 2 None 3 2 5 2 25
count how many detectors are in the file .,def _precheck self with open self filePath as fh for line in fh sline line split if not sline continue if DET in sline 0 return error No detectors found in format self filePath
initialized the classe using the filename,def __init__ self filename None if filename self test_file filename
construct a new solver instance .,def __init__ self model data kwargs self model model self X_train data X_train self y_train data y_train self X_val data X_val self y_val data y_val self update_rule kwargs pop update_rule sgd self optim_config kwargs pop optim_config self lr_decay kwargs pop lr_decay 1 0 self batch_size kwargs pop batch_size 100 self num_epochs kwargs pop num_epochs 10 self print_every kwargs pop print_every 10 self verbose kwargs pop verbose True if len kwargs 0 extra join s k for k in kwargs keys raise ValueError Unrecognized arguments s extra if not hasattr optim self update_rule raise ValueError Invalid update_rule s self update_rule self update_rule getattr optim self update_rule self _reset
return the json string to send to the java plugin,def dumps self vType str self valueType split 1 if self operationalMode is None mode else mode str self operationalMode split 1 if self valueType IASType ALARM value str self value split 1 else value str self value return json dumps JsonMsg idJsonParamName self mPointID JsonMsg tStampJsonParamName self timestamp JsonMsg valueJsonParamName value JsonMsg valueTypeJsonParamName vType JsonMsg operationaModeParamName mode
the signature contained within the : class:`signedmessage ` .,property def signature self return self _signature
"internal driver for the options processing framework . this gets the options from all of the verb for this noun , and assembles them into a python argparse subparser for this noun .",def internal_setup_options_parser self argparser self setup_options_parser argparser subparser argparser add_subparsers dest verb title subcommands for name verb in self verbs items vparser subparser add_parser name help verb help description verb help for opt in verb get_options opt add_to_parser vparser for plugin in self commandline plugins for opt in plugin get_options opt add_to_parser vparser for opt in GlobalCommandHookRegistry get_options opt add_to_parser vparser
return a masked array that corresponds to the input polygon : param polygon : : return :,def rasterMaskLayer self shapefile fieldname None target_ds gdal GetDriverByName MEM Create self cols self rows 1 gdal GDT_Byte target_ds SetGeoTransform self gt assert len shapefile 0 The ShapeFile path is empty driver ogr GetDriverByName ESRI Shapefile src_ds driver Open shapefile 0 src_lyr src_ds GetLayer options ALL_TOUCHED TRUE if fieldname and len fieldname 0 options append ATTRIBUTE fieldname err gdal RasterizeLayer target_ds 1 src_lyr options options band target_ds GetRasterBand 1 return band ReadAsArray
this method creates & returns json data : param kwargs : key / value pair : return : json data,def create_request_data kwargs data for key value in kwargs iteritems if list in key and not value is None and not metrics_list in key temp split_and_convert key value data key temp elif metrics_list in key data key name n for n in value else data key value return json dumps data
get maximum date of storage for file : return : date in two weeks,def get_date_in_two_weeks today datetime datetime today date_in_two_weeks today datetime timedelta days 14 return date_in_two_weeks date
checks whether a func has been decorated with @add_arg_scope or not .,def has_arg_scope func return _key_op func in _DECORATED_OPS
gather and return all devices ( name and xid ),def gather_devices self devices for device_name in self gather_devices_names_with_xid devices append XinputWarper find_xid_by_name device_name device_name return devices
upload a blueprint ( i d specified ),swagger operation responseClass models Blueprint nickname upload notes Submitted blueprint should be an archive containing the directory which contains the blueprint Archive format may be zip tar tar gz or tar bz2 Blueprint archive may be submitted via either URL or by direct upload parameters name application_file_name description File name of yaml containing the main blueprint required False allowMultiple False dataType string paramType query defaultValue blueprint yaml name blueprint_archive_url description url of a blueprint archive file required False allowMultiple False dataType string paramType query name body description Binary form of the tar gzipped blueprint directory required True allowMultiple False dataType binary paramType body consumes application octet stream exceptions_handled authorize blueprint_upload marshal_with models Blueprint def put self blueprint_id kwargs validate_inputs blueprint_id blueprint_id return UploadedBlueprintsManager receive_uploaded_data blueprint_id
format a string in a good way .,def format_string text if text is None return return join text translate 8216 39 8217 39 8220 34 8221 34 160 32 10 32 13 32 encode utf 8 split
load and save `` pagecolorscheme `` for every `` pagetheme ``,def collect self u n Load and save PageColorScheme for every PageTheme n n code block bash n n static themes bootswatch united variables scss n static themes bootswatch united styles scss n n self ignore_patterns u png u jpg u js u gif u ttf u md u rst u svg page_themes PageTheme objects all for finder in get_finders for path storage in finder list self ignore_patterns for t in page_themes static_path u themes 0 format t name split u 1 if static_path in path try page_theme PageTheme objects get id t id except PageTheme DoesNotExist raise Exception u Run sync_themes before this command except Exception as e self stdout write u Cannot load into database original error format t e skins_path os path join storage path u join path split u 0 1 for dirpath skins filenames in os walk skins_path for skin in s for s in skins if s not in u fonts for skin_dirpath skins filenames in os walk os path join dirpath skin skin created PageColorScheme objects get_or_create theme page_theme label skin name skin title for f in filenames if u styles in f with codecs open os path join skin_dirpath f as style_file skin styles style_file read elif u variables in f with codecs open os path join skin_dirpath f as variables_file skin variables variables_file read skin save self skins_updated 1 self page_themes_updated len page_themes
return the first element of a set .,def first s sorted False if not len s raise IndexError empty containter if sorted l set_to_list s l sort return l 0 else for x in s return x
return the dot product of this quaternion and another .,def dot self other return self
compile a set of .el files using emacs,def compile_el fn load None cmdlist emacs Q if load cmdlist append l cmdlist append load cmdlist batch f batch byte compile cmdlist extend fn sh_args cmdlist
returns a vulkanstruct representing the vkdescriptorpoolcreateinfo struct used in the given create_descriptor_pool command .,def get_descriptor_pool_create_info create_descriptor_pool architecture return VulkanStruct architecture DESCRIPTOR_POOL_CREATE_INFO_ELEMENTS lambda offset size little_endian_bytes_to_int require create_descriptor_pool get_read_data create_descriptor_pool hex_pCreateInfo offset size
' certainty ' values for every feature .,property def certainty self return x certainty for x in self _content
calls create_object generic view with a custom form class .,def custom_create request class SlugChangingArticleForm forms ModelForm Custom form class to overwrite the slug class Meta model Article def save self args kwargs self instance slug some other slug return super SlugChangingArticleForm self save args kwargs return create_object request post_save_redirect views create_update view article slug s form_class SlugChangingArticleForm
recursively crawl starting from * start_url*. returns a set of urls that were found .,def crawl start_url pool eventlet GreenPool seen set fetch start_url seen pool pool waitall return seen
"simple single entry per line in the format of : "" full name "" < my@address.com > ;",def address self qs out out write u n join u s s full_name ent ent email for ent in qs encode self encoding out write n
"returns a formatted string of the current listeners on the current hub . this can be useful in determining what 's going on in the event system , especially when used in conjunction with : func:`hub_listener_stacks ` .",def format_hub_listeners from eventlet import hubs hub hubs get_hub result READERS for l in hub get_readers result append repr l result append WRITERS for l in hub get_writers result append repr l return os linesep join result
gets a ctypes pointer array ( of length ` n ` ) for geosgeom_t opaque pointer .,def get_pointer_arr n GeomArr GEOM_PTR n return GeomArr
regression for # 10349 : a callable can be provided as the initial value for an m2 m field,def test_callable self def formfield_for_dbfield db_field kwargs if db_field name publications kwargs initial lambda Publication objects all order_by date_published 2 return db_field formfield kwargs Publication title First Book date_published date 2007 1 1 save Publication title Second Book date_published date 2008 1 1 save Publication title Third Book date_published date 2009 1 1 save ModelForm modelform_factory Article formfield_callback formfield_for_dbfield form ModelForm self assertEquals form as_ul u li label for id_headline Headline label input id id_headline type text name headline maxlength 100 li n li label for id_publications Publications label select multiple multiple name publications id id_publications n option value 1 selected selected First Book option n option value 2 selected selected Second Book option n option value 3 Third Book option n select Hold down Control or Command on a Mac to select more than one li
gets ' relativee ' relative to ' basepath ' .,def relativeTo base relativee basepath os path abspath base relativee os path abspath relativee if relativee startswith basepath relative relativee len basepath if relative startswith os sep relative relative 1 return os path join base relative raise ValueError s is not a subpath of s relativee basepath
parse challenge and send response from the mechanism .,def onChallenge self element try challenge fromBase64 str element except SASLIncorrectEncodingError self _deferred errback else self sendResponse self mechanism getResponse challenge
"hook for modifying the formwizard 's internal state , given a fully validated form object . the form is guaranteed to have clean , valid data .",def process_step self request form step pass
l{loopback.loopbackasync } does not call a protocol 's c{datareceived } method while that protocol 's transport 's c{write } method is higher up on the stack .,def test_writeNotReentrant self class Server Protocol def dataReceived self bytes self transport write bytes class Client Protocol ready False def connectionMade self reactor callLater 0 self go def go self self transport write foo self ready True def dataReceived self bytes self wasReady self ready self transport loseConnection server Server client Client d loopback loopbackAsync client server def cbFinished ignored self assertTrue client wasReady d addCallback cbFinished return d
close all connections ( even the one currently in use . ),def closeall self self _lock acquire try self _closeall finally self _lock release
gets ` buffer_id ` input of bufratescale .,property def buffer_id self index self _ordered_input_names index buffer_id return self _inputs index
constructs a control - rate quadratic noise generator .,classmethod def kr cls frequency 500 import supriya synthdefs calculation_rate supriya synthdefs CalculationRate CONTROL ugen cls _new_expanded calculation_rate calculation_rate frequency frequency return ugen
muting is not mutally exclusive .,def test_04 mixer mixer bar set_mute True mixer foo set_mute True time sleep 0 25 assert mixer foo is_muted assert mixer bar is_muted assert not mixer baz is_muted assert not mixer foo output_synth active value assert not mixer bar output_synth active value assert mixer baz output_synth active value levels mixer master input_levels assert round levels rms 0 2 0 25
constucts a control - rate fold ugen .,classmethod def kr cls maximum 1 minimum 0 source None import supriya synthdefs calculation_rate supriya synthdefs CalculationRate CONTROL ugen cls _new_expanded calculation_rate calculation_rate maximum maximum minimum minimum source source return ugen
gets ` frequency ` input of lincongl.,property def frequency self index self _ordered_input_names index frequency return self _inputs index
gets ` earlyreflevel ` input of gverb .,property def earlyreflevel self index self _ordered_input_names index earlyreflevel return self _inputs index
this test runs a pool of processes and calculates the square values from a list of list of integers .,def test_pool2 size print Running test_pool2 with processes format size p multiprocessing Pool size data range 2 i for i in range 2 size returnedData p map worker2 data for i in range len data print data i print returnedData i print p terminate p join
prints out all the scores calculated .,def build_ui self mean False for i score in enumerate self scores print Cross Validation d i 1 print 40 if mean print Mean Accuracy f score else print Precision tRecall t tF Score print t t t precision score 0 recall score 1 f_score score 2 print f t f t f precision recall f_score print
test `` get_user `` for a valid user .,mock patch django contrib auth get_user_model def test_get_user_fail self mock_get_user_model mock_get_user_model return_value User auth_backend WebMailAuthenticationBackend self assertNotEqual auth_backend get_user 1 self user
push the var_name / var_value pair onto the stack .,def push self var_value var_name if var_name stack_frame_ix 2 var_name gp get_arg_name 0 1 stack_frame_ix if var_name in self __stack_dict self __stack_dict var_name append var_value else self __stack_dict var_name var_value
"check to make sure c_overviewer works and is up - to - date . prints out a helpful error and returns 1 if something 's wrong , returns 0 otherwise .",def check_c_overviewer root_dir util get_program_path try import c_overviewer except ImportError if os environ get OVERVIEWER_DEBUG_IMPORT 1 traceback print_exc if hasattr sys frozen and platform system Windows print Something has gone wrong importing the c_overviewer extension Please print make sure the 2008 and 2010 redistributable packages from Microsoft print are installed return 1 ext os path join root_dir overviewer_core c_overviewer s pyd if platform system Windows else so if os path exists ext traceback print_exc print print Something has gone wrong importing the c_overviewer extension Please print make sure it is up to date clean and rebuild return 1 print You need to compile the c_overviewer module to run Minecraft Overviewer print Run python setup py build or see the README for details return 1 if hasattr sys frozen pass elif extension_version in dir c_overviewer if os path exists os path join root_dir overviewer_core src overviewer h with open os path join root_dir overviewer_core src overviewer h as f lines f readlines lines filter lambda x x startswith define OVERVIEWER_EXTENSION_VERSION lines if lines l lines 0 if int l split 2 strip c_overviewer extension_version print Please rebuild your c_overviewer module It is out of date return 1 else print Please rebuild your c_overviewer module It is out of date return 1 return 0
"args : x kernel_shape : [ height , weights ] kernel_stride : [ height , weights ]",def maxpool_2d_layer x kernel_shape kernel_stride layer_name with tf variable_scope layer_name max_pool _max_pool x 1 kernel_shape 0 kernel_shape 1 1 1 kernel_stride 0 kernel_stride 1 1 return max_pool
test if menu item removal works .,def test_file_close self self app self launch_test_application gedit time sleep 0 2 panel self unity panels get_active_panel menu panel menus get_menu_by_label _Documents menu mouse_click menu mouse_click panel get_panel_accessible self desktop app_menu get_app_menu_accessible panel documents_item get_label_accessible_with_name app_menu Documents documents_menu get_submenu_accessible documents_item untitled_document_1_item get_menu_item_accessible_with_name documents_menu Untitled Document 1 self assertTrue untitled_document_1_item get_state_set contains pyatspi STATE_CHECKED panel self unity panels get_active_panel menu panel menus get_menu_by_label _File menu mouse_click self keyboard press_and_release Up self keyboard press_and_release Up self keyboard press_and_release Enter menu panel menus get_menu_by_label _Documents menu mouse_click menu mouse_click tabs self app select_many GeditTab self assertFalse tabs untitled_document_1_item get_menu_item_accessible_with_name documents_menu Untitled Document 1 self assertFalse untitled_document_1_item
a string representing the location of the token in the holy quran .,property def location_string self return d d d self chapter_no self verse_no self token_no
performs interactive login and caches authentication token .,subcommand usage hostname def CMDlogin parser args hostname authenticator parser parse_args args authenticator logout authenticator login print_token_info hostname authenticator return 0
"check that the given file has the given mode(s ) set , else try to set it .",def ensure_fs_mode filepath desired_mode S_IWRITE mode stat filepath ST_MODE if not mode desired_mode chmod filepath mode desired_mode
removes an item from the list . similar to list.remove ( ) .,def remove self elem self _values remove elem self _message_listener Modified
construct instance - level session to expose,def __enter__ self if self session is None self session Context _session_factory return self
"run this to determine if the local machine has win32com , and if it does , include additional tests .",def has_win32com if not sys platform startswith win32 return False try mod __import__ win32com except ImportError return False return True
"when only one djangotemplates backend is configured , returns it .",staticmethod lru_cache lru_cache def get_default from django template import engines from django template backends django import DjangoTemplates django_engines engine for engine in engines all if isinstance engine DjangoTemplates if len django_engines 1 return django_engines 0 engine elif len django_engines 0 raise ImproperlyConfigured No DjangoTemplates backend is configured else raise ImproperlyConfigured Several DjangoTemplates backends are configured You must select one explicitly
sets the x component of the point .,def set_x self value self _cs setOrdinate 0 0 value
returns true if the given request * should n't * notify the site managers .,def is_ignorable_request self request uri domain referer if not referer or not self is_internal_request domain referer and in referer return True return any pattern search uri for pattern in settings IGNORABLE_404_URLS
month without leading zeros ; i.e. ' 1 ' to ' 12 ',def n self u return self data month
enumerate processes based on user options .,def get_processes self addr_space tasks linux_pslist linux_pslist self _config calculate try if self _config PID is not None pidlist int p for p in self _config PID split tasks t for t in tasks if int t pid in pidlist except ValueError TypeError debug error Invalid PID 0 format self _config PID return tasks
"parameters ---------- log_data_i : microdrop.experiment_log.experimentlog microdrop experiment log , as pickled in the `` data `` file in each experiment log directory .",def log_data_to_frame log_data_i def log_frame_experiment_info df_log experiment_info df_log core iloc 0 copy experiment_info update df_log core iloc 1 start_time arrow get experiment_info start time naive experiment_info utc_start_time start_time isoformat for k in step start time time attempt utc_timestamp if k in experiment_info index del experiment_info k return experiment_info dropna plugin_names_i sorted reduce lambda a b a union b keys log_data_i data set frames_i OrderedDict for plugin_name_ij in plugin_names_i try frame_ij pd DataFrame map lambda v pickle loads v if v else s get plugin_name_ij for s in log_data_i data except Exception as exception print plugin_name_ij exception else frames_i plugin_name_ij frame_ij df_log_i pd concat frames_i values axis 1 keys frames_i keys start_time_i arrow get df_log_i iloc 0 core start time naive df_log_i core utc_timestamp start_time_i df_log_i core time map lambda s dt timedelta seconds s if s s else None df_log_i sort_index axis 1 inplace True experiment_info log_frame_experiment_info df_log_i experiment_info uuid log_data_i uuid df_log_i dropna subset core step core attempt inplace True return experiment_info df_log_i
filter based on whether an update ( of any sort ) is available .,def queryset self request queryset if self value 1 return queryset filter latest_version__isnull True elif self value 0 return queryset filter current_version__isnull False latest_version__isnull False latest_version F current_version elif self value 1 return queryset filter current_version__isnull False latest_version__isnull False exclude latest_version F current_version else return queryset
create a new fits file from a container .,def save_fits cont path cont save_fits path
produces an icontains lookup on the question title .,def search self terms query None for term in normalize_query terms q models Q text__icontains term models Q details__icontains term query q if query is None else query q return self filter query
adds variables provided within the function arguments to the namespace for this deployment . use to keep track of all variables for a deployment .,def add_vars_to_namespace self to_add for k v in to_add iteritems if v self namespace k v
called when the user launches the skill without specifying what they want,def on_launch launch_request session print on_launch requestId launch_request requestId sessionId session sessionId return get_welcome_response
"gt with more than one overlap get false detections : param prediction_confidences : : param iou_mask : mask of valid intersection over union ( np.array ) iou shape [ n_pred , n_gt ] : param gt_classes : : param accumulators : : return : updated version of the iou mask",staticmethod def multiple_prediction_on_gt IoU_mask gt_classes accumulators pred_max np sum IoU_mask axis 0 for i gt_sum in enumerate pred_max gt_cls gt_classes i if gt_sum 1 for j in range gt_sum 1 accumulators gt_cls inc_bad_prediction
test pasting into text without a selection .,def test_paste_text_no_selection self text self text tag ans onetwo n text delete 1 0 end text insert 1 0 one tag text event_generate Paste self assertEqual text get 1 0 end ans
return the current status of this harvester .,def status self return self status_info
"this is at 1/16 scale . the two 32-bit float channel values { u , v } at source_image_map voxel ( x y , z ) indicate that pixel location ( 16x , 16y , z ) in the source image stack is mapped to ( u , v , z ) in the realigned volume . if { u , v } are nan values , that source pixel did n't fall within the realigned volume ( there are probably no cases of this in j0126_13 ) .",def source_to_target orig_coord realign_map x_rem y_rem orig_coord 1 16 orig_coord 0 16 x y z orig_coord 1 16 orig_coord 0 16 orig_coord 2 realigned_coord np array np round realign_map 0 x y z x_rem np round realign_map 1 x y z y_rem z dtype np int T return realigned_coord
"retrieves the selected words for this annotation . order is based on the xml_id , e.g. w18.1.10 should be after w18.1.9 . : return : a space - separated string with the selected words .",def selected_words self ordered_words sorted self words all key lambda w map int w xml_id 1 split return join word word for word in ordered_words
returns the output of classic `` fortune `` command in unix .,def fortune short False cmd fortune if short cmd append s output subprocess check_output cmd return output decode ascii ignore
unsubscribes a webhook from new blocks,def unsubscribe_new_blocks self identifier response self client delete webhook s block identifier auth True return response json
blocks until all items in the queue have been gotten and processed .,def join self with self all_tasks_done while self unfinished_tasks self all_tasks_done wait
test the nltk boundary format .,def test_boundary_format_nltk self value segmentation_similarity 0100100000 0101000000 boundary_format BoundaryFormat nltk self assertAlmostEqual Decimal 0 95 value
version of cwltool used to execute the workflow .,def versionstring pkg pkg_resources require cwltool if pkg return u s s sys argv 0 pkg 0 version return u s s sys argv 0 unknown version
"the get_contents ( ) member function loads the file into memory and reads the contents . the file buffer is then closed and then a beautifulsoup object is instantiated , with the contents . more on this can be read at the beautifulsoup documentation website ( https://www.crummy.com/software/beautifulsoup/bs4/doc/ ) .",def get_contents self with open download packages html as f contents f read contents BeautifulSoup contents html parser from_encoding utf 8 return contents
checks the validity of the the user provided by querying the ipa server,def check_valid self if self _valid is not None return self _valid api_connect try response api Command user_show uid self username except errors NotFound self _valid False return self _valid mail response result get mail if mail and mail 0 strip self email mail 0 self _valid True else self _valid False return self _valid
"give an array of mnist digits , blend random background patches to build the mnist - m dataset as described in http://jmlr.org/papers/volume17/15-239/15-239.pdf",def create_mnistm X X_ np zeros X shape 0 28 28 3 np uint8 for i in range X shape 0 if i 1000 0 print i bg_img rand choice background_data d mnist_to_img X i d compose_image d bg_img X_ i d return X_
"returns a function with same code , globals , defaults , closure , and name ( or provide a new name ) .",def copy_func f name None sinceversion None doc None fn types FunctionType f __code__ f __globals__ name or f __name__ f __defaults__ f __closure__ fn __dict__ update f __dict__ if doc is not None fn __doc__ doc if sinceversion is not None fn since sinceversion fn return fn
: param component : component the mate is relative to : type component : : class:`component < cqparts . component > ` : param local_coords : coordinate system of mate relative to component 's origin : type local_coords : : class:`coordsystem < cqparts.utils.geometry.coordsystem > `,def __init__ self component local_coords None from component import Component if isinstance component Component self component component elif component is None self component None else raise TypeError component must be a r got a r Component component if isinstance local_coords CoordSystem self local_coords local_coords elif local_coords is None self local_coords CoordSystem else raise TypeError local_coords must be a r got a r CoordSystem local_coords
attach logger to logging interface .,def attach self logger self loggers append logger
"since django 1.11 , postprocess algorythm has been changed for css files is such a way that they save is called 4 times total . it must be taken into consideration in unittests . hopefully this will be removed at some point once django introduces optimization of postprocess handler .",def get_save_calls_counter_in_postprocess_of_adjustable_file if version get_complete_version 1 11 return 4 return 1
validate the name field of a dataset,def _validate_dataset_name name if not isinstance name string_types raise ValidationException Field name must be a string if not DATASET_NAME_LEN_MIN len name DATASET_NAME_LEN_MAX raise ValidationException Class name must be between s and s characters DATASET_NAME_LEN_MIN DATASET_NAME_LEN_MAX
leb size of ubi blocks in file .,def _get_leb_size self return self _leb_size
test the list of output fields when no data has been fetched,def test_get_fields_no_data self fields set self roller get_fields for field in self OUTPUT_FIELDS self assertIn field fields
channel gating kinetics . functions of membrane voltage,def beta_n self V return 0 125 sp exp V 65 80 0
get a datetimeindex of valid open business days .,def valid_days self start_date end_date tz UTC return pd date_range start_date end_date freq self holidays normalize True tz tz
the length of the sequence is the total number of pages .,def __len__ self u return self _page paginator num_pages
check that the suspicious operation method gets a 400 response .,def test_suspicious_operation self u n Check that the suspicious operation method gets a 400 response n n def get self request args kwargs return self suspicious_operation self assertViewBehavior u get get status_code 400
multi - class version of non maximum suppression .,def multiclass_non_max_suppression boxes scores score_thresh iou_thresh max_size_per_class max_total_size 0 clip_window None change_coordinate_frame False masks None additional_fields None scope None if not 0 iou_thresh 1 0 raise ValueError iou_thresh must be between 0 and 1 if scores shape ndims 2 raise ValueError scores field must be of rank 2 if scores shape 1 value is None raise ValueError scores must have statically defined second dimension if boxes shape ndims 3 raise ValueError boxes must be of rank 3 if not boxes shape 1 value scores shape 1 value or boxes shape 1 value 1 raise ValueError second dimension of boxes must be either 1 or equal to the second dimension of scores if boxes shape 2 value 4 raise ValueError last dimension of boxes must be of size 4 if change_coordinate_frame and clip_window is None raise ValueError if change_coordinate_frame is True then a clip_windowmust be specified with tf name_scope scope MultiClassNonMaxSuppression num_boxes tf shape boxes 0 num_scores tf shape scores 0 num_classes scores get_shape 1 length_assert tf Assert tf equal num_boxes num_scores Incorrect scores field length actual vs expected num_scores num_boxes selected_boxes_list per_class_boxes_list tf unstack boxes axis 1 if masks is not None per_class_masks_list tf unstack masks axis 1 boxes_ids range num_classes if len per_class_boxes_list 1 else 0 num_classes for class_idx boxes_idx in zip range num_classes boxes_ids per_class_boxes per_class_boxes_list boxes_idx boxlist_and_class_scores box_list BoxList per_class_boxes with tf control_dependencies length_assert class_scores tf reshape tf slice scores 0 class_idx tf stack num_scores 1 1 boxlist_and_class_scores add_field fields BoxListFields scores class_scores if masks is not None per_class_masks per_class_masks_list boxes_idx boxlist_and_class_scores add_field fields BoxListFields masks per_class_masks if additional_fields is not None for key tensor in additional_fields items boxlist_and_class_scores add_field key tensor boxlist_filtered box_list_ops filter_greater_than boxlist_and_class_scores score_thresh if clip_window is not None boxlist_filtered box_list_ops clip_to_window boxlist_filtered clip_window if change_coordinate_frame boxlist_filtered box_list_ops change_coordinate_frame boxlist_filtered clip_window max_selection_size tf minimum max_size_per_class boxlist_filtered num_boxes selected_indices tf image non_max_suppression boxlist_filtered get boxlist_filtered get_field fields BoxListFields scores max_selection_size iou_threshold iou_thresh nms_result box_list_ops gather boxlist_filtered selected_indices nms_result add_field fields BoxListFields classes tf zeros_like nms_result get_field fields BoxListFields scores class_idx selected_boxes_list append nms_result selected_boxes box_list_ops concatenate selected_boxes_list sorted_boxes box_list_ops sort_by_field selected_boxes fields BoxListFields scores if max_total_size max_total_size tf minimum max_total_size sorted_boxes num_boxes sorted_boxes box_list_ops gather sorted_boxes tf range max_total_size return sorted_boxes
implement switch - like behavior .,def act_like_switch self packet packet_in DELETE THIS LINE TO START WORKING ON THIS AND THE ONE BELOW Here s some psuedocode to start you off implementing a learning switch You ll need to rewrite it as real Python code Learn the port for the source MAC self mac_to_port add or update entry if the port associated with the destination MAC of the packet is known Send packet out the associated port self resend_packet packet_in Once you have the above working try pushing a flow entry instead of resending the packet comment out the above and uncomment and complete the below log debug Installing flow Maybe the log statement should have source destination port msg of ofp_flow_mod Set fields to match received packet msg match of ofp_match from_packet packet Set other fields of flow_mod timeouts buffer_id Add an output action and send similar to resend_packet else Flood the packet out everything but the input port This part looks familiar right self resend_packet packet_in of OFPP_ALL
"load a frame from an image , the current gametime , the deplacement / s of the player in this frame , it 's hardshape .",def __init__ self image gametime hardshape trails None self image image self trails trails self time int gametime if type hardshape is str self hardshape pygame Rect int i for i in hardshape split elif type hardshape is pygame Rect self hardshape hardshape else logging error incorrect type for hardshape hardshape self hardshape_reverse loaders image self image 1 2 self hardshape 0 self hardshape 2 self hardshape 1 self hardshape 2 self hardshape 3 self agressivpoints self agressivpoints_reverse
return the value of ` www - authenticate ` header in a ` 401 unauthenticated ` response .,def get_authenticate_header self pass
"setuptools was imported prior to invocation , so it is unsafe to unload it . bail out .",def _conflict_bail VC_err version conflict_tmpl textwrap dedent The required version of setuptools version is not available and can t be installed while this script is running Please install a more recent version first using easy_install U setuptools Currently using VC_err args 0 r msg conflict_tmpl format locals sys stderr write msg sys exit 2
convert an openmm topology object into an mdt molecule .,exports def topology_to_mol topo name None positions None velocities None assign_bond_orders True from simtk import unit as stku atommap newatoms masses u amu atom element mass value_in_unit stku amu for atom in topo atoms for atom mass in zip topo atoms masses newatom mdt Atom atnum atom element atomic_number name atom name mass mass atommap atom newatom newatoms append newatom if positions is not None poslist np array p value_in_unit stku nanometer for p in positions u nm poslist ito u default length for newatom position in zip newatoms poslist newatom position position if velocities is not None velolist np array v value_in_unit stku nanometer stku femtosecond for v in velocities u nm u fs velolist u default convert velolist for newatom velocity in zip newatoms velolist newatom momentum newatom mass simtk2pint velocity chains for chain in topo chains if chain id not in chains chains chain id mdt Chain name chain id index chain index newchain chains chain id for residue in chain residues newresidue mdt Residue name s d residue name residue index chain newchain pdbindex int residue id pdbname residue name newchain add newresidue for atom in residue atoms newatom atommap atom newatom residue newresidue newresidue add newatom bonds for bond in topo bonds a1 a2 bond na1 na2 atommap a1 atommap a2 if na1 not in bonds bonds na1 if na2 not in bonds bonds na2 b mdt Bond na1 na2 b order 1 if name is None name Unnamed molecule from OpenMM newmol mdt Molecule newatoms name name if assign_bond_orders for residue in newmol residues try residue assign_template_bonds except KeyError ValueError pass return newmol
: param obj : : type obj : translationentry : return :,def remote_translation self obj return obj remote_translation_entry translation
"given the field_paths of the queryset , returns a resultmap instance . resultmap.result_fields is a list of field_paths minus specifically omitted ones-- the parent i d and geometry column . resultmap.title_lookup is a lookup from the field_path to a title appropriate for the user . the generated title uses ' . ' in place of ' _ _ ' resultmap.value_map is a lookup from the field_path to a property path that describes how to convert the value to a more human readable form . this is used to convert instances to a readable label and dates , etc , to a more readable format . : param : related_models : pass the related_models represented in the query results so that unneeded paraent reference fields can be removed from the result fields : param : map_path_segments : an optional dict that matches segments of the field_paths . the value corresponding the key is the name to convert it to for the title . if the value is none it will be eliminated from the path when it is rejoined with ' . '",def create_result_map self related_models map_path_segments result_paths self model_result_paths related_models result_field_path_lookup self model_result_field_path_field_lookup related_models True join_models map lambda model full_module_path model __base__ related_models return ResultMap result_fields map lambda path string replace path __ _x_ result_paths title_lookup map_to_dict lambda path string replace path __ _x_ __ join compact map lambda segment map_path_segments get segment segment path split __ result_paths field_lookup map_dict_to_dict lambda field_path tup field_path tup 0 result_field_path_lookup related_model_lookup compact_dict map_dict_to_dict lambda field_path tup field_path tup 1 result_field_path_lookup join_models join_models
"> > > from pymel.all import * > > > versions.parseversionstr('2008 service pack1 x64 ' ) ' 2008 ' > > > versions.parseversionstr('2008 service pack1 x64 ' , extension = true ) ' 2008-x64 ' > > > versions.parseversionstr('2008x64 ' , extension = true ) ' 2008-x64 ' > > > versions.parseversionstr('8.5 ' , extension = true ) ' 8.5 ' > > > versions.parseversionstr('2008 extension 2 ' ) ' 2008 ' > > > versions.parseversionstr('/applications/autodesk/maya2009/maya.app/contents ' , extension = true ) ' 2009 ' > > > versions.parseversionstr('c:\program files ( x86)\autodesk\maya2008 ' , extension = true ) ' 2008 '",def parseVersionStr versionStr extension False from pymel all import versions parseVersionStr 2008 Service Pack1 x64 2008 versions parseVersionStr 2008 Service Pack1 x64 extension True 2008 x64 versions parseVersionStr 2008x64 extension True 2008 x64 versions parseVersionStr 8 5 extension True 8 5 versions parseVersionStr 2008 Extension 2 2008 versions parseVersionStr Applications Autodesk maya2009 Maya app Contents extension True 2009 versions parseVersionStr C Program Files x86 Autodesk Maya2008 extension True 2008 ma re search maya P base d 3 P ext x d versionStr version ma group base if extension and ma group ext is not None version ma group ext return version
convert a sequence of integers into a tuple of slice objects,def sequenceToSlices intList sort True pass
"given a sequence , will return an iterator over the possible permutations .",def permutations sequence length None pass
strip all whitespace from postcode and convert to uppercase this will make it easier to query based on user - supplied postcode,def save self args kwargs self postcode Postcode self postcode without_space super save args kwargs
returns a set of operation ids for the specified dates .,staticmethod def _GetStoredOperations zone config date number_days 3 if number_days 1 raise GceZoneOperationsInputException GetOperationsForDays number_days is less than one d number_days operation_ids sets Set if not GceZoneOperationsInput _BigQueryTableExists config logging info s does not exist in dataset s config destinationTable datasetId config destinationTable tableId return operation_ids bq bigquery BigQuery config destinationTable projectId query_str GceZoneOperationsInput _StoredOperationsQueryString config destinationTable datasetId config destinationTable tableId zone date number_days logging debug BigQuery Query s query_str start_index 0 total_rows 1 while start_index total_rows result bq Query query_str table_info None offset start_index max_results 100 if len result 3 raise GceZoneOperationsInputException error Big Query query quit Please review your Big Query query for query syntax _ _ reply result total_rows int reply totalRows reply_rows reply get rows if not reply_rows logging info No BigQuery operation rows found for zone s for date s zone date else operation_ids update row f 0 v for row in reply_rows start_index len reply_rows return operation_ids
this function takes hidden state and returns output,def get_output self hidden_state output tf nn relu tf matmul hidden_state self Wo self bo return output
verify if the specified operation responses are json schema compatible .,def is_json_schema_compatible self response_definition if not response_definition return False return schema in response_definition and all_json self mimetype or self mimetype text plain
determine the root directory in which switchmap.is installed .,def root_directory switchmap_dir switchmap __path__ 0 components switchmap_dir split os sep root_dir os sep join components 0 2 return root_dir
return one image field ( image = field name ) in a card object . returns a default image when the field does n't exist or the card does n't have this image stored .,register simple_tag takes_context True def imageurl context card image english_version False if english_version image english_ image if hasattr card image card_image getattr card image if card_image return _imageurl unicode card_image context context return context static_url u static default card attribute png
"list the n most common elements and their counts from the most common to the least . if n is none , then list all element counts .",def most_common self n None if n is None return sorted self iteritems key itemgetter 1 reverse True return nlargest n self iteritems key itemgetter 1
send an e - mail using ses,application route customer registered methods POST def customer_registered response None if request json is None response Response status 415 else message dict try if request json has_key TopicArn and request json has_key Message message json loads request json Message else message request json ses boto ses connect_to_region application config AWS_REGION ses send_email source application config SOURCE_EMAIL_ADDRESS subject SUBJECT body BODY message name to_addresses message email response Response status 200 except Exception as ex logging exception Error processing message s request json response Response ex message status 500 return response
simulate writing by the socket - datacollector,def simulate_socket_datacollector params dir_idx params index dir assert dir_idx 0 output_dir params dir_idx 1 filepattern_idx params index filepattern assert filepattern_idx 0 filepattern params filepattern_idx 1 filename os path join output_dir filepattern with open filename w as f f write FPROBE_FRAME print Write file s filename with open filename tmp w as f f write FPROBE_FRAME
add a test to the table and update the results .,def add_test self test row test test save_method test load_method self rows append row for dt in self headers 3 row append test run_test dt
register an observer to a specific event,def register self function observer event function __name__ if event not in self observers self observers event try self observers event observer 1 except KeyError op False else op True return op
transactional implementation of : func:`queue.take ( ) < hazelcast.proxy.queue.queue.take > `,def take self return self _encode_invoke transactional_queue_take_codec
send events to a firehose delivery stream .,def send_to_delivery_stream events delivery_stream if events logger info Sending d events to delivery stream s len events delivery_stream stream_name delivery_stream stream_name if filter in delivery_stream logger info Applying filter before delivery events copy deepcopy ev for ev in events if delivery_stream filter ev logger info Selected d events for delivery len events if not events logger info All events were filtered out nothing delivered return if mapper in delivery_stream logger info Mapping d events before delivery len events events delivery_stream mapper copy deepcopy ev for ev in events logger info First delivered event s pretty events 0 resp utils send_to_delivery_stream events stream_name if resp ResponseMetadata HTTPStatusCode 200 raise FirehoseError json dumps resp logger info resp
convert a quicktime / mp4 file for streaming by moving the metadata to the front of the file . this method writes a new file .,def process infilename outfilename limit float inf to_end False cleanup True datastream open infilename rb index get_index datastream moov_pos 999999 mdat_pos 999999 free_size 0 for atom in index if atom name moov moov_atom atom moov_pos atom position elif atom name mdat mdat_pos atom position elif atom name free and atom position mdat_pos and cleanup free_size atom size plugin log info Removing free atom at d d bytes atom position atom size elif atom name x00 x00 x00 x00 and atom position mdat_pos free_size 8 plugin log info Removing strange zero atom at s 8 bytes atom position if moov_pos 999999 return False offset free_size if moov_pos mdat_pos if to_end offset moov_atom size elif not to_end offset moov_atom size if offset 0 msg This file appears to already be setup plugin log error msg plugin log info s msg return True is_compressed _moov_is_compressed datastream moov_atom if is_compressed msg Movies with compressed headers are not supported plugin log error msg return False moov _patch_moov datastream moov_atom offset plugin log info Writing output outfile open outfilename wb for atom in index if atom name ftyp plugin log debug Writing ftyp d bytes atom size datastream seek atom position outfile write datastream read atom size if not to_end _write_moov moov outfile skip_atom_types ftyp moov if cleanup skip_atom_types free atoms item for item in index if item name not in skip_atom_types for atom in atoms plugin log debug Writing s d bytes atom name atom size datastream seek atom position cur_limit limit or float inf cur_limit min cur_limit atom size for chunk in get_chunks datastream CHUNK_SIZE cur_limit outfile write chunk if to_end _write_moov moov outfile outfile close try shutil copymode infilename outfilename except plugin log warn Could not copy file permissions
continue hashing of a message by consuming the next chunk of data .,def update self data if self _digest_done and not self _update_after_digest raise TypeError You can only call digest or hexdigest on this object expect_byte_string data result _raw_blake2s_lib blake2s_update self _state get data c_size_t len data if result raise ValueError Error d while hashing BLAKE2s data result return self
"disables the ball save logic when multiple saves are not allowed . this is typically linked to a trough object so the trough can notify this logic when a ball is being saved . if ' self.callback ' is externally defined , that method will be called from here .",def launch_callback self self logger debug a ball has been saved if self callback self callback if not self allow_multiple_saves self disable
"call the appropriate upgrade function to convert current_version to target_version . if a direct conversion function does not exist , use consecutive conversion functions .",def upgrade path current_version target_version STORAGE_VERSION if current_version not in STORAGE_VERSIONS raise NotImplementedError Cannot handle version s yet current_version if target_version not in STORAGE_VERSIONS raise NotImplementedError Cannot handle version s yet current_version if current_version target_version in upgrade_classes upgrade_class upgrade_classes current_version target_version u upgrade_class path u upgrade else i STORAGE_VERSIONS index current_version while True version_a STORAGE_VERSIONS i version_b STORAGE_VERSIONS i 1 try upgrade_class upgrade_classes version_a version_b except KeyError raise NotImplementedError Cannot convert version s to s yet version_a version_b u upgrade_class path u upgrade if version_b target_version break i 1
true if this object has a custom name .,property def is_named self return self _name
create all directories described by path if they do n't exist .,def mkdir_p path u try os makedirs path except OSError as exc if exc errno errno EEXIST and os path isdir path pass else raise
reverberation time according to sabine .,def t60_sabine surfaces alpha volume c SOUNDSPEED Reverberation time according to Sabine param surfaces Surface of the room math S NumPy array that contains different surfaces type surfaces class np ndarray param alpha Absorption coefficient of the room math alpha Contains absorption coefficients of surfaces It could be one value or some values in different bands 1D and 2D array respectively type alpha class np ndarray param volume Volume of the room math V type volume class float param c Speed of sound math c type c class float returns Reverberation time math T_ 60 Sabine s formula for the reverberation time is math T_ 60 frac 24 ln 10 c frac V S alpha mean_alpha np average alpha axis 0 weights surfaces S np sum surfaces axis 0 A S mean_alpha t60 4 0 np log 10 0 6 0 volume c A return t60
"return all channels if exclude_archived ( default : true ) , only shows non - archived channels",def get_all_channel_objects self exclude_archived True url_template self url channels list exclude_archived token if exclude_archived exclude_archived 1 else exclude_archived 0 url url_template format exclude_archived self token payload self get_with_retry_to_json url assert channels in payload return payload channels
"creates a test database , prompting the user for confirmation if the database already exists . returns the name of the test database created .",def create_test_db self verbosity 1 autoclobber False serialize True keepdb False from django core management import call_command test_database_name self _get_test_db_name if verbosity 1 action Creating if keepdb action Using existing print s test database for alias s action self _get_database_display_str verbosity test_database_name self _create_test_db verbosity autoclobber keepdb self connection close settings DATABASES self connection alias NAME test_database_name self connection settings_dict NAME test_database_name call_command migrate verbosity max verbosity 1 0 interactive False database self connection alias run_syncdb True if serialize self connection _test_serialized_contents self serialize_db_to_string call_command createcachetable database self connection alias self connection ensure_connection return test_database_name
remove all the cache files .,def clear self if not os path exists self _dir return for fname in self _list_cache_files self _delete fname
coordinates of the raster origin .,property def origin self return TransformPoint self origin
add my options to command line .,def options self parser env env_opt NOSE_WITHOUT_SKIP parser add_option no skip action store_true dest noSkip default env get env_opt False help Disable special handling of SkipTest exceptions
add failure output to xunit report .,def addFailure self test err capt None tb_info None taken self _timeTaken tb format_exception err self encoding self stats failures 1 id test id self errorlist append u testcase classname cls s name name s time taken 3f failure type errtype s message message s CDATA tb s failure systemout s systemerr s testcase cls self _quoteattr id_split id 0 name self _quoteattr id_split id 1 taken taken errtype self _quoteattr nice_classname err 0 message self _quoteattr exc_message err tb escape_cdata tb systemout self _getCapturedStdout systemerr self _getCapturedStderr
"parses a visual studio log pointed to by the build_log_path and returns a dependency graph for the built projects . to get a fully - fledged graph make sure to add "" /bt+ /showincludes /nologo- /fc "" to the compiler options .",def parse_vs_log build_log_path dependency_graph DependencyGraph channels collections defaultdict _Channel_state with open build_log_path as f for l in f l l rstrip n m _CHANNEL_PATTERN match l if m channel_id int m group 1 channels channel_id parse_line l dependency_graph for c in channels values c end dependency_graph return dependency_graph
creates a default instance of a basic non - relational field .,def get_field_kwargs field_name model_field kwargs validator_kwarg list model_field validators kwargs model_field model_field if model_field verbose_name and needs_label model_field field_name kwargs label capfirst model_field verbose_name if model_field help_text kwargs help_text model_field help_text max_digits getattr model_field max_digits None if max_digits is not None kwargs max_digits max_digits decimal_places getattr model_field decimal_places None if decimal_places is not None kwargs decimal_places decimal_places if isinstance model_field models TextField or postgres_fields and isinstance model_field postgres_fields JSONField kwargs style base_template textarea html if isinstance model_field models AutoField or not model_field editable kwargs read_only True return kwargs if model_field has_default or model_field blank or model_field null kwargs required False if model_field null and not isinstance model_field models NullBooleanField kwargs allow_null True if model_field blank and isinstance model_field models CharField or isinstance model_field models TextField kwargs allow_blank True if isinstance model_field models FilePathField kwargs path model_field path if model_field match is not None kwargs match model_field match if model_field recursive is not False kwargs recursive model_field recursive if model_field allow_files is not True kwargs allow_files model_field allow_files if model_field allow_folders is not False kwargs allow_folders model_field allow_folders if model_field choices kwargs choices model_field choices else max_value next validator limit_value for validator in validator_kwarg if isinstance validator validators MaxValueValidator None if max_value is not None and isinstance model_field NUMERIC_FIELD_TYPES kwargs max_value max_value validator_kwarg validator for validator in validator_kwarg if not isinstance validator validators MaxValueValidator min_value next validator limit_value for validator in validator_kwarg if isinstance validator validators MinValueValidator None if min_value is not None and isinstance model_field NUMERIC_FIELD_TYPES kwargs min_value min_value validator_kwarg validator for validator in validator_kwarg if not isinstance validator validators MinValueValidator if isinstance model_field models URLField validator_kwarg validator for validator in validator_kwarg if not isinstance validator validators URLValidator if isinstance model_field models EmailField validator_kwarg validator for validator in validator_kwarg if validator is not validators validate_email if isinstance model_field models SlugField validator_kwarg validator for validator in validator_kwarg if validator is not validators validate_slug if isinstance model_field models GenericIPAddressField validator_kwarg validator for validator in validator_kwarg if validator is not validators validate_ipv46_address if isinstance model_field models DecimalField validator_kwarg validator for validator in validator_kwarg if not isinstance validator validators DecimalValidator max_length getattr model_field max_length None if max_length is not None and isinstance model_field models CharField or isinstance model_field models TextField or isinstance model_field models FileField kwargs max_length max_length validator_kwarg validator for validator in validator_kwarg if not isinstance validator validators MaxLengthValidator min_length next validator limit_value for validator in validator_kwarg if isinstance validator validators MinLengthValidator None if min_length is not None and isinstance model_field models CharField kwargs min_length min_length validator_kwarg validator for validator in validator_kwarg if not isinstance validator validators MinLengthValidator if getattr model_field unique False unique_error_message model_field error_messages get unique None if unique_error_message unique_error_message unique_error_message model_name model_field model _meta verbose_name field_label model_field verbose_name validator UniqueValidator queryset model_field model _default_manager message unique_error_message validator_kwarg append validator if validator_kwarg kwargs validators validator_kwarg return kwargs
"device instance implementing the following methods : getsize ( ) - > int size of the underlying storage . write(offset , data ) write < data > starting at < offset>. read(offset , length ) - > string read < length > bytes starting at < offset>.",def __init__ self device self _device device self _size device getSize
validate the contents of the specified configuration . : arguments : 1 . datastore = the name of the configuration datastore being validated : returns : rpc_reply,def validate self datastore return self nc_manager validate datastore
locate all setuptools entry points by the name ' keyring backends ' and initialize them . any third - party library may register an entry point by adding the following to their setup.py : :,def _load_plugins if pkg_resources not in globals return group keyring backends entry_points pkg_resources iter_entry_points group group for ep in entry_points try log info Loading s ep name init_func ep load if callable init_func init_func except Exception log exception Error initializing plugin s ep
run self.case reporting activity to result .,def run self result None if result is None actual_result self case defaultTestResult actual_result startTestRun else actual_result result try return self _run_one actual_result finally if result is None actual_result stopTestRun
exchange login id and api key for a temporary auth token,def authenticate self return self post v2 authenticate api login_id self config login_id api_key self config api_key authenticated False retry False
function that draws a sample from the posterior approximation to the weights distribution .,def sample_weights self self pbp_instance sample_w
# return list of sync jobs,pytest mark parametrize offset records user_guid None None None 100 100 None 100000000 1000 None None None 1 100 100 1 100000000 1000 1 def test_db_sync_list self offset records user_guid self db_connection db_rollback self db_connection db_sync_list offset records user_guid
set theta 's in the database,def set_theta self thetas key self r_server hmset key thetas return True
colorize a string containing only python code . this method differs from l{colorize_doctest } in that it will not search for doctest prompts when deciding how to colorize the string .,def colorize_codeblock self s body self DOCTEST_RE sub self subfunc s return self PREFIX body self SUFFIX
todo : this is n't tested,classmethod def handle_message cls poll_service poll_message django_request prp PollRequestProperties from_poll_request_10 poll_service poll_message query_kwargs prp get_db_kwargs content_blocks cls get_content prp query_kwargs response cls create_poll_response poll_service prp content_blocks return response
handle the exception raised by given listener . send the traceback to all subscribers of topic self.topicuncaughtexc .,def __call__ self listenerID topicObj tbInfo TracebackInfo self __topicObj publish listenerStr listenerID excTraceback tbInfo
method that processes robtarget to ^ conversion .,def processRobt2AstModFile self self openModFile self writeToModRobt2AstFile
build the arguments to ' python setup.py install ' on the setuptools package,def _build_install_args options return user if options user_install else
sets global param mode to train .,staticmethod def train filename Param trainMode True return Param ParamStore filename
print vertex names on line 1 and vertex component ids on line 2 .,def prt_ids self prt prt write id v n format join self _id keys prt write id v n format join str i for i in self _id values
takes a state variable and returns the measurement that would correspond to that state .,def h self x ident_matrix np eye len x sensor_out ident_matrix dot x return sensor_out
read and report license information from raw license file,def process_licenses settings None licenseServer settings licenseServer with codecs open settings input r utf 8 as f licenseRaw f readlines status timestamp None serverStatus DOWN licenses extensions licenseType None license None for i line in enumerate licenseRaw line line replace n replace r line line encode ascii ignore if i 1 strTimestamp line split status on 1 timestamp datetime strptime strTimestamp a m d Y H M status timestamp timestamp strftime m d Y I M p del strTimestamp del timestamp if license server in line and UP in line status serverStatus UP if Users of in line or i 1 len licenseRaw if not licenseType None and not license None dictTarget licenses if licenseType in settings extensions dictTarget extensions license calcValues status dictTarget licenseType license __dict__ license None parensStart line find licenseType line 9 parensStart 3 if licenseType in settings licenses license License name settings licenses licenseType name total settings licenses licenseType count id licenseType display settings licenses licenseType display order settings licenses licenseType order if licenseServer in line line line strip split license addUser hash line 2 user line 0 machine line 1 for type in licenses extensions licenseRemove for key in status type license status type key if license display False licenseRemove append key for license in licenseRemove del status type license return status
"training set consists of pairs ( message , is_spam )",def count_words training_set counts defaultdict lambda 0 0 for message is_spam in training_set for word in tokenize message counts word 0 if is_spam else 1 1 return counts
make the dicitonary of state methods for the scene .,def make_state_dict self state_dict c TRANSITION_IN self transition_in c TRANSITION_OUT self transition_out c NORMAL self normal_update return state_dict
"addmilestone(plannerinterface self , pyobject * milestone ) - > int",def addMilestone self args return _motionplanning PlannerInterface_addMilestone self args
yield lines with hexdump of data,def hexdump data values ascii offset 0 for h a in sixteen data if h is None yield offset join join values join ascii del values del ascii offset 16 else values append h ascii append a
"assign permission to the given user , e.g. ' clusters.view_cluster ' ,",def assign_permission self user perm perm s_ s perm self _meta model_name get_user_obj_perms_model self objects assign_perm perm user self
assert the xml is valid according to schema,def test_validate_xml self tree etree XML self xml self xmlschema assertValid tree
test setup with configuration missing required entries .,def test_setup_missing_config self assert not run_coroutine_threadsafe rest async_setup_platform self hass platform rest None self hass loop result
setup the enocean light platform .,def setup_platform hass config add_devices discovery_info None sender_id config get CONF_SENDER_ID devname config get CONF_NAME dev_id config get CONF_ID add_devices EnOceanLight sender_id devname dev_id
return i d of the device .,property def device_id self return self _id 0
utc datetime object of the next sun setting .,def next_setting_utc hass entity_id None entity_id entity_id or ENTITY_ID state hass states get ENTITY_ID try return dt_util parse_datetime state attributes STATE_ATTR_NEXT_SETTING except AttributeError KeyError return None
return the name of the garage door if any .,property def name self return self _name if self _name else DEFAULT_NAME
return true if lock is locked .,property def is_locked self return hub lock_status self _id status
request an update from the bloomsky api .,def update self self _bloomsky refresh_devices state self _bloomsky devices self _device_id Data self _sensor_name if self _sensor_name in FORMAT_NUMBERS self _state 0 2f format state else self _state state
stop everything that was started .,def teardown_method self self hass stop
"unit of measurement of this entity , if any .",property def unit_of_measurement self return self _unit_of_measurement
main section of the script .,def main if not os path isfile requirements_all txt print Run this from HA root dir return data gather_modules if data is None sys exit 1 if sys argv 1 validate if validate_file data sys exit 0 print ERROR print requirements_all txt is not up to date print Please run script gen_requirements_all py sys exit 1 write_file data
get the latest data from the glances rest api .,Throttle MIN_TIME_BETWEEN_UPDATES def update self try response requests get self _resource timeout 10 self data response json except requests exceptions ConnectionError _LOGGER error No route to host endpoint s self _resource self data None
call a rest command with post .,def test_rest_command_post self aioclient_mock data payload data self config rc DOMAIN post_test update data with assert_setup_component 4 setup_component self hass rc DOMAIN self config aioclient_mock post self url content success self hass services call rc DOMAIN post_test self hass block_till_done assert len aioclient_mock mock_calls 1 assert aioclient_mock mock_calls 0 2 data
convert plexapi _ na ( ) instances to none .,def _convert_na_to_none self value if value is self na_type return None else return value
get a certain number of sentences .,def get_paragraph num_lines return_lines for line_num in range num_lines return_lines lines randint 0 len lines 1 return return_lines
check that private variables defined at the top level are used later .,def private_vars_at_toplevel abstract_syntax_tree errors variables_set find_all toplevel_set_private_vars abstract_syntax_tree def _not_in_variables_set node Return false if in variables_set try return not node line node col in variables_set node contents except KeyError return True def _starts_with_underscore name Return true if variable name starts with an underscore return name startswith _ variables_used find_all variables_used_matching abstract_syntax_tree _not_in_variables_set _starts_with_underscore for var in variables_set keys if var not in variables_used keys msg Unused set variable at toplevel 0 format var errors append LinterFailure msg variables_set var 0 0 return errors
encode labels into one - hot representation,def _onehot self y n_classes onehot np zeros n_classes y shape 0 astype int for idx val in enumerate y onehot val idx 1 0 return onehot T
create a session object . username and password are both required parameters,def __init__ self username password self username username self password password self state closed self authToken None self last_request_time None
get the directory containing the tensorflow framework library .,def get_lib import tensorflow as tf return _os_path join _os_path dirname tf __file__ core
starts a thread to automatically reload the given multiplexer .,def StartMultiplexerReloadingThread multiplexer path_to_run load_interval def _ReloadForever while True ReloadMultiplexer multiplexer path_to_run time sleep load_interval thread threading Thread target _ReloadForever thread daemon True thread start return thread
creates default input parsing using estimator 's feature signatures .,deprecated 2016 09 23 The signature of the input_fn accepted by export is changing to be consistent with what s used by tf Learn Estimator s train evaluate which makes this function useless This will be removed after the deprecation date def _default_input_fn estimator examples return estimator _get_feature_ops_from_example examples
form the correct create_option to append to results .,def get_create_option self context q create_option display_create_option False if self create_field and q page_obj context get page_obj None if page_obj is None or page_obj number 1 display_create_option True existing_options self get_result_label result lower for result in context object_list if q lower in existing_options display_create_option False if display_create_option and self has_add_permission self request create_option id q text _ Create new_value s new_value q create_id True return create_option
filters the annotations for only democratic annotations .,def democratic self return self filter label__slug democratic
returns a domain - specified email address based on an owner string .,staticmethod def GetCanonicalEmail owner if not in owner owner user domain format user owner domain DEFAULT_DOMAIN return owner
resolve field reference form context .,def resolve_part self context part self part_id resolve context if isinstance part BoundField part part field return part
return cost of training camp for a single player .,def get_player_cost self quality self options quality 1 550 self options quality location self options location 1 425 self options location purpose self options purpose 1 350 cost quality location purpose self options days return cost
add ticket price object for stadium category .,def add_ticket_price self ticket multiplier self categories ticket TicketPrices multiplier
resolve a single node or all when node is omitted .,def resolve_node self node None resolved None seen None if seen is None seen if resolved is None resolved if node is None dependencies sorted self _nodes keys else dependencies self _nodes node seen append node for dependency in dependencies if dependency in resolved continue if dependency in seen raise Exception Circular dependency s s str node str dependency self resolve_node dependency resolved seen if node is not None resolved append node return resolved
initialize a chemical functional group given a string name .,classmethod def parse cls scheme text def append_to_psgs count psg for i in range count psgs append psg parts cls _parser_re split text csg parts 0 next_psg None psgs for part in parts 1 if not part continue if part isdigit if next_psg is None raise GroupSyntaxError Expected base atom for Benson group got number instead append_to_psgs int part next_psg next_psg None else if next_psg is not None append_to_psgs 1 next_psg next_psg None next_psg part if next_psg is not None append_to_psgs 1 next_psg return cls scheme csg psgs
it should produce a mets : div element . it should have a type and label . it should have a child mets : fptr element with fileid .,def test_serialize_structmap_file self f metsrw FSEntry file1 txt file_uuid str uuid uuid4 f add_dublin_core dc el f serialize_structmap recurse False assert el tag http www loc gov METS div assert el attrib TYPE Item assert el attrib LABEL file1 txt assert len el attrib DMDID split 1 assert len el 1 assert el 0 tag http www loc gov METS fptr assert el 0 attrib FILEID startswith file
return a scratch array dimensioned for our grid,def scratchArray self return numpy zeros self nx 2 self ng dtype numpy float64
"make a move on the board ,",def mm_move board player if board check_win is not None return SCORES board check_win 1 1 result 1 1 1 for move in board get_empty_squares copied_board board clone copied_board move move 0 move 1 player score _ mm_move copied_board switch_player player if score SCORES player 1 return score move elif score SCORES player result 0 result score move elif result 0 1 result result 0 move return result 0 SCORES player result 1
perform an static analysis on the sample and return the json,def binskim sample signature _check_challenge signature if len re findall a f d 32 sample 0 return Wrong Input binskim_path config binskim file_x64 command analyze path config MobSF samples sample output_p o output_d config MobSF samples sample _binskim verbose v policy_p config policy_d default params binskim_path command path output_p output_d verbose policy_p policy_d pipe subprocess Popen subprocess list2cmdline params pipe wait out_file open output_d return out_file read
get the i d of the artifacts project,def get_project_id self return self __project_id
generate and write out challenge certificate .,def _setup_challenge_cert self achall s None cert_path self get_cert_file achall self configurator reverter register_file_creation True cert_path cert_pem response achall gen_cert_and_response s with open cert_path w as cert_chall_fd cert_chall_fd write cert_pem return response
""" rotates array arr left between l and r. r is included .",def rotate_left arr l r temp arr l for i in range l r arr i arr i 1 arr r temp
basic routine to run a shell command .,def shell_run arg_list timeout 268435455 assert type arg_list in list str unicode arg list must be list or str s type arg_list if type arg_list in str unicode arg_list arg_list split stdout_fd tempfile TemporaryFile stderr_fd tempfile TemporaryFile try p subprocess Popen arg_list stdout stdout_fd stderr stderr_fd close_fds True rc None max_wait 1 0 wait 0 001 timeout time time while rc is None rc p poll if rc is None time sleep 1 if time time timeout p kill stdout_fd seek 0 stderr_fd seek 0 return RunResult 254 stdout_fd read decode ascii ignore stderr_fd read decode ascii ignore True elif wait max_wait wait 2 0 else stdout_fd seek 0 stderr_fd seek 0 return RunResult rc stdout_fd read decode ascii ignore stderr_fd read decode ascii ignore False finally stdout_fd close stderr_fd close
ensures the response is returning a http 304 .,def assertHttpNotModified self resp return self assertEqual resp status_code 304
the scrypt_keymaster kdf which is * supposed * to be hw bound,def scrypt_keymaster passwd crypto_footer privkey ikey scrypt_crypto_footer passwd crypto_footer KEY_LEN_BYTES IV_LEN_BYTES buf x00 ikey buf x00 privkey n bit_length 8 len buf signature X privkey sign buf 0 if len signature 2 0 signature 0 signature signature signature decode hex return scrypt_crypto_footer signature crypto_footer KEY_LEN_BYTES IV_LEN_BYTES
"the matplotlib datalim , autoscaling , locators etc work with scalars which are the units converted to floats given the current unit . the converter may be passed these floats , or arrays of them , even when units are set . derived conversion interfaces may opt to pass plain - ol unitless numbers through the conversion interface and this is a helper function for them .",staticmethod def is_numlike x u n The matplotlib datalim autoscaling locators etc work with n scalars which are the units converted to floats given the n current unit The converter may be passed these floats or n arrays of them even when units are set Derived conversion n interfaces may opt to pass plain ol unitless numbers through n the conversion interface and this is a helper function for n them n if iterable x for thisx in x return is_numlike thisx else return is_numlike x
transform a python signature into rst nodes .,def handle_signature self sig signode name_prefix None name sig arglist None retann None modname self options get module self env temp_data get py module classname self env temp_data get py class fullname name signode module modname signode class classname signode fullname fullname sig_prefix self get_signature_prefix sig if sig_prefix signode addnodes desc_annotation sig_prefix sig_prefix if name_prefix signode addnodes desc_addname name_prefix name_prefix anno self options get annotation signode addnodes desc_name name name if not arglist if self needs_arglist signode addnodes desc_parameterlist if retann signode addnodes desc_returns retann retann if anno signode addnodes desc_annotation anno anno return fullname name_prefix _pseudo_parse_arglist signode arglist if retann signode addnodes desc_returns retann retann if anno signode addnodes desc_annotation anno anno return fullname name_prefix
get the poses from the objects identified by the given object ids list .,def get_object_poses self object_ids ser_ops self _psi get_object_poses object_ids ops dict for key in ser_ops msg Pose conversions msg_from_string msg ser_ops key ops key msg return ops
marginalizing over the sub - gradient,def construct_weights self full_state if not self _setup raise ValueError setup_sampler should be called before using this function threshold self threshold weights np zeros_like self boundary np float weights self boundary self randomization _density threshold self boundary full_state self boundary self randomization _density threshold self boundary full_state self boundary 1 self randomization _cdf threshold self boundary full_state self boundary self randomization _cdf threshold self boundary full_state self boundary weights self boundary self randomization _density threshold self boundary full_state self boundary self randomization _density threshold self boundary full_state self boundary self randomization _cdf threshold self boundary full_state self boundary self randomization _cdf threshold self boundary full_state self boundary return weights
"takes a url , and turns it into a partial media object dict",classmethod def partial_media_dict_from_url cls url url url strip for s media_type in cls URL_PATTERNS if s in url if media_type MediaType CD_PHOTO_THREAD return cls _partial_media_dict_from_cd_photo_thread url elif media_type MediaType GRABCAD return cls _partial_media_dict_from_grabcad url elif media_type in cls OEMBED_PROVIDERS return cls _partial_media_dict_from_oembed media_type url else return cls _create_media_dict media_type url if url logging warning Failed to determine media type from url format url return None
remotely import the test library with given ` name ` .,keyword def import_remote_library self name if name not in self allow_import raise RuntimeError Importing Remote Library s is not allowed name lib self Import name if self register_keywords self _register_library_keywords lib
an alias is not recorded in .sconsign files,def sconsign self pass
sets the essential infomation about a rule and automatically computes inverse match and rewrite .,def set_rule self table in_ports out_ports match mask rewrite self input_ports in_ports self output_ports out_ports self match match self mask mask self rewrite rewrite self table table if mask __class__ wildcard and rewrite __class__ wildcard masked wildcard_and match mask rewritten wildcard_or masked rewrite self inverse_match rewritten self inverse_rewrite wildcard_and wildcard_not mask match else self mask None self rewrite None self inverse_match match self inverse_rewrite None return self
verify no rate limiter is used if the configuration is missing .,mock patch object google auth default return_value mock Mock spec_set credentials Credentials test project def test_no_quota self mock_google_credential ae_api_client ae AppEngineClient global_configs self assertEqual None ae_api_client repository _rate_limiter
test get_dataset_access raises when there is an http exception .,def test_get_dataset_access_raises self http_mocks mock_http_response fbq PERMISSION_DENIED 403 with self assertRaises api_errors ApiExecutionError self bq_api_client get_dataset_access fbq PROJECT_IDS 0 fbq DATASET_ID
raise violation is the ip is not in the whitelist .,def find_violations self instance_network_interface_list for instance_network_interface in instance_network_interface_list network_and_project re search compute projects networks instance_network_interface network project network_and_project group 1 network network_and_project group 2 is_external_network instance_network_interface access_configs is not None ips None if network not in self rules whitelist get project and is_external_network ips config natIP for config in instance_network_interface access_configs if natIP in config yield self RuleViolation resource_type resource_mod ResourceType INSTANCE resource_id instance_network_interface name full_name instance_network_interface full_name rule_name self rule_name rule_index self rule_index violation_type INSTANCE_NETWORK_INTERFACE_VIOLATION project project network network ip ips resource_data instance_network_interface as_json
initialize a new instance of the class .,def __init__ self instrumentation_key wsgi_application args kwargs if not instrumentation_key raise Exception Instrumentation key was required but not provided if not wsgi_application raise Exception WSGI application was required but not provided telemetry_channel kwargs pop telemetry_channel None if not telemetry_channel sender applicationinsights channel AsynchronousSender queue applicationinsights channel AsynchronousQueue sender telemetry_channel applicationinsights channel TelemetryChannel None queue self client applicationinsights TelemetryClient instrumentation_key telemetry_channel self client context device type PC self _wsgi_application wsgi_application self _common_properties kwargs pop common_properties
"ensure that btax submission does not advance the worker node counter , nor use the dropq_offset",def test_btax_submit_to_single_host self wnc created WorkerNodesCounter objects get_or_create singleton_enforce 1 wnc current_offset 1 wnc save import sys webapp_views sys modules webapp apps btax views webapp_views dropq_compute MockComputeBtax data OK_POST_DATA copy response self client post ccc data self assertEqual response status_code 302 link_idx response url 1 rfind self assertTrue response url link_idx 1 endswith ccc data OK_POST_DATA copy response self client post ccc data self assertEqual response status_code 302
called when the power state changes .,def _state_changed self state logger debug Adapter state change 0 format state if state 5 self _powered_off clear self _powered_on set elif state 4 self _powered_on clear self _powered_off set
checks whether the given word is a stop word,abc abstractmethod def is_stop_word self word raise NotImplementedError Abstract Data Type
": param type : the type of phone number to search for . : param string country : only show numbers for this country ( iso2 ) : param string region : when searching the us , show numbers in this state : param string postal_code : only show numbers in this area code : param string rate_center : us only . : param tuple near_lat_long : find close numbers within distance miles . : param integer distance : search radius for a near- query in miles .",def search self kwargs return self available_phone_numbers list kwargs
test that lines that have blank lines before and after are flagged as headings,def test_heading_check Lines Heading assert heading_check Lines 1 True
do forward prop and return the values of the output layer for a single observation vector,def predict self obs return self sess run self layers 1 feed_dict self inputs obs reshape 1 self net_dims 0
"takes a list of arrays a_1 , ... , a_n where the elements of the first n dimensions line up . for every possible index into the first n dimensions , apply fn to the corresponding slices , and combine the results into an n - dimensional array . supports broadcasting but does not prepend 1 's to the shapes .",def array_map fn arrs n if n 0 return fn arrs full_shape tuple np array a shape n for a in arrs max 0 result None for full_idx in itertools product map range full_shape inputs a broadcast full_idx a shape n Ellipsis for a in arrs curr fn inputs if result is None if type curr tuple result tuple np zeros full_shape np asarray c shape for c in curr else result np zeros full_shape np asarray curr shape if type curr tuple for i c in enumerate curr result i full_idx Ellipsis c else result full_idx Ellipsis curr return result
set an individual motor 's direction and speed,def set_motor motor direction value if direction BACKWARD For now assume CW is forwards forwards in1 LOW in2 HIGH GPIO output motor_ins motor 0 GPIO LOW GPIO output motor_ins motor 1 GPIO HIGH elif direction FORWARD GPIO output motor_ins motor 0 GPIO HIGH GPIO output motor_ins motor 1 GPIO LOW else there has been an error stop motors GPIO output STBY GPIO LOW PWM set_duty_cycle motor_pwms motor value
remove a single node from the ring,def remove_node self node self remove_nodes node
allow user to control which file to receive by setting the local date selected file will be the one at index ( day of year ) mod ( file count ) .,def filter_list_by_date data token try userData GamespyDatabase get_nas_login token date time strptime userData devtime y m d H M S files data splitlines ret files int date tm_yday 1 len files r n except ret filter_list_random_files data 1 return ret
return layers of dense neural network .,def DenseWordEmbed nb_labels dense_nb_nodes dense_actfcn vecsize 100 reg_coef 0 1 final_activiation softmax optimizer adam if len dense_nb_nodes len dense_actfcn raise UnequalArrayLengthsException dense_nb_nodes dense_actfcn nb_layers len dense_nb_nodes model Sequential if nb_layers 0 model add Dense nb_labels input_shape vecsize kernel_regularizer l2 reg_coef else model add Dense dense_nb_nodes 0 input_shape vecsize activation dense_actfcn 0 kernel_regularizer l2 reg_coef for nb_nodes activation in zip dense_nb_nodes 1 dense_actfcn 1 model add Dense nb_nodes activation activation kernel_regularizer l2 reg_coef model add Dense nb_labels kernel_regularizer l2 reg_coef model add Activation final_activiation model compile loss categorical_crossentropy optimizer optimizer return model
returns the z for which p(z < = z ) = probability,def normal_upper_bound probability mu 0 sigma 1 return inverse_normal_cdf probability mu sigma
return a suite of all tests cases contained in the given module,def loadTestsFromModule self module tests if module __name__ setuptools tests doctest tests append TestLoader loadTestsFromModule self module if hasattr module additional_tests tests append module additional_tests if hasattr module __path__ for file in resource_listdir module __name__ if file endswith py and file __init__ py submodule module __name__ file 3 elif resource_exists module __name__ file __init__ py submodule module __name__ file else continue tests append self loadTestsFromName submodule if len tests 1 return self suiteClass tests else return tests 0
lints a group of files using a given rcfile .,def lint_fileset dirnames kwargs try rc_filename kwargs rc_filename description kwargs description if len kwargs 2 raise KeyError except KeyError raise KeyError _LINT_FILESET_MSG pylint_shell_command pylint rcfile rc_filename pylint_shell_command extend dirnames status_code subprocess call pylint_shell_command if status_code 0 error_message _ERROR_TEMPLATE format description status_code print error_message file sys stderr sys exit status_code
takes a module name ( as a string ) and removes all references - from sys.modules - from workflowstepmountpoint class,def removeWorkflowStep step_module for key in list sys modules keys if step_module in key del sys modules key for cls in WorkflowStepMountPoint plugins if cls and step_module in cls __module__ index WorkflowStepMountPoint plugins index cls WorkflowStepMountPoint plugins pop index
terminates the connection with the device,def close self if self ptr cphidgets InterfaceKit_close self ptr
return true if state has child fsms,def hasChildren self return len self __FSMList 0
test that the context for the sidebar is correct and that the sidebar has got at least : return : none,def test_admin_page self response self client get reverse admin index self assertIn admin_app_list response context self assertContains response div class panel heading role tab id auth
this is a convenience function that makes it easy to access the value of a preference / constant without needing to check if the django_dynamic_preferences app has been set up and without needing to load from that model directly .,def getConstant name if dynamic_preferences_globalpreferencemodel in connection introspection table_names and not isPreliminaryRun params global_preferences_registry manager try return params get name except NotFoundInRegistry as e logger error Error in getting constant s e return None
"loops through the conditionals set on this object , returning false if any of them evaluate as such .",def evaluate_conditional self templar all_vars ds None if hasattr self _ds ds getattr self _ds try if isinstance self when bool return self when for conditional in self when if not self _check_conditional conditional templar all_vars return False except Exception as e raise AnsibleError The conditional check s failed The error was s to_native conditional to_native e obj ds return True
fetch file over scp from remote device,def fetch_file self source destination pass
helps the gui go from lists of instruction data to a cleanly formatted string,def parse_llil context llil_list newText for llil in llil_list if llil is not None tokens llil deref_tokens if hasattr llil deref_tokens else llil tokens newText format llil instr_index newText join context escape str token for token in tokens else newText None newText context newline if len llil_list 0 return newText strip context newline else return None
decode caveat by decrypting the encrypted part using key .,def decode_caveat key caveat if len caveat 0 raise VerificationError empty third party caveat first caveat 1 if first e return _decode_caveat_v1 key caveat first_as_int six byte2int first if first_as_int VERSION_2 or first_as_int VERSION_3 if len caveat _VERSION3_CAVEAT_MIN_LEN and first_as_int VERSION_3 raise VerificationError caveat id payload not provided for caveat id format caveat return _decode_caveat_v2_v3 first_as_int key caveat raise VerificationError unknown version for caveat
creates an initial pcollection by reading the vcf file headers .,def read_headers pipeline pipeline_mode known_args if pipeline_mode PipelineModes LARGE headers pipeline beam Create known_args input_pattern vcf_header_io ReadAllVcfHeaders else headers pipeline vcf_header_io ReadVcfHeaders known_args input_pattern return headers
installs a deb package through apt - get .,task def install package print Installing format package cmd apt get y install s package sudo cmd
prepares a video file for posting . defaults for size and aspect ratio from https://help.instagram.com/1469029763400082,def prepare_video vid thumbnail_frame_ts 0 0 max_size 1080 1350 aspect_ratios 4 0 5 0 90 0 47 0 max_duration 60 0 save_path None skip_reencoding False kwargs from moviepy video io VideoFileClip import VideoFileClip from moviepy video fx all import resize crop min_size kwargs pop min_size 612 320 progress_bar True if kwargs pop progress_bar None else False save_only kwargs pop save_only False preset kwargs pop preset medium if save_only and not save_path raise ValueError save_path cannot be empty if save_path if not save_path lower endswith mp4 raise ValueError You must specify a mp4 save path vid_is_modified False temp_video_file tempfile NamedTemporaryFile prefix ipae_ suffix mp4 delete False if is_remote vid res requests get vid temp_video_file write res content video_src_filename temp_video_file name else shutil copyfile vid temp_video_file name video_src_filename vid vidclip VideoFileClip temp_video_file name if vidclip duration 3 1 0 raise ValueError Duration is too short if vidclip duration max_duration 1 0 vidclip vidclip subclip 0 max_duration vid_is_modified True if thumbnail_frame_ts vidclip duration raise ValueError Invalid thumbnail frame if aspect_ratios crop_box calc_crop aspect_ratios vidclip size if crop_box vidclip crop vidclip x1 crop_box 0 y1 crop_box 1 x2 crop_box 2 y2 crop_box 3 vid_is_modified True if max_size or min_size new_size calc_resize max_size vidclip size min_size min_size if new_size vidclip resize vidclip newsize new_size vid_is_modified True temp_vid_output_file tempfile NamedTemporaryFile prefix ipae_ suffix mp4 delete False if vid_is_modified or not skip_reencoding vidclip write_videofile temp_vid_output_file name codec libx264 audio True audio_codec aac verbose False progress_bar progress_bar preset preset remove_temp True else shutil copyfile video_src_filename temp_vid_output_file name if save_path shutil copyfile temp_vid_output_file name save_path temp_thumbnail_file tempfile NamedTemporaryFile prefix ipae_ suffix jpg delete False vidclip save_frame temp_thumbnail_file name t thumbnail_frame_ts video_duration vidclip duration video_size vidclip size del vidclip video_thumbnail_content temp_thumbnail_file read if not save_only video_content_len os path getsize temp_vid_output_file name video_content temp_vid_output_file read else video_content_len os path getsize save_path video_content save_path if video_content_len 50 1024 1000 raise ValueError Video file is too big return video_content video_size video_duration video_thumbnail_content
return a string representation of the puzzle . the blank space is represented by an underscore .,def __str__ self digits len str self size1 self size2 1 result n for i in range self size1 for j in range self size2 if i j self blank_index result append digits 1 result append _ else num str self puzzle i j result append digits len num result append num result append n space return space join result
: param n_nucleotide : default number of typies of nucleotide is 4 : return : dict,def build_dict print Building a simple dictionary worddict a 2 c 3 g 4 t 5 return worddict
searches for running instances of gpsd and kill them,def stop_gpsd self for proc in psutil process_iter if proc name gpsd os kill proc pid
gets path to the directory containing the states of all pkb runs .,def GetAllRunsDirPath return os path join FLAGS temp_dir _RUNS
format a dict of tags into arguments for ' tag ' parameter .,def FormatTags tags_dict return Key s Value s k v for k v in tags_dict iteritems
stop and remove docker containers . remove images .,def Cleanup benchmark_spec master benchmark_spec vm_groups master 0 workers benchmark_spec vm_groups workers def CleanupCommon vm vm RemoteCommand sudo docker rm v data def CleanupMaster vm vm RemoteCommand sudo docker stop spark master vm RemoteCommand sudo docker rm spark master CleanupCommon vm def CleanupWorker vm vm RemoteCommand sudo docker stop spark worker vm RemoteCommand sudo docker rm spark worker CleanupCommon vm target_arg_tuples CleanupWorker vm for vm in workers CleanupMaster master vm_util RunParallelThreads target_arg_tuples len target_arg_tuples
returns a dict mapping valid package names to their modules .,def _GetValidPackages if FLAGS os_type in os_types WINDOWS_OS_TYPES return windows_packages PACKAGES return linux_packages PACKAGES
mark an interest in a pep subscription by including a disco feature with the ' + notify ' extension .,def add_interest self namespace jid None if not isinstance namespace set and not isinstance namespace list namespace namespace for ns in namespace self xmpp xep_0030 add_feature s notify ns jid jid self xmpp xep_0115 update_caps jid
sends a reject to the caller,def _send_reject self session callback callback session result error nodeId self nodeId timestamp_block None error_msg Reject
upload file : param path_from : path from : param path_to : path to yandex disk,def upload_file self path_from path_to url self _base_url resources upload payload path path_to r requests get url headers self base_headers params payload self _check_code r json_dict r json upload_link json_dict href with open path_from rb as fh files file fh r2 requests put upload_link headers self base_headers files files self _check_code r2
test whether predict_proba works as expected for multi class .,def test_predict_proba_multi X Xdigits_multi 10 y ydigits_multi 10 clf ELMClassifier n_hidden 5 clf fit X y y_proba clf predict_proba X n_samples n_classes y shape 0 np unique y size assert_equal y_proba shape n_samples n_classes
users : update should reverse to /users/~update/.,def test_update_reverse self self assertEqual reverse users update users update
add post filter by threat assesses confidence : type operator : filteroperator,def add_pf_threat_assess_confidence self data operator FilterOperator EQ post_filter PostFilterObject post_filter set_description post filter by threat assess confidence 0 1 format operator name data post_filter set_method filter_threat_assess_confidence post_filter set_filter data post_filter set_operator operator self add_post_filter post_filter
send a workflow event to rabbitmq,def send_sys_wide_wf_event ctx event_type message None args None additional_context None out_func None _send_event ctx system_wide_workflow event_type message args additional_context out_func
save the current model state to the output netcdf file .,def save self if not self ds isopen msg cannot save output the NetCDF writer is already closed raise IOError msg index self time size self time index self model t self u index self model u_grid self v index self model v_grid self vrt index self model vrt_grid
"create a dummy layout for use in an ' application ' that does n't have a layout specified . when enter is pressed , the application quits .",def create_dummy_layout u n Create a dummy layout for use in an Application that doesn t have a n layout specified When ENTER is pressed the application quits n kb KeyBindings kb add u enter def enter event event app exit control FormattedTextControl HTML u No layout specified Press reverse ENTER reverse to quit key_bindings kb window Window content control height D min 1 return Layout container window focused_element window
only get language directory in the values- * * and values-**- * * * format,def test_getLangDir self self assertEqual localizr getLangDir drawable None self assertEqual localizr getLangDir values hdpi None self assertEqual localizr getLangDir values es es self assertEqual localizr getLangDir values en GB en GB self assertEqual localizr getLangDir values zh rTW zh rTW
filters queryset by the authenticated user,def get_queryset self return self model objects filter subscription__owner self request user distinct
"outputs a randomly generated , undirected , connected graph laplacian with ' n ' nodes .",def random_gl v e laplacian np tril np ones v v temp np where np triu laplacian reshape v v 0 pot_edges temp 0 sz laplacian shape laplacian np zeros v v num_edges np where e len pot_edges e len pot_edges temp np random permutation len pot_edges edge_indices temp 0 num_edges i j ind_to_sub sz pot_edges edge_indices laplacian i j 1 laplacian j i 1 laplacian i i 1 laplacian j j 1 return laplacian
process the erase background event .,def processEraseBackgroundEvent self event pass
performs asynchronous video annotation . progress and results can be retrieved through the ` google.longrunning.operations ` interface . ` operation.metadata ` contains ` annotatevideoprogress ` ( progress ) . ` operation.response ` contains ` annotatevideoresponse ` ( results ) .,def AnnotateVideo self request context context set_code grpc StatusCode UNIMPLEMENTED context set_details Method not implemented raise NotImplementedError Method not implemented
str : the name of the field .,property def name self return self _name
the entry point for the worker thread .,def _thread_main self _LOGGER debug Background thread started quit_ False while True batch self _cloud_logger batch items _get_many self _queue max_items self _max_batch_size max_latency self _max_latency for item in items if item is _WORKER_TERMINATOR quit_ True else batch log_struct item self _safely_commit_batch batch for _ in range len items self _queue task_done if quit_ break _LOGGER debug Background thread exited gracefully
set a key 's value on a protobuf message or dictionary .,def set msg_or_dict key value if not isinstance msg_or_dict collections MutableMapping Message raise TypeError set expected a dict or protobuf message got r format type msg_or_dict basekey subkey _resolve_subkeys key if subkey is not None if isinstance msg_or_dict collections MutableMapping msg_or_dict setdefault basekey set get msg_or_dict basekey subkey value return if isinstance msg_or_dict collections MutableMapping msg_or_dict key value else _set_field_on_message msg_or_dict key value
sends a simple sms message .,app route sms send def send_sms to request args get to if not to return Please provide the number to message in the to query string parameter 400 client rest Client TWILIO_ACCOUNT_SID TWILIO_AUTH_TOKEN rv client messages create to to from_ TWILIO_NUMBER body Hello from Twilio return str rv
handle one request at a time until stopped .,def serve_forever self self stop False while not self stop self handle_request
checks to see if the extracted features for the naive bayes models are saved .,def trained_model_exists return os path exists data model pkl
update the schedule times for all the provided recurrences .,def update_schedule self time None _update_schedule self time time
validates that an active user exists with the given email address .,def clean_email self email self cleaned_data email self users_cache User objects filter email__iexact email is_active True if not len self users_cache raise forms ValidationError User not found for user in self users_cache if user password startswith UNUSABLE_PASSWORD_PREFIX raise forms ValidationError Error password not set This happens because the user account was created with an OpenID or OAuth provider tipically Google Facebook MyOpenID etc Try logging in with your login provider see http freedomsponsors org s user get_view_link return email
adds common options to |option_parser| .,def _AddCommonOptions option_parser build_utils AddDepfileOption option_parser option_parser add_option input path help Path to input file s Either the classes directory or the path to a jar option_parser add_option output path help Path to output final file s to Either the final classes directory or the directory in which to place the instrumented copied jar option_parser add_option stamp help Path to touch when done option_parser add_option coverage file help File to create with coverage metadata option_parser add_option sources list file help File to create with the list of sources
returns an instance from a json file saved by tojsonfile ( ) .,classmethod def FromJsonFile cls json_path with open json_path as input_file return cls FromJsonDict json load input_file
add a thread to the group .,def Add self thread assert thread _thread_group is None thread _thread_group self self _threads append thread
generator for paths within a zip file whose contents have changed .,def IterModifiedSubpaths self path for subpath in self new_metadata IterSubpaths path old_tag self _GetOldTag path subpath new_tag self new_metadata GetTag path subpath if old_tag is not None and old_tag new_tag yield subpath
returns the list of input strings .,def GetStrings self return self _strings
function which adds the directory line item into the kodi navigation menu,def addDirectoryItem name url None isFolder False icon None fanart None li None parameters if li None li xbmcgui ListItem name if icon None li setIconImage icon li setArt thumb icon poster icon if fanart None li setArt fanart fanart landscape fanart li setInfo type Video infoLabels Title name if url None url sys argv 0 urllib urlencode parameters return xbmcplugin addDirectoryItem handle handle url url listitem li isFolder isFolder
wrapper to get a brick connector object .,def _brick_get_connector self protocol driver None execute None use_multipath False device_scan_attempts 3 args kwargs return connector InitiatorConnector factory protocol brick_utils get_root_helper driver driver execute execute use_multipath use_multipath device_scan_attempts device_scan_attempts args kwargs
trims the box with respect to the image provided .,def trim_to_borders self img_shape img_h img_w img_shape 2 self xmin max 0 self xmin self xmax min img_h 1 self xmax self ymin max 0 self ymin self ymax min img_w 1 self ymax return self
return information about the leftmost variable in the string .,staticmethod def _find_next_var raw_str autom_state read_idx 0 sz_raw len raw_str var_name while read_idx sz_raw cur_char raw_str read_idx if autom_state _PreprocessorAutomataState INITIAL_STATE if cur_char autom_state _PreprocessorAutomataState INSIDE_DOUBLE_QUOTES elif cur_char autom_state _PreprocessorAutomataState INSIDE_SINGLE_QUOTES elif cur_char autom_state _PreprocessorAutomataState MET_DOLLAR else pass elif autom_state _PreprocessorAutomataState INSIDE_DOUBLE_QUOTES if cur_char autom_state _PreprocessorAutomataState INITIAL_STATE elif cur_char autom_state _PreprocessorAutomataState MET_DOLLAR_INSIDE_DOUBLE_QUOTES else pass elif autom_state _PreprocessorAutomataState INSIDE_SINGLE_QUOTES if cur_char autom_state _PreprocessorAutomataState INITIAL_STATE else pass elif autom_state _PreprocessorAutomataState MET_DOLLAR if cur_char autom_state _PreprocessorAutomataState INSIDE_DOUBLE_QUOTES elif cur_char autom_state _PreprocessorAutomataState INSIDE_SINGLE_QUOTES elif cur_char pass elif cur_char isspace autom_state _PreprocessorAutomataState INITIAL_STATE else var_name cur_char autom_state _PreprocessorAutomataState READING_VAR_NAME elif autom_state _PreprocessorAutomataState READING_VAR_NAME if cur_char in or cur_char isspace return raw_str read_idx len var_name 1 var_name raw_str read_idx _PreprocessorAutomataState INITIAL_STATE else var_name cur_char elif autom_state _PreprocessorAutomataState MET_DOLLAR_INSIDE_DOUBLE_QUOTES if cur_char autom_state _PreprocessorAutomataState INITIAL_STATE elif cur_char pass elif cur_char isspace autom_state _PreprocessorAutomataState INSIDE_DOUBLE_QUOTES else var_name cur_char autom_state _PreprocessorAutomataState READING_VAR_NAME_INSIDE_DOUBLE_QUOTES elif autom_state _PreprocessorAutomataState READING_VAR_NAME_INSIDE_DOUBLE_QUOTES if cur_char in or cur_char isspace return raw_str read_idx len var_name 1 var_name raw_str read_idx _PreprocessorAutomataState INSIDE_DOUBLE_QUOTES else var_name cur_char read_idx 1 if autom_state _PreprocessorAutomataState READING_VAR_NAME return raw_str read_idx len var_name 1 var_name _PreprocessorAutomataState INITIAL_STATE return None
: description : this function adds a payload to the database .,def setPayload input type waf conn sqlite3 connect db db sqlite c conn cursor if waf is None waf generic list input type waf sql Insert into payload payload type waf VALUES c execute sql list conn commit conn close print Payload inserted successfully
the aggregation type of the current aggregation,property def aggregation_type self return self _aggregation_type
create and instance of this analyse handler .,def __init__ self args kwargs super __init__ args kwargs self projects OrderedDict self nprojects 0
"given a matrix of distances between test points and training points , predict a label for each test point .",def predict_labels self dists k 1 num_test dists shape 0 y_pred np zeros num_test for i in xrange num_test closest_y closest_indices np argsort dists i k closest_y self y_train closest_indices y_pred i np bincount closest_y argmax return y_pred
"same as dict_from_qs , but in reverse i.e. { "" period "" : { "" di "" : { } , "" fhr "" : { } } } = > "" period.di,period.fhr """,def qs_from_dict qsdict prefix prefix prefix if prefix else def descend qsd for key val in sorted qsd items if val yield qs_from_dict val prefix key else yield prefix key return join descend qsdict
split data frame into features and labels .,def get_x_y data_frame attr_labels pos_label None survival True if survival if len attr_labels 2 raise ValueError expected sequence of length two for attr_labels but got d len attr_labels if pos_label is None raise ValueError pos_label needs to be specified if survival True return _get_x_y_survival data_frame attr_labels 0 attr_labels 1 pos_label return _get_x_y_other data_frame attr_labels
runs specified sql query in bigquery .,def run_query client query job_config query_job client query query job_config job_config return query_job result
deletes blobs identified in ' blob_key ' form variables .,def post self super BlobstoreRequestHandler self post redirect_url str self request get return_to blobstore keys self request get_all blob_key blobstore delete keys self redirect redirect_url
registers a set of configuration names .,def register self prefix mapping if not prefix endswith _ prefix _ self _lock acquire try handle self _registrations get prefix if handle is None handle ConfigHandle prefix self self _registrations prefix handle finally self _lock release handle _update_defaults mapping return handle
returns the instance serving this request .,def get_instance self request_id with self _lock return self _request_id_to_instance get request_id None
get the http status code from an http status string .,def _get_status_code self http_status try return int http_status split 1 0 except TypeError logging warning Unable to find status code in HTTP status r http_status return 500
"given a string that looks like a zone name , creates a shorter version .",def ShortenZoneName zone geo coord number letter re findall w w d w zone 0 geo geo lower if len geo 2 else default LOC geo lower coord default LOC coord lower number str number letter letter lower return geo coord number letter
notify the c{iobservers } for a particular c{inotification}.,def notifyObservers self notification observers self observerMap get notification getName for obsvr in observers obsvr notifyObserver notification
get issue details by issue id,def describe self issue_id endpoint v1 issues s issue_id request HttpHelper self session response request get endpoint return response
a method to measure time of execution of a method,def timeExecution method args kwargs start time time result method args kwargs end time time return result end start
compute bounding - box regression targets for an image .,def _compute_targets ex_rois gt_rois assert ex_rois shape 0 gt_rois shape 0 assert ex_rois shape 1 4 assert gt_rois shape 1 5 return bbox_transform ex_rois gt_rois 4 astype np float32 copy False
get the specified report as a csv file .,def get_report_as_csv self report_id download_path alternate_file_name None if not os path isdir download_path raise ValueError download_path must be a directory _op fresh_operation get_report_as_csv _op method GET _op path reports str report_id _op header_params Accept text csv _op dl_path download_path expected DownloadedFile prepped_request self _base prepare_request _op response self _base request prepped_request expected _op if alternate_file_name is not None response filename alternate_file_name response save_to_file return response
ignore everything except the message .,def message_warning msg a kwargs return str msg n
comparison for equality that uses the hash of the object .,def __eq__ self other if not isinstance other self __class__ return False return self __hash__ other __hash__
"results_set is a set of tuples ( locator , filename )",def create_trace_function results_set def trace_function frame event arg Trace any calls to the InputLocator co frame f_code func_name co co_name if func_name write return line_no frame f_lineno filename co co_filename if event call return trace_function elif event return if isinstance arg basestring and inputlocator in filename lower and not func_name startswith _ results_set add func_name arg print s s func_name arg return return trace_function
"sanitize output(remove sensitive information like serial numbers , etc . )",def test_sanitize self out_with_sanitize process system_output lshw sanitize for line in process system_output lshw strip t n r splitlines if serial in line and line in out_with_sanitize self fail Sensitive data is present in output
upgrade the database to a newer revision .,def upgrade op create_table analysis_requests sa Column ecosystem sa Integer nullable True sa Column package sa String length 255 nullable True sa Column version sa String length 255 nullable True sa Column id sa Integer nullable False sa Column job_id sa String length 255 nullable True sa Column submitted_at sa DateTime nullable True sa Column fulfilled_at sa DateTime nullable True sa Column analysis_id sa Integer nullable True sa ForeignKeyConstraint analysis_id analyses id sa PrimaryKeyConstraint id op create_index epv_index analysis_requests ecosystem package version unique True postgresql_where sa text fulfilled_at IS NULL
get a row with specified name .,classmethod def by_name cls session name try return cls _by_attrs session name name except NoResultFound raise
"checks if there is socialfrind model record for the user if not attempt to create one if all fail , redirects to the next page",def get_context_data self kwargs context super FriendListView self get_context_data kwargs friends for friend_list in self social_friend_lists fs friend_list existing_social_friends for f in fs friends append f context friends friends connected_providers for sa in self social_auths connected_providers append sa provider context connected_providers connected_providers return context
return a dict of sleep dataframes . sleep is defined as 5 + consecutive minutes without beam - crossings . the sleep df consists of int arrays where sleep = 1 .,def calculate_sleep activity_dict sleep_dict dict for genotype in activity_dict df activity_dict genotype sleep_dict genotype pd DataFrame index df index channel_length sleep_dict genotype shape 0 for channel in df sleep_dict genotype channel 0 channel_length i 0 while i channel_length if i 4 channel_length and df channel i 4 0 i 5 continue if df channel i 0 i 5 continue if i 4 channel_length and df channel i 1 i 3 sum 0 i 5 continue j 4 while i j 1 channel_length and df channel i j 1 0 j 1 sleep_dict genotype channel i i j 1 i i j 1 return sleep_dict
"acquire the lock , if possible . if the lock is in use , it check again every ` wait ` seconds . it does this until it either gets the lock or exceeds ` timeout ` number of seconds , in which case it throws an exception .",def acquire self start_time time time pid os getpid while True try self fd os open self lockfile os O_CREAT os O_EXCL os O_RDWR os write self fd d pid break except OSError as e if e errno errno EEXIST raise if time time start_time self timeout raise FileLockException Timeout occured time sleep self delay self is_locked True
fetches a list all floating ips .,abc abstractmethod def list self pass
returns the queryset of bucketlists created by the current user .,def get_queryset self return BucketList objects filter created_by self request user
"shift datetime in ` direction ` in _ valid_shift_directions and by some unit in _ valid_shifts and shift that amount by some multiple , defined by by args[0 ] if it exists",def _shift_date self direction unit args this_module sys modules __name__ num_shifts 1 if len args 0 num_shifts int args 0 if unit in monday tuesday wednesday thursday friday saturday sunday shift_func move_datetime_namedday dt shift_func self _dt direction unit if num_shifts 1 for n in range num_shifts 1 dt shift_func dt direction unit else shift_func getattr this_module move_datetime_ s unit dt shift_func self _dt direction num_shifts return Delorean datetime dt replace tzinfo None timezone self _tz
"takes an initial response , and a way to repeat the request that produced it and retries the request with an increasing sleep period between requests if rate limiting resposne codes are encountered .",def check_for_rate_limiting response response_lambda timeout 1 attempts 0 if attempts 3 raise RateLimitingException if response status_code 429 sleep timeout new_timeout timeout 1 new_attempts attempts 1 return check_for_rate_limiting response_lambda timeout attempts response_lambda timeout new_timeout attempts new_attempts return response
computes the rime from the supplied argument .,def rime ant_uvw sources frequencies l m I Q U V sources T lm lm_2_rad l m B brightness I Q U V ntime na _ ant_uvw shape nbl na na 1 2 nsrc _ lm shape nchan frequencies shape print RIME Dimensions print nsrc s nsrc print ntime s ntime print na s na print nbl s nbl print nchan s nchan K_per_ant phase lm ant_uvw frequencies ap_idx ap_index nsrc nsrc ntime ntime na na nchan nchan K_per_bl K_per_ant ap_idx K_p K_q K_per_bl 0 K_per_bl 1 X_pqs K_p np newaxis np newaxis B np newaxis np newaxis np newaxis K_q np newaxis np newaxis assert X_pqs shape nsrc ntime nbl nchan 2 2 V_pq X_pqs sum axis 0 assert V_pq shape ntime nbl nchan 2 2 return V_pq reshape ntime nbl nchan 2 2
this will parse out the text section from the input data . this is the part that the linker will modify in order to build usable code . : param data : byte string : return : bytestring limited to only the data inside the text section,def _extractText self data result sResult re search Text 0 Text data flags re DOTALL result sResult group 0 result result replace Text result result replace Text return result
"given the command - line arguments , this figures out which subcommand is being run , creates a parser appropriate to that command , and runs it .",def execute self u n Given the command line arguments this figures out which subcommand is n being run creates a parser appropriate to that command and runs it n try subcommand self argv 1 except IndexError subcommand u help parser CommandParser None usage u prog s subcommand options args add_help False parser add_argument u settings parser add_argument u pythonpath parser add_argument u args nargs u try options args parser parse_known_args self argv 2 handle_default_options options except CommandError pass no_settings_commands u help u version u help u version u h u compilemessages u makemessages u startapp u startproject try settings INSTALLED_APPS except ImproperlyConfigured as exc self settings_exception exc if subcommand in no_settings_commands settings configure if settings configured if subcommand u runserver and u noreload not in self argv try autoreload check_errors django setup except Exception pass else django setup self autocomplete if subcommand u help if u commands in args sys stdout write self main_help_text commands_only True u n elif len options args 1 sys stdout write self main_help_text u n else self fetch_command options args 0 print_help self prog_name options args 0 elif subcommand u version or self argv 1 u version sys stdout write django get_version u n elif self argv 1 in u help u h sys stdout write self main_help_text u n else self fetch_command subcommand run_from_argv self argv
take in noisy input image and output temporal coefficients for mu and sigma .,application def apply self X Y self mlp_conv apply X Y Y dimshuffle 0 2 3 1 if self n_hidden_dense_lower 0 n_images X shape 0 astype int16 X X reshape n_images self n_colors self spatial_width 2 Y_dense self mlp_dense_lower apply X Y_dense Y_dense reshape n_images self spatial_width self spatial_width self n_hidden_dense_lower_output Y T concatenate Y T sqrt self n_hidden_conv Y_dense T sqrt self n_hidden_dense_lower_output axis 3 Z self mlp_dense_upper apply Y return Z
return a topojson transform dictionary and a point - transforming function .,def get_transform bounds size 1024 tx ty bounds 0 bounds 1 sx sy bounds 2 bounds 0 size bounds 3 bounds 1 size def forward lon lat Transform a longitude and latitude to TopoJSON integer space return int round lon tx sx int round lat ty sy return dict translate tx ty scale sx sy forward
"coerces a dataframe to all floats , and standardizes the values .",def _coerce data return _standardize data apply _coerce_types
: parameters : session : ` mw.api.session ` an api session to use for post & get .,def __init__ self session self session session
test getting all fields for a superuser .,def test_get_field_for_superuser self self user is_superuser True self user save ser self _get_serializer_instance fields ser get_fields self assertIsInstance fields collections OrderedDict self assertEqual set fields user is_expired cards full_name expired_date
store the result of the play,def v2_runner_on_ok self result self result result self raw_result result _result
"> > > merge_sort([3 , 5 , 1 , 2 , 10 , 6 ] ) [ 1 , 2 , 3 , 5 , 6 , 10 ]",def merge_sort array if len array 2 return array mid len array 2 left merge_sort array mid right merge_sort array mid res i j 0 0 while i len left and j len right if left i right j res append left i i 1 else res append right j j 1 if left i res extend left i if right j res extend right j return res
read and clean lines from a .sql file,classmethod def read_sql_str cls filename full_path os path join cls sql_rules_path filename sql with open full_path rU as f return f read
generate_f_rows should find and convert subaward data relevant to a specific submission i d . we 'll compare the resulting duns values for uniqueness,def test_generate_f_rows database monkeypatch sess database session sub_1 SubmissionFactory sub_2 SubmissionFactory sess add_all sub_1 sub_2 sess commit awards AwardProcurementFactory submission_id sub_1 submission_id piid PIID1 parent_award_id PIID1 awarding_sub_tier_agency_c 1234 AwardProcurementFactory submission_id sub_1 submission_id piid PIID2 parent_award_id PIID2 awarding_sub_tier_agency_c 1234 AwardFinancialAssistanceFactory submission_id sub_1 submission_id fain FAIN1 AwardFinancialAssistanceFactory submission_id sub_1 submission_id fain FAIN2 AwardProcurementFactory submission_id sub_2 submission_id piid PIID1 parent_award_id PIID1 awarding_sub_tier_agency_c 1234 AwardFinancialAssistanceFactory submission_id sub_2 submission_id fain FAIN1 sess add_all awards procurements for piid in PIID1 PIID2 PIID3 procurements piid FSRSProcurementFactory contract_number piid idv_reference_number piid subawards FSRSSubcontractFactory for _ in range 3 contracting_office_aid 1234 FSRSProcurementFactory contract_number piid idv_reference_number piid subawards contracting_office_aid 1234 FSRSProcurementFactory contract_number piid idv_reference_number piid subawards FSRSSubcontractFactory for _ in range 2 contracting_office_aid 1234 sess add_all procurements piid grants for fain in FAIN0 FAIN1 grants fain FSRSGrantFactory fain fain subawards FSRSSubgrantFactory for _ in range 3 FSRSGrantFactory fain fain subawards FSRSGrantFactory fain fain subawards FSRSSubgrantFactory for _ in range 2 sess add_all grants fain sess commit actual result SubAwardeeOrRecipientUniqueIdentifier for result in fileF generate_f_rows sub_1 submission_id expected set expected update sub duns for proc in procurements PIID1 for sub in proc subawards expected update sub duns for proc in procurements PIID2 for sub in proc subawards expected update sub duns for grant in grants FAIN1 for sub in grant subawards assert actual expected
parse project file to get mcu definition,def get_mcu_definition self project_file project_file join getcwd project_file ewp_dic xmltodict parse file project_file dict_constructor dict mcu MCU_TEMPLATE try ewp_dic project configuration except KeyError logging debug The project_file s seems to be not valid ewp file return mcu mcu tool_specific iar OGChipSelectEditMenu state OGCoreOrChip state 1 try index_general self _get_option ewp_dic project configuration 0 settings General configuration ewp_dic project configuration 0 except KeyError index_general self _get_option ewp_dic project configuration settings General configuration ewp_dic project configuration index_option self _get_option configuration settings index_general data option OGChipSelectEditMenu OGChipSelectEditMenu configuration settings index_general data option index_option mcu tool_specific iar OGChipSelectEditMenu state append OGChipSelectEditMenu state replace t 1 fileVersion 1 try if self _get_option configuration settings index_general data option FPU2 fileVersion 2 except TypeError pass index_option self _get_option configuration settings index_general data option GBECoreSlave GBECoreSlave configuration settings index_general data option index_option mcu tool_specific iar GBECoreSlave state int GBECoreSlave state if fileVersion 2 index_option self _get_option configuration settings index_general data option GFPUCoreSlave2 GFPUCoreSlave2 configuration settings index_general data option index_option mcu tool_specific iar GFPUCoreSlave2 state int GFPUCoreSlave2 state index_option self _get_option configuration settings index_general data option CoreVariant CoreVariant configuration settings index_general data option index_option mcu tool_specific iar CoreVariant state int CoreVariant state else index_option self _get_option configuration settings index_general data option GFPUCoreSlave GFPUCoreSlave configuration settings index_general data option index_option mcu tool_specific iar GFPUCoreSlave state int GFPUCoreSlave state index_option self _get_option configuration settings index_general data option Variant Variant configuration settings index_general data option index_option mcu tool_specific iar Variant state int Variant state return mcu
tests that the cbsd data setter and getter works .,def test_set_cbsd_record self fad FullActivityDump fad setCbsdRecords 13 14 15 self assertEqual fad getCbsdRecords 13 14 15 self assertDictEqual fad getData cbsd 13 14 15 esc_sensor zone
"return a native python type from the list of compiled nodes . if the result is a single node , its value is returned . otherwise , the nodes are concatenated as strings . if the result can be parsed with : func:`ast.literal_eval ` , the parsed value is returned . otherwise , the string is returned .",def native_concat nodes head list islice nodes 2 if not head return None if len head 1 out head 0 else out u join text_type v for v in chain head nodes try return literal_eval out except ValueError SyntaxError MemoryError return out
one - line classes do n't get a suite in the parse tree so we add one to normalize the tree,def fixup_parse_tree cls_node for node in cls_node children if node type syms suite return for i node in enumerate cls_node children if node type token COLON break else raise ValueError No class suite and no suite Node syms suite while cls_node children i 1 move_node cls_node children i 1 suite append_child move_node clone move_node remove cls_node append_child suite node suite
+ the implementation for this class returns the max_count attribute from the specialized header class that would be used to construct a header of type ' name ' .,def header_max_count self name return self header_factory name max_count
checks for a valid version number ( e.g. ` 3.2 ` or ` 2.7.1 ` or ` 3 ` ) and returns a corresponding version info that is always two characters long in decimal .,def parse_version_string version None if version is None version s s sys version_info 2 if not isinstance version unicode str raise TypeError version must be a string like 3 2 return _parse_version version
load extensions . returns number of extensions loaded .,def load_idlex_extensions self userExt None if userExt is None userExt self IDLEX_EXTENSIONS d idleConf GetUserCfgDir usercfgfile os path join d idlex config extensions cfg if os path isfile usercfgfile U open usercfgfile read else U count 0 userConfParser make_config_parser U key_isdefault idleConf GetOption main Keys default type bool for extName in userExt if self reload_cfg extName count 1 self transfer_cfg extName userConfParser keys not key_isdefault idleConf SaveUserCfgFiles return count
download the file at url to target using powershell .,def download_file_powershell url target target os path abspath target ps_cmd System Net WebRequest DefaultWebProxy Credentials System Net CredentialCache DefaultCredentials new object System Net WebClient DownloadFile url r target r vars cmd powershell Command ps_cmd _clean_check cmd target
gets an appengine operation based on the operation name .,def _get_operation self project_id op_name resource self _gaeadmin apps operations request resource get appsId project_id operationsId op_name return request execute
builds an input blob from the images in the roidb at the specified scales .,def _get_image_blob roidb scale_inds num_images len roidb processed_ims im_scales for i in xrange num_images im cv2 imread roidb i image if roidb i flipped im im 1 target_size cfg TRAIN SCALES scale_inds i im im_scale prep_im_for_blob im cfg PIXEL_MEANS target_size cfg TRAIN MAX_SIZE im_scales append im_scale processed_ims append im blob im_list_to_blob processed_ims return blob im_scales
retrieves the current existing parameters from xbmc .,def get_params param paramstring sys argv 2 if len paramstring 2 params sys argv 2 cleanedparams params replace if params len params 1 params params 0 len params 2 pairsofparams cleanedparams split param for i in range len pairsofparams splitparams splitparams pairsofparams i split if len splitparams 2 param splitparams 0 splitparams 1 return param
"delete a database named ` name ` . blocks until the response returns , and raises an error if the deletion failed .",def __delitem__ self name response self database name self opts delete if hasattr response result response response result response raise_for_status
generate a set of cavariances matrices for test purpose,def generate_cov Nt Ne np random seed 123 diags 1 0 0 1 np random randn Nt Ne covmats np empty Nt Ne Ne for i in range Nt covmats i np diag diags i return covmats
test reading and writing of freesurfer surface mesh files,testing requires_testing_data def test_io_surface tempdir _TempDir fname_quad op join data_path subjects bert surf lh inflated nofix fname_tri op join data_path subjects fsaverage surf lh inflated for fname in fname_quad fname_tri pts tri read_surface fname write_surface op join tempdir tmp pts tri c_pts c_tri read_surface op join tempdir tmp assert_array_equal pts c_pts assert_array_equal tri c_tri
"similar to ` pathway_scores_from_zscores ` , but with different subsetting logic that makes sense with integer variants per gene .",def pathway_scores_from_variants variants_df pathway_df index_field x variants_df join pathway_df dfs dfs append index_converter pd pivot_table x index index_field aggfunc np sum sum_var dfs append index_converter pd pivot_table x index index_field aggfunc np mean mean_var return pd concat dfs
"add a new row to the table . create new combo boxes for the new row . if modellandmark and or inputlandmark are provided , those landmark names will be preselected .",def addLandmark self modelLandmark None inputLandmark None self table setRowCount self _rowCount 1 combMode self _addComboBox self _rowCount 0 self modelLandmarks modelLandmark combInput self _addComboBox self _rowCount 1 self inputLandmarks inputLandmark self _comboBoxes append combMode combInput self _rowCount 1 print row added format self _rowCount
"decorator that does nothing , for date type data field , since we do n't know how to convert different file format 's data string . it leaves to the reader",def identical func return func
@brief start up the dataplane and attach port interfaces @param args the command line arguments,def start_dataplane args logging info Starting dataplane dataplane DataPlane port_idx 1 for port in args interfaces split logging info Adding port s port spec_parts port split if len spec_parts 1 port_num spec_parts 0 port_name spec_parts 1 else port_num port_idx port_name port dataplane port_add port port_num port_idx 1 return dataplane
shutdown sub - command unit test with invalid optional param .,def testShutdown_InvalidOption self with mock patch gce_cluster GceCluster hadoop_cluster compute_cluster_for_hadoop ComputeClusterForHadoop self assertRaises SystemExit hadoop_cluster ParseArgumentsAndExecute shutdown project name image foo
get surface sets : param line : name of the line . all if unspecified : param value : name of the surfaced value . all if unspecified : param time : times for which the surfaces are to be got . all if unspecified,def getData self surface None value None time None if surface None surface self surfaces if value None value list self values if time None time self times sets for t in time for l in surface for v in value try d self t l v sets append d except KeyError pass return sets
adds the new instance to managed cluster by registering ip address .,def post self name self request get name instance ComputeEngineController GetInstanceInfo name if not instance return logging info Instance created s str instance external_ip instance networkInterfaces 0 accessConfigs 0 natIP LoadInfo RegisterInstanceIpAddress name external_ip
the name and shape of label provided by this iterator,property def provide_label self if self rename_label is None return sum i provide_label for i in self iters else return sum DataDesc r x name x shape x dtype if isinstance x DataDesc else DataDesc x for x in i provide_label for r i in zip self rename_label self iters
go through all genbank files and extract sequences and metadata for each one,def extract_sequences path strain_list folders_dict gbk_present enable_RNA_clustering gbk_path folders_dict gbk_path protein_path folders_dict protein_path nucleotide_path folders_dict nucleotide_path RNA_path folders_dict RNA_path geneID_to_geneSeqID_file sgeneID_to_geneSeqID cpk path geneID_to_description_file sgeneID_to_description cpk path RNAID_to_SeqID_file sRNAID_to_SeqID cpk path RNAID_to_description_file sRNAID_to_description cpk path protein_dict_path s s protein_path all_protein_seq cpk nucleotide_dict_path s s nucleotide_path all_nucleotide_seq cpk RNA_dict_path s s RNA_path all_RNA_seq cpk geneID_to_geneSeqID_dict defaultdict geneID_to_description_dict defaultdict RNAID_to_SeqID_dict defaultdict RNAID_to_description_dict defaultdict gene_aa_dict defaultdict dict gene_na_dict defaultdict dict RNA_dict defaultdict dict if gbk_present os system rm rf protein_path faa os system rm rf nucleotide_path fna missing_CDS_list for strainID in strain_list gbk_fname join gbk_path strainID gbk protein_fname join protein_path strainID faa nucleotide_fname join nucleotide_path strainID fna RNA_fname join RNA_path strainID fna check_CDS_passed gbk_translation strainID gbk_fname protein_fname nucleotide_fname RNA_fname geneID_to_geneSeqID_dict geneID_to_description_dict RNAID_to_SeqID_dict RNAID_to_description_dict gene_aa_dict gene_na_dict RNA_dict enable_RNA_clustering if not check_CDS_passed missing_CDS_list append strainID if len missing_CDS_list 0 print Warning no CDS found in the following genome genomes please double check n missing_CDS_list exit else for strainID in strain_list protein_fname join protein_path strainID faa nucleotide_fname join nucleotide_path strainID fna aa_sequence_dt read_fasta protein_fname na_sequence_dt read_fasta nucleotide_fname for geneID in aa_sequence_dt keys geneName annotation geneID_to_geneSeqID_dict geneID geneID geneID_to_description_dict geneID geneName geneName annotation annotation gene_aa_dict strainID geneID aa_sequence_dt geneID gene_na_dict strainID geneID na_sequence_dt geneID write_pickle geneID_to_geneSeqID_file geneID_to_geneSeqID_dict write_pickle geneID_to_description_file geneID_to_description_dict write_pickle protein_dict_path gene_aa_dict write_pickle nucleotide_dict_path gene_na_dict if enable_RNA_clustering write_pickle RNA_dict_path RNA_dict write_pickle RNAID_to_SeqID_file RNAID_to_SeqID_dict write_pickle RNAID_to_description_file RNAID_to_description_dict return gene_aa_dict gene_na_dict
retrieves rpc manager object of firewall agent .,mock patch __name__ fo FakeObjects sc mock patch __name__ fo FakeObjects conf def _get_FWaasRpcManager_object self conf sc agent fw FWaasRpcManager sc conf return agent sc
return core to sibling mapping of the host cpus,def get_host_cpu_siblings siblings conn libvirt openReadOnly qemu system capxml ET fromstring conn getCapabilities cpu_cells capxml findall host topology cells cell cpus for cell in cpu_cells cpus cell findall cpu for cpu in cpus cpu_id int cpu get id sib cpu get siblings _siblings get_siblings_list sib siblings update cpu_id _siblings return siblings
represents the state of the driver .,def is_connected self raise NotImplementedError
creates a signed url given a queue name,def signed_url_create transport request queue_name paths None ttl_seconds None project_id None methods None request operation signed_url_create request params queue_name queue_name body if ttl_seconds is not None expiry timeutils utcnow datetime timedelta seconds ttl_seconds body expires expiry isoformat if project_id is not None body project_id project_id if paths is not None body paths paths if methods is not None body methods methods request content json dumps body resp transport send request return resp deserialized_content
"add a callback so that when the gtk widget emits a signal , we emit signal from the wrapper widget .",def forward_signal self signal_name forwarded_signal_name None if forwarded_signal_name is None forwarded_signal_name signal_name self wrapped_widget_connect signal_name self do_forward_signal forwarded_signal_name
"return the directory where experimental artifacts are placed . if the directory does not exist , it is created .",def get_output_dir imdb net None outdir osp abspath osp join __C ROOT_DIR output __C EXP_DIR imdb name if net is not None outdir osp join outdir net name if not os path exists outdir os makedirs outdir return outdir
implement : py : meth:`pymco.connector . connector.get_target `,def get_target self agent collective return exchange collective _broadcast agent format agent agent collective collective
default validation function which accepts anything .,def accept_all args return True
an internal function used for g0 and g1 moves,def move_common self x None y None z None a None gcode G0 gcodestring xstring ystring zstring astring if x None x self lastx if y None y self lasty if z None z self lastz if a None a self lasta if x self lastx xstring X 4f x self lastx x if y self lasty ystring Y 4f y self lasty y if z self lastz zstring Z 4f z self lastz z if a self lasta astring A 4f a self lasta a if xstring ystring zstring astring return if gcode self lastgcode gcodestring gcode self lastgcode gcode cmd join gcodestring xstring ystring zstring astring if cmd self write cmd
create random walk points and more favor towards center,def random_walk self x random gauss np mean self map_dim 0 0 25 np ptp self map_dim 0 y random gauss np mean self map_dim 1 0 25 np ptp self map_dim 1 return self map_constrain x y
"load ptb raw data from data directory "" data_path "" .",def ptb_raw_data data_path None train_path os path join data_path ptb train txt valid_path os path join data_path ptb valid txt test_path os path join data_path ptb test txt word_to_id _build_vocab train_path train_data _file_to_word_ids train_path word_to_id valid_data _file_to_word_ids valid_path word_to_id test_data _file_to_word_ids test_path word_to_id vocabulary len word_to_id return train_data valid_data test_data vocabulary
returns true if all characters in the string are spaces or letters ; otherwise returns false .,def is_alphaspace string return all any char isspace char isalpha for char in string
anything in the 400 or 500 range should raise an exception .,fudge patch requests get def test_bad_responses fake client soundcloud Client client_id foo client_secret foo for status in range 400 423 with response_status fake status assert_raises HTTPError lambda client get me for status in 500 501 502 503 504 505 with response_status fake status assert_raises HTTPError lambda client get me
search and filter through bills in congress .,pageable def bills self kwargs return self get bills kwargs
transform a vega data list from version 2 to 3 .,def vega2to3 data def keymapping key Map vega data keys from version 2 to 3 The mapping is test expr and field as otherwise the input key is just returned Args key the key to map Returns a new key return dict test expr field as get key key update_transform fcompose map keymap keymapping list return pipe data map update_in keys transform func update_transform default list
forget the ` pyobject ` this ` pyname ` holds,def invalidate self self pyobject set None
table_options : dictionary containing skin.conf options for particluar table all_stats : link to all_stats timespanbinder,def _statsHTMLTable self table_options table_stats table_name NOAA False bgColours zip table_options minvalues table_options maxvalues table_options colours if NOAA is True unit_formatted else obs_type table_options obs_type aggregate_type table_options aggregate_type converter table_stats converter readingBinder getattr table_stats obs_type if aggregate_type in max_ge max_le min_le sum_ge try threshold_value float table_options aggregate_threshold 0 except KeyError syslog syslog syslog LOG_INFO s Problem with aggregate_threshold Should be in the format value units os path basename __file__ return Could not generate table s table_name threshold_units table_options aggregate_threshold 1 try reading getattr readingBinder aggregate_type threshold_value threshold_units except IndexError syslog syslog syslog LOG_INFO s Problem with aggregate_threshold units s os path basename __file__ str threshold_units return Could not generate table s table_name else try reading getattr readingBinder aggregate_type except KeyError syslog syslog syslog LOG_INFO s aggregate_type s not found os path basename __file__ aggregate_type return Could not generate table s table_name unit_type reading converter group_unit_dict reading value_t 2 unit_formatted if units in table_options unit_formatted table_options units elif unit_type count unit_formatted Days elif unit_type in reading formatter unit_label_dict unit_formatted reading formatter unit_label_dict unit_type if unit_type count format_string d else format_string reading formatter unit_format_dict unit_type htmlText table class table htmlText thead htmlText tr htmlText th s th unit_formatted for mon in table_options get monthnames Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec htmlText th s th mon htmlText tr htmlText thead htmlText tbody for year in table_stats years year_number datetime fromtimestamp year timespan 0 year htmlLine 8 tr n if NOAA is True htmlLine 12 s n self _NoaaYear datetime fromtimestamp year timespan 0 table_options else htmlLine 12 td d td n year_number for month in year months if NOAA is True if month timespan 1 table_stats timespan start or month timespan 0 table_stats timespan stop htmlLine td td n else htmlLine self _NoaaCell datetime fromtimestamp month timespan 0 table_options else if unit_type count try value getattr getattr month obs_type aggregate_type threshold_value threshold_units value_t except value 0 count else value converter convert getattr getattr month obs_type aggregate_type value_t htmlLine 12 self _colorCell value 0 format_string bgColours htmlLine 8 tr n htmlText htmlLine htmlText 4 tbody n htmlText table n return htmlText
"set up a faked session , and add a faked cpc in classic mode , and add two faked activation profiles of each type .",def setup_method self self session FakedSession fake host fake hmc 2 13 1 1 8 self client Client self session self faked_cpc self session hmc cpcs add object id fake cpc1 oid parent None class cpc name fake cpc1 name description CPC 1 classic mode status active dpm enabled False is ensemble member False iml mode lpar self cpc self client cpcs find name fake cpc1 name self faked_reset_ap_1 self faked_cpc reset_activation_profiles add name rap_1 parent self faked_cpc uri class reset activation profile description RAP 1 self faked_reset_ap_2 self faked_cpc reset_activation_profiles add name rap_2 parent self faked_cpc uri class reset activation profile description RAP 2 self faked_image_ap_1 self faked_cpc image_activation_profiles add name iap_1 parent self faked_cpc uri class image activation profile description IAP 1 self faked_image_ap_2 self faked_cpc image_activation_profiles add name iap_2 parent self faked_cpc uri class image activation profile description IAP 2 self faked_load_ap_1 self faked_cpc load_activation_profiles add name lap_1 parent self faked_cpc uri class load activation profile description LAP 1 self faked_load_ap_2 self faked_cpc load_activation_profiles add name lap_2 parent self faked_cpc uri class load activation profile description LAP 2
a helper to squash notes and items .,def _finalize_changelog changelog dct_versions dict result list process_note_line lambda text text if text else n for version in changelog for section in version sections section items join item strip for item in section items section notes join process_note_line note for note in section notes strip version sections section for section in version sections if section notes or section items version_data dct_versions get version version if version_data version_data sections extend version sections else dct_versions version version version result append version return result
"construct unique batch name indicating date , workflow , and build , as well as any group or subgroup identifier tags .",def _build_batch_name self workflow_id os path splitext os path basename self workflow_template 0 logger debug creating batch name from workflow ID group tag subgroup tags date tag and strandedness format workflow_id self group_tag self subgroup_tags self date_tag self strand_tag batch_inputs _ join self group_tag _ join self subgroup_tags rstrip _ return _ _ _ _ format self date_tag batch_inputs workflow_id self build self strand_tag
"when the stat file did not change between calls , the c{_get_cpu_usage } method returns none .",def test_get_cpu_usage_file_not_changed self contents1 cpu 100 100 100 100 100 100 100 0 0 0 thefile self _write_stat_file contents1 plugin CPUUsage create_time self reactor time self monitor add plugin result plugin _get_cpu_usage stat_file thefile self assertIs None result result plugin _get_cpu_usage stat_file thefile self assertIs None result
c{get_process_info } reads the process state from the status file and uses the first character to represent the process state .,def test_get_process_info_state self self _add_process_info 12 state A some state process_info ProcessInformation self proc_dir info process_info get_process_info 12 self assertEqual A info state
the link speed for an unplugged interface is reported as 0 .,patch struct unpack patch fcntl ioctl def test_unplugged self mock_ioctl mock_unpack sock socket socket socket AF_INET socket SOCK_DGRAM socket IPPROTO_IP mock_unpack return_value 65535 False result get_network_interface_speed sock eth0 mock_ioctl assert_called_with ANY ANY ANY mock_unpack assert_called_with 12xHB28x ANY self assertEqual 0 False result
recursively build commands from scan arguments @param log : devices to log so far while going down the argument list @param args : remaining scan arguments @return list of commands,def _decodeScan self log args if len args 0 if len log 0 return cleaned_log for device in log if device not in cleaned_log cleaned_log append device return LogCommand cleaned_log arg args pop 0 if isinstance arg str log append arg return self _decodeScan log args elif isinstance arg tuple scan self _decodeLoop arg log append scan 0 return LoopCommand scan 0 scan 1 scan 2 scan 3 self _decodeScan log args elif isinstance arg ScanCommand if isinstance arg SetCommand log append arg getDeviceName cmds arg cmds extend self _decodeScan log args return cmds else raise Exception Cannot handle scan parameter of type s arg __class__ __name__
override the _ get_choices method to use mpttmodelchoiceiterator .,def _get_choices self return MPTTModelChoiceIterator self
open giswater.jar with last opened .gsw file,def open_giswater self if nt in sys builtin_module_names self execute_giswater ed_giswater_jar else self controller show_info Function not supported in this Operating System
create a meta object by passing in the meta dict .,def __init__ self user_xid message code time self user_xid user_xid self message message self code code self time datetime datetime fromtimestamp time
detects if a file has hidden attributes,def has_hidden_attribute file_path try attrs ctypes windll kernel32 GetFileAttributesW unicode file_path assert attrs 1 result bool attrs 2 except AttributeError AssertionError result False return result
parses xml file expected to follow junit / gtest conventions see http://code.google.com/p/googletest/wiki/advancedguide#generating_an_xml_report,def read_junit filename tree ElementTree root tree parse filename num_tests int root attrib tests num_errors int root attrib errors num_failures int root attrib failures return num_tests num_errors num_failures
get list of tweet entities of desired type,def get_entities_of_type self type return self data get entities get type
true if shortcuts should be shown at startup ; default true .,def _show_shortcuts_at_startup return 1 QSettings value _KEY 1
"fetch data from a given url . if the url starts with https:// , ca_certs can be a path to pem file with ca certificate chain to validate server certificate .",def fetch_data url out_file ca_certs None out_dir os path dirname out_file utils ensure_dir_exists out_dir if can_fetch_from url _curl_fetch url out_file ca_certs else msg Cannot fetch data from s unknown URL format url raise UnknownURLformatError msg
changes the location of the player,def move self x y tiles if x 0 new_x self x x if not tiles self y new_x in WALL DOOR self x new_x if y 0 new_y self y y if not tiles new_y self x in WALL DOOR self y new_y
returns the index of the subtree this pedestrian is in .,def get_subtree_index self pedestrian x_index 0 y_index 0 if pedestrian position 0 self xmin 0 5 self length x_index 1 if pedestrian position 1 self ymin 0 5 self length y_index 1 return x_index 2 y_index
writes the data out to a file,def saveMatrixToCVSDict data csvfile fieldNames csvWriter csv DictWriter csvfile fieldNames dialect excel headers dict n n for n in fieldNames csvWriter writerow headers for row in data d dict str k str v for k v in zip fieldNames row csvWriter writerow d
set the property for the given key,def setProperty self key value if type key is str and type value is str self processPair key value else raise TypeError both key and value should be strings
adapt position or height to other skin resolution .,def ScaleY y return ScaleGeneral str y settings base_resolution 1 settings out_resolution 1
patched patch method to enforce jsonapi format .,def patch self path data None kwargs return super patch path path data self _parse_data data content_type self _content_type kwargs
"user is visiting a saved , shared link to rivescript code .",controllers route s uuid def saved_code uuid if re match A Za z0 9 uuid return error Improperly formatted UUID snippet db_session query Snippet get uuid if snippet is None return error The RiveScript snippet you re looking for was not found It may have been deleted otherwise double check the URL snippet accessed datetime datetime utcnow db_session add snippet db_session commit sharing request cookies get sharing false true resp make_response render_template index html source snippet source sharing sharing url request url resp set_cookie sharing expires 0 return resp
rename new dir over a file,def subtest_10 ctx d ctx non_empty_dir new ctx termslash f ctx non_empty_dir a ctx termslash ctx mkdir d 493 ctx open_file d a wo 1 crt 1 write aaaa ctx rename d f err ENOTDIR ctx open_dir d ro 1 ctx open_file d a ro 1 read aaaa
"copies source_item to dest_item , overwriting if allowed",def copy self source_item dest_item overwrite False if os path exists dest_item and overwrite try if os path isdir dest_item and not os path islink dest_item shutil rmtree dest_item else os unlink dest_item except OSError as err raise ProcessorError Can t remove s s dest_item err strerror try if os path isdir source_item shutil copytree source_item dest_item symlinks True elif not os path isdir dest_item shutil copyfile source_item dest_item else shutil copy source_item dest_item self output Copied s to s source_item dest_item except BaseException as err raise ProcessorError Can t copy s to s s source_item dest_item err
sends the provided command and optionally ( default ) confirms an ack response .,def _send_instruction self command confirm_ack True self _send_data command if confirm_ack self confirm_ack
tpm column index : transrate uses older salmon ; use index = 2 . newer salmon : index=3,def filter_task assembly_path assembly_name out_dir quant_file_list tpm_threshold tpm_column_index tasks log_flag True opc None trgs 0 s 1 s _ 2 s tpm fasta format out_dir assembly_name tpm_threshold quants join quant_files x for x in quant_file_list cmd python 0 s filter_contigs_by_tpm py assembly 1 s tpm 2 s 3 s out 4 s tpm_column_index 5 s format statics PATH_UTIL assembly_path tpm_threshold quants trgs 0 tpm_column_index name filt_ 0 s _ 1 s tpm format assembly_name tpm_threshold out err os devnull os devnull return Task command cmd dependencies tasks targets trgs name name stdout out stderr err
a wrapper over : meth:`~.find ` that gets a single row with a single field look up .,def get self db table fields value data self find db table fields str value if data data data 0 return data
a decorator that defines _ _ unicode _ _ and _ _ str _ _ methods under python 2 . under python 3 it does nothing .,def python_2_unicode_compatible klass if six PY2 if __str__ not in klass __dict__ raise ValueError python_2_unicode_compatible cannot be applied to s because it doesn t define __str__ klass __name__ klass __unicode__ klass __str__ klass __str__ lambda self self __unicode__ encode utf 8 return klass
fasta to relaxed phylip format .,def __init__ inputfile outputfile AlignIO convert inputfile fasta outputfile phylip relaxed
resize an image such that the size is constrained to min_side and max_side .,def resize_image img min_side 800 max_side 1333 rows cols _ img shape smallest_side min rows cols scale min_side smallest_side largest_side max rows cols if largest_side scale max_side scale max_side largest_side img cv2 resize img None fx scale fy scale return img scale
this function counts the ngrams in tokens ( a list of things ) for each order between 1 and max_order,def ngrams tokens max_order ngram_maps l len tokens for i in xrange l for d in xrange 1 max_order 1 ngram_map ngram_maps d j i d if not j l key glue_tokens tokens i j ngram_map key 1 return ngram_maps
convert raw input value of the field .,def _converter self value if not isinstance value datetime date raise TypeError 0 is not valid date format value return value
sets the search algorithm to use .,def search self search javabridge call self jobject setSearch Lweka attributeSelection ASSearch V search jobject
a property you * must * match is probably better than one you have to match a part of .,def test_oneOf_and_anyOf_are_weak_matches self validator Draft4Validator minProperties 2 anyOf type string type number oneOf type string type number best self best_match validator iter_errors self assertEqual best validator minProperties
target database must support parenthesized select in union when offset / limit is specifically not present .,property def parens_in_union_contained_select_wo_limit_offset self return exclusions closed
creates a container image from a list of partial images .,def assemble_image output images manifest tar archive TarFileWriter output for image in images tar add_tar image name_filter _image_filter manifest GetManifestFromTar image manifest_content json dumps manifest sort_keys True tar add_file manifest json content manifest_content
@brief stop image ( do nothing actually .. ),def StopImage self pass
initialize openbabel - specific variables .,def __init__ self args kwargs super EB_OpenBabel self __init__ args kwargs self with_python False
custom sanity check for arb .,def sanity_check_step self custom_paths files os path join self subdir bin arb dirs os path join self subdir x for x in lib super EB_ARB self sanity_check_step custom_paths custom_paths
use mock to test createfshare with protocol first .,def test_createfshare_mock self self assertRaises TypeError self cl createfshare self cl createfshare nfs testvfs testfshare self cl ssh run assert_called_with createfshare nfs f testvfs testfshare multi_line_stripper True self cl createfshare smb testvfs testfshare self cl ssh run assert_called_with createfshare smb f testvfs testfshare multi_line_stripper True self cl createfshare nfs testvfs testfstore fpg testfpg fstore testfstore sharedir testsharedir comment test comment self cl ssh run assert_called_with self ArgMatcher self assertEqual createfshare nfs f fpg testfpg fstore testfstore sharedir testsharedir comment test comment testvfs testfstore multi_line_stripper True
reads a 32bit integer from the buffer .,def read_int32 buf offset return 4 unpack I buf offset offset 4 0
"takes the specified items from collection c , creating a new collection : param c : the collection to take the items from : param items : the items to take : return : the new collection",def take c items if isinstance c tuple return tuple c i for i in items elif isinstance c list return c i for i in items elif isinstance c dict return i c i for i in items
renders 3d bounding boxes from the given list on the current image .,def _render_3d_boxes self iml mapping gt False filename self file_list self cursor if filename in iml if self pgps is not None and filename in self pgps pgp self pgps filename self ax2 plot pgp C_3x1 0 0 pgp C_3x1 0 0 10 150 color CCCCCC linewidth 4 for bb in iml filename if mapping bb label in CATEGORIES and gt or bb confidence self confidence id CATEGORIES index mapping bb label color ffd633 if gt else COLORS id if self pgps is not None if filename in self pgps pgp self pgps filename X_3x8 pgp reconstruct_bb3d bb self ax2 plot X_3x8 0 0 X_3x8 0 1 X_3x8 2 0 X_3x8 2 1 color 00FF00 linewidth 2 self ax2 plot X_3x8 0 0 X_3x8 0 3 X_3x8 2 0 X_3x8 2 3 color color linewidth 2 self ax2 plot X_3x8 0 1 X_3x8 0 2 X_3x8 2 1 X_3x8 2 2 color color linewidth 2 self ax2 plot X_3x8 0 2 X_3x8 0 3 X_3x8 2 2 X_3x8 2 3 color FF0000 linewidth 2 x_2x8 pgp project_X_to_x X_3x8 self ax1 plot x_2x8 0 4 x_2x8 0 5 x_2x8 1 4 x_2x8 1 5 color g linewidth 2 self ax1 plot x_2x8 0 5 x_2x8 0 1 x_2x8 1 5 x_2x8 1 1 color g linewidth 2 self ax1 plot x_2x8 0 0 x_2x8 0 1 x_2x8 1 0 x_2x8 1 1 color g linewidth 2 self ax1 plot x_2x8 0 0 x_2x8 0 4 x_2x8 1 0 x_2x8 1 4 color g linewidth 2 self ax1 plot x_2x8 0 2 x_2x8 0 3 x_2x8 1 2 x_2x8 1 3 color r linewidth 2 self ax1 plot x_2x8 0 7 x_2x8 0 3 x_2x8 1 7 x_2x8 1 3 color r linewidth 2 self ax1 plot x_2x8 0 7 x_2x8 0 6 x_2x8 1 7 x_2x8 1 6 color r linewidth 2 self ax1 plot x_2x8 0 6 x_2x8 0 2 x_2x8 1 6 x_2x8 1 2 color r linewidth 2 self ax1 plot x_2x8 0 4 x_2x8 0 7 x_2x8 1 4 x_2x8 1 7 color color linewidth 2 self ax1 plot x_2x8 0 5 x_2x8 0 6 x_2x8 1 5 x_2x8 1 6 color color linewidth 2 self ax1 plot x_2x8 0 1 x_2x8 0 2 x_2x8 1 1 x_2x8 1 2 color color linewidth 2 self ax1 plot x_2x8 0 0 x_2x8 0 3 x_2x8 1 0 x_2x8 1 3 color color linewidth 2 else print WARNING PGP entry not found for image filename else self ax1 plot bb fblx bb fbrx bb fbly bb fbry color g linewidth 2 self ax1 plot bb fblx bb fblx bb fbly bb ftly color g linewidth 2 self ax1 plot bb fblx bb rblx bb fbly bb rbly color color linewidth 2 txt mapping bb label if gt else mapping bb label 3f bb confidence self ax1 text bb fblx bb ftly 5 txt fontsize 15 color color
initialize a ` linearoperatorcomposition ` .,def __init__ self operators is_non_singular None is_self_adjoint None is_positive_definite None name None check_ops assert_proper_iterable operators operators list operators if not operators raise ValueError Expected a non empty list of operators Found s operators self _operators operators dtype operators 0 dtype for operator in operators if operator dtype dtype name_type str o name o dtype for o in operators raise TypeError Expected all operators to have the same dtype Found s join name_type if all operator is_non_singular for operator in operators if is_non_singular is False raise ValueError The composition of non singular operators is always non singular is_non_singular True graph_parents for operator in operators graph_parents extend operator graph_parents if name is None name _o_ join operator name for operator in operators with ops name_scope name values graph_parents super LinearOperatorComposition self __init__ dtype dtype graph_parents graph_parents is_non_singular is_non_singular is_self_adjoint is_self_adjoint is_positive_definite is_positive_definite name name
return the cargo of the tree,def getCargo self return self cargo
should not set a signal for sigusr1 when not available,mock patch twitter_monitor basic_stream signal new_callable FakeSignal mock patch twitter_monitor basic_stream logger def test_set_debug_listener self loggerMock signal stream mock Mock self assertFalse signal signal called self assertFalse loggerMock warn called basic_stream set_debug_listener stream self assertFalse signal signal called self assertTrue loggerMock warn called
dump articles list into mongo .,def dump_articles self if self articles client MongoClient db client nytimes collection db gen_articles collection insert_many self articles client close self articles
"{ "" title "" = "" turn 5 off "" , "" desc "" = "" turn 5 off "" , "" group "" = "" outlet 5 "" }",def local_action_Turn5Off arg None print Action Turn5Off requested set_status 5 OFF
reads cites appendices directly from web pages .,def from_html self url http www cites org eng app appendices php logging info Downloading CITES appendix webpage CITES_url urllib2 urlopen url html CITES_url read logging debug Parsing the CITES html page CITES_page BeautifulSoup html logging debug Parsing the CITES appendix footnotes CITES_notes fntable CITES_page findAll table border 2 rows fntable 0 findAll tr for tr in rows notes tr findAll td CITES_notes self clean_cell notes 0 self clean_cell notes 1 self date self clean_cell CITES_page b find strong trs CITES_page findAll tr class c10 for tr in trs tds tr findAll td if len tds 4 for i in range 1 4 text self clean_cell tds i if re match w text words for word in text if re match word break else words append word taxon join words taxon re sub d taxon taxon re sub s taxon logging debug CITES appendix d taxon s i taxon notes refs self clean_cell note for note in tds i findAll a for ref in refs if ref continue notes ref CITES_notes ref self taxa append Taxon name taxon description self clean_cell tds i appendix i footnotes notes
"if no c{message } argument is passed to the l{error } constructor and the c{code } argument is a valid http status code , c{code } is mapped to a descriptive string to which c{message } is assigned .",def test_noMessageValidStatus self e error Error 200 self assertEqual e message OK
c{reactor.suggestthreadpoolsize ( ) } sets the maximum size of the reactor threadpool .,def test_suggestThreadPoolSize self reactor self buildReactor reactor suggestThreadPoolSize 17 pool reactor getThreadPool self assertEqual pool max 17
"if a system platform name is supplied to l{platform } 's initializer , it is used to determine the result of l{platform.islinux } , which returns c{true } for values beginning with c{""linux "" } , c{false } otherwise .",def test_isLinux self self assertFalse Platform None darwin isLinux self assertTrue Platform None linux isLinux self assertTrue Platform None linux2 isLinux self assertTrue Platform None linux3 isLinux self assertFalse Platform None win32 isLinux
l{ireactorudp.listenudp } returns an object providing l{ilisteningport}.,def test_interface self reactor self buildReactor port reactor listenUDP 0 DatagramProtocol self assertTrue verifyObject IListeningPort port
try to rebuild a new style class with slots defined : this should fail .,def test_errorSlots self classDefinition class SlottedClass object __slots__ a exec classDefinition in self m __dict__ inst self m SlottedClass inst a 7 exec classDefinition in self m __dict__ self assertRaises rebuild RebuildError rebuild updateInstance inst
"ctrl+l is generally used as a redraw - screen command in terminal applications . manhole does n't currently respect this usage of it , but it should at least do something reasonable in response to this event ( rather than , say , eating your face ) .",def testControlL self self _testwrite n1 1 helloWorld self wfd self recvlineClient expect 1 yield helloWorld helloWorld getResult self _assertBuffer 1 1 self _testwrite manhole CTRL_L 1 redrew self wfd self recvlineClient expect 1 1 1 yield redrew redrew getResult self _assertBuffer 1 1 1
updates tenant_id to tenant_name mapping information .,def update_tenant_mapping context networks tenant_id tenant_name dbi add_or_update_tenant context session tenant_id tenant_name tenant_ids net tenant_id True for net in networks if tenant_id in tenant_ids tenant_ids tenant_id False unknown_ids _get_unknown_ids_from_dict tenant_ids if unknown_ids db_tenants dbi get_tenants context session tenant_ids unknown_ids for tenant in db_tenants tenant_ids tenant tenant_id False if _get_unknown_ids_from_dict tenant_ids sync_tenants_from_keystone context
return a string representing the formatted value,classmethod def serialize cls value raise NotImplementedError
write the ring out to a tmp file,def _write_ring self response ring_type tmp dirname pathjoin self swiftdir ring_type fd tmppath mkstemp dir tmp suffix tmp try with os fdopen fd wb as fdo while True chunk response read 4096 if not chunk break fdo write chunk fdo flush os fsync fdo except Exception if tmppath os unlink tmppath raise return tmppath
check to see if a system is a discrete time system,def isdtime sys strict False if isinstance sys int float complex np number return True if not strict else False if isinstance sys LTI return sys isdtime strict return False
run the experiment for num_queries queries .,def run self outcomes click_counts for method_id in self methods outcomes method_id click_counts method_id for _ in range self num_queries for method_id method in self methods items better_ranker worse_ranker self rankers method ranker method ranker_args better_ranker init_ranking list self better worse_ranker init_ranking list self worse l a method instance interleave worse_ranker better_ranker None self length clicks self um get_clicks l self labels better_ranker init_ranking list self better worse_ranker init_ranking list self worse o method instance infer_outcome l a clicks None outcomes method_id append float o click_counts method_id append clicks tolist count 1 yaml dump outcomes outcomes click_counts click_counts self log_fh default_flow_style False for method_id method in self methods items o mean outcomes method_id if o 0 print nUnexpected outcome o print method
set the value(s ) for a single cell or a cell range . this can be used when it is not known if ' cell_ref ' refers to a single cell or a range,def set_cells self sheet cell_ref value self __validate_sheet_name sheet self __validate_cell_ref cell_ref if self __is_single_cell cell_ref self set_cell sheet cell_ref value else self set_cell_range sheet cell_ref value
extract the labels into a 1d uint8 numpy array [ index ] .,def extract_labels filename one_hot False print Extracting filename with gzip open filename as bytestream magic _read32 bytestream if magic 2049 raise ValueError Invalid magic number d in MNIST label file s magic filename num_items _read32 bytestream buf bytestream read num_items labels numpy frombuffer buf dtype numpy uint8 if one_hot return dense_to_one_hot labels return labels
"creates a user with the given username , populating info with web scraper .",def create_user username first_name last_name major year try user_obj User objects create username username except IntegrityError raise CreateUserError Username already taken except ValueError raise CreateUserError Invalid username try user_obj email username wpi edu user_obj first_name first_name user_obj last_name last_name password User objects make_random_password user_obj set_password password user_info_obj UserInfo objects create user user_obj user_info_obj major major user_info_obj graduationYear year user_obj save user_info_obj save if not settings DEBUG send_mail_to_new_user user_obj username user_obj email password except ValueError ValidationError if user_obj user_obj delete raise CreateUserError Invalid name major or year
target dialect supports representation of python datetime.time ( ) with microsecond objects .,property def time_microseconds self return exclusions closed
create an authorization function based on a collection filter .,def filter_as_authorization model filter if isinstance model str unicode model model split model get_model model 0 model 1 def filter_as_authorization_fun request obj return filter request model objects all filter id obj id exists filter_as_authorization_fun __doc__ Only allow access to objects in the filter s filter __doc__ if filter __doc__ else filter __name__ return filter_as_authorization_fun
"as with ` single_char_or_unicode ` , but "" tab "" and "" space "" are also supported . ( directive option conversion function . )",def single_char_or_whitespace_or_unicode argument if argument tab char t elif argument space char else char single_char_or_unicode argument return char
string representation of the self ( echorequest ) .,def __str__ self return EchoHeader __str__ self self payload
"resets breakout , returns initial frames",def reset self self framebuffer np zeros_like self framebuffer self update_buffer self env reset return self framebuffer
test if server does n't respond on a request with an invalid crc .,def test_no_response_for_request_with_invalid_crc rtu_server pdu rtu read_coils 1 9 2 adu struct pack B 1 pdu struct pack BB 0 0 rtu_server serial_port write adu with pytest raises CRCError rtu_server serve_once
return accepted extensions for this loader,staticmethod def extensions return bmp jpg jpeg lbm pcx png pnm tga tiff webp xcf xpm xv
start the steam selector window .,def start self locations bk SteamLocator locate_steam for user_id loc in locations self listbox_selector insert tk END loc self listbox_selector autowidth 250 self root mainloop
update lists created from base lists,def update_derived_lists infopath GFW VESSEL_INFO CONSOLIDATED_LISTS csv path GFW FISHING_MMSI KNOWN print Updating path with open os path join asset_dir infopath as fin with open os path join asset_dir path ALL_YEARS txt w as fout reader csv DictReader fin for row in reader if row label in fishing_classes mmsi row mmsi strip fout write mmsi n infopath GFW VESSEL_INFO CONSOLIDATED_LISTS csv path GFW NONFISHING_MMSI KNOWN print Updating path with open os path join asset_dir infopath as fin with open os path join asset_dir path ALL_YEARS txt w as fout reader csv DictReader fin for row in reader if row label in non_fishing_classes mmsi row mmsi strip fout write mmsi n path GFW FISHING_MMSI KNOWN_AND_LIKELY print Updating path any_year set for date_range in default_date_ranges start_date end_date date_range year end_date 4 print year combined build_combined_fishing_list asset_dir year any_year set combined dest_path os path join asset_dir path txt format year with open dest_path w as dest for mmsi in combined dest write mmsi n dest_path os path join asset_dir path ANY_YEAR txt with open dest_path w as dest for mmsi in sorted any_year dest write mmsi n path GFW FISHING_MMSI SUSPECTED ANY_YEAR txt print Updating path joint set any_year with open os path join asset_dir GFW VESSEL_INFO VESSEL_LISTS ALL_YEARS csv as fin with open os path join asset_dir path w as fout reader csv DictReader fin for row in reader label row inferred if label in fishing_classes mmsi row mmsi strip joint add mmsi fout write mmsi n else assert label in non_fishing_classes not in non fishing format label path GFW FISHING_MMSI KNOWN_LIKELY_AND_SUSPECTED ANY_YEAR txt print Updating path any_year set with open os path join asset_dir path w as fout for mmsi in sorted joint fout write str mmsi n
function that return the i d of the last image on the proyect,def get_last_id self last_line 0 infile open os environ LS_PROJECT_PATH pics ls r for line in infile last_line 1 infile close return last_id last_line
"returns annotation alias , label , and aggregate function turned into a cypher key format",property def alias self return key_for_cypher _ _ format self annotation alias self label self aggregate function
"returns ( pixels , width , height , bpp )",def _pixel_data image if PIL in str type image pixels image tobytes width height image size elif numpy ndarray in str type image if uint8 str image dtype image image astype uint8 try pixels image tobytes except AttributeError pixels image tostring height width image shape 2 else pixels width height image if 0 len pixels width height raise PyLibDMTXError Inconsistent dimensions image data of 0 bytes is not divisible by width x height 1 format len pixels width height bpp 8 len pixels width height if bpp not in _PACK_ORDER raise PyLibDMTXError Unsupported bits per pixel 0 Should be one of 1 format bpp sorted _PACK_ORDER keys return pixels width height bpp
returns `` unachieved `` for a given tracked_id . see : ref:``achievement ``,def unachieved self tracked_id achievement achievement self achievement_for_id tracked_id achievement return achievement unachieved
here we assume that the macrosize is the same for each particle,def analyzeBunch self bunch comm bunch getMPIComm self _cleanPhaseHist self x_avg 0 0 self y_avg 0 0 self phase_avg 0 0 self phase_max 0 0 self synch_pahse 0 0 self fourier_amp 0 0 self fourier_phase 0 0 self amp 0 0 nPartsGlobal bunch getSizeGlobal if nPartsGlobal 0 return x_avg 0 0 y_avg 0 0 phase_avg 0 0 beta bunch getSyncParticle beta z_to_phase 360 0 self frequency speed_of_light beta synch_phase 360 0 bunch getSyncParticle time self frequency self synch_pahse phaseNearTargetPhaseDeg synch_phase 0 0 nParts bunch getSize for ind in range nParts x_avg bunch x ind y_avg bunch y ind phase_avg z_to_phase bunch z ind x_avg y_avg phase_avg orbit_mpi MPI_Allreduce x_avg y_avg phase_avg mpi_datatype MPI_DOUBLE mpi_op MPI_SUM comm x_avg nPartsGlobal y_avg nPartsGlobal phase_avg nPartsGlobal phase2_avg 0 0 for ind in range nParts phase2_avg z_to_phase bunch z ind phase_avg 2 phase2_avg nPartsGlobal self rms_phase math sqrt phase2_avg self x_avg x_avg self y_avg y_avg phase_avg synch_phase self phase_avg phaseNearTargetPhaseDeg phase_avg 0 0 nHistP len self phase_hist_arr for ind in range nParts phase_ind int 180 0 phaseNearTargetPhaseDeg z_to_phase bunch z ind 0 0 self phase_step phase_ind phase_ind nHistP if phase_ind 0 phase_ind 0 if phase_ind nHistP phase_ind nHistP 1 self phase_hist_arr phase_ind 1 0 phase_hist_arr orbit_mpi MPI_Allreduce self phase_hist_arr mpi_datatype MPI_DOUBLE mpi_op MPI_SUM comm phase_hist_arr list phase_hist_arr total_sum 0 0 ind_max 1 max_val 0 for ind in range nHistP val phase_hist_arr ind if val max_val ind_max ind max_val val self phase_hist_arr ind val total_sum val self phase_max ind_max 0 5 self phase_step self phase_max 180 0 self phase_max synch_phase self phase_max phaseNearTargetPhaseDeg self phase_max 0 0 sin_sum 0 0 cos_sum 0 0 grad_to_rad_coeff math pi 180 0 phase_step self phase_step grad_to_rad_coeff n_local_coeff 1 0 total_sum phase_step for ind in range nHistP phase_hist_arr ind n_local_coeff for ind in range nHistP self phase_hist_arr ind phase_hist_arr ind for ind in range nHistP val phase_hist_arr ind phase ind 0 5 self phase_step grad_to_rad_coeff sin_sum val math sin phase cos_sum val math cos phase sin_sum self phase_step grad_to_rad_coeff cos_sum self phase_step grad_to_rad_coeff self fourier_amp math sqrt sin_sum 2 cos_sum 2 math pi self amp self norm_coeff self fourier_amp self fourier_phase math atan2 cos_sum sin_sum 180 0 math pi 90 0 self fourier_phase synch_phase self fourier_phase phaseNearTargetPhaseDeg self fourier_phase 0 0
"fir bandpass filter length estimator . freq1 and freq2 are normalized to the sampling frequency . delta_p is the passband deviation ( ripple ) , delta_s is the stopband deviation ( ripple ) .",def bporder freq1 freq2 delta_p delta_s df abs freq2 freq1 ddp math log10 delta_p dds math log10 delta_s a1 0 01201 a2 0 09664 a3 0 51325 a4 0 00203 a5 0 57054 a6 0 44314 t1 a1 ddp ddp t2 a2 ddp t3 a4 ddp ddp t4 a5 ddp cinf dds t1 t2 a3 t3 t4 a6 ginf 14 6 math log10 delta_p delta_s 16 9 n cinf df ginf df 1 return n
check if a user has a custom system role assigned . ` role_id ` is i d of a ` customsysrole ` instance .,def is_sys_role self role_id role UserSystemRole query filter_by user self role_id role_id first return bool role
remove all listeners connected to event_name .,def remove_all_listeners self event_name if event_name is None raise ValueError self emitter remove_all_listeners event_name
returns a transformed androidmanifest.xml for use with _ incremental apks .,def _ProcessManifest main_manifest disable_isolated_processes if disable_isolated_processes main_manifest main_manifest replace isolatedProcess true isolatedProcess false doc ElementTree fromstring main_manifest app_node doc find application if app_node is None app_node ElementTree SubElement doc application real_app_class app_node get _AddNamespace name _DEFAULT_APPLICATION_CLASS app_node set _AddNamespace name _INCREMENTAL_APP_NAME meta_data_node ElementTree SubElement app_node meta data meta_data_node set _AddNamespace name _META_DATA_NAME meta_data_node set _AddNamespace value real_app_class return ElementTree tostring doc encoding UTF 8
adds localized message strings to each item in a list of policies and groups . also breaks up the content of ' supported_on ' attributes into lists of dictionaries .,def _ProcessPolicyList self policy_list for policy in policy_list self _ProcessPolicy policy
"test numberrange validator sets - error situation . note , only age_3 is within range .",def test_validator_numberrange_error_multiple setup post deepcopy setup post add u age_1 4 post add u age_2 12 post add u age_3 30 post add u age_4 42 dynamic_form WTFormsDynamicFields dynamic_form add_field age Age IntegerField dynamic_form add_validator age NumberRange min 30 max 40 message Please enter an age between min s to max s form dynamic_form process SimpleForm post form validate assert form validate False assert form errors age_1 Please enter an age between 30 to 40 assert form errors age_2 Please enter an age between 30 to 40 assert form errors age_4 Please enter an age between 30 to 40 assert form age_1 input id age_1 name age_1 type text value 4 assert form age_2 input id age_2 name age_2 type text value 12 assert form age_3 input id age_3 name age_3 type text value 30 assert form age_4 input id age_4 name age_4 type text value 42
randomly permute the training roidb .,def _shuffle_roidb_inds self self _perm np random permutation np arange len self _roidb self _cur 0
writes feature importances to file .,def feature_importances_to_file self filename feature_importances csv method a with open self output_dir filename method as f for i in range self X_train shape 1 feature i importance self importances i result 0 1 2 3 n format self N self iteration feature importance f write result
"> > > allure_report = getfixture('allure_report ' ) > > > assert_that(allure_report , ... has_test_case('testdecoratedclass#test_decorated_method ' , ... all_of(has_severity('minor ' ) , ... is_not(has_severity('trivial ' ) ) ... ) ... ) ... )",pytest allure severity pytest allure severity_level MINOR def test_decorated_method self pass
verify whether filename is a ppm file .,def is_ppm filename try size os path getsize filename with open filename rb as fin assert fin readline strip P6 width height map int fin readline split assert width 0 and height 0 assert fin readline strip 255 size_read fin tell assert size size_read width height 3 return True except AssertionError return False
"add an entry to the store , where item_map is a dictionary in the format item_map[identifier ] = value - where ' identifier ' is a string that was used as a key in the constructor , and ' value ' is the value of that item .",def add_map self item_map self append self _create_initial_entry item_map
"rather than reimplementing _ _ init _ _ , which you can do instead , you can just override this and setup and variables and such that you need to set up . this is the recommended approach .",def initialize self args kwargs self myInstanceVar kwargs get my_var None self blacklist set 10 0 0 1 self my_pid os getpid
validate and return the output names useable graphfunction,def validated_output tfobj_or_name graph graph validated_graph graph return op_name tfobj_or_name graph
"ensure if default_database_url and database_url are set , latter wins .",def test_multiple_default_databases self IGNORED_DB_NAME should_be_ignored DATABASE_URL postgres username password host 1234 dbname IGNORED postgres username password host 1234 s IGNORED_DB_NAME with debugenv DATABASE_URL DATABASE_URL DEFAULT_DATABASE_URL IGNORED default_db d12f DATABASES default self assertNotEquals default_db NAME IGNORED_DB_NAME Parsed the contents of DEFAULT_DATABASE_URL instead of ignoring it in favour of DATABASE_URL
remove a ` message ` instance from ` user ` 's inbox .,def inbox_delete self user msg_id raise NotImplementedError
define the model with its inputs . use this function to define the model in training and when exporting the model in the protobuf format .,def get self images num_classes train_phase False l2_penalty 0 0 is_training_ tf placeholder_with_default False shape name is_training_ logits self _inference images num_classes is_training_ train_phase l2_penalty return is_training_ logits
load request data as json using the given schema .,def load_request_data request_schema partial False try json_data request get_json force True or except Exception json_data request_data request_schema load json_data partial partial if request_data errors raise with_context UnprocessableEntity Validation error message Could not validate field format field field field reasons reasons for field reasons in request_data errors items return request_data data
creates the expanded dynamic search ad .,def _CreateExpandedDSA client ad_group_id ad_group_ad_service client GetService AdGroupAdService operations operator ADD operand xsi_type AdGroupAd adGroupId ad_group_id ad xsi_type ExpandedDynamicSearchAd description Buy your tickets now status PAUSED ad ad_group_ad_service mutate operations value 0 ad print Expanded dynamic search ad with ID d and description s was added ad id ad description
return 's the datetime 's format,def __format__ self args kwargs return format self datetime args kwargs
"load a matlab file containing inputs x and outputs y , output as np.arrays - x is ( data points ) x ( input dimensions ) array - y is ( data points ) x ( output dimensions ) array - y_dim selects which output dimension is returned ( 10 indexed ) returns tuple ( x , y , # data points )",def load_mat data_file y_dim 0 data scipy io loadmat data_file if Xtest in data return data X data y y_dim np shape data X 1 data Xtest data ytest y_dim else return data X data y y_dim np shape data X 1
compute the hyperbolic matrix cosine .,def coshm A A asarray A if A dtype char not in F D G return toreal 0 5 expm A expm A else return 0 5 expm A expm A
"update the cache for an instance , with cascading updates .",shared_task ignore_result True def update_cache_for_instance model_name instance_pk instance None version None cache SampleCache invalid cache update_instance model_name instance_pk instance version for invalid_name invalid_pk invalid_version in invalid update_cache_for_instance delay invalid_name invalid_pk version invalid_version
convenience function to create timer object and call repeat method .,def repeat stmt pass setup pass timer default_timer repeat default_repeat number default_number return Timer stmt setup timer repeat repeat number
validate the code belongs to the client .,def validate_code self client_id code client request args kwargs try record Session query AuthorizationCode filter AuthorizationCode code code AuthorizationCode application request client one except NoResultFound record None if record is None return False if datetime datetime utcnow record expiration return False request user record user request scopes record scope return True
this method decides whether other star is in eps range of this star according to coordinates,def getInRange self other eps if not isinstance eps u quantity Quantity eps eps u deg if self coo is None warn Star 0 has no coordinates format self name return self getDistance other eps
tests that the username in url is case insensitive,def test_username_case self self _create_test_data iliekcomputers response1 self client get url_for user profile user_name iliekcomputers response2 self client get url_for user profile user_name IlieKcomPUteRs self assert200 response1 self assert200 response2 self assertEqual response1 data decode utf 8 response2 data decode utf 8
this method defines the parameters that will be passed to mortar when starting this pigscript .,def parameters self return OUTPUT_PATH self output_base_path INPUT_PATH self input_base_path
returns a group message form .,membership_required def message_create request slug topic_id template_name groups messages message_form html group get_object_or_404 Group slug slug topic get_object_or_404 GroupTopic pk topic_id group group if request method POST form GroupMessageForm request POST if form is_valid message form save commit False message user request user message topic topic message save return redirect request topic else form GroupMessageForm return render request template_name group group topic topic form form
gets a list of reference patterns either in markdown fenced code blocks or in html comments from the notebook .,def get_reference_patterns abs_nb_path version notebook nbformat read abs_nb_path version referenced_list for cell in notebook cells references get_cell_reference_patterns cell if references referenced_list referenced_list references return referenced_list
serialize an object into a list of sendable buffers .,def serialize_object obj buffer_threshold MAX_BYTES item_threshold MAX_ITEMS buffers if istype obj sequence_types and len obj item_threshold cobj can_sequence obj for c in cobj buffers extend _extract_buffers c buffer_threshold elif istype obj dict and len obj item_threshold cobj for k in sorted obj c can obj k buffers extend _extract_buffers c buffer_threshold cobj k c else cobj can obj buffers extend _extract_buffers cobj buffer_threshold buffers insert 0 pickle dumps cobj PICKLE_PROTOCOL return buffers
strip transient values that should n't be stored in files .,def strip_transient nb nb metadata pop orig_nbformat None nb metadata pop orig_nbformat_minor None nb metadata pop signature None for cell in nb cells cell metadata pop trusted None return nb
disables bundlers defined in a python package .,def disable_bundler_python module user True sys_prefix False logger None return _set_bundler_state_python False module user sys_prefix logger logger
returns a ` .future ` which resolves when the process exits .,def wait_for_exit self raise_error True future Future def callback ret if ret 0 and raise_error future set_exception CalledProcessError ret None else future set_result ret self set_exit_callback callback return future
deserialize a string to a dictionary .,def deserialize self datastring return self get_deserialize_handler application json deserialize datastring
save the picture to the given path .,def export self directory keynote_file zipfile ZipFile self keynote_path keynote_file extract self relative_path directory
scaling factors of these student 's t distribution(s ) .,property def sigma self return self _sigma
@type service : l{mailservice } @param service : a mail service .,def __init__ self service user host smtp DNSNAME self service service self user user self host host
specify an extension to ignore . these will be processed in order .,def opt_ignore_ext self ext if not isinstance self root static File raise usage UsageError You can only use ignore_ext after path self root ignoreExt ext
fires off the fedex request .,def _assemble_and_send_request self del self ClientDetail IntegratorId self logger debug self WebAuthenticationDetail self logger debug self ClientDetail self logger debug self TransactionDetail self logger debug self VersionId return self client service serviceAvailability WebAuthenticationDetail self WebAuthenticationDetail ClientDetail self ClientDetail TransactionDetail self TransactionDetail Version self VersionId Origin self Origin Destination self Destination ShipDate self ShipDate CarrierCode self CarrierCode Service self Service Packaging self Packaging
combine a list of files into one big file using command line tools,def concatenate_shards self filenames cmd cat for f in filenames cmd f cmd self output_file try subprocess call cmd shell True except subprocess CalledProcessError as e raise Exception Couldn t concatenate these files join filenames
"finish the compression process , returning a bytes object containing any data stored in the compressor 's internal buffers and a frame footer .",def flush self result compress_end self _context self _context None self _started False return result
retrieve hackerearth submissions after last retrieved timestamp @param last_retrieved ( datetime ) : last retrieved timestamp for the user @return ( dict ) : dictionary of submissions containing all the information about the submissions,def get_submissions self last_retrieved handle self handle url https www hackerearth com submissions handle t get_request url if t in REQUEST_FAILURES return t tmp_string t headers set cookie csrf_token re findall csrftoken w tmp_string 0 10 headers host www hackerearth com user agent user_agent accept application json text javascript q 0 01 accept language en US en q 0 5 accept encoding gzip deflate content type application x www form urlencoded X CSRFToken csrf_token X Requested With XMLHttpRequest Referer https www hackerearth com submissions handle Connection keep alive Pragma no cache Cache Control no cache Cookie tmp_string submissions for page_number in xrange 1 1000 url https www hackerearth com AJAX feed newsfeed submission user handle page str page_number tmp get_request url headers headers timeout 20 if tmp in REQUEST_FAILURES return tmp json_response tmp json if json_response status ERROR break body json_response data soup bs4 BeautifulSoup body lxml trs soup find tbody find_all tr for tr in trs all_tds tr find_all td all_as tr find_all a time_stamp all_tds 1 contents 1 title time_stamp time strptime str time_stamp Y m d H M S time_stamp datetime datetime time_stamp tm_year time_stamp tm_mon time_stamp tm_mday time_stamp tm_hour time_stamp tm_min time_stamp tm_sec datetime timedelta minutes 630 curr time strptime str time_stamp Y m d H M S if curr last_retrieved return submissions problem_link https www hackerearth com all_as 1 href problem_name all_as 1 contents 0 try status all_tds 2 contents 1 title except IndexError status Others if status __contains__ Accepted status AC elif status __contains__ Partially status PS elif status __contains__ Wrong status WA elif status __contains__ Compilation status CE elif status __contains__ Runtime status RE elif status __contains__ Memory status MLE elif status __contains__ Time status TLE else status OTH if status AC points 100 else points 0 language all_tds 5 contents 0 submissions append str time_stamp problem_link problem_name status points language https www hackerearth com submission tr id split 1 return submissions
insert data into the entity_description table,def insert_into_entity_description self data self _insert_into_table entity_description data
a helper function that reads the images in a given directory,def read_images directory count normalize True downsample 0 gray False if count 1 count len os listdir directory img_list for i in range 0 count img_name s 03d png directory i if not gray img cv2 imread img_name else img cv2 imread img_name cv2 CV_LOAD_IMAGE_GRAYSCALE if img is None print Unable to read image s img_name exit 1 if normalize img normalize_img img for i in range 0 downsample img cv2 pyrDown img img_list append img return img_list
same as python bisect.bisect_left but for lists with reversed order,def reverse_bisect_left a x lo 0 hi None if lo 0 raise ValueError lo must be non negative if hi is None hi len a while lo hi mid lo hi 2 if x a mid hi mid else lo mid 1 return lo
"returns the total number of objects , across all pages .",property def count self if self _count is None try self _count self object_list count except AttributeError TypeError self _count len self object_list return self _count
get config for given directory name .,def get_config dir_name defaults normalize False skip False input_ext txt output_ext html config YamlConfig defaults os path join dir_name test cfg return config
train mnist for a number of steps .,def run_training data_sets input_data read_data_sets FLAGS input_data_dir FLAGS fake_data with tf Graph as_default images_placeholder labels_placeholder placeholder_inputs FLAGS batch_size logits mnist inference images_placeholder FLAGS hidden1 FLAGS hidden2 loss mnist loss logits labels_placeholder train_op mnist training loss FLAGS learning_rate eval_correct mnist evaluation logits labels_placeholder summary tf summary merge_all init tf global_variables_initializer saver tf train Saver sess tf Session summary_writer tf summary FileWriter FLAGS log_dir sess graph sess run init for step in xrange FLAGS max_steps start_time time time feed_dict fill_feed_dict data_sets train images_placeholder labels_placeholder _ loss_value sess run train_op loss feed_dict feed_dict duration time time start_time if step 100 0 print Step d loss 2f 3f sec step loss_value duration summary_str sess run summary feed_dict feed_dict summary_writer add_summary summary_str step summary_writer flush if step 1 1000 0 or step 1 FLAGS max_steps checkpoint_file os path join FLAGS log_dir model ckpt saver save sess checkpoint_file global_step step print Training Data Eval do_eval sess eval_correct images_placeholder labels_placeholder data_sets train print Validation Data Eval do_eval sess eval_correct images_placeholder labels_placeholder data_sets validation print Test Data Eval do_eval sess eval_correct images_placeholder labels_placeholder data_sets test
return a pretty - printed xml string for the element .,def prettify elem rough_string ElementTree tostring elem utf 8 reparsed minidom parseString rough_string return reparsed toprettyxml indent
: param message : : param text : : return :,listen_to remind re IGNORECASE def remind message text print REMIND data message _body u_id data user u_name get_user_name_by_id u_id unique_id u_name u_id db_add_row Reminder added_user unique_id added_time arrow utcnow datetime added_chan data channel message text remind_time arrow utcnow datetime messages get_reminders unique_id print m for m in messages
generates n visually distinct rgb colors,def gen_distinct_rgb_colors n seed None np random seed seed h np random random np random seed None golden_ratio_conjugate np sqrt 5 1 2 0 color_list colorsys hsv_to_rgb h i golden_ratio_conjugate 1 1 0 1 0 for i in range n return color_list
create and return a feed - dict with an image .,def create_feed_dict self image image np expand_dims image axis 0 if False dropout_fix 1 0 feed_dict self tensor_name_input_image image self tensor_name_dropout dropout_fix self tensor_name_dropout1 dropout_fix else feed_dict self tensor_name_input_image image return feed_dict
returns region from either ec2 or lambda,def get_region self try region requests get http 169 254 169 254 latest dynamic instance identity document json region return region except pass try session boto3 session Session return session region_name except pass return False
"put a list of hostnames into maintenance mode , to de - prioritize scheduling .",def start_maintenance self hostnames resp self _client start_maintenance Hosts set hostnames check_and_log_response resp result host_status host for host_status in resp result startMaintenanceResult statuses if len result len hostnames log warning Skipping maintenance for unknown hosts s set hostnames set result return result
"creates new task . arguments : time until callback is called , callback , hide from power management",def new target callback hfpm False global scheduler item pos 0 target target cb callback hfpm hfpm scheduler append item
returns true if the container still exists on the server .,def server_container_exists self container_id_or_name try self server containers get container_id_or_name return True except return False
"handle the latest subcommand : param args : parsed command line arguments : return : none , output is written to console",def run_latest args image args image branch args branch try version get_latest_version image branch except DockerTagNamingException as de print de sys exit 1 if version is None sys exit 1 print version
maximum entropy loss for multiclass problems .,def per_example_maxent_loss labels weights logits num_classes eps 1e 15 labels math_ops to_int64 labels labels_shape labels get_shape if len labels_shape 2 labels array_ops expand_dims labels 1 target_one_hot array_ops one_hot indices labels depth num_classes labels math_ops reduce_sum input_tensor target_one_hot reduction_indices 1 labels math_ops to_float labels unnormalized_probs math_ops exp logits normalizers math_ops reduce_sum unnormalized_probs 1 keep_dims True softmax_predictions math_ops divide unnormalized_probs math_ops add normalizers eps probs_for_real_class math_ops reduce_sum labels softmax_predictions 1 zeros array_ops zeros_like probs_for_real_class dtype logits dtype eps one_minus_eps array_ops ones_like probs_for_real_class dtype logits dtype eps cond probs_for_real_class eps probs_for_real_class array_ops where cond probs_for_real_class zeros cond probs_for_real_class 1 eps probs_for_real_class array_ops where cond probs_for_real_class one_minus_eps unweighted_loss array_ops expand_dims math_ops log probs_for_real_class 1 if weights is None return unweighted_loss control_flow_ops no_op else return unweighted_loss weights control_flow_ops no_op
a `` get `` to the compose view,def test_compose self self _test_login userena_umessages_compose client self client login username john password blowfish response self client get reverse userena_umessages_compose self assertEqual response status_code 200 self assertTemplateUsed response umessages message_form html self assertTrue isinstance response context form ComposeForm
returns the server 's reason for this error .,def reason self return invalidParameter
moves the bot counter - clockwise at a percentage of its full power,def turn_counter_clockwise power message LEFT str power n sock sendall message return
calculate the great circle distance between two points on the earth ( specified in decimal degrees ),def haversine lon1 lat1 lon2 lat2 lon1 lat1 lon2 lat2 map radians lon1 lat1 lon2 lat2 dlon lon2 lon1 dlat lat2 lat1 a sin dlat 2 2 cos lat1 cos lat2 sin dlon 2 2 c 2 asin sqrt a meters 6367 1000 c return meters
' ideas form post must be redirect to home,def test_redirect self self client Client self username diego self email test djangoapp com self password test user User objects create_user self username self email self password self client login username self username password self password self idea Ideas objects create user user title test app data title Test text description Test text resp_post self client post r ideas_form data self assertEqual 302 resp_post status_code self assertRedirects resp_post r home
parses a list of reactions in kegg format,staticmethod def from_formulas reaction_strings arrow has_reaction_ids False raise_exception False try reactions not_balanced_count 0 for line in reaction_strings rid None if has_reaction_ids tokens re findall w s line strip 0 rid tokens 0 line tokens 1 try reaction KeggReaction parse_formula line arrow rid except KeggParseException as e logging warning str e reaction KeggReaction if not reaction is_balanced fix_water True raise_exception raise_exception not_balanced_count 1 logging warning Model contains an unbalanced reaction line reaction KeggReaction reactions append reaction logging debug Adding reaction reaction write_formula if not_balanced_count 0 warning_str d out of the d reactions are not chemically balanced not_balanced_count len reaction_strings logging debug warning_str return KeggModel from_kegg_reactions reactions has_reaction_ids except ValueError as e if raise_exception raise e else logging debug str e return None
"searchfor(inp , re , j , l ) : searches for regex re in inp . it will automatically add more lines . if j is set , the lines will be joined together . l can provide a starting line to help search against . return value is a tuple of the last line , and the match if any .",def searchfor inp re j 0 l None ret None if not l l inp readline ret re search l while l and not ret if j l inp readline else l inp readline ret re search l return l ret
pull a single datum from the db .,def _selectSingle datumId tableLabel cursor dictCursor table tables tableLabel cursor execute SELECT FROM 0 WHERE sid 1 format table datumId rows cursor fetchall if len rows 0 raise Exception Found 0 entries in DB for 0 ID 1 format tableLabel datumId elif len rows 1 raise Exception Found 1 entries in DB for 0 ID 1 format tableLabel datumId else datum rows 0 del datum db_update_time datum id datum pop sid return datum
"update the health state , health severity , and health history .",def update_score self test score for group in HealthTest _get_groups test if test in HealthTest _get_tests group if group not in self state keys self state group self state group utils init_score_dict self state group test self state group test utils update_score_dict self state group test score self severity utils init_score_dict self severity group self severity group utils update_score_dict self severity group self _calculate_severity group if test not in self history keys self history test score else self history test utils push_pop_deque score self history test self save
creates structure for given ruleset in the trie . @param ruleset : rules . ruleset instance,def addRuleset self ruleset for target in ruleset targets node self root parts list enumerate target split depth 0 for idx part in reversed parts depth 1 partNode node children get part if not partNode partNode DomainNode part depth node addChild partNode if idx 0 partNode rulesets append ruleset node partNode
"decorator for views that checks that the user is logged in and is a staff member , displaying the login page if necessary .",def staff_member_required view_func def _checklogin request args kwargs if request user is_active and request user is_staff return view_func request args kwargs assert hasattr request session The Django admin requires session middleware to be installed Edit your MIDDLEWARE_CLASSES setting to insert django contrib sessions middleware SessionMiddleware if LOGIN_FORM_KEY not in request POST if request POST message _ Please log in again because your session has expired else message return _display_login_form request message if not request session test_cookie_worked message _ Looks like your browser isn t configured to accept cookies Please enable cookies reload this page and try again return _display_login_form request message else request session delete_test_cookie username request POST get username None password request POST get password None user authenticate username username password password if user is None message ERROR_MESSAGE if in username users list User objects filter email username if len users 1 and users 0 check_password password message _ Your e mail address is not your username Try s instead users 0 username else message _ Usernames cannot contain the character return _display_login_form request message elif user is_active and user is_staff login request user return http HttpResponseRedirect request get_full_path else return _display_login_form request ERROR_MESSAGE return wraps view_func _checklogin
"config_validator ( ) - > [ ( config_variable , error_message ) ]",def config_validator from hadoop cluster import get_all_hdfs from liboozie oozie_api import get_oozie res status down try status str get_oozie get_oozie_status except pass if NORMAL not in status res append status _ The Oozie server is not available class ConfigMock def __init__ self value self value value def get self return self value def get_fully_qualifying_key self return self value for cluster in get_all_hdfs values res extend validate_path REMOTE_DEPLOYMENT_DIR is_dir True fs cluster message _ The deployment directory of Oozie workflows does not exist Please run Setup App on the Oozie workflow page res extend validate_path ConfigMock user oozie share lib is_dir True fs cluster message _ Oozie Share Lib not installed in default location return res
"returns a queryset from a model , manager , or queryset . created to make get_object_or_404 and get_list_or_404 more dry .",def _get_queryset klass if isinstance klass QuerySet return klass elif isinstance klass Manager manager klass else manager klass _default_manager return manager all
"check for a flat page ( for 404s ) and calculate the etag , if needed .",def process_response self request response if response status_code 404 if settings SEND_BROKEN_LINK_EMAILS domain request get_host referer request META get HTTP_REFERER None is_internal _is_internal_request domain referer path request get_full_path if referer and not _is_ignorable_404 path and is_internal or not in referer ua request META get HTTP_USER_AGENT none ip request META get REMOTE_ADDR none mail_managers Broken slink on s is_internal and INTERNAL or domain Referrer s Requested URL s User agent s IP address s referer request get_full_path ua ip return response if settings USE_ETAGS if response has_header ETag etag response ETag else etag s md5_constructor response content hexdigest if response status_code 200 and response status_code 300 and request META get HTTP_IF_NONE_MATCH etag cookies response cookies response http HttpResponseNotModified response cookies cookies else response ETag etag return response
` x.__delitem__(index ) ` < = = > ` del x[index ] `,def __delitem__ index
calling c{repr } on a version with a prerelease returns a human - readable string representation of the version including the prerelease .,def test_reprWithPrerelease self self assertEquals repr Version dummy 1 2 3 prerelease 4 Version dummy 1 2 3 prerelease 4
commits changes if the system is not in managed transaction mode .,def commit_unless_managed using None if using is None using DEFAULT_DB_ALIAS connection connections using if not is_managed using using connection _commit clean_savepoints using using else set_dirty using using
send a message to the browser .,def send self message packed self _pack_message message self _sendlock acquire try self socket sendall packed finally self _sendlock release
configure the twisted mainloop to be run inside the gtk mainloop .,def portableInstall useGtk True reactor PortableGtkReactor from twisted internet main import installReactor installReactor reactor return reactor
compute rouge - l score given one candidate and references for an image : param candidate : str : candidate sentence to be evaluated : param refs : list of str : coco reference sentences for the particular image to be evaluated : returns score : int ( rouge - l score for the candidate evaluated against references ),def calc_score self candidate refs assert len candidate 1 assert len refs 0 prec rec token_c candidate 0 split for reference in refs token_r reference split lcs my_lcs token_r token_c prec append lcs float len token_c rec append lcs float len token_r prec_max max prec rec_max max rec if prec_max 0 and rec_max 0 score 1 self beta 2 prec_max rec_max float rec_max self beta 2 prec_max else score 0 0 return score
"value='portugal , faro , castro marim < br/>portugal ' returns ' portugal ' , ' faro ' , ' castro marim ' ,",def clean_place value places re split BR value places re split place for place in places place places 0 place location for location in place if n xc3 xa3o determinado not in location while len place 3 place append None return tuple place
constructs an audio - rate inbus .,classmethod def ar cls bus None channel_count None clip None offset 0 import supriya synthdefs calculation_rate supriya synthdefs CalculationRate AUDIO ugen cls _new_expanded calculation_rate calculation_rate bus bus channel_count channel_count clip clip offset offset return ugen
gets ` pv_chain_a ` input of pv_max .,property def pv_chain_a self index self _ordered_input_names index pv_chain_a return self _inputs index
constructs a control - rate bufwr .,classmethod def kr cls buffer_id None source None loop 1 phase 0 import supriya synthdefs calculation_rate supriya synthdefs CalculationRate CONTROL ugen cls _new_expanded calculation_rate calculation_rate buffer_id buffer_id source source loop loop phase phase return ugen
gets ` frequency ` input of twopole .,property def frequency self index self _ordered_input_names index frequency return self _inputs index
gets ` center ` input of splayaz .,property def center self index self _ordered_input_names index center return self _inputs index
gets ` source ` input of panaz .,property def source self index self _ordered_input_names index source return self _inputs index
check if block is a double quote string literal .,def is_string_literal_dq state return state JsBlockType STRING_DQ
access dict values by key .,def __getitem__ self key value super _AttrDict self __getitem__ key if isinstance value dict self key value _AttrDict value return value
make two children as parts of their parents .,def breed self mother father children for _ in range 2 child for param in self nn_param_choices child param random choice mother network param father network param network Network self nn_param_choices network create_set child children append network return children
test the existence of all constraint classes .,def test_all_constraints self self assertIn NoConstraint self class_map self assertIn ActiveHostsConstraint self class_map self assertIn DifferentHostConstraint self class_map
args : audio_dir : dir where all main .wav file are stored . json_dir : dir where all related .json file are stored . json should exist for each video . output_dir_train : output train data dir . output_dir_dev : output validation data dir . output_dir_test : output test data dir . train_split : train data ratio / % dev_split : validation data ratio / % test_split : test data ratio / %,def split_aligned_audio audio_dir json_dir output_dir_train output_dir_dev output_dir_test train_split dev_split test_split split_info total_audio_files 0 json_file_names sorted glob glob json_dir json for file_path in json_file_names data read_json_file file_path split_info append find_text_and_time_limits data total_audio_files len split_info 1 dev_limit_start int train_split total_audio_files dev_limit_end dev_limit_start int dev_split total_audio_files split_file_count 0 shuffled_data for file_path info in zip json_file_names split_info audio_file_name file_path split 1 split 0 audio_file_path audio_dir audio_file_name wav for data i in zip info range len info shuffled_data append data i audio_file_name audio_file_path random shuffle shuffled_data for data in shuffled_data if split_file_count dev_limit_start output_dir output_dir_train elif split_file_count dev_limit_end output_dir output_dir_dev else output_dir output_dir_test split_file_path output_dir data 2 str data 1 zfill 5 wav transcript_file_path output_dir data 2 str data 1 zfill 5 txt split split_file_path data 3 transcript_file_path data 0 split_file_count 1
"wrapper of numpy 's nansum etc . : for < = 1.8 , just return the function 's results . for > = 1.9 , any axes with all - nan values will have all - nan outputs in the collapsed version",def allbadtonan function def f data axis None result function data axis axis if LooseVersion np __version__ LooseVersion 1 9 0 and hasattr result __len__ if axis is None if np all np isnan data return np nan else return result nans np all np isnan data axis axis result nans np nan return result return f
todo add more checks for the performance data . eg . check for invalid chars,def check_performance_data the_plugin_path the_check_type the_expected_value warning_thres critical_thres build_threshold_range_strings the_expected_value p subprocess Popen the_plugin_path H localhost 1234 t the_check_type c critical_thres w warning_thres shell True stdout subprocess PIPE a_plugin_return p stdout read a_pluginoutput pynag Utils PluginOutput a_plugin_return assert a_pluginoutput perfdata
test that mean works on a numeric data frame .,def test_mean self numeric_grouped_frame self numericframe groupby a sort True dist_num_grouped_frame self numericpframe groupby a sort True self _compare_dfs numeric_grouped_frame mean dist_num_grouped_frame mean collect
load a credential file as is setup like the java utilities,def load_credential_file self path c_data StringIO StringIO c_data write Credentials n for line in open path r readlines c_data write line replace AWSAccessKeyId aws_access_key_id replace AWSSecretKey aws_secret_access_key c_data seek 0 self readfp c_data
get prefix form of listed uri .,def GetPrefix self if not self prefix raise BucketListingRefException Attempt to call GetPrefix on Prefix less BucketListingRef uri s self uri return self prefix
"downloads the latest version of easylist , and if newer replaces any existing one .",def _fetch_easylist self tmp_easylist tmp_ self EASYLIST cur_version self _easylist_version urllib urlretrieve self EASYLIST_URL tmp_easylist tmp_version self _easylist_version path tmp_easylist if tmp_version cur_version and cur_version 1 os remove self EASYLIST shutil move tmp_easylist self EASYLIST print Updated easylist from to format cur_version tmp_version elif cur_version 1 shutil move tmp_easylist self EASYLIST print New easylist format tmp_version else os remove tmp_easylist print Easylist already up to date at format tmp_version
"transform a list of command line arguments into fully processed , de - deprecated forms .",def _arguments_to_overrides self arguments key_values self _arguments_to_key_values arguments overrides for key values in key_values iteritems if key in self _flag_args self _handle_flag_arg key values overrides else self _handle_value_arg key values overrides return overrides
adds a georss point with the given coords using the given handler . handles the differences between simple georss and the more popular w3c geo specification .,def add_georss_point self handler coords w3c_geo False u n Adds a GeoRSS point with the given coords using the given handler n Handles the differences between simple GeoRSS and the more popular n W3C Geo specification n if w3c_geo lon lat coords 2 handler addQuickElement u geo lat u f lat handler addQuickElement u geo lon u f lon else handler addQuickElement u georss point self georss_coords coords
the string name of the feature .,def __str__ self return Feature FID d in Layer s self fid self layer_name
returns an httpresponseredirect to the appropriate url for the arguments passed .,def redirect to args kwargs if kwargs pop permanent False redirect_class HttpResponsePermanentRedirect else redirect_class HttpResponseRedirect return redirect_class resolve_url to args kwargs
check if the field value can be fetched from a parent field already loaded in the instance . this can be done if the to - be fetched field is a primary key field .,def _check_parent_chain self instance name u n Check if the field value can be fetched from a parent field already n loaded in the instance This can be done if the to be fetched n field is a primary key field n opts instance _meta f opts get_field name link_field opts get_ancestor_link f model if f primary_key and f link_field return getattr instance link_field attname return None
return a sequence comprising the lines of code necessary to construct the inner meta class for the model corresponding to the given database table name .,def get_meta self table_name constraints u n Return a sequence comprising the lines of code necessary n to construct the inner Meta class for the model corresponding n to the given database table name n unique_together for index params in constraints items if params u unique columns params u columns if len columns 1 tup u u join u s c for c in columns u unique_together append tup meta u u class Meta u managed False u db_table s table_name if unique_together tup u u join unique_together u meta u unique_together s tup return meta
logs a message at the warning level,def warning msg log msg logging WARNING
dump summary of plugins to log .,def log_summary observers ExtensionPoint IPlugin logging info Registered plugins for observer in observers logging info t s observer observers ExtensionPoint IWaveformGenerator logging info Registered function generator plugins for observer in observers logging info t s observer observers ExtensionPoint ILoggingPlugin logging info Registered logging plugins for observer in observers logging info t s observer
returns true if the video was played .,def get_played self return self _played
set default params to algorithm 's cofiguration . every algorithm has to implement their own default parameters .,def default_params self pass
returns a string representation of the time since the timestamp .,def timesince self now None return timesince self timestamp now encode utf8 replace xc2 xa0 decode utf8
image have no style and transform to a link,def test_wrap_image tmpdir data n html n body n img src test html style test n body n html d DriveDocument 42 Test data str tmpdir html files d _process assert a href eac0a7ec83537763d3ba7671828d0989 jpg target _blank img src eac0a7ec83537763d3ba7671828d0989 jpg a in html
a helper method that returns the url to the view,staticmethod def create_url kwargs return reverse content_gallery gallery_data kwargs kwargs
install or upgrade salt minion and/or master if needed .,task def install_salt version master False minion False restart True master_version None install_master False if master master_version get_salt_version salt install_master master_version version or not service_enabled salt master if install_master and master_version sudo apt get remove salt master yq if restart and not install_master sudo service salt master restart minion_version None install_minion False if minion minion_version get_salt_version salt minion install_minion minion_version version or not service_enabled salt minion if install_minion and minion_version sudo apt get remove salt minion yq if restart and not install_minion sudo service salt minion restart if install_master or install_minion args if install_master args append M if not install_minion args append N args join args put local_path install_salt sh remote_path install_salt sh sudo sh install_salt sh D args git v version format args args version version return True return False
randomly generate a possible example for this condition,classmethod def help_text cls return Ex not_ condstr key format not_ random choice NOT condstr cls condstr key cls key_example
"data for the test models , one row per model .",pytest fixture def modelobj model return model objects create title en english ar arabic
: type new_filter : serial_filter . filterfile,def add_filter self new_filter output_view filter_args _FilterArgs new_filter output_view with self filter_lock self _filters append filter_args
log data + preset as error message,def error self data text self _create_syslog_string data syslog syslog syslog LOG_ERR text
equivalent of round(unit ) for python 2 compatibility,def round self ndigits return self __round__ ndigits
parse an xml document from a system identifier or an inputsource .,def parse self source raise NotImplementedError This method must be implemented
evaluate a numeric gradient for a function that accepts a numpy array and returns a numpy array .,def eval_numerical_gradient_array f x df h 1e 05 grad np zeros_like x it np nditer x flags multi_index op_flags readwrite while not it finished ix it multi_index oldval x ix x ix oldval h pos f x x ix oldval h neg f x x ix oldval grad ix np sum pos neg df 2 h it iternext return grad
"will return number of shares completed , average price ... as a dict",def advanced_order_status self order_ID
initialize soupdataoutput object args : data : dict containing the data elements,def __init__ self data self data data
convert a word bitstring ( 16-bits ) into two unsigned bytes .,def wordBitStrToUBytes bits u Convert a word bitstring 16 bits into two unsigned bytes n n Returns a two byte tupple n n byteH int bits 0 8 base 2 byteL int bits 8 16 base 2 return byteH byteL
convert gemelnet xml result to array of dict per < row/ >,def _parse_xml xml return dict field tag field text for field in row for row in xml iter Row
imports process configuration file and tries to add all the processes to the master list ( to be used for spinning up each process ) . : param fullconfigpath : full file path to process config file : type fullconfigpath : str : raises : valueerror,def importProcessConfig self fullConfigPath self fullConfigPath fullConfigPath self processNode processNode ProcessNode fullConfigPath PROCESSMANAGERNAME masterProcessConfig processNodeUtils importConfigJson fullConfigPath processList masterProcessConfig processList for process in processList if process processName PROCESSMANAGERNAME self processInputList append process
map each category color a good distance from each other on the hsv color space .,def to_color category v category 1 137 5 360 return colorsys hsv_to_rgb v 1 1
calls sub - functions convert_avi_to_numpy and save_numpy_to_tfrecords in order to directly export tfrecords files : param source_path : directory where avi videos are stored : param destination_path : directory where tfrecords should be stored : param videos_per_file : specifies the number of videos within one tfrecords file : param use_meta : boolean that indicates whether to use meta information,def save_avi_to_tfrecords source_path destination_path videos_per_file FLAGS num_videos type FLAGS type video_filenames None dense_optical_flow False global NUM_CHANNELS_VIDEO assert NUM_CHANNELS_VIDEO 3 and not dense_optical_flow or NUM_CHANNELS_VIDEO 4 and dense_optical_flow correct NUM_CHANNELS_VIDEO assert type in ALLOWED_TYPES str type is not an allowed type if video_filenames is not None filenames video_filenames else filenames gfile Glob os path join source_path FILE_FILTER if not filenames raise RuntimeError No data files found print Total videos found str len filenames filenames_split list chunks filenames videos_per_file if type activity_net meta_dict create_activity_net_metadata_dicts FLAGS source METADATA_SUBCLIPS_DICT METADATA_TAXONOMY_DICT FILE_FILTER elif type youtube8m meta_dict create_youtube8m_metadata_dicts FLAGS source METADATA_DICT FILE_FILTER elif type 20bn_train meta_dict create_20bn_metadata_dicts FLAGS source CSV_20BN_TRAIN FILE_FILTER elif type 20bn_valid meta_dict create_20bn_metadata_dicts FLAGS source CSV_20BN_VALID FILE_FILTER elif type UCF101 meta_dict create_ucf101_metadata_dicts FLAGS source METADATA_DICT_UCF101 FILE_FILTER else meta_dict None for i batch in enumerate filenames_split data meta_info convert_avi_to_numpy batch type type meta_dict meta_dict dense_optical_flow dense_optical_flow total_batch_number int math ceil len filenames videos_per_file print Batch str i 1 str total_batch_number save_numpy_to_tfrecords data destination_path meta_info train_blobs_batch_ videos_per_file i 1 total_batch_number
overwritten as static files can be of any resource type .,def get_resource_types self return set RESOURCE_TYPES values
returns the details of a particular job . api key argument is required .,bp_dataset_eval route jobs uuid job_id methods GET auth_required def job_details job_id job db dataset_eval get_job job_id if not job raise exceptions APINotFound No such job job dataset datasets get_check_dataset job dataset_id return jsonify job
validates a pattern against the stix pattern grammar . error messages are returned in a list . the test passed if the returned list is empty .,def run_validator pattern start if isinstance pattern six string_types start pattern 2 pattern InputStream pattern if not start start pattern readline 2 pattern seek 0 parseErrListener STIXPatternErrorListener lexer STIXPatternLexer pattern lexer removeErrorListeners stream CommonTokenStream lexer parser STIXPatternParser stream parser buildParseTrees False parser removeErrorListeners parser addErrorListener parseErrListener for i lit_name in enumerate parser literalNames if lit_name u INVALID parser literalNames i parser symbolicNames i parser pattern if not start 0 or start parseErrListener err_strings 0 FAIL Error found at line 1 0 input is missing square brackets return parseErrListener err_strings
"returns a list of dicts of counties and csv formatted results files for elections 2008-present . first item is statewide , remainder are county - level .",def _find_csv_links self url r requests get url soup BeautifulSoup r text html parser return http apps sos wv gov elections results x href for x in soup find_all a if x text Download Comma Separated Values CSV
returns the params dict that contains all the information required by this task to execute at any point of time .,def params self return self _params
returns the language given a dbpedia link ( xml : lang predicate ) @param dblink : a dbedia link ( http://dbpedia.org/resource/tom_cruise ) @type dblink : str @return : the language ( or none if there is no lang ) @rtype : str,def get_language_for_dblink self dblink dbpedia_json self query_dbpedia_for_dblink dblink lang None for dictionary in dbpedia_json if xml lang in dictionary object lang dictionary object xml lang break return lang
return an instance of ajaxlistview .,def make_view self args kwargs u return views AjaxListView as_view args kwargs
optionally decorates the base view function with django.views.decorators.csrf.ensure_csrf_cookie ( ) .,classonlymethod def as_view cls kwargs u n Optionally decorates the base view function with n django views decorators csrf ensure_csrf_cookie n n view super EnsureCsrfCookie cls as_view kwargs return csrf ensure_csrf_cookie view if cls ensure_csrf_cookie else view
"when accessing to the name of the field itself , the value in the current language will be returned . unless it 's set , the value in the default language will be returned .",def get_localized_property context field None language None if language return getattr context get_real_fieldname field language if hasattr settings FALLBACK_LANGUAGES attrs translation get_language attrs get_fallback_languages else attrs translation get_language translation get_language 2 settings LANGUAGE_CODE def predicate x value getattr context get_real_fieldname field x None return value if valid_for_gettext value else None return first_match predicate attrs
compute beta - smooth sensitivity .,def smoothed_sens counts noise_eps l beta k 0 smoothed_sensitivity sens_at_k counts noise_eps l k while k max counts k 1 sensitivity_at_k sens_at_k counts noise_eps l k smoothed_sensitivity max smoothed_sensitivity math exp beta k sensitivity_at_k if sensitivity_at_k 0 0 break return smoothed_sensitivity
return the name of a user - specified icon - set,def iconset self return self _args iconset
check if health check is disabled .,def _check_disabled self if self config check_disabled and self config on_disabled withdraw self log info Check is disabled and ip_prefix will be withdrawn del_operation DeleteOperation name self name ip_prefix self ip_with_prefixlen ip_version self ip_version self log info adding s in the queue self ip_with_prefixlen self action put del_operation self log info Check is now permanently disabled return True elif self config check_disabled and self config on_disabled advertise self log info check is disabled ip_prefix wont be withdrawn add_operation AddOperation name self name ip_prefix self ip_with_prefixlen ip_version self ip_version self log info adding s in the queue self ip_with_prefixlen self action put add_operation self log info check is now permanently disabled return True return False
scales all values in the ndarray ndar to be between 0 and 1,def zero_mean_unit_variance Data Mean numpy mean Data axis 0 Data Mean Std numpy std Data axis 0 index numpy abs Std 10 5 Std index 1 Data Std return Data Mean Std
return true if arrays are almost equal up to numerical noise,def arrays_almost_equal a1 a2 a1units False if isinstance a1 MdtQuantity if a1 dimensionless a1mag a1 value_in ureg dimensionless else a1units True a1mag a1 magnitude else a1mag a1 if isinstance a2 MdtQuantity if a2 dimensionless if a1units raise DimensionalityError a1 units ureg dimensionless Cannot compare objects else a2mag a2 value_in ureg dimensionless elif not a1units raise DimensionalityError ureg dimensionless a2 units Cannot compare objects else a2mag a2 value_in a1 units elif a1units raise DimensionalityError a1 units ureg dimensionless Cannot compare objects else a2mag a2 return np allclose a1mag a2mag atol 1e 12
returns a list of package_id from a local cache package folder,def conan_packages self conan_reference assert isinstance conan_reference ConanFileReference packages_dir self packages conan_reference try packages dirname for dirname in os listdir packages_dir if isdir os path join packages_dir dirname except packages return packages
"filters fixtures by given matching_dict_obj . all keys specified in the matching_dict that are present in the fixture must match : param kwargs : key / values that are used to filter the fixtures . if the value is an array , the fixture is evaluated as values in fixture[key ] . otherwise it is evaluated as value==fixture[key ] you may optionally specify a special ' non_matches ' with a subset list of keys that should not match : return : the fixtures that pass the filter",def matching_keys self kwargs return self __class__ filter lambda fixtures all_existing_keys_match fixtures kwargs self fixtures
"to update the rds instance attribute on this service , the previous one is removed and a new json cfv is added .",def replace_instance_data_on_service instance instance_cfv service new_instance_cfv _ CustomFieldValue objects get_or_create field__name rds_instance value json dumps instance service attributes remove instance_cfv service attributes add new_instance_cfv instance_cfv delete
entry point for all desired functions . it is advised you use the amtools menu in maya to enable and disable features .,def modifyExport rigs exportRigs blendShapes exportBlendShapes return
specifies the function called when the apply or create button is clicked,def doOptions input_pelvis input_hipAimAxis input_hipFrontAxis input_pelvisAimAxis input_pelvisFrontAxis try selection utils dg validateSelection type transform msg Please select your hip object and then the twist object to constrain exact 2 pelvis cmds textFieldGrp input_pelvis q True tx True utils dg verifyNode pelvis cmds am_hipConstraint selection 1 pelvisObject pelvis hipObject selection 0 ha cmds floatFieldGrp input_hipAimAxis q True v True hf cmds floatFieldGrp input_hipFrontAxis q True v True pa cmds floatFieldGrp input_pelvisAimAxis q True v True pf cmds floatFieldGrp input_pelvisFrontAxis q True v True except raise
decorator to patch the ` requests ` api to return files from the fixture_files directory .,def patch_cbs_requests f return mock patch requests get _filter_fixtures_get f
fetches rcpkey from metadata of the instance .,def GetKey try response urllib urlopen http metadata computeMetadata v1beta1 instance attributes rpckey return response read except IOError return
filter a cardinality dataframe to rows that exceed a warning threshold .,def cardinality_threshold_filter dataframe ratio_name warning_threshold 0 3 if warning_threshold 1 0 raise HealthcareAIError The warning_threshold maximum is 1 0 and you set it to format warning_threshold warnings dataframe dataframe ratio_name warning_threshold results warnings drop labels index axis 1 return results
dumps the links available in the network,def do_dump_links self _line for topo in self emulator topologies print s topo topologyLayer for link in topo linkList print Link d s s s s link linkId link interfacesObj 0 getNeName link interfacesObj 0 getInterfaceName link interfacesObj 1 getInterfaceName link interfacesObj 1 getNeName print
get system data from device .,def system self data_dict defaultdict lambda defaultdict dict final hw_rev self entphysicalhardwarerev fw_rev self entphysicalfirmwarerev sw_rev self entphysicalsoftwarerev name self entphysicalname model self entphysicalmodelname serial self entphysicalserialnum classtype self entphysicalclass description self entphysicaldescr count 0 for key value in sorted serial items if bool value is True data_dict entPhysicalSerialNum count serial key data_dict entPhysicalName count name key data_dict entPhysicalModelName count model key data_dict entPhysicalHardwareRev count hw_rev key data_dict entPhysicalSoftwareRev count sw_rev key data_dict entPhysicalFirmwareRev count fw_rev key data_dict entPhysicalClass count classtype key data_dict entPhysicalDescr count description key count count 1 final ENTITY MIB data_dict return final
gather info about the remote git repository . get list of refs .,def gather_git_info root conf_rel_paths whitelist_branches whitelist_tags log logging getLogger __name__ log info Getting list of all remote branches tags try remotes list_remote root except GitError as exc log error exc message log error exc output raise HandledError log info Found s join i 1 for i in remotes try try dates_paths filter_and_date root conf_rel_paths i 0 for i in remotes except GitError log info Need to fetch from remote fetch_commits root remotes try dates_paths filter_and_date root conf_rel_paths i 0 for i in remotes except GitError as exc log error exc message log error exc output raise HandledError except subprocess CalledProcessError as exc log debug json dumps dict command exc cmd cwd root code exc returncode output exc output log error Failed to get dates for all remote commits raise HandledError filtered_remotes i 0 i 1 i 2 dates_paths i 0 for i in remotes if i 0 in dates_paths log info With docs s join i 1 for i in filtered_remotes if not whitelist_branches and not whitelist_tags return filtered_remotes whitelisted_remotes list for remote in filtered_remotes if remote 2 heads and whitelist_branches if not any re search p remote 1 for p in whitelist_branches continue if remote 2 tags and whitelist_tags if not any re search p remote 1 for p in whitelist_tags continue whitelisted_remotes append remote log info Passed whitelisting s join i 1 for i in whitelisted_remotes return whitelisted_remotes
finds a single entity in the table .,classmethod def get self kwds query Session query self autoflush False query query filter_by kwds first return query
gets the profile directory that is currently being used,property def path self return self profile_dir
add a infoblox domain determination to a feed,def action self sensors domain try logger info Adding domain s domain with self feed_lock if domain not in self feed_domains self sync_needed True self feed_domains domain timestamp time time json dump self feed_domains open s s self data_dir infoblox_domains json w self feed self generate_feed if self sync_needed and self feed self feed_object synchronize False self sync_needed False except logger error s traceback format_exc
write task to appropriate dag file .,def emit self command inputs outputs options raise NotImplementedError
"len_data : none - > ( msb , lsb ) 16-bit integer length , two bytes",def len_bytes self count len self data return struct pack h count
retrieve the expression 's value from the options file .,def __init__ self path t None try if libspud have_option path constant self val libspud get_option path constant self type constant elif libspud have_option path python v libspud get_option path python self type python exec v self val val self t t elif libspud have_option path cpp self type cpp v libspud get_option path cpp exec v self val val self t t else raise ValueError Unknown expression type except ValueError as e LOG exception e sys exit return
acquires and returns all permits that are immediately available .,def drain_permits self return self _encode_invoke semaphore_drain_permits_codec
read png images from input directory in batches .,def load_images input_dir batch_shape label_file None idx 0 batch_size batch_shape 0 if label_file with tf gfile Open os path join input_dir label_file as f label_dict row 0 int row 1 for row in csv reader f if len row 2 for filepath in tf gfile Glob os path join input_dir png if idx 0 filenames images np zeros batch_shape labels np zeros batch_size with tf gfile Open filepath rb as f image imread f mode RGB astype np float 255 0 images idx image 2 0 1 0 f_basename os path basename filepath filenames append f_basename if label_file labels idx label_dict f_basename idx 1 if idx batch_size yield filenames images labels idx 0 if idx 0 yield filenames images labels
initialize apps for django 1.7 and later,def setup_django import django try django setup except AttributeError pass
create a started : class:`timeout ` .,classmethod def start_new cls timeout None exception None ref True if isinstance timeout Timeout if not timeout pending timeout start return timeout timeout cls timeout exception ref ref timeout start return timeout
dispatches a game event of the given type if an evt _ method has been defined,def handle_game_event self evt_name params None fn self event_map evt_name if params is None return fn else return fn params
check if the user and password can authenticate with github .,def check_login credentials response requests get https api github com auth credentials return response ok
parameters ---------- value_store : storage . variable the store that references the store variable to store the values by index,def __init__ self value_store super StoredDict self __init__ self value_store value_store
return a binary path for tor browser .,def get_tb_bin_path version os_name linux lang en US major get_tbb_major_version version bin_path TBB_FF_BIN_PATH_DICT major dir_path get_tbb_path version os_name lang return join dir_path bin_path
saturation pressure : math:`p_{sat } ` .,property def saturation_pressure self return saturation_pressure self temperature self reference_pressure self triple_temperature
print colored suffix message after command .,def ui_print_suffix to_print clr C_WARN ui_print 1 0 2 format to_print clr C_NORM
adds a message with the `` debug `` level .,def debug request message extra_tags fail_silently False add_message request constants DEBUG message extra_tags extra_tags fail_silently fail_silently
send signal from sender to all connected receivers .,def send self sender named responses if not self receivers or self sender_receivers_cache get sender is NO_RECEIVERS return responses for receiver in self _live_receivers sender response receiver signal self sender sender named responses append receiver response return responses
clone a container ( without all options ),def clone orig None new None snapshot False storage None if orig and new if exists new raise ContainerAlreadyExists Container already exist format new command lxc clone o n format orig new if snapshot command s if storage command B format storage return _run command
add a series of bars to the chart .,def AddBars self points label None color None if label is not None and util _IsColor label warnings warn Your code may be broken Label is a hex triplet Maybe it is a color The old argument order color before label is deprecated DeprecationWarning stacklevel 2 style BarsStyle color series common DataSeries points label label style style self data append series return series
triggered by posts to chat = > [ chatevent ],def pollChatPosts self s self conn sendReceive events chat posts events e for e in s split if e return ChatEvent Post int e e find e e find 1 for e in events
"since analysis objects only maintain references to proxies for data objects , the toimage conversion need only update that proxy 's reference",def toImage self kwargs image Image self analysis kwargs self _propagate_values image kwargs self proxy update_reference image return image
convert adc reading into a resistance in ohms,def resist self adc r self rp self voltage adc VCC self voltage adc return r
"add a new property to specific element when called since steps are logged as property , need special handling to create kw item",def add_property self name value elem_type timestamp kwargs if elem_type pj elem self root elif elem_type ts elem self get_ts_with_timestamp timestamp else elem self get_tc_with_timestamp timestamp if elem_type kw item self create_element property kwargs keyword_items else item self create_element property name name value value elem find properties append item
decrypt the password using the cryptapi .,def decrypt self password_encrypted return _win_crypto decrypt password_encrypted
return the full dns name of our own host . used as a default for hostname when running status queries,def netcmd_dnsname lp return lp get netbios name lower lp get realm lower
entrypoint function for class ... downloads data and imports to mariadb,def main self offer_index self load_offer_index filenames urls number_of_threads 0 for offer offer_info in offer_index get offers items number_of_threads 1 filenames append csv format offer urls append offer_info get currentVersionUrl PARSING_ERROR for url in urls self download_offer_file url for filename in filenames self import_csv_into_mariadb filename
ensure using a different setting for ` jwt_auth_header_prefix ` and posting form over jwt auth without correct credentials fails and generated correct www - authenticate header,def test_post_form_failing_jwt_auth_different_auth_header_prefix self api_settings JWT_AUTH_HEADER_PREFIX Bearer response self csrf_client post jwt example example self assertEqual response status_code status HTTP_401_UNAUTHORIZED self assertEqual response WWW Authenticate Bearer realm api api_settings JWT_AUTH_HEADER_PREFIX DEFAULTS JWT_AUTH_HEADER_PREFIX
does the ` pomodori_schedule ` method return a single pomodoro if there 's just enough time ?,freeze_time 2014 01 01 00 00 00 def test_pomodori_single_pomodoro self pomodori PomodoroCalculator end 00 26 pomodori_schedule self assertEqual len pomodori segments 1 self assertEqual pomodori segments 0 get type pomodoro
display main page for internet radio,blueprint route iradio methods GET POST login_required def user_iradio_list page per_page offset common_pagination get_page_items media if session search_text is not None mediadata g db_connection db_iradio_list offset per_page search_value session search_text else mediadata g db_connection db_iradio_list offset per_page return render_template users user_iradio_list html
test that deprecated fields are added correctly,def test_deprecated_fields self start_year 2017 tsi TaxSaveInputs raw_input_fields FICA_ss_trt 0 10 ID_BenefitSurtax_Switch_0 True STD_cpi True deprecated_param 1000 first_year start_year tsi set_fields assert tsi deprecated_fields deprecated_param tsi raw_input_fields yet_another_deprecated_param 1001 tsi set_fields assert tsi deprecated_fields deprecated_param yet_another_deprecated_param assert tsi raw_input_fields deprecated_param 1000 assert tsi raw_input_fields yet_another_deprecated_param 1001 assert deprecated_param not in tsi input_fields assert yet_another_deprecated_param not in tsi input_fields
tests whether populating the slug from multiple fields works correctly .,staticmethod def test_populate_multiple_from_fields_fk model_fk get_fake_model name LocalizedField model get_fake_model title LocalizedField other models ForeignKey model_fk on_delete models CASCADE slug LocalizedUniqueSlugField populate_from title other name other model_fk objects create name settings LANGUAGE_CODE swen obj model for lang_code lang_name in settings LANGUAGES obj other_id other id obj title set lang_code title s lang_name obj save for lang_code lang_name in settings LANGUAGES assert obj slug get lang_code title s swen lang_name lower
"when called from any thread other than the main gui thread , invoke(function , * args , * * kwargs ) will call ' function ' from the gui thread , block until it returns , and return its return value , or returns immediately if ' sync ' is false .",def Invoke self sync func args kwargs event InvokeEvent sync func args kwargs wx PostEvent self event if sync event event wait if event exception raise event exception return event result
return the children of item as a list .,def GetItemChildren self item None recursively False if not item item self GetRootItem if not item return children child cookie self GetFirstChild item while child children append child if recursively children extend self GetItemChildren child True child cookie self GetNextChild item cookie return children
return the name of the function represented by this call .,property def function_name self return self _function_name
configure the secret_key from a file in the instance directory .,def install_secret_keys application secret_session secret_key secret_csrf secret_csrf do_exit False session_file os path join application root_path secret_session csrf_file os path join application root_path secret_csrf try application config SECRET_KEY open session_file rb read except IOError traceback print_exc print Error No secret key Create it with if not os path isdir os path dirname session_file print mkdir p os path dirname session_file print head c 24 dev urandom session_file do_exit True try application config CSRF_SESSION_KEY open csrf_file rb read except IOError print Error No secret CSRF key Create it with if not os path isdir os path dirname csrf_file print mkdir p os path dirname csrf_file print head c 24 dev urandom csrf_file do_exit True if do_exit sys exit 1
decorator to check for auth before running a function . assumes that the function is a member of this class .,decorator def require_auth f self None args kw if not self sid raise NotLoggedIn return f self args kw
"traces is a list of trace objects ( defined in traceclass.py ) assumed to all have the same length traces with the same sampling rate . velocities are a 1d numpy array of velocities of interest ( m / s ) . minfreq and maxfreq are the minimum / maximum positive frequencies of interest ( hz ) . filterfunction is a user - defined function that takes a single trace as input and filters it . this calculates the common factor ( sigma ) in all dispersion images that use these traces as receivers , which is returned as a 2d numpy array nvel x 2*nfrq where nfrq is the number of frequency bins between minfreq and maxfreq . this will return results in the order velocities[0],velocities[1], ... ,velocities[-1 ] and in the other direction minfreq, ... ,maxfreq ,- maxfreq ,...,- minfreq",def sigma2D traces velocities minFreq maxFreq filterFunction nVel velocities size minFrqIdx traces 0 getIdxFromHz minFreq maxFrqIdx traces 0 getIdxFromHz maxFreq nFrq maxFrqIdx minFrqIdx sigma np zeros nVel 2 nFrq actualMinFrq minFrqIdx traces 0 getNHzPerBin actualMaxFrq maxFrqIdx traces 0 getNHzPerBin posNegFrqs np hstack np linspace actualMinFrq actualMaxFrq nFrq 1 np flipud np linspace actualMinFrq actualMaxFrq nFrq p 1 0 velocities phaseShiftMat np exp 2 np pi 1j np outer p posNegFrqs for r in traces filterFunction r if minFrqIdx 1 subsetSpec np hstack r dataSpec minFrqIdx maxFrqIdx r dataSpec 1 maxFrqIdx else subsetSpec np hstack r dataSpec minFrqIdx maxFrqIdx r dataSpec 1 maxFrqIdx 1 minFrqIdx sigma sigma np tile subsetSpec nVel 1 np power phaseShiftMat r x return sigma
import oauth 2.0 session credentials from storage file . parameters filename ( str ) name of storage file . returns credentials ( dict ) all your app credentials and information imported from the configuration file .,def import_oauth2_credentials filename STORAGE_FILENAME u Import OAuth 2 0 session credentials from storage file n Parameters n filename str n Name of storage file n Returns n credentials dict n All your app credentials and information n imported from the configuration file n with open filename u r as storage_file storage safe_load storage_file client_secret storage get u client_secret refresh_token storage get u refresh_token credentials u access_token storage u access_token u client_id storage u client_id u client_secret client_secret u expires_in_seconds storage u expires_in_seconds u grant_type storage u grant_type u refresh_token refresh_token u scopes storage u scopes return credentials
close the underlying stream and audio interface .,def close self if self _audio_stream self stop self _audio_stream close self _audio_stream None
the sum of the lengths of the shortest paths to each other user,def farness user return sum len paths 0 for paths in user shortest_paths values
printk_calculatedrifts - calculates the drifts for a dmesg log,def printk_calculateDrifts dmesgContents None onlyLatest False maxDriftRedetectTime PRINTK_DRIFT_REDETECT_TIME markIfRequired True drifts 0 0 procUptime getSystemUptime if dmesgContents is None pipe subprocess Popen dmesg shell True stdout subprocess PIPE dmesgContents tostr pipe stdout read pipe wait wasPassedContents False else wasPassedContents True dmesgContentsSplit dmesgContents split n dmesgContentsSplit reverse lineNo len dmesgContentsSplit 1 for line in dmesgContentsSplit if PRINTK_DRIFT_MSG in line matchObj PRINTK_DRIFT_PATTERN match line if matchObj is not None groupDict matchObj groupdict msgUptimeSeconds int groupDict uptime_seconds drift int groupDict printk_seconds msgUptimeSeconds if latest not in drifts if not maxDriftRedetectTime drifts earliest drifts latest drifts lineNo drift elif procUptime msgUptimeSeconds maxDriftRedetectTime drifts earliest drifts latest drifts lineNo drift else break if onlyLatest is True return drifts else drifts earliest drifts lineNo drift lineNo 1 if latest in drifts return drifts if wasPassedContents is True raise NotRecentEnoughDriftDelta Cannot calculate printk drift a close enough sample is not present and an input was provided Please run this on the host that provided the file to calculate the current drift NOTE There is an issue to where this is only accurate with recent dates due to varying drift if markIfRequired try printk_markCurrentDrift except Exception as e raise NotRecentEnoughDriftDelta Cannot calculate printk drift a close enough sample is not present Please retry as root or another user that can write to dev kmsg after which you can resume unprivileged usage else raise NotRecentEnoughDriftDelta Cannot calculate printk drift a close enough sample is not present and marking has been disabled Either increase maxDriftRedetectTime or set to 0 or call with markIfRequired True when root or otherwise provide marking time sleep 0 001 pipe subprocess Popen dmesg shell True stdout subprocess PIPE content tostr pipe stdout read pipe wait lines content split n lineNo len lines 1 while lineNo 0 line lines lineNo if line matchObj PRINTK_DRIFT_PATTERN match line if matchObj is not None groupDict matchObj groupdict msgUptimeSeconds int groupDict uptime_seconds drift int groupDict printk_seconds msgUptimeSeconds drifts earliest drifts latest drifts lineNo drift return drifts lineNo 1 raise NotRecentEnoughDriftDelta Wrote latest drift but could not find it upon reopening
: type haystack : str : type needle : str : rtype : int,def strStr self haystack needle return haystack find needle
restore the world state to the checkpoint,def restoreCheckpoint self self conn send world checkpoint restore
normalize the image range for visualization,def visstd self a s 0 1 return a a mean max a std 0 0001 s 0 5
setup the test image_processing platform .,def setup_platform hass config add_devices discovery_info None add_devices TestImageProcessing camera demo_camera Test
set up the zoneminder switch platform .,def setup_platform hass config add_devices discovery_info None on_state config get CONF_COMMAND_ON off_state config get CONF_COMMAND_OFF switches monitors zoneminder get_state api monitors json for i in monitors monitors switches append ZMSwitchMonitors int i Monitor Id i Monitor Name on_state off_state add_devices switches
volume level of the media player ( 0 .. 1 ) .,property def volume_level self return self _volume
return the state of the sensor .,property def state self return self _state
called by the wemo device callback to update state .,def _update_callback self _device _params _LOGGER info Subscription update for s _device if self _model_name CoffeeMaker self wemo subscription_callback _params self _update force_update False else self update if not hasattr self hass return self schedule_update_ha_state
return true if the binary sensor is on .,property def is_on self return self iss_data is_above if self iss_data else False
return the state of the sensor .,property def state self return self _battery_stat capacity
retrieve the light 's brightness from the litejet system .,def update self self _brightness self _lj get_load_level self _index 99 255
return the state of the device .,property def state self return self _state
search for the next event .,def update self if not self data or not self data update return if not self data event self cleanup return def _get_date date Get the dateTime from date or dateTime as a local if date in date return dt start_of_local_day dt dt datetime combine dt parse_date date date dt dt time min else return dt as_local dt parse_datetime date dateTime start _get_date self data event start end _get_date self data event end summary self data event summary reg 0 9 0 2 0 9 0 2 format self _offset search re search reg summary if search and search group 1 time search group 1 if not in time if time 0 or time 0 time 0 format time 0 time 1 else time 0 format time offset_time time_period_str time summary summary search start summary search end strip else offset_time dt dt timedelta self _cal_data message re sub summary strip self _cal_data offset_time offset_time self _cal_data location self data event get location self _cal_data description self data event get description self _cal_data start start self _cal_data end end self _cal_data all_day date in self data event start
get the latest data from fido .,Throttle MIN_TIME_BETWEEN_UPDATES def update self from pyfido client import PyFidoError try self client fetch_data except PyFidoError as err _LOGGER error Error on receive last Fido data s err return self data self client get_data
"return the class of this sensor , from device_classes .",property def device_class self try return DEVICE_CLASS_MAP self _sensor except KeyError return None
artist of current playing media ( music track only ) .,property def media_artist self return self _artist
sends job status to the browser when a job is modified,receiver post_save sender Job dispatch_uid update_job_status_listeners def update_job_status_listeners sender instance kwargs logger debug Job modified status format instance instance status user instance owner group_name job user format user username message job_id instance id title instance title status instance status modified instance modified isoformat channel_layer channels layers get_channel_layer async_to_sync channel_layer group_send group_name type send_message text message
test that a variable is marked as used in a function when nested .,parameterized expand VARIABLE_USAGE_METHODS def test_used_in_func_foreach self call script function name foreach VAR 0 endforeach endfunction format call global_scope find_variables_in_scopes used_in_tree ast parse script self assertThat global_scope scopes 0 used_vars 0 MatchesStructure source Equals VarSrc FunctionVar
updates a single value in the current open project 's configuration file . writes nothing and returns -1 if no project currently open . creates sections in the config file if they do not already exist .,def update_config_with_sections config_path section option value if not os path exists config_path print ERR update_config_with_sections File does not exist format config_path return 1 cfp SafeConfigParser cfp read config_path if section not in cfp sections cfp add_section section cfp set section option value with open config_path wb as cfg_file cfp write cfg_file
make a batch request with invalid http method .,def test_invalid_http_method self resp self client post api v1 batch json dumps self _batch_request select views content_type application json self assertEqual resp status_code 400 Method validation is broken self assertEqual resp content lower invalid request method Method validation is broken
construct a new adam optimizer .,def __init__ self learning_rate 0 001 beta1 0 9 beta2 0 999 epsilon 1e 08 use_locking False name Adam super AdamOptimizer self __init__ use_locking name self _lr learning_rate self _beta1 beta1 self _beta2 beta2 self _epsilon epsilon self _lr_t None self _beta1_t None self _beta2_t None self _epsilon_t None self _beta1_power None self _beta2_power None self _updated_lr None
similar to gradient for the sum op ( i.e. tf.reduce_sum ( ) ) .,ops RegisterGradient SparseReduceSum def _SparseReduceSumGrad op out_grad sp_indices op inputs 0 sp_shape op inputs 2 output_shape_kept_dims math_ops reduced_shape sp_shape op inputs 3 out_grad_reshaped array_ops reshape out_grad output_shape_kept_dims scale sp_shape math_ops to_int64 output_shape_kept_dims return None array_ops gather_nd out_grad_reshaped sp_indices scale None None
"wraps ` call ` , applying pre- and post - processing steps .",def __call__ self inputs kwargs current_custom_getter vs get_variable_scope custom_getter def variable_getter getter name shape dtype None initializer None regularizer None trainable True kwargs if current_custom_getter is not None getter functools partial current_custom_getter getter return self _add_variable name shape initializer initializer regularizer regularizer dtype dtype trainable trainable variable_getter functools partial getter kwargs with vs variable_scope self _scope reuse True if self _built else self _reuse custom_getter variable_getter as scope with ops name_scope scope original_name_scope if not self built input_list _to_list inputs input_shapes x get_shape for x in input_list if len input_shapes 1 self build input_shapes 0 else self build input_shapes self _built True outputs self call inputs kwargs if hasattr self activity_regularizer and self activity_regularizer output_list _to_list outputs for output in output_list with ops name_scope ActivityRegularizer activity_regularization self activity_regularizer output self _losses append activity_regularization _add_elements_to_collection activity_regularization ops GraphKeys REGULARIZATION_LOSSES _add_elements_to_collection self updates ops GraphKeys UPDATE_OPS return outputs
instanciate a browser for the whole test session .,classmethod def setUpClass cls global GLOBAL_BROWSER if GLOBAL_BROWSER is None GLOBAL_BROWSER Browser os environ get BROWSER firefox cls browser GLOBAL_BROWSER super AutocompleteTestCase cls setUpClass
simple identity function works as a passthrough .,def identity arg return arg
"returns true if the current user is an admin , the owner or a contributor .",def canEdit self return self isOwner or self isContributor
load list of get commands that tenhou.net sent to us,def _parse_text self results self text split n for item in results if Get not in item continue item item split Get 1 item item replace x00 item x00 self commands append item
removes specified player i d from role of responsibility .,def remove_responsiblity self player if player is self captain self captain None if player is self corner_taker self corner_taker None if player is self free_kick_taker self free_kick_taker None if player is self penalty_taker self penalty_taker None
update cost of construction works .,def update_construction_cost self spinbutton Buildings totals update_construction_cost
calculates the spline interpolation for the airfoil params specified,def _spline self u np linspace 0 1 100 x_u y_u x_l y_l temp_var1 np array 1 0 0 0 0 0 1 0 3 3 2 1 2 2 1 1 A 0 0 B 1 0 ta_u self ta_u ta_l self ta_l tb_u self tb_u tb_l self tb_l alpha_b self alpha_b alpha_c self alpha_c TA_u ta_u cos pi 2 ta_u abs sin pi 2 TB_u tb_u cos alpha_c alpha_b pi 180 tb_u sin alpha_b alpha_c pi 180 TA_l ta_l cos pi 2 ta_l sin pi 2 TB_l tb_l cos alpha_c pi 180 tb_l sin alpha_c pi 180 for j in range 2 temp_var np array A j B j TA_u j TB_u j temp_var_coord np dot temp_var1 temp_var for i in range len u temp_var4 1 u i u i 2 pow u i 3 if j 1 x_u append np dot temp_var4 temp_var_coord else y_u append np dot temp_var4 temp_var_coord for j in range 2 temp_var np array A j B j TA_l j TB_l j temp_var_coord np dot temp_var1 temp_var for i in range len u temp_var4 1 u i u i 2 pow u i 3 if j 1 x_l append np dot temp_var4 temp_var_coord else y_l append np dot temp_var4 temp_var_coord coords np array x_l y_l x_u y_u return coords
is the character a voiced consonant,def is_voiced c lang o get_offset c lang return o in VOICED_LIST
"return the experimental data in a quadratic + random fashion , with a1 , a2 , a3 the coefficients of the quadratic and sigma is the error . this will be poorly matched to a linear fit for a3 ! = 0",def yExperiment2 a1 a2 a3 sigma x N len x r numpy random randn N y a1 a2 x a3 x x sigma r return y
"checks whether cell with index ( row , col ) is empty",def is_empty self row col return self _cells row col EMPTY
cast a string to a strictly positive integer .,def _positive_int integer_string strict False cutoff None ret int integer_string if ret 0 or ret 0 and strict raise ValueError if cutoff ret min ret cutoff return ret
doctests that can be selected by ' manage.py test thismodule.doctests ',def doc_tests import doctest return doctest DocTestSuite salesforce backend introspection
returns the image stream 's url . this camera returns it as a constantly updating image . : return :,def get_stream_url self return self url videostream cgi user self user pwd self password
decodes a script operation from a byte code back to words,def decodeScriptOp opCode if opCode v return OP_DUP elif opCode xa9 return OP_HASH160 elif opCode x88 return OP_EQUALVERIFY elif opCode xac return OP_CHECKSIG elif opCode x01 return SIGNHASH_ALL elif ord opCode 75 return PUSHDATA 0 format ord opCode else raise Error I don t know how to translate script operation code 0 into words format opCode return False
to ensure that the plugin template directory does exist .,def _validate_template self target if not path exists target raise CommandError Plugin template directory missing reinstall biohub or just manually create the plugin
"return serialized samples ( i d , dt , value ) suitable for bulk stats insertion .",def serialize self stat_name stat_properties stat_data update for datapoint in stat_data ts datapoint timestamp val datapoint value if isinstance stat_properties statistics Gauge update ts stat_name value val type Gauge elif isinstance stat_properties statistics Counter update ts stat_name value val type Counter elif isinstance stat_properties statistics BytesHistogram bins_dict for i in range 0 len val bin_stat_name s_ s stat_name i bins_dict bin_stat_name value val i type Gauge update ts bins_dict return list MetricStore serialize self update
"creates the options table as pyqt4 objects when called with a submodule . very messy code , needs to be rewritten . parameters ---------- submodule : string , name of submodule",def createTable self submodule h 411 w 891 from procedural_city_generation additional_stuff Param import paramsFromJson jsonFromParams from procedural_city_generation additional_stuff Singleton import Singleton params paramsFromJson os getcwd procedural_city_generation inputs submodule conf table QtGui QTableWidget getattr self ui submodule _frame save_button QtGui QPushButton getattr self ui submodule _frame text Save save_button setGeometry QtCore QRect w 100 h 100 31 save_button hide default_button QtGui QPushButton getattr self ui submodule _frame text Reset Defaults default_button setGeometry QtCore QRect w 260 h 150 31 default_button hide table hide table setGeometry QtCore QRect 0 0 w h table setColumnCount 6 table setHorizontalHeaderItem 0 QtGui QTableWidgetItem Parameter Name table setColumnWidth 0 int 0 2 w table setHorizontalHeaderItem 1 QtGui QTableWidgetItem Description table setColumnWidth 1 int 0 5 w table setHorizontalHeaderItem 2 QtGui QTableWidgetItem Default Value table setColumnWidth 2 int 0 125 w table setHorizontalHeaderItem 3 QtGui QTableWidgetItem Value table setColumnWidth 3 int 0 125 w table setHorizontalHeaderItem 4 QtGui QTableWidgetItem min table setColumnWidth 4 int 0 1 w table setHorizontalHeaderItem 5 QtGui QTableWidgetItem max table setColumnWidth 5 int 0 1 w table setRowCount len params i 0 for parameter in params g QtGui QTableWidgetItem str parameter name g setFlags g flags QtCore Qt ItemIsEditable g setBackground QtGui QBrush QtGui QColor 235 235 235 table setItem i 0 g g QtGui QTableWidgetItem str parameter description g setFlags g flags QtCore Qt ItemIsEditable g setBackground QtGui QBrush QtGui QColor 235 235 235 table setItem i 1 g g QtGui QTableWidgetItem str parameter default g setFlags g flags QtCore Qt ItemIsEditable g setBackground QtGui QBrush QtGui QColor 235 235 235 table setItem i 2 g g QtGui QTableWidgetItem str parameter value table setItem i 3 g s if parameter value_lower_bound is None else str parameter value_lower_bound g QtGui QTableWidgetItem s g setFlags g flags QtCore Qt ItemIsEditable g setBackground QtGui QBrush QtGui QColor 235 235 235 table setItem i 4 g s if parameter value_upper_bound is None else str parameter value_upper_bound g QtGui QTableWidgetItem s g setFlags g flags QtCore Qt ItemIsEditable g setBackground QtGui QBrush QtGui QColor 235 235 235 table setItem i 5 g i 1 getattr self ui submodule _Options clicked connect table show getattr self ui submodule _Options clicked connect save_button show getattr self ui submodule _Options clicked connect default_button show setattr self ui submodule _table table def save_params for i param in enumerate params it table item i 3 text try it eval str it except it str it param setValue it Singleton submodule kill jsonFromParams os getcwd procedural_city_generation inputs submodule conf params print Save successful save_button hide default_button hide table hide print UI donemessage save_button clicked connect save_params setattr self ui submodule _save_button save_button def default_params for i param in enumerate params table item i 3 setText _fromUtf8 str param default default_button clicked connect default_params setattr self ui submodule _default_button default_button
get a projection class from its * name*.,def get_projection_class self name u n Get a projection class from its name n return self _all_projection_types name
deletes a key using a certain adapter .,app route adapter_id keys key_id methods DELETE def key_delete adapter_id key_id adapter get_adapter adapter_id if not adapter return output failure That adapter doesn t yet exist Please check the adapter name and try again 501 if not adapter do_verify request headers return output failure Credential verification failed Please check your credentials and try again 401 result adapter do_key_delete request headers key_id if isinstance result dict and error in result return output failure result error result status return
"constructs two populations of neurons ( comprising two layers each ) that oscillate in the gamma range using ping , and that can be couped together to study various synchronisation phenomena",def Sync2Connect N1 N2 D1 6 D2 4 D 5 net iz IzNetwork 2 N1 2 N2 max D1 D2 1 r rn rand N1 ex1_a 0 02 np ones N1 ex1_b 0 2 np ones N1 ex1_c 65 15 r 2 ex1_d 8 6 r 2 r rn rand N2 in1_a 0 02 0 08 r in1_b 0 25 0 05 r in1_c 65 np ones N2 in1_d 2 np ones N2 r rn rand N1 ex2_a 0 02 np ones N1 ex2_b 0 2 np ones N1 ex2_c 65 15 r 2 ex2_d 8 6 r 2 r rn rand N2 in2_a 0 02 0 08 r in2_b 0 25 0 05 r in2_c 65 np ones N2 in2_d 2 np ones N2 a np hstack ex1_a in1_a ex2_a in2_a b np hstack ex1_b in1_b ex2_b in2_b c np hstack ex1_c in1_c ex2_c in2_c d np hstack ex1_d in1_d ex2_d in2_d sparseSynapse lambda n m 1 rn rand n m 0 01 denseSynapse lambda n m rn rand n m W np bmat 17 sparseSynapse N1 N1 2 denseSynapse N1 N2 np zeros N1 N1 np zeros N1 N2 2 denseSynapse N2 N1 2 denseSynapse N2 N2 np zeros N2 N1 np zeros N2 N2 np zeros N1 N1 np zeros N1 N2 17 sparseSynapse N1 N1 2 denseSynapse N1 N2 np zeros N2 N1 np zeros N2 N2 2 denseSynapse N2 N1 2 denseSynapse N2 N2 D np bmat D1 np ones N1 N2 N1 N2 D np ones N1 N2 N1 N2 D np ones N1 N2 N1 N2 D2 np ones N1 N2 N1 N2 D np array D dtype int net setWeights W net setDelays D net setParameters a b c d return net
generates a useable facebook graph api url,def get_url userid access_token root https graph facebook com endpoint s photos type uploaded fields source updated_time access_token s userid access_token return s s root endpoint
"checks whether or not neighborhoods are already loaded , raises an error if the neighborhood table already has data . this prevents user from just duplicate copies of the neighborhood data .",def check_neighborhood_table self n_count Neighborhood objects filter count if n_count 0 raise IntegrityError Neighborhood table already has data in it please remove this data to proceed
"@param items a list of ( domain , language , path ) tuples",def build_index items tokenizer outdir buckets NUM_BUCKETS jobs None chunksize CHUNKSIZE sample_count None sample_size None term_freq False line_level False global b_dirs complete complete False if jobs is None jobs mp cpu_count 4 b_dirs os path join outdir bucket 0 format i for i in range buckets for d in b_dirs os mkdir d chunk_size max 1 min len items jobs 2 chunksize item_chunks list chunk items chunk_size pass_tokenize_globals tokenizer b_dirs sample_count sample_size term_freq line_level with MapPool jobs setup_pass_tokenize pass_tokenize_globals as f pass_tokenize_out f pass_tokenize item_chunks doc_count defaultdict int chunk_count len item_chunks print chunk size 0 1 chunks format chunk_size chunk_count print job count 0 format jobs if sample_count print sampling based tokenization size 0 count 1 format sample_size sample_count else print whole document tokenization for i keycount in enumerate pass_tokenize_out print tokenized chunk d d d keys i 1 chunk_count keycount complete True return b_dirs
build the script for apache / mod_wsgi,def make_wsgi_script recipe buildout from zc recipe egg egg import Eggs app_egg recipe egg wsgi_filepath recipe script app_mod app_obj recipe app rsplit 1 reqs ws Eggs buildout app_egg recipe working_set egg_paths pkg location for pkg in ws src_egg_paths n join 0 format path for path in egg_paths with open wsgi_filepath w as fh fh write WSGISCRIPT_TEMPLATE format src_egg_paths app_mod app_obj return
process fg fdm input from jsbsim,def process_jsb_input buf global fdm fg_out sim_out fdm parse buf if fg_out try agl fdm get agl units meters fdm set altitude agl sitl_state ground_height units meters fdm set rpm sitl_state throttle 1000 fg_out send fdm pack except socket error as e if e errno not in errno ECONNREFUSED raise simbuf struct pack 17dI fdm get latitude units degrees fdm get longitude units degrees fdm get altitude units meters fdm get psi units degrees fdm get v_north units mps fdm get v_east units mps fdm get v_down units mps fdm get A_X_pilot units mpss fdm get A_Y_pilot units mpss fdm get A_Z_pilot units mpss fdm get phidot units dps fdm get thetadot units dps fdm get psidot units dps fdm get phi units degrees fdm get theta units degrees fdm get psi units degrees fdm get vcas units mps 1280721231 try sim_out send simbuf except socket error as e if e errno not in errno ECONNREFUSED raise
is this post election locked ?,property def locked self return self post_election candidates_locked
"get the current api client , not implemented .",def get_client self raise NotImplementedError The get_client function of the crawler
returns the json string representation of the resource .,property def json self if not self _json self _json self _create_json_str return self _json
returns mnist training data with n columns and d rows,def mnist_training mndata MNIST MNIST_PATH train_ims train_labels mndata load_training train_X np array train_ims T train_y np array train_labels T return train_X train_y
initializes the current instance of the object .,def _initialize self pass
use curl and set admin status to enable on pong and ping vnfs,def stop_traffic yaml_cfg logger def disable_service mgmt_ip port vnf_type curl_cmd curl D dev null H Accept application json H Content Type application json m 30 X POST d enable false http mgmt_ip mgmt_port api v1 vnf_type adminstatus state format mgmt_ip mgmt_ip mgmt_port port vnf_type vnf_type logger debug Executing cmd s curl_cmd subprocess check_call curl_cmd shell True for index vnfr in yaml_cfg vnfr items logger debug VNFR format index vnfr if ping_vnfd in vnfr name vnf_type ping port 18888 disable_service vnfr mgmt_ip_address port vnf_type break time sleep 0 1 for index vnfr in yaml_cfg vnfr items logger debug VNFR format index vnfr if pong_vnfd in vnfr name vnf_type pong port 18889 disable_service vnfr mgmt_ip_address port vnf_type break
create snippet string for a list of decorators .,def decorators self attributes return
delete the stored password ( only the first one ),def delete_password self service username collection self get_default_collection items collection search_items username username service service for item in items return item delete raise PasswordDeleteError No such password
returns wheter the given value is not none and whether the path can be constructed by creating one directory . so without the last path part it should ba a valid and existing directory .,def pathIsValidOutputFolder path head tail os path split path return os path exists path or os path exists head
"apply soft hyphenation to the text , which inserts `` & shy ; `` markers .",def softhyphen_filter textitem html language textitem language_code if language en language en us elif not in language language 0 0 format language return hyphenate html language language
get the line from char index .,def get_line self pt line None for r in self line_range if pt r 0 and pt r 1 line r 2 break return line
""" 0a : ff:10:aa:12 "" - > "" 0000101011111111000100001010101000010010 """,def bitesFromHex in_hex outbin if in_hex 0 in_hex in_hex 1 if len in_hex 3 0 in_hex for x in xrange 0 len in_hex 3 hex_chunk in_hex x 3 x 3 2 outbin outbin hex_to_binary hex_chunk return outbin
"initialize the test schema once for all tests , and disable max diff limits .",def setUp self self maxDiff None self schema get_schema
get default storage engine of mysql,cached_property def mysql_storage_engine self tblname INTROSPECT_TEST droptable DROP TABLE IF EXISTS table format table tblname with self connection cursor as cursor cursor execute droptable cursor execute CREATE TABLE table X INT format table tblname if self connection mysql_version 5 0 0 cursor execute SELECT ENGINE FROM INFORMATION_SCHEMA TABLES WHERE TABLE_SCHEMA s AND TABLE_NAME s self connection settings_dict NAME tblname engine cursor fetchone 0 else cursor execute SHOW TABLE STATUS WHERE Name table format table tblname engine cursor fetchone 1 cursor execute droptable self _cached_storage_engine engine return engine
performs pca analysis on the valid pixels and filters according to the distance from the principle eigenvector .,def generate_ols_regression_pixel_list candidate_pifs reference_pifs logging info Transformation Calculating ordinary least squares regression transformations gain offset r_value p_value std_err linregress candidate_pifs reference_pifs logging debug Fit statistics r_value p_value std_err format r_value p_value std_err logging info Transformation gain offset format gain offset return LinearTransformation gain offset
"order urls by extension . this function accepts a list of urls and orders them by their extension . css files are sorted to the start of the list , then js , then everything else .",def sort_urls urls order css 0 js 1 urls sort key lambda x order get x rsplit 1 lower 2 return urls
adds a rectangle to the zoomed area of the ax - graph and updates the axzoom - graph,def zoom self x y self x x self y y self draw self drawzoom self ax add_patch Rectangle x 1 y 1 2 2 facecolor grey alpha 0 2 self fig canvas draw
set the number of image to download . set to self.image_dl_per_search . args : num_image ( int ) : num of image to download .,def set_num_image_to_dl self num_image self image_dl_per_search num_image
called on receipt of a heartbeat .,def on_heartbeat self pass
the identifier is a string that must be unique within a workflow .,def getIdentifier self return self _config identifier
"make a text node from string , put it into the 2d sg and set it up with all the indicated parameters .",def __init__ self text style Plain pos 0 0 roll 0 scale None fg None bg None shadow None shadowOffset 0 04 0 04 frame None align None wordwrap None drawOrder None decal 0 font None parent None sort 0 mayChange True if parent None parent aspect2d textNode TextNode self textNode textNode NodePath __init__ self if style Plain scale scale or 0 07 fg fg or 0 0 0 1 bg bg or 0 0 0 0 shadow shadow or 0 0 0 0 frame frame or 0 0 0 0 if align None align TextNode ACenter elif style ScreenTitle scale scale or 0 15 fg fg or 1 0 2 0 2 1 bg bg or 0 0 0 0 shadow shadow or 0 0 0 1 frame frame or 0 0 0 0 if align None align TextNode ACenter elif style ScreenPrompt scale scale or 0 1 fg fg or 1 1 0 1 bg bg or 0 0 0 0 shadow shadow or 0 0 0 1 frame frame or 0 0 0 0 if align None align TextNode ACenter elif style NameConfirm scale scale or 0 1 fg fg or 0 1 0 1 bg bg or 0 0 0 0 shadow shadow or 0 0 0 0 frame frame or 0 0 0 0 if align None align TextNode ACenter elif style BlackOnWhite scale scale or 0 1 fg fg or 0 0 0 1 bg bg or 1 1 1 1 shadow shadow or 0 0 0 0 frame frame or 0 0 0 0 if align None align TextNode ACenter else raise ValueError if not isinstance scale types TupleType scale scale scale self scale scale self pos pos self roll roll self wordwrap wordwrap if decal textNode setCardDecal 1 if font None font DGG getDefaultFont textNode setFont font textNode setTextColor fg 0 fg 1 fg 2 fg 3 textNode setAlign align if wordwrap textNode setWordwrap wordwrap if bg 3 0 textNode setCardColor bg 0 bg 1 bg 2 bg 3 textNode setCardAsMargin 0 1 0 1 0 1 0 1 if shadow 3 0 textNode setShadowColor shadow 0 shadow 1 shadow 2 shadow 3 textNode setShadow shadowOffset if frame 3 0 textNode setFrameColor frame 0 frame 1 frame 2 frame 3 textNode setFrameAsMargin 0 1 0 1 0 1 0 1 self updateTransformMat if drawOrder None textNode setBin fixed textNode setDrawOrder drawOrder self setText text if not text self mayChange 1 else self mayChange mayChange if not self mayChange self textNode textNode generate self isClean 0 self assign parent attachNewNode self textNode sort
return the list of child fsms,def getChildren self return self __FSMList
return the upgrade script for a specific version . : param current_version : the version of the script to return .,def get_upgrade_script self current_version return None
"returns ( model , perm , ) for all models that match models / exclude patterns and are visible by current user .",def filter_models request models exclude items get_avail_models request included def full_name model return s s model __module__ model __name__ if len models 0 included items else for pattern in models wildcard_models for item in items model perms item model_str full_name model if model_str pattern included append item elif fnmatch model_str pattern and item not in wildcard_models wildcard_models append item if wildcard_models wildcard_models sort key lambda x x 0 _meta verbose_name_plural included wildcard_models result included for pattern in exclude for item in included model perms item if fnmatch full_name model pattern try result remove item except ValueError pass return result
allow setting of a custom stat,def set_custom_stats self which what host None if host is None host _run if host not in self custom self custom host which what else self custom host which what
fetch a file from zone to local,def fetch_file self in_path out_path super Connection self fetch_file in_path out_path display vvv FETCH s TO s in_path out_path host self zone in_path shlex_quote self _prefix_login_path in_path try p self _buffered_exec_command dd if s bs s in_path BUFSIZE except OSError raise AnsibleError zone connection requires dd command in the zone with open out_path wb as out_file try chunk p stdout read BUFSIZE while chunk out_file write chunk chunk p stdout read BUFSIZE except traceback print_exc raise AnsibleError failed to transfer file s to s in_path out_path stdout stderr p communicate if p returncode 0 raise AnsibleError failed to transfer file s to s n s n s in_path out_path stdout stderr
checks validator in all fields .,def validator_all self description name validator CustomExamValidator validator validator_name name validator validator_description description
returns a detailed commit message .,def build added deleted updated subject None commitmsg if subject commitmsg n format subject else today date today isoformat commitmsg Autogenerated update n format today if added commitmsg nAdd n for id_ in sorted added commitmsg n format id_ if deleted commitmsg nDelete n for id_ in sorted deleted commitmsg n format id_ if updated commitmsg nUpdate n for id_ in sorted updated commitmsg n format id_ return commitmsg rstrip
returns a sanitized float for bigquery .,def _get_bigquery_sanitized_float input_float if input_float float inf return _INF_FLOAT_VALUE elif input_float float inf return _INF_FLOAT_VALUE elif math isnan input_float return None else return input_float
deploys a new nginx configuration site .,def add_site filename context destination etc nginx sites available format env prefix env branch upload_template filename destination context context use_sudo True cmd chown root root format destination sudo cmd
prepares an image file for posting . defaults for size and aspect ratio from https://help.instagram.com/1469029763400082,def prepare_image img max_size 1080 1350 aspect_ratios 4 0 5 0 90 0 47 0 save_path None kwargs min_size kwargs pop min_size 320 167 if is_remote img res requests get img im Image open io BytesIO res content else im Image open img if aspect_ratios crop_box calc_crop aspect_ratios im size if crop_box im im crop crop_box new_size calc_resize max_size im size min_size min_size if new_size im im resize new_size if im mode RGB im im convert RGBA im2 Image new RGB im size 255 255 255 im2 paste im 0 0 im im im2 if save_path im save save_path b io BytesIO im save b JPEG return b getvalue im size
return the name of the agent you are playing against .,def do_name self arg opts None return True type self agent __name__
"dqn learning : instead of the q - learning : q(s , a ) + = alpha * ( reward(s , a ) + gamma * max(q(s ' ) - q(s , a ) ) we 'll be updating the network following : target = reward(s , a ) + gamma * max(q(s ' )",def learnQ self state action reward newState terminal False state numpy asarray state state state reshape 1 4 newState numpy asarray newState newState newState reshape 1 4 qval self network predict state batch_size 1 newQ self network predict newState batch_size 1 maxNewQ numpy max newQ y numpy zeros 1 2 y qval if terminal newReward reward else newReward reward self gamma maxNewQ y 0 action newReward self network fit state y batch_size 1 nb_epoch 1 verbose 0
we are only interested in charset,def check_mimetype self self validator_info format mimetype self metadata_info format mimetype
method to validate the existence of a bigquery cluster .,def _Exists self return True
run mdtest against the master vm .,def RunMdtest master_vm num_tasks mdtest_args directory posixpath join master_vm scratch_disks 0 mount_point mdtest mdtest_cmd mpiexec machinefile MACHINEFILE n num_tasks mdtest d directory additional_args format directory directory num_tasks num_tasks additional_args mdtest_args stdout _ master_vm RobustRemoteCommand mdtest_cmd return ParseMdtestResults stdout
installs the hpcc package on the vm .,def YumInstall vm _Install vm
creates the pkb user and sets the password .,def _PostCreate self cmd util GcloudCommand self sql users create self spec database_username instance 0 format self instance_id password 0 format self spec database_password _ _ _ cmd Issue if self spec engine managed_relational_db POSTGRES cmd util GcloudCommand self sql users set password postgres dummy_host instance 0 format self instance_id password 0 format self spec database_password _ _ _ cmd Issue
"connection variable is n't stable . porkfolio can be offline , but updates will continue to occur . always returning true to avoid this issue .",def available self return self _available
generate a random probable prime .,def generate_probable_prime kwargs exact_bits kwargs pop exact_bits None randfunc kwargs pop randfunc None prime_filter kwargs pop prime_filter lambda x True if kwargs print Unknown parameters list kwargs keys if exact_bits is None raise ValueError Missing exact_bits parameter if exact_bits 160 raise ValueError Prime number is not big enough if randfunc is None randfunc Random new read result COMPOSITE while result COMPOSITE candidate Integer random exact_bits exact_bits randfunc randfunc 1 if not prime_filter candidate continue result test_probable_prime candidate randfunc return candidate
: return : the key that was used for the idempotent request .,property def idempotence_key self return self __idempotence_key
animation of flower coming out of box,def revealing self self rect y self y_vel if self rect bottom self box_height self rect bottom self box_height self state c RESTING self animation
"sets the path to the password file . if just a filename is given in the ' run.ini ' file , the path is modified to point to the default path which is ' /opt / pgf / leaks ' .",def set_pw_file self pw_file if not in pw_file pw_file opt pgf leaks s pw_file self pw_file os path abspath pw_file if not os path isfile self pw_file raise IOError Password file not found exit 1
generate json body for post and put api requests,property def gen_body self body_dict for prop values in self _properties items if getattr self prop is not None body_dict values api_field getattr self prop return json dumps body_dict
can not assign to .runtime_properties if modifiable is false .,def test_setting_runtime_properties_checks_modifiable self node NodeInstance instance_id node_id runtime_properties preexisting key val node runtime_properties modifiable False try node runtime_properties other key other val except exceptions NonRecoverableError pass else self fail Error should be raised when assigning runtime_properties with the modifiable flag set to False
return the grpc stub for { $ apimethod.name}.,property def delete_all_contexts self return self _stubs contexts_stub DeleteAllContexts
simplest representation of what a configuration looks like,def __repr__ self return self name
call this function in the main event loop . similar to twisted 's `` callfromthread `` .,abstractmethod def call_from_executor self callback _max_postpone_until None u n Call this function in the main event loop Similar to Twisted s n callFromThread n n param _max_postpone_until None or time time value For internal n use If the eventloop is saturated consider this task to be low n priority and postpone maximum until this timestamp For instance n repaint is done using low priority n n Note In the past this used to be a datetime datetime instance n but apparently executing time time is more efficient it n does fewer system calls It doesn t read etc localtime n
gets the endpoint path based on the regular expression pattern of the url pattern . cleans out the regex characters and replaces with restful url descriptors,def __get_path__ self endpoint return simplify_regex endpoint __path
returns the next identifier to use in the export document as a string .,def _GetNextId self next_id self next_id self next_id 1 return str next_id
remove all keys with nones as values,def clean_dict dict if sys version_info 0 3 return k v for k v in dict iteritems if v is not None else return k v for k v in dict items if v is not None
get the string of the label of the rect .,def get_chall_string self string if self label_chall is not Not Set string str self label_chall return string
get the current package directory . prints the package directory out so callers can consume it .,def main if TAG_ENV not in os environ print ERROR_MSG file sys stderr sys exit 1 tag_name os environ TAG_ENV match TAG_RE match tag_name if match is None print BAD_TAG_MSG tag_name file sys stderr sys exit 1 pkg_name match group pkg if pkg_name is None print ROOT_DIR else pkg_dir pkg_name rstrip replace _ print os path join ROOT_DIR pkg_dir
return the minimum value in this histogram .,property def min self if len self _data 0 return 10 return next iter sorted self _data keys
"try to start fetching data , if not yet started .",def _try_fetch self size None if self _query_job is None raise exceptions InterfaceError No query results execute must be called before fetch is_dml self _query_job statement_type and self _query_job statement_type upper SELECT if is_dml self _query_data iter return if self _query_data is None client self connection _client rows_iter client list_rows self _query_job destination selected_fields self _query_job _query_results schema page_size self arraysize self _query_data iter rows_iter
create a one - off transfer from amazon s3 to google cloud storage .,def main description project_id year month day hours minutes source_bucket access_key secret_access_key sink_bucket storagetransfer googleapiclient discovery build storagetransfer v1 transfer_job description description status ENABLED projectId project_id schedule scheduleStartDate day day month month year year scheduleEndDate day day month month year year startTimeOfDay hours hours minutes minutes transferSpec awsS3DataSource bucketName source_bucket awsAccessKey accessKeyId access_key secretAccessKey secret_access_key gcsDataSink bucketName sink_bucket result storagetransfer transferJobs create body transfer_job execute print Returned transferJob format json dumps result indent 4
"demonstrate using offsets directly , using encoding = utf32 .",def test_annotate_text_utf32_directly_index_into_unicode test_string u a xe3 u0201 U0001f636 b result analyze analyze_syntax test_string encoding UTF32 tokens result tokens assert tokens 0 text content a offset tokens 0 text get beginOffset 0 assert test_string offset tokens 0 text content assert tokens 1 text content u xe3 offset tokens 1 text get beginOffset 0 assert test_string offset tokens 1 text content assert tokens 2 text content u u0201 offset tokens 2 text get beginOffset 0 assert test_string offset tokens 2 text content
draw rectangles around the tracked facial features .,def drawDebugRects self image if utils isGray image faceColor 255 leftEyeColor 255 rightEyeColor 255 noseColor 255 mouthColor 255 else faceColor 255 255 255 leftEyeColor 0 0 255 rightEyeColor 0 255 255 noseColor 0 255 0 mouthColor 255 0 0 for face in self faces rects outlineRect image face faceRect faceColor rects outlineRect image face leftEyeRect leftEyeColor rects outlineRect image face rightEyeRect rightEyeColor rects outlineRect image face noseRect noseColor rects outlineRect image face mouthRect mouthColor
set path where spark is installed on worker nodes .,def setSparkHome self value self _jconf setSparkHome value return self
handle a query observer unsubscription request .,def post self request try observer_id request query_params observer session_id request query_params subscriber except KeyError return response Response status 400 observer remove_subscriber session_id observer_id return response Response
"matching according to rfc 6125 , section 6.4.3",def _DNSNameMatch dn hostname max_wildcards 1 pats if not dn return False parts dn split leftmost parts 0 remainder parts 1 wildcards leftmost count if wildcards max_wildcards raise CertificateError too many wildcards in certificate DNS name repr dn if not wildcards return dn lower hostname lower if leftmost pats append elif leftmost startswith xn or hostname startswith xn pats append re escape leftmost else pats append re escape leftmost replace for frag in remainder pats append re escape frag pat re compile A join pats Z re IGNORECASE return pat match hostname
loop over and repack the given locales .,def repack_locales locales for locale in locales inputs inputs calc_inputs locale output calc_output locale data_pack DataPack RePack output inputs
generates and deploys a test certificate authority .,def _InstallTestCa self print Installing test certificate authority on device s self _device adb GetDeviceSerial self _wpr_ca_cert_path os path join tempfile mkdtemp testca pem certutils write_dummy_ca_cert cert_path self _wpr_ca_cert_path certutils generate_dummy_ca_cert self _device_cert_util adb_install_cert AndroidCertInstaller self _device adb GetDeviceSerial None self _wpr_ca_cert_path self _device_cert_util install_cert overwrite_cert True self _is_test_ca_installed True
reverse the effects that funky < include > preprocessing steps have on errors messages .,def _clean_up_error self error assert self _target assert self _expanded_file expanded_file self _expanded_file fixed re sub s d expanded_file self _get_line_number error return fixed replace expanded_file os path abspath self _target
true if properties have changed and a commit would be needed .,property def changed self return self _changed
this property will be able to return engraved names for customized items . : return : string of current name .,property def name self return self item name
"passed a parseresult instance , returns true if the url is that of a movie or tv show on imdb .",def _url_is_imdb self url if not isinstance url ParseResult url urlparse url return url netloc endswith imdb com and len re search self title_match url path groups 0
add repo to list regardless of server status,def forceaddrepo self repo isroot args self repositories append repo self makerepofolders isroot args
an auto - batching wrapper for memcache.get ( ) or .get_multi ( ) .,def memcache_get self key for_cas False namespace None use_cache False deadline None if not isinstance key basestring raise TypeError key must be a string received r key if not isinstance for_cas bool raise TypeError for_cas must be a bool received r for_cas if namespace is None namespace namespace_manager get_namespace options for_cas namespace deadline batcher self memcache_get_batcher if use_cache return batcher add_once key options else return batcher add key options
flask application factory . initializes and returns the flask application .,def create_app config_obj no_sql False app Flask __name__ template_folder TEMPLATE_FOLDER static_folder STATIC_FOLDER config_dict dict k getattr config_obj k for k in dir config_obj if not k startswith _ app config update config_dict with app app_context for module in app config get DB_MODELS_IMPORTS list import_module module app add_url_rule favicon ico favicon lambda app send_static_file favicon ico for bp in all_blueprints import_module bp import_name app register_blueprint bp if not no_sql db init_app app Statics app redis init_app app celery init_app app mail init_app app locale setlocale locale LC_ALL en_US UTF 8 with app app_context import_module pypi_portal middleware return app
wrap the mysql conn object with traceconnection .,def wrap_conn conn_func def call args kwargs try conn conn_func args kwargs cursor_func getattr conn CURSOR_WRAP_METHOD wrapped wrap_cursor cursor_func setattr conn cursor_func __name__ wrapped return conn except Exception logging warning Fail to wrap conn mysql not traced return conn_func args kwargs return call
find all class arguments ( parameters ) which can be passed in `` _ _ init _ _ `` .,def find_class_args klass u n Find all class arguments parameters which can be passed in __init__ n args set for i in klass mro if i is object or not hasattr i u __init__ continue args set find_function_args i __init__ return list args
performs vanilla stochastic gradient descent .,def sgd w dw config None if config is None config config setdefault learning_rate 0 01 w config learning_rate dw return w config
generator to compute felsenszwalb 's efficient graph based image segmentation .,def felzenszwalb_generator scale SCALE sigma SIGMA min_size MIN_SIZE def _generator image return felzenszwalb image scale sigma min_size return _generator
saves a picture showing the current progress of the model,def save_image data data_format e X_G X_real data Xg X_G 8 Xr X_real 8 if data_format NHWC X np concatenate Xg Xr axis 0 list_rows for i in range int X shape 0 4 Xr np concatenate X k for k in range 4 i 4 i 1 axis 1 list_rows append Xr Xr np concatenate list_rows axis 0 if data_format NCHW X np concatenate Xg Xr axis 0 list_rows for i in range int X shape 0 4 Xr np concatenate X k for k in range 4 i 4 i 1 axis 2 list_rows append Xr Xr np concatenate list_rows axis 1 Xr Xr transpose 1 2 0 if Xr shape 1 1 plt imshow Xr 0 cmap gray else plt imshow Xr plt axis off plt savefig os path join FLAGS fig_dir current_batch_ s png e plt clf plt close
use the ` pygments ` library to create a highlighted html representation of the code snippet .,def save self args kwargs lexer get_lexer_by_name self language linenos self linenos and table or False options self title and title self title or formatter HtmlFormatter style self style linenos linenos full True options self highlighted highlight self code lexer formatter super Snippet self save args kwargs
"lowers case , removes punctuation and collapses whitespace .",def NormalizeString value return _StripSeparators value lower
tests the get_user_info function when the cookie is malformed .,def test_get_user_info_bad_cookie self cookie_name SinaRot g get cookie_value blah http_cookie s s cookie_name cookie_value email admin user_id login get_user_info http_cookie cookie_name cookie_name self assertEqual email self assertFalse admin self assertEqual user_id
starts a google analytics session for the current client .,def Start self client_id user_agent None runtimes None environment None self _client_id client_id self _user_agent user_agent self _runtimes join sorted list runtimes if runtimes else None self _environment join sorted list environment if environment else None self Log DEVAPPSERVER_CATEGORY START_ACTION self _start_time Now
return the _ _ property _ _ key for kind .,classmethod def key_for_kind cls kind return db Key from_path Kind KIND_NAME kind
generate the key for the active config record belonging to app_version .,def _get_active_config_key app_version return db Key from_path CONFIG_KIND s s app_version ACTIVE_KEY_NAME namespace NAMESPACE
"creates a new user with the given email address , username , and password : param email : user 's email address : type email : basestring : param username : user 's username : type username : basestring : param password : user 's password : type password : basestring : return : whether the creation was successful : rtype : boolean",def create_user email username password permissions models UserPermissions user models User email email username username password password permissions permissions util try_add user user logger logger util try_add permissions permissions logger logger
check if a mediator is registered or not,def hasMediator self mediatorName return self view hasMediator mediatorName
yields one item from a time - series query against halo . forever .,def __iter__ self while True if self stop raise StopIteration for item in self get_next_batch yield item
cluster data using k - means,hlp timeit def findClusters_kmeans data no_of_clusters kmeans cl KMeans n_clusters no_of_clusters n_jobs 1 verbose 0 n_init 30 return kmeans fit data
": param timestamps_1 : list of tuple ( index , start , stop ) with start and stop float values , stop > = start : param timestamps_2 : list of tuple ( index , start , stop ) with start and stop float values , stop > = start : return :",def find_overlap timestamps_1 timestamps_2 associated for index_1 a_start a_stop in timestamps_1 for index_2 b_start b_stop in timestamps_2 if _overlap a_start a_stop b_start b_stop associated append index_1 index_2 return associated
perform the inverse transformation to encoded data .,def inverse_transform self Xt warnings warn Inverse transform in basen is a currently experimental feature please be careful X Xt copy deep True X convert_input X if self _dim is None raise ValueError Must train encoder before it can be used to inverse_transform data X self basen_to_interger X self cols self base if X shape 1 self _dim if self drop_invariant raise ValueError Unexpected input dimension d the attribute drop_invariant should set as False when transform data X shape 1 else raise ValueError Unexpected input dimension d expected d X shape 1 self _dim if not self cols return X if self return_df else X values if self impute_missing and self handle_unknown impute for col in self cols if any X col 1 raise ValueError inverse_transform is not supported because transform impute the unknown category 1 when encode s col for switch in self ordinal_encoder mapping col_dict col_pair 1 col_pair 0 for col_pair in switch get mapping X switch get col X switch get col apply lambda x col_dict get x return X if self return_df else X values
convert class labels from scalars to one - hot vectors .,def dense_to_one_hot labels_dense num_classes num_labels labels_dense shape 0 index_offset numpy arange num_labels num_classes labels_one_hot numpy zeros num_labels num_classes labels_one_hot flat index_offset labels_dense ravel 1 return labels_one_hot
translates datastore results into the format expected by the application .,def from_datastore entity if not entity return None if isinstance entity builtin_list entity entity pop entity id entity key id return entity
set the multiton key for this facade instance .,def initializeNotifier self key self multitonKey key
1 . disable all the idle states 2 . run ebizzy when smt = off and smt = on 3 . enable all the idle states .,def test self self cpu 0 cpu online self cpu process run cpupower idle set D 0 shell True process system_output ppc64_cpu smt off shell True throughput_off self run_ebizzy process system_output ppc64_cpu smt on shell True throughput_on self run_ebizzy process run cpupower idle set E 0 shell True if int throughput_off int throughput_on self log info PASS Single thread performance is better than multi thread performance else self fail FAIL Performance is degraded when SMT off
returns a tree.py cart built from the input file data,def build_tree conf cp input_file temp_dir tempfile mkdtemp ti os path join temp_dir rcart R to os path join temp_dir out categories rfile open ti w rfile write library rpart n rfile write data read table 0 n format input_file for i f in enumerate conf factors if f type categorical rfile write data V 0 as factor data V 1 n format i 1 i 1 categories append f values else categories append f range rfile write rtree rpart data V 0 data data control rpart control cp 1 n format i 2 cp rfile write if xerror in colnames rtree cptable rfile write bcp rtree cptable which min rtree cptable xerror CP n rfile write rtree prune rtree bcp n n rfile write print rtree n rfile close print Building CART model os system R slave no save 0 1 format ti to tf open to r print Parsing CART tree T parse_cart_tree tf readlines categories tf close return T
downgrade the database to an older revision .,def downgrade op drop_table downstream_map
convert a tensor of slices and corresponding values to a sparse tensor .,def slices_values_to_sparse_tensor slices values dense_shape slices tf cast tf convert_to_tensor slices dtype tf int64 values tf convert_to_tensor values shape tf shape slices out_type tf int64 nrows shape 0 row_inds tf range nrows flattened_indices tf reshape slices nrows row_inds None 1 twod_inds tf stack flattened_indices nrows flattened_indices nrows axis 1 return tf SparseTensor twod_inds values tf reshape values 1 dense_shape dense_shape
grouppolicy - policy - action - list --sort - key name --sort - key i d --sort - key asc --sort - key desc,def test_list_policy_actions_sort self resources policy_actions cmd gbp ListPolicyAction test_cli20 MyApp sys stdout None self _test_list_resources resources cmd sort_key name id sort_dir asc desc
"returns true if it 's meant to give a completion , and sets our internal truth flag",def ShouldUse self target request_data if self _main_directory is None self _ComputeMainDirectory request_data match self output_regex search target if match is not None self completion_wanted True else self completion_wanted False return self completion_wanted
a convenient function for constructing convolutional layer,def conv2d x filter_size stride output_size initializer scope use_bias padding VALID N H W C x get_shape as_list stride 1 stride stride 1 with tf variable_scope scope w tf get_variable W shape filter_size filter_size C output_size initializer initializer dtype tf float32 tf add_to_collection tf GraphKeys MODEL_VARIABLES w x tf nn conv2d x w strides stride padding padding if use_bias b tf get_variable b shape output_size initializer tf constant_initializer 0 01 dtype tf float32 tf add_to_collection tf GraphKeys MODEL_VARIABLES b x tf nn bias_add x b return x
create a vip for a specified pool .,def vip_create request kwargs body vip name kwargs name description kwargs description subnet_id kwargs subnet_id protocol_port kwargs protocol_port protocol kwargs protocol pool_id kwargs pool_id session_persistence kwargs session_persistence admin_state_up kwargs admin_state_up if kwargs get connection_limit body vip connection_limit kwargs connection_limit if kwargs get address body vip address kwargs address vip neutronclient request create_vip body get vip return Vip vip
"return number of visitors who convert , given conversion fraction p.",def simulate_conversion p n_visitors outcomes random random p for i in range n_visitors return sum outcomes
used to create a country object in the python server scope,def __init__ self country_name self country_name country_name
"downloads a "" tab separate value "" database from the supplied "" url "" , searches for the argument supplied "" desired_model "" , and returns the associated "" download_link "" for said model .",def search_for_mac desired_model url print set_color M nAttempting to download database of availible mac models set_color W try binary_response urllib request urlopen url read except urllib error URLError as error exit set_color R ERROR Database download failed n str error set_color W print set_color G Database downloaded set_color W string_response binary_response decode utf 8 mac_list string_response split r n print set_color M nSearching database for set_color Y desired_model set_color M download link set_color W download_link x split t 1 for x in mac_list if x find desired_model 1 if download_link print set_color G Successfully found link for model set_color Y desired_model set_color G nLink set_color Y download_link 0 set_color W return download_link 0 else exit set_color R ERROR Unable to find link for model set_color Y desired_model set_color R Please verify manually at https goo gl U1OOJt set_color W
splits the posts xml file into individual answer units by pairing 1 answer to its corresponding question to prepare for document ingestion ( thus the question will be duplicated for multiple answers ),def writeDocuments postsXML votesDict usersDict OUTPUT_DIR documents for post in postsXML findall row postTypeId int post get PostTypeId if postTypeId 1 handleQuestion documents post OUTPUT_DIR elif postTypeId 2 handleAnswer documents post votesDict usersDict OUTPUT_DIR
escape a fragment of a postgresql .pgpass file .,def _escape_pgpass txt return txt replace replace
generate template config based on python objects .,def GenerateConfig context properties context properties region properties region compute_resource_util SetContext context network ComputeResource network compute_constants NETWORKS vpn_gateway ComputeResource vpg compute_constants TARGETVPNGATEWAYS network network SelfLink region region ip ComputeResource static ip compute_constants ADDRESSES region region esp_rule ComputeResource esp rule compute_constants FORWARDINGRULES IPProtocol ESP IPAddress ip Ref address region region target vpn_gateway SelfLink udp4500_rule ComputeResource udp 4500 rule compute_constants FORWARDINGRULES IPProtocol UDP IPAddress ip Ref address region region target vpn_gateway SelfLink portRange 4500 udp500_rule ComputeResource udp 500 rule compute_constants FORWARDINGRULES IPProtocol UDP IPAddress ip Ref address region region target vpn_gateway SelfLink portRange 500 cloud_router ComputeResource cloud router compute_constants ROUTERS region region network network SelfLink asn properties asn ComputeResource vpn tunnel compute_constants VPNTUNNELS region region ikeVersion 2 sharedSecret properties sharedSecret peerIp properties peerAddress router cloud_router SelfLink targetVpnGateway vpn_gateway SelfLink description Must be deployed after esp_rule SelfLink udp500_rule SelfLink udp4500_rule SelfLink return Resources
"temporal autoencoder sub - task argument : action_logits : shape [ 1 , action_space ]",def tAE self action_logits bias torch unsqueeze self action_head bias 0 repeat action_logits size 0 1 output action_logits bias output F linear output torch transpose self action_head weight 0 1 return output
accepts a text string and replaces : 1 ) urls with urlhere 2 ) lots of whitespace with one instance 3 ) mentions with mentionhere 4 ) hashtags with hashtaghere,def count_twitter_objs text_string space_pattern s giant_url_regex http s a zA Z 0 9 _ 0 9a fA F 0 9a fA F mention_regex w hashtag_regex w parsed_text re sub space_pattern text_string parsed_text re sub giant_url_regex URLHERE parsed_text parsed_text re sub mention_regex MENTIONHERE parsed_text parsed_text re sub hashtag_regex HASHTAGHERE parsed_text return parsed_text count URLHERE parsed_text count MENTIONHERE parsed_text count HASHTAGHERE
set the position of the servo,def move self channel position steps 250 if channel 1 and channel 16 self __channel channel else raise ValueError move channel out of range if steps 0 or steps 4095 raise ValueError move steps out of range if position 0 and position steps pwm_value float self __highpos float self __lowpos steps float position self __lowpos self __pwm set_pwm channel 0 int pwm_value print pwm_value else raise ValueError move channel out of range
if a framework project was created move it to project root .,def set_up_framework_and_tests framework cookiecutter framework if framework none return LOG info Moving files for s project framework framework_folder join _ frameworks framework for file_or_folder in listdir framework_folder shutil move join framework_folder file_or_folder if framework in Django Flask LOG info Moving test setup for s project framework testing_folder join _ testing python for file_or_folder in listdir testing_folder shutil move join testing_folder file_or_folder
"set the frequency of the output pin square - wave options are : 1 = 1hz , 2 = 4.096khz , 3 = 8.192khz , 4 = 32.768khz",def set_frequency self frequency if frequency 1 self __config self __updatebyte self __config 0 0 self __config self __updatebyte self __config 1 0 if frequency 2 self __config self __updatebyte self __config 0 1 self __config self __updatebyte self __config 1 0 if frequency 3 self __config self __updatebyte self __config 0 0 self __config self __updatebyte self __config 1 1 if frequency 4 self __config self __updatebyte self __config 0 1 self __config self __updatebyte self __config 1 1 self _bus write_byte_data self __rtcAddress self CONTROL self __config return
performs a uniform crossover between the two parents . each segments is swapped with probability * proba *,def cxUniform ind1 ind2 proba nBuildings child1 toolbox clone ind1 child2 toolbox clone ind2 def swap inda indb n inda n indb n indb n inda n def cross_integer_variables child_1 child_2 number_of_plants index_on_individual for i in range number_of_plants if random random proba child_1 index_on_individual 2 i child_2 index_on_individual 2 i child_2 index_on_individual 2 i child_1 index_on_individual 2 i cross_integer_variables child1 child2 N_HEAT 0 cross_integer_variables child1 child2 N_SOLAR N_HEAT 2 N_HR cross_integer_variables child1 child2 N_COOL N_HEAT N_SOLAR 2 N_HR INDICES_CORRESPONDING_TO_DHN for i in range N_HR if random random proba swap child1 child2 N_HEAT 2 i for i in range INDICES_CORRESPONDING_TO_DHN if random random proba swap child1 child2 N_HEAT N_SOLAR 2 N_HR i for i in range INDICES_CORRESPONDING_TO_DCN if random random proba swap child1 child2 N_HEAT N_SOLAR 2 N_HR INDICES_CORRESPONDING_TO_DHN N_COOL 2 i for i in range 2 nBuildings if random random proba swap child1 child2 N_HEAT N_SOLAR 2 N_HR INDICES_CORRESPONDING_TO_DHN N_COOL 2 INDICES_CORRESPONDING_TO_DCN i del child1 fitness values del child2 fitness values return child1 child2
"when provided , primaryplaceofperformancezip+4 must be in the format # # # # # , # # # # # # # # # , # # # # # - # # # # , or "" city - wide "" .",def test_success database det_award_1 DetachedAwardFinancialAssistanceFactory place_of_performance_zip4a det_award_2 DetachedAwardFinancialAssistanceFactory place_of_performance_zip4a None det_award_3 DetachedAwardFinancialAssistanceFactory place_of_performance_zip4a city wide det_award_4 DetachedAwardFinancialAssistanceFactory place_of_performance_zip4a 12345 det_award_5 DetachedAwardFinancialAssistanceFactory place_of_performance_zip4a 123456789 det_award_6 DetachedAwardFinancialAssistanceFactory place_of_performance_zip4a 12345 6789 errors number_of_errors _FILE database models det_award_1 det_award_2 det_award_3 det_award_4 det_award_5 det_award_6 assert errors 0
"gets the last time the file was uploaded to s3 , or alternatively the last time the local file was modified .",def get_date_of_current_pa_upload base_path if CONFIG_BROKER use_aws last_uploaded boto3 client s3 region_name CONFIG_BROKER aws_region head_object Bucket PA_BUCKET Key PA_SUB_KEY PA_FILE_NAME LastModified last_uploaded last_uploaded replace tzinfo None else pa_file get_program_activity_file base_path last_uploaded datetime datetime utcfromtimestamp os path getmtime pa_file return last_uploaded
returns tool specific dic or none if it does not exist for defined tool,def get_tool_definition self target if target not in self targets_mcu_list logging debug Target not found in definitions return None mcu_record self targets get_mcu_record target if self mcus get_mcu_record target is None else self mcus get_mcu_record target try return mcu_record tool_specific self tool except KeyError return None
parses the latitude and longitude from a ned dem tile .,def ParseLatLonFromNedFile fname if fname 0 lower f lat int fname 6 8 lon int fname 9 12 if fname 5 lower s lat lat if fname 8 lower w lon lon elif fname 0 lower u lat int fname 12 14 lon int fname 15 18 if fname 11 lower s lat lat if fname 14 lower w lon lon else lat 0 lon 0 return lat lon
"make an ajax call to the xblock , and assert the state is as desired .",def student_submit self block answer resp self ajax student_submit block answer answer self assertEqual resp status_code 200 self assertEqual resp data success True answer answer
returns the scope in which the user resides . this includes flows .,def get_user_scope module_context position user_stmt get_statement_of_position module_context tree_node position if user_stmt is None def scan scope for s in scope children if s start_pos position s end_pos if isinstance s tree Scope tree Flow return scan s or s elif s type in suite decorated return scan s return None scanned_node scan module_context tree_node if scanned_node return module_context create_context scanned_node node_is_context True return module_context else return module_context create_context user_stmt
: param factory : an instance of : class:`autobahn.twisted.websocket . websocketserverfactory ` . : type factory : obj,def __init__ self factory self _factory factory
start watching the file descriptor for read availability .,def add_reader self fd callback u h msvcrt get_osfhandle fd self _read_fds h callback
"key bindings , required for mouse support . ( mouse events enter through the key binding system . )",def load_mouse_bindings u n Key bindings required for mouse support n Mouse events enter through the key binding system n registry Registry registry add_binding Keys Vt100MouseEvent def _ event u n Handling of incoming mouse event n if event data 2 u M mouse_event x y map ord event data 3 mouse_event 32 MouseEventType MOUSE_DOWN 35 MouseEventType MOUSE_UP 96 MouseEventType SCROLL_UP 97 MouseEventType SCROLL_DOWN get mouse_event if x 56320 x 56320 if y 56320 y 56320 x 32 y 32 else data event data 2 if data 1 u sgr True data data 1 else sgr False mouse_event x y map int data 1 split u m data 1 if sgr mouse_event 0 u M MouseEventType MOUSE_DOWN 0 u m MouseEventType MOUSE_UP 64 u M MouseEventType SCROLL_UP 65 u M MouseEventType SCROLL_DOWN get mouse_event m else mouse_event 32 MouseEventType MOUSE_DOWN 35 MouseEventType MOUSE_UP 96 MouseEventType SCROLL_UP 97 MouseEventType SCROLL_DOWN get mouse_event x 1 y 1 if event cli renderer height_is_known and mouse_event is not None try y event cli renderer rows_above_layout except HeightIsUnknownError return handler event cli renderer mouse_handlers mouse_handlers x y handler event cli MouseEvent position Point x x y y event_type mouse_event registry add_binding Keys WindowsMouseEvent def _ event u n Handling of mouse events for Windows n assert is_windows event_type x y event data split u x int x y int y screen_buffer_info event cli renderer output get_win32_screen_buffer_info rows_above_cursor screen_buffer_info dwCursorPosition Y event cli renderer _cursor_pos y y rows_above_cursor handler event cli renderer mouse_handlers mouse_handlers x y handler event cli MouseEvent position Point x x y y event_type event_type return registry
a function for fetching input list for cellranger count run for a specific experiment,def get_cellranger_count_input_list db_session_class experiment_igf_id fastq_collection_type demultiplexed_fastq active_status ACTIVE try fastq_dir_list dbconnected False base BaseAdaptor session_class db_session_class base start_session dbconnected True subquery base session query Run run_igf_id join Experiment filter Run experiment_id Experiment experiment_id filter Experiment experiment_igf_id experiment_igf_id filter Run status active_status query base session query File file_path join Collection_group join Collection filter Collection collection_id Collection_group collection_id filter Collection_group file_id File file_id filter Collection type fastq_collection_type filter Collection name in_ subquery results base fetch_records query query output_mode object for row in results fastq_dir_list append os path dirname row file_path if len fastq_dir_list 0 fastq_dir_list list set fastq_dir_list else raise ValueError No fastq directory found for experiment 0 format experiment_igf_id base close_session return fastq_dir_list except if dbconnected base close_session raise
check that an invalid token does not authenticated .,def test_invalid_token self try self test_instance authenticate_credentials xyz789 except AuthenticationFailed as e self assertEqual e __str__ Invalid token else self fail AuthenticationFailed not raised
generate a random sample of rois comprising foreground and background examples .,def _sample_rois roidb fg_rois_per_image rois_per_image num_classes labels roidb max_classes overlaps roidb max_overlaps rois roidb boxes fg_inds np where overlaps cfg TRAIN FG_THRESH 0 fg_rois_per_this_image np minimum fg_rois_per_image fg_inds size if fg_inds size 0 fg_inds npr choice fg_inds size fg_rois_per_this_image replace False bg_inds np where overlaps cfg TRAIN BG_THRESH_HI overlaps cfg TRAIN BG_THRESH_LO 0 bg_rois_per_this_image rois_per_image fg_rois_per_this_image bg_rois_per_this_image np minimum bg_rois_per_this_image bg_inds size if bg_inds size 0 bg_inds npr choice bg_inds size bg_rois_per_this_image replace False keep_inds np append fg_inds bg_inds labels labels keep_inds labels fg_rois_per_this_image 0 overlaps overlaps keep_inds rois rois keep_inds bbox_targets bbox_inside_weights _get_bbox_regression_labels roidb bbox_targets keep_inds num_classes return labels overlaps rois bbox_targets bbox_inside_weights
returns os path for show image,def __get_show_image_path data image_path os path join __settings__ getAddonInfo path resources media data image return image_path
tests is the stuff you get from yaml test_cache is the test result dictionary,def main tests test_cache languages for t in tests for l in languages if l not in test_cache get t expr test_cache setdefault t expr l run_test l t expr todel set test_cache t expr set languages for l in todel print sys stderr Deleting l del test_cache t expr l print out8 t name print out8 print out8 t desc print out8 print out8 u Search expression t expr u if pos_ex in t print out8 print out8 u Correct example print out8 print out8 u sdparse print out8 print out8 t pos_ex print out8 print out8 u print out8 if neg_ex in t print out8 print out8 u Incorrect example print out8 print out8 u sdparse print out8 print out8 t neg_ex print out8 print out8 u print out8 print out8 print out8 u a href t link u Link to documentation a print out8 print out8 u div id accordion class jquery ui accordion print out8 u div print out8 u span class doublewidespan style padding left 3em s span u Hit overview print out8 u span class widespan span print out8 u div print out8 u div if t expr startswith u _ hit_table test_cache t expr t expr elif expr pos in t hit_table test_cache t expr t expr pos else print out8 u Hits table not produced since the query does not start with the simple token spec _ Please add expr pos to the test which starts with _ that will be substituted for the various POS in the links print out8 u div for l in languages if test_cache t expr l hits 0 continue print out8 u div print out8 u span class doublewidespan style padding left 3em s span l print out8 u span class widespan d hits span test_cache t expr l hits print out8 u div print out8 u div q urllib urlencode db l search t expr print out8 a href http bionlp www utu fi dep_search query s dev Go to search a p q print out8 u div print out8 u div print out8 print out8
stop a virtual machine . @param label : vm uuid,def stop self label None ref self _get_vm_ref label vm self _get_vm_record ref if self _is_halted vm log warning Trying to stop an already stopped machine s label else try self session xenapi VM hard_shutdown ref except XenAPI Failure as e raise CuckooMachineError Error shutting down virtual machine s s label e details 0
get paths to local copy of eegbci dataset files,verbose def load_data subject runs path None force_update False update_path None base_url EEGMI_URL verbose None if not hasattr runs __iter__ runs runs data_paths for r in runs url u S s 03d S s 03d R r 02d edf format u base_url s subject r r data_paths extend data_path url path force_update update_path return data_paths
"returns the effective rate of reaction , accounting for diffusion . for 1<=>2 reactions , the reverse rate is limited . for 2<=>2 reactions , the faster direction is limited . for 2<=>1 or 2<=>3 reactions , the forward rate is limited .",def getEffectiveRate self reaction T intrinsicKinetics reaction kinetics reactants len reaction reactants products len reaction products k_forward intrinsicKinetics getRateCoefficient T P 10000000 0 Keq reaction getEquilibriumConstant T k_reverse k_forward Keq k_eff k_forward if reactants 1 if products 1 k_eff k_forward else k_diff self getDiffusionLimit T reaction forward False k_eff_reverse k_reverse k_diff k_reverse k_diff k_eff k_eff_reverse Keq elif products 1 or products 3 k_diff self getDiffusionLimit T reaction forward True k_eff k_forward k_diff k_forward k_diff elif Keq 1 0 k_diff self getDiffusionLimit T reaction forward True k_eff k_forward k_diff k_forward k_diff else k_diff self getDiffusionLimit T reaction forward False k_eff_reverse k_reverse k_diff k_reverse k_diff k_eff k_eff_reverse Keq return k_eff
evaluate the gradient of the log of the pdf at x.,def _eval_grad self x res scipy linalg cho_solve self L self mu x return res None
return a string of type for ` fieldname `,def typeof self fieldname return self _info fieldname 0
"runs /usr / sbin / softwareupdate to check for any available updates , and then returns any updates found with "" firm "" or "" efi "" in their names .",def check_software_update available_updates subprocess check_output usr sbin softwareupdate l split n if available_updates 4 return available_updates available_updates 5 available_updates item 5 for item in available_updates if item startswith firmware_updates item for item in available_updates if firm in item lower or efi in item lower return firmware_updates
unit test of listinstance ( ) with filter string .,def testListInstance_Filter self mock_api MagicMock name Mock Google Client API self gce_api GetApi MagicMock return_value mock_api mock_api instances return_value list return_value execute return_value items dummy list instance_list self gce_api ListInstances filter condition self assertEqual 1 self gce_api GetApi call_count mock_api instances return_value list assert_called_once_with project project name zone zone name filter filter condition mock_api instances return_value list return_value execute assert_called_once_with self assertEqual dummy list instance_list
run the hooks after the execution of the solver,def runPostHooks self if self opts runPostHook self hookmessage Running post hooks for h spec in iteritems self postHookInstances self executeHook h spec else self hookmessage Post hooks disabled pass
receives request from instance and updates load information .,def post self name self request get name load self request get load if not load load 0 force self request get force force_set None if force if int force force_set True else force_set False LoadInfo UpdateLoadInfo name int load force_set self response headers Content Type text plain self response out write ok
"check to see if the parent pid is 1 , and if it is , call pyro4.shutdown ( )",def ppidCheck server while True if 1 os getppid server shutdown break time sleep 5
test irr on unique distribution .,def test_irr3 d bivariates cat red i_rr d 0 1 2 assert red pytest approx 0
this computes unique information as min(delta(i(inputs : output ) ) ) where delta is taken over a restricted dependency decomposition which never constrains dependencies among the inputs .,def i_dep_c d inputs output var_to_index var i for i var in enumerate inputs output d d coalesce list sorted var_to_index keys key lambda k var_to_index k invars var_to_index var for var in inputs outvar var_to_index var for var in output measure I lambda d coinformation d invars outvar dd DependencyDecomposition d list var_to_index values measures measure uniques for input_ in inputs constraint var_to_index input_ var_to_index output edge_set edge for edge in dd edges constraint if tuple invars in edge 0 u min dd delta edge I for edge in edge_set uniques input_ u return uniques
"start resource binding , if allowed at this time . used internally .",def plugin self owner if not self sasl self bound return if self _owner Dispatcher Stream features try self FeaturesHandler self _owner Dispatcher self _owner Dispatcher Stream features except NodeProcessed pass else self _owner RegisterHandler features self FeaturesHandler xmlns NS_STREAMS self needsUnregister 1
updates data when modified in the view,def setData self index value role None if role Qt EditRole if index column 3 routeNum int index sibling index row 0 data self _editor routes routeNum initialState value self dataChanged emit index index return True return False
create a csv out of the sensor data then sends it to the client to be downloaded,login_required def download_csv request sensor_name from_date to_date payload from from_date to to_date size max_query_size headers create_headers request user data json loads requests get oauth_sensors_url sensor_name data headers headers params payload data add_time data response HttpResponse content_type text csv response Content Disposition attachment filename sensor_name csv writer csv writer response if error in data return HttpResponseForbidden writer writerow field name field unit if field unit is not None else no unit field type if field type is not None else no type for field in data properties fields if values in data properties for value in data properties values writer writerow value else writer writerow No data for the selected timespan from_date to_date return response
test if registry throws an error when not finding anything .,def test_class_not_found_error reg with pytest raises exc ClassNotFoundError reg get NonExistentClass
both try to insert lines in the same place .,def test_replace_clash self m3 Merge3 aaa 000 bbb aaa 111 bbb aaa 222 bbb self assertEquals m3 find_unconflicted 0 1 2 3 self assertEquals list m3 find_sync_regions 0 1 0 1 0 1 2 3 2 3 2 3 3 3 3 3 3 3
returns true if address is currently greylisted .,def address_greylisted cache addr subnet _addr_subnet addr if not subnet return None if cache exists ipgrey format utils sha512 subnet return True return False
convert a path to uri . the path will be made absolute and will not have quoted path parts .,def path_to_url path path os path normpath os path abspath path drive path os path splitdrive path filepath path split os path sep url join filepath if drive return file drive url return file url
test cloning a git repository from a non - editable url with a given tag .,pytest mark network def test_git_with_non_editable_unpacking script tmpdir result script pip install global option version local_checkout git https github com pypa pip test package git 0 1 2 egg pip test package tmpdir join cache expect_error True assert 0 1 2 in result stdout
datasets_tests : test the clearing of the data cache for a data set,def test_clear_cache self for dataset_name in dataset_selection print Remove data dataset_name pods datasets clear_cache dataset_name self assertFalse pods datasets data_available dataset_name
leave expert mode in testpointshared .,def leave_expert_mode self if self expert_mode try self prompt self app_prompt self execute_command self change_mode_command self expert_mode False except self prompt self expert_mode_prompt raise Exception Could not switch to regular mode
"enter loop , read user input then run command . repeat",def loop self while True text compat input ctl command args self parse_input text if not command continue response self call command args response show
delays a sequence by the given amount .,def delay sequences delay if delay 0 return for seq in sequences ct 0 while ct len seq 1 if seq ct ControlFlow Wait or seq ct ControlFlow Sync seq insert ct 1 TAPulse Id seq ct 1 channel delay 0 ct 1
give the managing editor 's journal form a full workout,def test_01_maned_review_success self fc formcontext JournalFormFactory get_form_context role admin source models Journal JOURNAL_SOURCE assert isinstance fc formcontext ManEdJournalReview assert fc form is not None assert fc source is not None assert fc form_data is None assert fc template is not None fc formcontext JournalFormFactory get_form_context role admin form_data MultiDict JOURNAL_FORM source models Journal JOURNAL_SOURCE assert isinstance fc formcontext ManEdJournalReview assert fc form is not None assert fc source is not None assert fc form_data is not None fc pre_validate fc form subject choices mock_lcc_choices assert fc validate fc form errors fc form2target assert fc target is not None fc patch_target assert fc target created_date 2000 01 01T00 00 00Z assert fc target id abcdefghijk_journal assert fc target current_application qwertyuiop related fc target related_applications assert len related 2 assert related 0 get application_id asdfghjkl assert related 0 get date_accepted 2018 01 01T00 00 00Z assert related 1 get application_id zxcvbnm assert related 1 get date_accepted is None fc finalise assert True
a slug that does n't match any sourcefiletype or moduleslug,def test_get_derived_slug_no_exist self with self assertRaises exceptions NoFileException as cm res self doc get_file foo self assertEqual cm exception message Cannot find a module with type foo
test that providing no parameter produces correct result .,pytest mark parametrize parameters None def test_format_operation_without_parameters parameters operation SELECT FROM TEST WHERE fuu bar assert format_operation operation parameters operation
creates a logging formatter with support for color messages,def format self record color ColorMessage levelname record levelname message logging Formatter format self record return color format_message levelname message
test to_knx function with normal operation .,def test_to_knx self xknx XKNX loop self loop remote_value RemoteValueColorRGB xknx self assertEqual remote_value to_knx 100 101 102 DPTArray 100 101 102 self assertEqual remote_value to_knx 100 101 102 DPTArray 100 101 102
convert current payload to value .,def from_knx self payload return self DPTMAP self value_type from_knx payload value
inform the recording thread that a new frame has arrived .,def newFrame self frame None if frame is None return self currentFrame frame with self lock if self recording self newFrames append frame self currentFrame dir self m getCurrentDir stack True self _stackSize 1 framesLeft len self newFrames if self recording if self frameLimit is not None and self _stackSize self frameLimit self frameLimit None self stopRecording return framesLeft
gets n solutions for an address .,def _eval self memory addr n kwargs return memory state se eval_upto addr n exact kwargs pop exact self _exact kwargs
check that invalid records do n't get loaded .,def test_load_from_msg_wrong self sr SummaryRecord invalid_values Month 0 Month 13 Year 2030 CpuDuration 123 WallDuration hello Site Null for key value in invalid_values sr load_from_msg self _records 1 sr _record_content key value self assertRaises InvalidRecordException sr get_msg
provide a standard presentation object .,def __init_presentation self self presentation Presentation handle_event_callbacks self _event_handlers
test context.__str _ _ method .,def test_004 self c nemo Context print str c c regions regions nsw print str c
"high - memory double extra large instance , 34.2 gb , 13 cpu ( 64-bit )",def double_extra_large_mem _64bit env instance_type m2 2xlarge
checks if a given matrix is of dia format .,def isspmatrix_dia x return isinstance x dia_matrix
call suite for an update .,def update self if self client is None self client SuiteRuntimeServiceClient self cfg suite self cfg owner self cfg host self cfg port self cfg comms_timeout self cfg my_uuid try my_state self client get_latest_state full_mode self full_mode except ClientError if cylc flags debug try traceback print_exc except IOError pass self set_stopped return if cylc flags debug sys stderr write s CONNECTED suite cylc version s n get_current_time_string my_state cylc_version self info_bar set_update_time None None if my_state full_mode gobject idle_add self app_window set_title s s s self cfg suite self client host self client port self full_mode False self connected True self set_status SUITE_STATUS_CONNECTED if my_state cylc_version CYLC_VERSION gobject idle_add self warn Warning cylc version mismatch Suite running with r gcylc at r my_state cylc_version CYLC_VERSION self stop_summary None self err_log_lines is_updated False if err_content in my_state and err_size in my_state self _update_err_log my_state is_updated True if ancestors in my_state self ancestors my_state ancestors is_updated True if ancestors_pruned in my_state self ancestors_pruned my_state ancestors_pruned is_updated True if descendants in my_state self descendants my_state descendants self all_families list self descendants is_updated True if summary in my_state and my_state summary 0 self _update_state_summary my_state is_updated True if self status in SUITE_STATUS_INITIALISING SUITE_STATUS_STOPPING gobject idle_add self info_bar prog_bar_start self status elif self is_reloading gobject idle_add self info_bar prog_bar_start reloading else gobject idle_add self info_bar prog_bar_stop if is_updated self update_interval 1 0 self last_update_time time elif time self last_update_time self update_interval self update_interval 1 0 if mean_main_loop_interval in my_state and my_state mean_main_loop_interval self update_interval self update_interval my_state mean_main_loop_interval if self update_interval self max_update_interval self update_interval self max_update_interval
provides an authed http object .,lru_cache def _get_http http httplib2 Http creds GoogleCredentials get_application_default create_scoped _FIREBASE_SCOPES creds authorize http return http
"> > > join_words(['hello ' , ' , ' , ' my ' , ' name ' , ' is ' , ' . ' ] ) ' hello , my name is . ' > > > join_words(['a ' , ' test ' , ' ( ' , ' for ' , ' parens ' , ' ) ' , ' ! ' ] ) ' a test ( for parens ) ! '",def join_words words return punctspace_re sub 1 spacepunct_re sub 1 join words
returns a reference to the line edit control .,def lineEdit self return self _txtOther
decorator that rolls back all open connections after fn execution .,decorator def rollback_open_connections fn args kw try fn args kw finally testing_reaper rollback_all
capture mouse release event when the user clicks to close the message,def eventFilter self watched e if QEvent is None return False if watched self lblClose and e type QEvent MouseButtonRelease self messageClosed emit self code self deleteLater return True else return QWidget eventFilter self watched e
util function for closing polygon by linking the last point to the first one .,def closePolygon self self _captureList append self _captureList 0
reads the rc config from the system .,def read self filename self filename if not os path isfile filename self _config else with open filename r as conf self _config yaml load conf read or wd_filename os path join os getcwd RC_FILE_NAME if os path isfile wd_filename with open wd_filename r as conf self _wd_config base_config BaseConfig yaml load conf read
"build testsuite to group tests based on labeling : param label : strings that should match a jobs 's platform , config , language , or test group",def __init__ self labels self triggers self labels labels
sets the terminal to the passed color . : param color : one of the availabe colors .,classmethod def set cls color u n Sets the terminal to the passed color n param color one of the availabe colors n sys stdout write cls colors get color cls colors u RESET
returns a list of instructions of the given ast node .,def my_visit self node if type node ast Module res for b in node body res res self my_visit_internal b return res else raise Exception Provided object of class str type node is not a Module instance
test adding storage instances to service .,def assess_add_storage client unit storage_type amount 1 client add_storage unit storage_type amount
return str of the rst text for the detail page of the file in info .,def make_detail_page info def a s append formatted s to output which will be joined into lines output append s format info output a title a len info title a n pic num image images examples dunder png n width 50 n align middle a n pic num a for paragraph in info enhanced_description for line in paragraph a line a last_lang py for fname in info files full_name slash info dir fname ext re search w fname group 0 a n _ full_name replace sep _ if in full_name full_name full_name replace sep sep 2 if ext in png jpg jpeg title Image full_name a n title a len title a n image examples full_name a align center else title File full_name a n title a len title if ext last_lang and ext txt a n highlight ext 1 a linenothreshold 3 last_lang ext elif ext txt a n highlight none a linenothreshold 3 last_lang ext a n include examples full_name a code return n join output n
validity check on user 's ' basic ' keybinding selection .,def KeysOK self keys self keyString get keys strip finalKey self listKeysFinal get ANCHOR modifiers self GetModifiers keySequence keys split keysOK False title Key Sequence Error if not keys tkMessageBox showerror title title parent self message No keys specified elif not keys endswith tkMessageBox showerror title title parent self message Missing the final Key elif not modifiers and finalKey not in self functionKeys self moveKeys tkMessageBox showerror title title parent self message No modifier key s specified elif modifiers Shift and finalKey not in self functionKeys self moveKeys Tab Space msg The shift modifier by itself may not be used with this key symbol tkMessageBox showerror title title parent self message msg elif keySequence in self currentKeySequences msg This key combination is already in use tkMessageBox showerror title title parent self message msg else keysOK True return keysOK
test that the semaphore is released after a successful trace edit .,def test_edit_successful self semaphore self tmp_base _get_semaphore assert semaphore value 1 self trace label _test_edit_label assert semaphore value 1
return a zone 's uri on the api .,def get_zone_uri zone return reverse zone_handler args zone name
call ` f ` with ` service ` running .,def callWithServiceRunning service f args kwargs d defer maybeDeferred service startService d addCallback call f args kwargs d addBoth callOut service stopService return d
create a physicalinterface for every macaddress in the database that is not associated with a interface .,def create_physical_interfaces MACAddress Interface Subnet Fabric VLAN macs find_macs_having_no_interfaces MACAddress previous_node 1 index 0 for mac in macs current_node mac node_id if current_node previous_node or current_node is None index 0 else index 1 now datetime datetime now iface Interface objects create mac mac type INTERFACE_TYPE PHYSICAL name eth str index vlan get_or_create_default_vlan Fabric VLAN created now updated now previous_node current_node ngi mac cluster_interface if ngi is not None and ngi subnet is not None subnet ngi subnet for ip in mac ip_addresses all if str ip ip in subnet cidr ip subnet subnet ip save update_interface_with_subnet_vlan iface subnet else for ip in mac ip_addresses all subnet Subnet objects get_best_subnet_for_ip ip ip if subnet is not None ip subnet subnet ip save update_interface_with_subnet_vlan iface subnet
use ` rndc - confgen ` ( from bind9utils ) to generate a rndc+named configuration .,def generate_rndc port 953 key_name rndc maas key include_default_controls True rndc_content call_and_check rndc confgen b 256 r dev urandom k key_name p str port encode ascii rndc_content rndc_content decode ascii named_comment extract_suggested_named_conf rndc_content named_conf uncomment_named_conf named_comment if include_default_controls named_conf DEFAULT_CONTROLS return rndc_content named_conf
is the bind server process still running ?,def is_running self if self process is None return False else return self process poll is None
display tags if they are available : tags : list : returns : bool,def display_tags tags print tags for e in tags print colorize msg e ty tags return True
"extract all members from the archive to the current working directory and set owner , modification time and permissions on directories afterwards . ` path ' specifies a different directory to extract to . ` members ' is optional and must be a subset of the list returned by getmembers ( ) .",def _extractall self path members None import copy import operator from tarfile import ExtractError directories if members is None members self for tarinfo in members if tarinfo isdir directories append tarinfo tarinfo copy copy tarinfo tarinfo mode 448 self extract tarinfo path if sys version_info 2 4 def sorter dir1 dir2 return cmp dir1 name dir2 name directories sort sorter directories reverse else directories sort key operator attrgetter name reverse True for tarinfo in directories dirpath os path join path tarinfo name try self chown tarinfo dirpath self utime tarinfo dirpath self chmod tarinfo dirpath except ExtractError e sys exc_info 1 if self errorlevel 1 raise else self _dbg 1 tarfile s e
remove all ansi control sequences from the output,def scrub_output output ansi_escape re compile x1b m m return ansi_escape sub output
"euclidean distance matrix between rows of arrays ` a ` and ` b ` . equivalent to ` scipy.spatial.distance.cdist(a , b , ' euclidean ' ) ` . returns a.shape[0 ] x b.shape[0 ] array .",def distance_matrix a b assert a shape 1 b shape 1 Inner dimensions do not match distm np zeros a shape 0 b shape 0 for i in range a shape 0 distm i np linalg norm a i b axis 1 return distm
will be useful when we need to get content from url,def get_content path ui None u if content_type path u url return _get_byte_url_content path ui ui decode encoding u utf 8 else return read_text_file path
force name to be global in scope .,def force_global self name self globals name 1 if name in self frees del self frees name for child in self children if child check_name name SC_FREE child force_global name
read a file and parse its contents into a message object model .,def message_from_file fp args kws from email parser import Parser return Parser args kws parse fp
return whether process is a daemon,property def daemon self return self _daemonic
make sure 2d fft satisfies parseval 's relation within machine double precision,def test_parseval self rtol 1e 15 p1 np random randn self m nz self m ny self m nx p1 p1 mean axis 2 1 np newaxis np newaxis ph1 self m fft p1 P_var_spec spec_var self m ph1 P_var_phys p1 var axis 2 1 error np abs P_var_phys P_var_spec P_var_phys sum print error 5 16f error self assertTrue error rtol fft does not satisfy Parseval s relation
this solely exists to allow timedelta.timedelta's keyword argument ( minutes / seconds / hours= ... ) to be selected with a variable .,def get_timedelta extra_kw_args return datetime timedelta extra_kw_args
called by pacman game at the terminal state,def final self state u n Called by Pacman game at the terminal state n deltaReward state getScore self lastState getScore self observeTransition self lastState self lastAction state deltaReward self stopEpisode if not u episodeStartTime in self __dict__ self episodeStartTime time time if not u lastWindowAccumRewards in self __dict__ self lastWindowAccumRewards 0 0 self lastWindowAccumRewards state getScore NUM_EPS_UPDATE 100 if self episodesSoFar NUM_EPS_UPDATE 0 print u Reinforcement Learning Status windowAvg old_div self lastWindowAccumRewards float NUM_EPS_UPDATE if self episodesSoFar self numTraining trainAvg old_div self accumTrainRewards float self episodesSoFar print u tCompleted d out of d training episodes self episodesSoFar self numTraining print u tAverage Rewards over all training 2f trainAvg else testAvg old_div float self accumTestRewards self episodesSoFar self numTraining print u tCompleted d test episodes self episodesSoFar self numTraining print u tAverage Rewards over testing 2f testAvg print u tAverage Rewards for last d episodes 2f NUM_EPS_UPDATE windowAvg print u tEpisode took 2f seconds time time self episodeStartTime self lastWindowAccumRewards 0 0 self episodeStartTime time time if self episodesSoFar self numTraining msg u Training Done turning off epsilon and alpha print u s n s msg u len msg
initialises a new ' grounddisconnector ' instance .,def __init__ self args kw_args super GroundDisconnector self __init__ args kw_args
initialises a new ' powertransformerinfo ' instance .,def __init__ self TransformerTankInfo None args kw_args self _TransformerTankInfo self TransformerTankInfo if TransformerTankInfo is None else TransformerTankInfo super PowerTransformerInfo self __init__ args kw_args
initialises a new ' coordinatesystem ' instance .,def __init__ self crsUrn Location None args kw_args self crsUrn crsUrn self _Location self Location if Location is None else Location super CoordinateSystem self __init__ args kw_args
initialises a new ' businesscase ' instance .,def __init__ self corporateCode Projects None Works None args kw_args self corporateCode corporateCode self _Projects self Projects if Projects is None else Projects self _Works self Works if Works is None else Works super BusinessCase self __init__ args kw_args
initialises a new ' electronicaddress ' instance .,def __init__ self password email radio userID lan web status None args kw_args self password password self email email self radio radio self userID userID self lan lan self web web self status status super ElectronicAddress self __init__ args kw_args
the power flow state associated with the terminal .,def getSvPowerFlow self return self _SvPowerFlow
measurement to which this value is connected .,def getDiscrete self return self _Discrete
conductor phase impedance to which this data belongs .,def getPhaseImpedance self return self _PhaseImpedance
wire type used for this wire arrangement .,def getWireType self return self _WireType
an identifiedobject belongs to a modeling authority set for purposes of defining a group of data maintained by the same modeling authority .,def getModelingAuthoritySet self return self _ModelingAuthoritySet
handle the file path changing .,def on_path self new self name basename new self graph self editor_input load
plot a multi panel plot fo gc / cov data,def plot_gc_cov gc_cov max_cov 60 title GC cov from matplotlib colors import LogNorm seq gc_cov seq_info fig plt figure figsize 12 8 rows cols 4 6 gc_lim 0 0 1 0 cov_lim 0 0 max_cov for row in range rows for col in range cols if row cols col len seq 1 break sn seq row cols col SN ax plt subplot rows cols row cols col 1 x y gc_cov sn gc gc_cov sn coverage x y x np isnan x np isnan y y np isnan x np isnan y ax hist2d x y bins 71 range gc_lim cov_lim cmap plt cm gray_r norm LogNorm plt title sn plt setp ax xlim gc_lim ylim cov_lim if row rows 1 and col 0 ax set_xlabel GC content ax set_ylabel Coverage else ax get_xaxis set_visible False ax get_yaxis set_visible False fig suptitle title
set model . : param model :,def set_model self model self proxy set_model model self model model
pymt usage : % s [ option ... ] : :,def pymt_usage print pymt_usage __doc__ os path basename sys argv 0
"on entry , this function assumes that all processes have a "" ppid "" field containing the pid of their parent process .",def resolve_links processes now for process in processes values process children set if 0 not in processes kernel_process create_kernel_process now processes 0 kernel_process for process in processes values if process pid 0 process parent None else process parent processes process ppid process parent children add process
evaluate an exec - compatible string in a specific environment .,def runctx self cmd globals locals code compile cmd string exec self _prof runcode code globals locals return self
"close the current file so that the next iteration will read the first line from the next file ( if any ) ; lines not read from the file will not count towards the cumulative line count . the filename is not changed until after the first line of the next file has been read . before the first line has been read , this function has no effect ; it can not be used to skip the first file . after the last line of the last file has been read , this function has no effect .",def nextfile if not _state raise RuntimeError no active input return _state nextfile
test whether a path is a mount point ( defined as root of drive ),def ismount path unc rest splitunc path if unc return rest in p splitdrive path 1 return len p 1 and p 0 in
"formats a blender matrix object for export , and transposes it so gl - matrix can use it correctly .",def format_matrix matrix target_matrix matrix copy target_matrix transpose matrix_builder Float16Array period 4 for vector in target_matrix to_4x4 matrix_builder add_vector vector return matrix_builder export
list of servers of types besides unknown .,property def known_servers self return s for s in self _server_descriptions values if s is_server_type_known
update fields in given slice object . see generic update _ * method description above .,def update_slice slice_urn credentials options raise GFedv1NotImplementedError Method not implemented
presents information about the metacity status bar .,def presentStatusBar self obj speech stop objName obj name if objName and len objName if objName 0 and objName 1 objName objName 1 1 try text obj name except text objName self displayBrailleMessage text speech speak text
returns an array of sounds indicating the toggled state of obj .,def _generateToggleState self obj args if not _settingsManager getSetting playSoundForState return filenames super _generateToggleState obj args result list map self _convertFilenameToIcon filenames if result return result return
"excecutes the given command while transfering control , till the execution is complete .",def run command kwargs print command p Popen shlex split command kwargs p wait return p returncode
the derivative of the covariance matrix with respect to i - th hyperparameter .,def Kgrad_theta self theta x1 i sigma SP exp 2 theta i Knoise SP diag 2 sigma 1 0 x1 self column i return Knoise
filter out stale usercourses that we do n't want to display .,classmethod def get_publicly_visible cls min_num_ucs 0 num_days None return util publicly_visible_ratings_and_reviews_filter cls objects get_user_course_modified_date min_num_ucs num_days
returns the list of possible drivers .,def get_parser_list self return self parsers
function : < number > number(<object > ? ),def Number context object None if object is None object context node return Conversions NumberValue object
"run shell command in subprocess args : cmd : shell command ignore_stderr_when_ok : when ignore_stderr_when_ok is true , ignoring the msg from stderr if run successfully return : ( shell_cmd_retcode , shell_cmd_msg ) ( -1 , shell_cmd_msg ) or ( 0 , shell_cmd_msg )",def RunCommand cmd ignore_stderr_when_ok False try if not ignore_stderr_when_ok t subprocess Popen cmd stdout subprocess PIPE stderr subprocess STDOUT shell True else t subprocess Popen cmd stdout subprocess PIPE stderr subprocess PIPE shell True msg err t communicate retcode t wait if retcode 0 and ignore_stderr_when_ok msg n str err except BaseException as e retcode 1 msg run_shell_cmd_in_subprocess Exception for s s str cmd e return retcode msg
get the grid layout specifier for the given figure using the given number of plots .,def get_gridspec self figure nmr_plots
present a single tiddler from a given tank .,def wiki_page environ start_response tank_name get_route_value environ bag_name store environ tiddlyweb store usersign environ tiddlyweb usersign config environ tiddlyweb config try bag store get Bag tank_name bag augment_bag store bag except NoBagError raise HTTP404 no tank found for s tank_name try tiddler_name get_route_value environ tiddler_name except KeyError AttributeError raise HTTP302 tank_page_uri environ tank_name INDEX_PAGE if tiddler_name in SPECIAL_PAGES return SPECIAL_PAGES tiddler_name environ start_response bag policy allows usersign read editable True creatable True deletable True try bag policy allows usersign write except PermissionsError editable False try bag policy allows usersign create except PermissionsError creatable False try bag policy allows usersign delete except PermissionsError deletable False try tiddler Tiddler tiddler_name tank_name tiddler store get tiddler except NoTiddlerError tiddler type text x markdown tiddler text This tiddler does not yet exist n if creatable editable True else editable False deletable False if tiddler title INDEX_PAGE sisterlinks get_sisterlinks environ tiddler tiddler text tiddler text n Other tiddlers with similar names n join s s s stiddler title stiddler bag stiddler bag for stiddler in sisterlinks if renderable tiddler environ backlinks get_backlinks environ tiddler rellinks get_rellinks environ tiddler compable full_search config id s app tank_name html render_wikitext tiddler environ start_response 200 OK Content Type text html charset UTF 8 Cache Control no cache return send_template environ WIKI_TEMPLATE tiddler tiddler html html bag bag backlinks backlinks create creatable edit editable delete deletable compable compable links rellinks else return tiddler_get environ start_response
retrieve all shot asset instances linked to asset .,jwt_required def get self asset_id asset assets_service get_asset asset_id user_service check_project_access asset project_id return breakdown_service get_shot_asset_instances_for_asset asset_id
compute nearest neighbours from abstracts to definitions .,def compute_nearest_neighbours definitions abstracts output for k v in abstracts items results labels vectors dict_to_tuple v try targets matrix dict_to_tuple definitions k except KeyError continue matrix Reach normalize np asarray matrix vectors Reach normalize np asarray vectors for vec in vectors result vec dot matrix T results append targets np argsort result 0 output k list zip labels results return output
this function creates a symlink from the backup to the live www directory for the server to run the app from .,def link_to_live run ln sf T backup_project_full_path s archive project_name s project_version s live_project_full_path s env
collect the tags from all base classes .,class_lazy def _class_tags cls u n Collect the tags from all base classes n class_tags set for base in cls mro 1 class_tags update getattr base u _class_tags set return class_tags
print the current stack configuration .,cli command pass_ctx def config ctx click echo dump ctx config default_flow_style False
"load in a serialized value , overwriting any previous values .",def loads self value self from_dict json loads value encoding utf 8
creates a cronjob object from a database result row .,def _CronjobFromRow self row job create_time disabled forced_run_requested last_run_status last_run_time current_run_id state leased_until leased_by row del forced_run_requested job rdf_cronjobs CronJob FromSerializedString job job current_run_id current_run_id job disabled disabled job last_run_status last_run_status job last_run_time mysql_utils MysqlToRDFDatetime last_run_time if state job state rdf_protodict AttributedDict FromSerializedString state job create_time mysql_utils MysqlToRDFDatetime create_time job leased_until mysql_utils MysqlToRDFDatetime leased_until job leased_by leased_by return job
read and lease some outstanding message handler requests .,utils Synchronized def _LeaseMessageHandlerRequests self lease_time limit leased_requests now rdfvalue RDFDatetime Now zero rdfvalue RDFDatetime FromSecondsSinceEpoch 0 expiration_time now lease_time leases self message_handler_leases for requests in self message_handler_requests values for r in requests values existing_lease leases get r handler_name get r request_id zero if existing_lease now leases setdefault r handler_name r request_id expiration_time r leased_until expiration_time r leased_by utils ProcessIdString leased_requests append r if len leased_requests limit break return leased_requests
returns a message instance corresponding to a given type url .,def TypeUrlToMessage type_url if not type_url startswith TYPE_URL_PREFIX raise ValueError Type URL has to start with a prefix s s TYPE_URL_PREFIX type_url full_name type_url len TYPE_URL_PREFIX try return symbol_database Default GetSymbol full_name except KeyError as e raise ProtobufTypeNotFound e message
returns feature at given location or none .,def _get_feature feature_db point for feature in feature_db if feature location point return feature return None
set the detection result and calculate the state information mean for normal state,def set_detect_result self detect_result assert len detect_result self detect_num self ano_free_idx i for i in xrange self detect_num if not detect_result i self norm_state_info_mean mean si self ano_free_idx for si in self state_info
join the ( previously split ) network halves together .,def join_network self assert self is_network_split stop_nodes self nodes self setup_network False
reads a fits file and returns a 2d numpy array of the data . use hdu to specify which hdu you want ( default = primary = 0 ),def fromfits infilename hdu 0 verbose True if verbose print Reading s os path basename infilename pixelarray hdr pyfits getdata infilename hdu header True pixelarray np asarray pixelarray transpose pixelarrayshape pixelarray shape if verbose print FITS import i i BITPIX s s pixelarrayshape 0 pixelarrayshape 1 hdr BITPIX str pixelarray dtype name return pixelarray hdr
return a function with a given _ _ name__.,def function_named fn name try fn __name__ name except TypeError fn types FunctionType fn __code__ fn __globals__ name fn __defaults__ fn __closure__ return fn
assign an issue to a user,click argument user required False click argument issue_key cli command click pass_obj def assign client issue_key user if user is None user client username client assign issue_key user click echo has been assigned to format issue_key user
creates and returns the argparse parser object .,def getParser parser argparse ArgumentParser description __description__ parser add_argument input help the input image parser add_argument output help the output image parser add_argument spacing type argparseu sequenceOfFloatsGt help the desired voxel spacing in colon separated values e g 1 2 1 2 5 0 parser add_argument o order type int default 2 dest order help the bspline order default is 2 means nearest neighbours see also medpy_binary_resampling py parser add_argument v verbose dest verbose action store_true help verbose output parser add_argument d dest debug action store_true help Display debug information parser add_argument f force dest force action store_true help overwrite existing files return parser
get actual numhostsessions @rtype : int @return : the number of host sessions,def numHostSessions pass
show the stderr of the most recently executed moa job,moa args needsJob moa args doNotLog moa args command def err job args err moa actor getLastStderr job if err None moa ui exitError No stderr found else print err
retrieve state variable from database .,def x self dt models data db dbio connect models dbname cur db cursor for s in self statevar sql select ensemble st_x geom st_y geom val from select ensemble ST_PixelAsCentroids rast from 0 1 where fdate date 2 3 4 foo group by ensemble geom order by ensemble format models name s dt year dt month dt day cur execute sql e lon lat vals zip cur fetchall gid models 0 lgid l 0 l 1 for l in zip lat lon nens max e data s np array vals reshape len vals nens nens lat np array lat reshape len lat nens nens lon np array lon reshape len lon nens nens gid np array gid reshape len gid nens nens cur close db close return data lat lon gid
compute the rectified linear unit function inplace .,def relu X np clip X 0 np finfo X dtype max out X return X
get the job identified by the uuid,def get_job self uuid return RemoteJob self address self port uuid uuid
will create a new list of random candidate solutions of the specified number given the context of the cantus_firmus .,def create_population number cantus_firmus result for i in range number new_chromosome for note in cantus_firmus valid_first_beat_range interval for interval in VALID_FIRST_BEAT_INTERVALS if interval note 17 valid_third_beat_range interval for interval in VALID_THIRD_BEAT_INTERVALS if interval note 17 first_beat_interval random choice valid_first_beat_range third_beat_interval random choice valid_third_beat_range new_chromosome append note first_beat_interval new_chromosome append note third_beat_interval genome Genome new_chromosome 1 result append genome return result
accept a filter dom element and checks if it 's a mac spoofing filter,def isMacSpoofingFilter filterElement filterValue filterElement getAttribute filter return filterValue vdsm no mac spoofing
called when assigning a value to a property .,def __set__ self obj value if self required and value is None raise ValueError Property s is required self name if value is not None value self validate value obj __dict__ self name value
service - status service - name get status of a system service .,expose service status def service_status_command cmdName args if len args 1 raise ExtraArgsError 1 return service_status args 0
check that assigning to a cons works as expected,def test_cons_replacing cons HyCons foo bar cons 0 car assert cons HyCons car bar cons 1 cdr assert cons HyCons car cdr try cons foo assert True is False except IndexError pass
get request form data or body and validate it against a schema .,def parse_request schema many None if request is_json data request get_json else data request form to_dict flat True return validate_data data schema many many
": param filterstring : : type filterstring : unicode : return : : rtype : tuple [ int , list [ filter ] ]",def readEncoded db sub_id filterString filters fstrings filterString split ds_match re search d fstrings 0 if ds_match ds int ds_match group else settings_model Settings db sub_id ds settings_model datasource for encodedFilter in fstrings 1 try params encodedFilter split typeIndex enabled params params 0 params 1 params 2 enabled enabled 1 filterClass filterTypes int typeIndex f filterClass enabled params filters append f except print ERROR unable to decode filter encodedFilter return ds filters
"edit custom examples for the given program , creating the file if it does not exist .",def edit_custom_examples program config if not config custom_dir or not os path exists config custom_dir _inform_cannot_edit_no_custom_dir return resolved_program get_resolved_program program config custom_file_paths get_file_paths_for_program resolved_program config custom_dir if len custom_file_paths 0 path_to_edit custom_file_paths 0 else path_to_edit os path join config custom_dir resolved_program md subprocess call config editor_cmd path_to_edit
retrieve the node1 object from the edge .,def get_node1 self return self edge get_node1
registers a box to the collection,def register_box self box if box not in self _boxes self _boxes append box
schedule for reorg operator . parameters ---------- outs : array of tensor the computation graph description of reorg in the format of an array of tensors .,generic schedule_reorg register cuda gpu def schedule_reorg outs target tvm target current_target allow_none False cpp_target cpp TEST_create_target target target_name return cpp cuda schedule_injective cpp_target outs
helper to clear non referenced params,def _remove_noref_params params graph arg_list set graph symbol list_input_names if params param_keys list params keys for key in param_keys if key not in arg_list params pop key
"execute specified script with command matlab , with default options "" -nodisplay -r "" . this action accepts common action arguments such as input , active , workdir , docker_image and args . in particular , content of one or more files specified by option input would be prepended before the specified script .",SoS_Action acceptable_args script args def octave script args kwargs return SoS_ExecuteScript script octave m args run kwargs
assert an expression ( given as a string ) is in dnf .,def assert_is_dnf self expr_str self assertTrue BooleanExpression expr_str is_dnf
test an expression of only a single constant value .,def test_single_constant_value self self helper_test_evaluate 0 expected_result 0 self helper_test_evaluate 1 expected_result 1
cleans up all the temporary files .,def __cleanup self try shutil rmtree self tmpdir except logger info Problem removing temporary files The files are probably in use
returns the last component of the name .,def get_short_name fq_name return fq_name split 1 0
a sitemap should only show objects associated with the current site .,unittest skipUnless django contrib sitemaps in settings INSTALLED_APPS Sitemaps not installed in this project nothing to test def test_sitemap self response self client get sitemap xml self assertContains response url loc http example com ptests photo test photo loc lastmod 2011 12 23 lastmod url self assertNotContains response url loc http example com ptests photo not on site photo loc lastmod 2011 12 23 lastmod url self assertContains response url loc http example com ptests gallery test gallery loc lastmod 2011 12 23 lastmod url self assertNotContains response url loc http example com ptests gallery not on site gallery loc lastmod 2011 12 23 lastmod url
is true when `` argument `` is an iterable collection of nonnegative integers .,def all_are_nonnegative_integers argument from abjad import mathtools try return all mathtools is_nonnegative_integer _ for _ in argument except TypeError return False
initialize interval set from component selection :,classmethod def from_selection class_ selection item_class None Initialize interval set from component selection container example staff_1 abjad Staff c 4 d fs a 4 b2 staff_2 abjad Staff c4 r8 g2 staff_group abjad StaffGroup staff_1 staff_2 abjad show staff_group doctest SKIP docs abjad f staff_group new StaffGroup new Staff c 4 d fs a 4 b2 new Staff c4 r8 g2 interval_classes abjad IntervalClassSet from_selection staff_group for interval_class in sorted interval_classes interval_class NamedIntervalClass M6 NamedIntervalClass P5 NamedIntervalClass A4 NamedIntervalClass M3 NamedIntervalClass m3 NamedIntervalClass M2 NamedIntervalClass m2 NamedIntervalClass M2 NamedIntervalClass m3 NamedIntervalClass M3 NamedIntervalClass P4 NamedIntervalClass A4 NamedIntervalClass P5 NamedIntervalClass M6 NamedIntervalClass m7 NamedIntervalClass M7 NamedIntervalClass P8 Returns interval set import abjad interval_set abjad IntervalSet from_selection selection return class_ items interval_set item_class item_class
insert works with really big negative values .,def test_Container_insert_06 voice abjad Voice c 8 d 8 e 8 f 8 beam abjad Beam abjad attach beam voice voice insert 1000 abjad Rest 1 8 assert abjad inspect voice is_well_formed assert format voice abjad String normalize new Voice r8 c 8 d 8 e 8 f 8
string representation of this model objects .,def __str__ self return self title or
opens all tfrecord shards for writing and adds them to an exit stack .,def open_sharded_output_tfrecords exit_stack base_path num_shards tf_record_output_filenames 05d of 05d format base_path idx num_shards for idx in range num_shards tfrecords exit_stack enter_context tf python_io TFRecordWriter file_name for file_name in tf_record_output_filenames return tfrecords
create a dictionary that is keyed by spl_set_id .,def read_harmonized_file harmonized_file spl_set_id_to_harmonized for row in read_json_file harmonized_file set_id row spl_set_id if set_id in spl_set_id_to_harmonized spl_set_id_to_harmonized set_id append row else spl_set_id_to_harmonized set_id row return spl_set_id_to_harmonized
"average frequency spacing for bending waves . valid when : math:`f < < c_{l,\phi } / 4 \pi \kappa ` .",property def average_frequency_spacing self Average frequency spacing for bending waves Valid when math f c_ L phi 4 pi kappa rtype class numpy ndarray math overline delta f _B 1D frac c_ B phi 1D L See Lyon eq 8 1 10 return self soundspeed_group self component length
creates an object that describes a c++ namespace declaration .,def __init__ self name declarations None scopedef scopedef_t __init__ self name if not declarations declarations self _declarations declarations
tests manipulating list of paths in the environment .,def test_path_manipulation env env append_path PATH_LIST path last env prepend_path PATH_LIST path first env append_path EMPTY_PATH_LIST path middle env append_path EMPTY_PATH_LIST path last env prepend_path EMPTY_PATH_LIST path first env append_path NEWLY_CREATED_PATH_LIST path middle env append_path NEWLY_CREATED_PATH_LIST path last env prepend_path NEWLY_CREATED_PATH_LIST path first env remove_path REMOVE_PATH_LIST remove this env remove_path REMOVE_PATH_LIST duplicate env apply_modifications expected path first path second path third path last assert os environ PATH_LIST expected expected path first path middle path last assert os environ EMPTY_PATH_LIST expected expected path first path middle path last assert os environ NEWLY_CREATED_PATH_LIST expected assert os environ REMOVE_PATH_LIST a b a c a d f g
fit null model trait by trait,def fitNullTraitByTrait self verbose False cache False out_dir cache fname None rewrite False read_from_file False if cache assert fname is not None MultiTraitSetTest specify fname if not os path exists out_dir os makedirs out_dir out_file os path join out_dir fname read_from_file os path exists out_file and not rewrite RV if read_from_file f h5py File out_file r for p in range self P trait_id self traitID p g f trait_id RV trait_id for key in list g keys RV trait_id key g key f close self nullST RV else create stSet and fit null column by column returns all info if self stSet is None y sp zeros self N 1 self stSet MTSet Y y S_R self S_R U_R self U_R F self F RV for p in range self P trait_id self traitID p self stSet Y self Y p p 1 RV trait_id self stSet fitNull self nullST RV if cache f h5py File out_file w smartDumpDictHdf5 RV f f close return RV
decodes the specified graph record .,def decode_record self buff kmer buff 0 8 offset 8 coverages struct unpack_from I self num_colours buff offset offset self num_colours 4 edges struct unpack_from B self num_colours buff offset record CortexRecord self kmer_size kmer coverages edges num_colours self num_colours binary_kmer self binary_kmers return record
"this is a main view called by other views that aim to render forms for transmitters , locations , targets , and deployments",def render_wizard_project_formset request project_id post_formset get_formset template_path success_url redirect_bool True extra_context None user request user project get_project project_id nav_options get_nav_options request thereis_newelement None if can_change project user if request method POST formset post_formset for form in formset form set_project project if formset is_valid saved_objects formset save if redirect_bool return redirect success_url else return saved_objects elif request method GET thereis_newelement request GET get new_element formset get_formset for form in formset form set_project project context formset formset nav_options nav_options changed thereis_newelement project project current_form txIDs targetIDs if extra_context None if isinstance extra_context dict context update extra_context else raise TypeError Passed in non dict for extra_context in render_project_formset return render request template_path context else return not_allowed_page request
bool determining whether script plays media,property def plays_media self patt play_pcap_audio if not self scen_file return False with open self scen_file r as sf return bool re search patt sf read
remove verifier result from a rule decommission for a task . need to use it when trying to put rule decommission task with verifier result,def remove_verifier_result self self verifier_result None
fetch usage for a list of prefixes,def fetch_usages prefixes starttime endtime if prefixes is None prefixes return fetch_usage prefix starttime endtime for prefix in prefixes
retrieves the forwarding databases of the device,defer inlineCallbacks def get_forwarding_database self columns yield self retrieve_columns dot1qTpFdbPort dot1qTpFdbStatus columns self translate_result columns valid row for row in columns values if row dot1qTpFdbStatus not in self invalid result for row in valid index row 0 _fdb_id index 0 mac index 1 mac join 02x o for o in mac 6 port row dot1qTpFdbPort result append mac port defer returnValue result
creates a table cell based on ip,def _create_cell self ip meta rowspan 1 key 0 return Cell prefixid meta prefixid colspan self _colspan ip rowspan rowspan content self _get_content key ip dataurl self _get_prefix_url ip netaddr ip
"yields new peaks split from peak at split_points = sample indices within peak samples at the split points will fall to the right ( so if we split [ 0 , 5 ] on 2 , you get [ 0 , 1 ] and [ 2 , 5 ] ) . hits that straddle a split point are themselves split into two hits : peak.hits is updated .",def split_peak self peak split_points hits peak hits for x in split_points x peak left selection hits left x hits right x hits_to_split hits selection new_hits hits True selection for h in hits_to_split pulse_i h found_in_pulse pulse self event pulses pulse_i baseline_to_subtract self config digitizer_reference_baseline pulse baseline w baseline_to_subtract pulse raw_data astype np float64 hits_buffer np zeros 2 dtype datastructure Hit get_dtype adc_to_pe dsputils adc_to_pe self config h channel hit_bounds np array h left x x 1 h right dtype np int64 hit_bounds pulse left build_hits w hit_bounds hit_bounds hits_buffer hits_buffer adc_to_pe adc_to_pe channel h channel noise_sigma_pe pulse noise_sigma adc_to_pe dt self config sample_duration start pulse left pulse_i pulse_i saturation_threshold self config digitizer_reference_baseline pulse baseline 0 5 central_bounds hit_bounds hits_buffer hits_buffer hits_buffer area 0 new_hits append hits_buffer hits np concatenate new_hits boundaries list zip 0 y 1 for y in split_points split_points float inf for left right in boundaries left peak left right peak left hs hits hits index_of_maximum left hits index_of_maximum right if not len hs self log info Localminimumclustering requested creation of peak s s without hits This is a possible outcome if there are large oscillations in one channel but it should be very rare left right continue right right if right float inf else peak right if not len hs raise RuntimeError Attempt to create a peak without hits in LocalMinimumClustering yield self build_peak hits hs detector peak detector left left right right
return list of logged light sensor resistances .,def get_log self r_log super get_log_raw return _int2r i for i in r_log
"merge a collection , with functions as items , into a single function that takes a collection and maps its items through corresponding functions .",def merge arg rest kwargs ensure_keyword_args kwargs optional default has_default default in kwargs if has_default default ensure_callable kwargs default unary_result True if rest fs ensure_callable arg tuple imap ensure_callable rest unary_result False else fs arg if is_mapping fs if has_default return lambda arg_ fs __class__ k fs get k default arg_ k for k in arg_ else return lambda arg_ fs __class__ k fs k arg_ k for k in arg_ else ensure_sequence fs if has_default func lambda arg_ fs __class__ fs i if i len fs else default x for i x in enumerate arg_ else func lambda arg_ fs __class__ fs i x for i x in enumerate arg_ return func if unary_result else lambda args func args
erases all information encrypted or protected under the key kw by destroying kw .,def delete request finalize False try w getParams request w except ServiceException as e return e errorResponse dropStateEntry w d status OK message Operation complete return JsonResponse d
load up what we know about these traffic sites,def load_metadata meta cur DBCONN cursor cursor_factory psycopg2 extras DictCursor cur execute SELECT from rwis_soil_data rows cur fetchall cur close for row in rows key s_ s row location_id row sensor_id meta key True return meta
get the raw infromations we need,def get_context fdict pgconn get_dbconn coop cursor pgconn cursor cursor_factory psycopg2 extras DictCursor today datetime date today thisyear today year ctx get_autoplot_context fdict get_description year ctx year station ctx station varname ctx var half ctx half table alldata_ s station 2 nt NetworkTable sCLIMATE station 2 startyear int nt sts station archive_begin year data np ma ones thisyear startyear 1 366 199 if half fall cursor execute SELECT extract doy from day year n varname from table WHERE station s and low is not null and high is not null and year s station startyear else cursor execute SELECT extract doy from day year n varname from table WHERE station s and high is not null and low is not null and year s station startyear for row in cursor data int row 1 startyear int row 0 1 row 2 data mask np where data 199 True False doys avg p25 p2p5 p75 p97p5 mins maxs dyear idx year startyear last_doy int today strftime j if half fall for doy in range 181 366 low np ma min data 1 180 doy 1 avg append np ma average low mins append np ma min low maxs append np ma max low p np percentile low 2 5 25 75 97 5 p2p5 append p 0 p25 append p 1 p75 append p 2 p97p5 append p 3 doys append doy if year thisyear and doy last_doy continue dyear append np ma min data idx 180 doy else for doy in range 1 181 low np ma max data 1 doy 1 avg append np ma average low mins append np ma min low maxs append np ma max low p np percentile low 2 5 25 75 97 5 p2p5 append p 0 p25 append p 1 p75 append p 2 p97p5 append p 3 doys append doy if year thisyear and doy last_doy continue dyear append np ma max data idx doy d dict doy pd Series doys mins pd Series mins maxs pd Series maxs p2p5 pd Series p2p5 p97p5 pd Series p97p5 p25 pd Series p25 p75 pd Series p75 avg pd Series avg thisyear pd Series dyear df pd DataFrame d sts datetime date 2000 1 1 datetime timedelta days doys 0 1 df dates pd date_range sts periods len doys df set_index doy inplace True ctx df df ctx year year ctx half half if ctx half fall title Minimum Daily s Temperature after 1 July else title Maximum Daily s Temperature before 1 July title title varname capitalize ctx ylabel title ctx title s s s s n s startyear thisyear 1 station nt sts station name title return ctx
get a sequence of objects representing the rows,def get_rows self return self rows
"used to mark template blocks for swagger / openapi output . if the specified method matches the * current * method in swagger / openapi generation , show the block . otherwise , the block is omitted .",register tag name ifmeth def ifmeth parser token allowed_methods m upper for m in token split_contents 1 nodelist parser parse endifmeth parser delete_first_token return MethodFilterNode allowed_methods nodelist
decorates a function with a deprecated or experimental annotation .,def annotate label since current extra_message def _annotate fnc wraps fnc def inner args kwargs if label deprecated warning_type DeprecationWarning else warning_type FutureWarning message s is s fnc __name__ label if label deprecated message since s since message Use s instead current if current else if extra_message message extra_message warnings warn message warning_type stacklevel 2 return fnc args kwargs return inner return _annotate
connects to a remote tcp server usage : connect [ --port < port > ] ip use adb forward tcp:12346 tcp:12346 when using an emulator or usb - connected device,def do_connect self args try parser argparse ArgumentParser prog connect add_help False parser add_argument ip parser add_argument port p metavar port splitargs parser parse_args shlex split args if not splitargs return ip splitargs ip if splitargs port port int splitargs port else port 12346 self session Server ip port bind self session sendData ping n resp self session receiveData if resp pong print Connected self prompt Afe self connected 1 else print Not Connected There is some Problem Try Again except pass
this function pales the color a bit for the interior of the boxes .,def whiter_shade_of_pale hex_color pale_shift 70 r_hex hex_color 1 3 g_hex hex_color 3 5 b_hex hex_color 5 7 r_dec int r_hex 16 g_dec int g_hex 16 b_dec int b_hex 16 r_dec min 255 r_dec pale_shift g_dec min 255 g_dec pale_shift b_dec min 255 b_dec pale_shift r_hex format r_dec 02x g_hex format g_dec 02x b_hex format b_dec 02x return 0 1 2 format r_hex g_hex b_hex
encode a utf-8 string to a sequence of bytes .,def encode_utf8 u import sys if sys version_info 0 2 u u encode utf 8 return u
perform an equal - weight binning of data points into hexagonal tiles .,def hexbin x y size orientation u pointytop aspect_scale 1 u Perform an equal weight binning of data points into hexagonal tiles n n For more sophiscticated use cases e g weighted binning or scaling n individual tiles proprtional to some other quantity consider using n HoloViews n n Args n x array float n A NumPy array of x coordinates for binning n n y array float n A NumPy array of y coordinates for binning n n size float n The size of the hexagonal tiling n n The size is defined as the distance from the center of a hexagon n to the top corner for pointytop orientation or from the center n to a side corner for flattop orientation n n orientation str optional n Whether the hex tile orientation should be pointytop or n flattop default pointytop n n aspect_scale float optional n Match a plot s aspect ratio scaling n n When working with a plot with aspect_scale 1 this n parameter can be set to match the plot in order to draw n regular hexagons insted of stretched ones n n This is roughly equivalent to binning in screen space and n it may be better to use axis aligned rectangular bins when n plot aspect scales are not one n n Returns n DataFrame n n The resulting DataFrame will have columns q and r that specify n hexagon tile locations in axial coordinates and a column counts that n provides the count for each tile n n warning n Hex binning only functions on linear scales i e not on log plots n n pd import_optional u pandas q r cartesian_to_axial x y size orientation aspect_scale aspect_scale df pd DataFrame dict r r q q return df groupby u q u r size reset_index name u counts
"log the connection ( redirection , link ) between two pages",def log_connection self source destination method flags None if not self json_enabled return if flags is None flags dict if exploit in flags and flags exploit self add_behavior_warn Exploit s s s source method destination else self add_behavior_warn s s s source method destination self data connections append source self fix source destination self fix destination method method flags flags
get this statistical result as an iris.cube.cube instance,def as_cube self cube Cube self num_points long_name Number of points used in calculations var_name num_points return cube
"high quality paired mapped reads should be add insert size standards flag : 2 , to kick out weird ( no 4 , no 8) both have mapping quality > = 1 input : list , [ [ ( pair1_flag , pair1_quality ) , ( pair2 ) ] , [ another ... ] ]",def pass_criteria l insert return all int l 0 1 1 int l 1 1 1 0 abs int l 0 2 insert 0 abs int l 1 2 insert bit_flag int l 0 0 bit_flag int l 1 0
writes src as attribute of gctx out file .,def write_src hdf5_out gctoo_object out_file_name if gctoo_object src None hdf5_out attrs src_attr out_file_name else hdf5_out attrs src_attr gctoo_object src
"in order to send a signal to a celery task , it is necessary to pickle the objects that will be used as parameters . however , django.dispatch.signal has an instance of threading . lock , which is an object that can not be pickled . therefore , this function changes the pickle behaviour of signal , making that only the providind_args of signal to be pickled .",def __reduce__ self return ColabSignal self providing_args
tries to find the parent catalog of a given catalog and returns it,def FindParentCatalogOf self catalog return self RetrieveCatalogForPath os path split catalog root_prefix 0
a list of strings for displaying when dumping state .,def info self return self dirs
gathers all the json info in ' metrics ' and ' params ' and returns them in individual dictionaries uses : load_qa,def Load_metrics_n_tests self dic_met dic_tst if isinstance self qa_name list qa_list self qa_name elif isinstance self qa_name str qa_list self qa_name else return Invalid QA format for i in qa_list try aux self Load_qa i if aux None dic_met update i aux dic_tst update i aux self error update i True elif self process_id is not None dic_met update i aux metrics dic_tst update i aux params else dic_met update i aux METRICS dic_tst update i aux PARAMS except Exception as e print print e return dic_met dic_tst
the variance / covariance matrix of the parameters .,property def var_cov_matrix self return self _var_cov
offer tab completion options for export,def complete_export self text line begidx endidx return self get_phil_completions text mode export
put a subsection of an amidata object in to a format ready for writing to a csv .,def createPlayerFile amiData meterName phase outFileName lines for row in amiData if row get meterName meterName and row get phase phase newLine row get readDateTime row get wh row get var j lines append newLine lines sort key lambda x x 0 with open outFileName w as outFile outFile write n join lines
executes the given query against all the given param sequences .,def executemany_lastrowid self query parameters cursor self _cursor try cursor executemany query parameters return cursor lastrowid finally cursor close
"creates a ` left ` "" calculation failed "" object . ` errormsg ` can be anything which gives information about what when wrong .",def __init__ self errorMsg super Either self __init__ errorMsg
standard subwindow button for option windows,def OptButton action window button_id button_strref button window GetControl button_id button SetEvent IE_GUI_BUTTON_ON_PRESS action button SetText button_strref
open up the fd and return it back .,def save self state pid return size state get size memory open proc d fd d pid state fd r
sends the given request to the server and returns the json object result .,def _remoteSend self action args data urllib urlencode args c urllib2 urlopen self _server action data res json loads c read self _checkError res return res
linemarker : hash number sconst linemarker - flags,def p_linemarker_1 p filename p 3 lineno p 2 flag p 4 if flag not in 1 2 return if flag 1 push_files_stack p filename 0 elif flag 2 pop_files_stack p filename p lineno 1 lineno
test extracting a single frame .,def test_extract_frame self sb FrameBuffer m1 self createMessage connect session uuid uuid4 This is the body sb append m1 msg sb extract_frame self assertIsInstance msg Frame self assertEqual m1 msg pack
"build the response surface of degree 2 argument ----------- x : np.ndarray [ nt , dim ] training points returns ------- m : np.ndarray matrix of the surface",def _response_surface self x dim self nx n x shape 0 n_app int scipy special binom dim 2 dim M np zeros n_app n x x T M 0 np ones 1 n for i in range 1 dim 1 M i x i 1 for i in range dim 1 2 dim 1 M i x i dim 1 2 for i in range dim 1 for j in range i 1 dim k int 2 dim 2 i dim i 1 i 2 j i 2 M k x i x j return M T
make_cid : make_cid does not work if first argument is not a str or byte,pytest mark parametrize value 1 1 0 object 3 2j def test_hash_invalid_type self value with pytest raises ValueError as excinfo make_cid value assert expected str or byte in str excinfo value
"process an image with densely sampled sift descriptors and save the results in a file . optional input : size of features , steps between locations , forcing computation of descriptor orientation ( false means all are oriented upwards ) , tuple for resizing the image .",def process_image_dsift imagename resultname size 20 steps 10 force_orientation False resize None im Image open imagename convert L if resize None im im resize resize m n im size if imagename 3 pgm im save tmp pgm imagename tmp pgm scale size 3 0 x y meshgrid range steps m steps range steps n steps xx yy x flatten y flatten frame array xx yy scale ones xx shape 0 zeros xx shape 0 savetxt tmp frame frame T fmt 03 3f if force_orientation cmmd str sift imagename output resultname read frames tmp frame orientations else cmmd str sift imagename output resultname read frames tmp frame os system cmmd print processed imagename to resultname
"returns url of specified file type ' source ' , ' egg ' , or ' all '",def filter_url pkg_type url bad_stuff modtime md5 for junk in bad_stuff if junk in url url url split junk 0 break if url endswith dev url url split egg 0 if pkg_type all return url elif pkg_type source valid_source_types tgz tar gz zip tbz2 tar bz2 for extension in valid_source_types if url lower endswith extension return url elif pkg_type egg if url lower endswith egg return url
counts the number of records for each group .,dfapi since 1 3 def count self
return if an interface is a user - to - network interface .,property def uni self return not self nni
"original code from twisted , hacked for request_counter proxying . request_counter is hack for http transport , did n't found cleaner solution how to indicate end of request processing in asynchronous manner .",def dataReceived self data lines self _buffer data split self delimiter self _buffer lines pop 1 for line in lines if self transport disconnecting return if len line self MAX_LENGTH return self lineLengthExceeded line else try self lineReceived line except Exception as exc log warning Failed message s from s str exc self _get_ip return error ConnectionLost Processing of message failed if len self _buffer self MAX_LENGTH return self lineLengthExceeded self _buffer
transform input * mem * in mb into psi4-type options for orca .,def muster_memory mem options defaultdict lambda defaultdict dict options ORCA ORCA_MAXCORE value int mem text MaxCore n format options ORCA ORCA_MAXCORE value for item in options ORCA options ORCA item clobber True return text options
load configuration from a file .,classmethod def load cls path data None try with open path as config_file file_config json load config_file except FileNotFoundError file_config if data is None data else data dict data data update file_config return cls path path data data
"view listing page , but not authorized to view this repository .",def test_listing_unauthorized self u self logout self login self USERNAME_NO_REPO self assert_status_code self repository_url UNAUTHORIZED return_body True
the preprocessing step prepares the image to improve detection probability .,def preprocess self img roi img cv2 cvtColor img cv2 COLOR_BGR2GRAY return img
bitonicsort : produces a bitonic sequence . recursive .,block def bitonic_sort list_a list_z direction len_list len list_a half_len len_list 2 width len list_a 0 if len_list 1 tmp Signal intbv 0 width for _ in range len_list lo_sort bitonic_sort list_a half_len tmp half_len ASCENDING hi_sort bitonic_sort list_a half_len tmp half_len DESCENDING merge bitonic_merge tmp list_z direction return lo_sort hi_sort merge else feed feedthru list_a 0 list_z 0 return feed
call all our tests in sequence .,def run_test_suite from time import clock ntests 0 start clock ntests test_mean_zero ntests eval_tests test_reductions ntests eval_tests test_binops end clock print 70 print Ran s tests in 3f ntests end start print nOK
"socket is the socket to be wrapped . outstream is the stream to write the pcap trace to . ethernet addresses have to be faked , and it can be convenient to fake ip and tcp addresses as well . thus , you can specify local_addrs or remote_addrs . these are tuples of ( ethaddr , ipaddr , tcpport ) . any item that is none gets a default value .",def __init__ self socket outstream close True local_addrs None None None remote_addrs None None None super CaptureSocket self __init__ socket self _close close self _writer PCapWriter outstream socket socket local_addrs local_addrs remote_addrs remote_addrs
creates a mock launch location . returns the location path .,def mock_cfg_location self return tempfile mkdtemp dir self tmppath
test code based on user submitted issue at https://github.com/numba/numba/issues/2159,def test_static_raise_in_objmode_fallback self def test0 n return n def test1 n if n 0 raise ValueError return test0 n compiled jit test1 self assertEqual test1 10 compiled 10 self _ensure_objmode compiled
a timeseries is anomalous if the deviation of its latest datapoint with respect to the median is x times larger than the median of deviations .,def median_absolute_deviation timeseries series pandas Series x 1 for x in timeseries median series median demedianed np abs series median median_deviation demedianed median if median_deviation 0 return False test_statistic demedianed iloc 1 median_deviation if test_statistic 6 return True else return False
filters the messages to remove unsubscribed users,def send_messages self email_messages final_messages for message in email_messages recipients message recipients for recipient in recipients name address email utils parseaddr recipient if Unsubscribe objects address_exists address if recipient in message to message to remove recipient if recipient in message cc message cc remove recipient if recipient in message bcc message bcc remove recipient LOGGER info u Email Stopped Unsub s S s recipient message subject if message to final_messages append message if final_messages return super ConnectMailerBackend self send_messages final_messages else return 0
form should unban a user .,def test_save_confirm_is_false_user_not_unbanned self self banned_user is_banned True self banned_user save form forms UnBanUserForm user self banned_user pk confirm True self assertTrue form is_valid form save user User objects get pk self banned_user pk self assertFalse user is_banned
returns a domain object representing a question .,def get_question_by_id question_id strict True question_model question_models QuestionModel get question_id strict strict if question_model question get_question_from_model question_model return question else return None
"on ' self[key ] ' , ' x in self ' , ' for x in self ' . implements all indexing - related operations . membership and iteration ( ' in ' , ' for ' ) repeatedly index from 0 until ' indexerror ' .",def __getitem__ self key return self data key
return : statements ( list ) : list of insert insertments cursor ( str ) : cursor for sync has_more ( bool ) : continue sync'ing,classmethod def sync cls account statements cursor account cursors get cls __tablename__ 0 resp account get cls endpoint format cursor cursor try resp raise_for_status except HTTPError if resp status_code 429 return statements cursor False raise HTTPError statements cls process_response resp cursor resp json end_time return statements cursor resp json count 1000
return string with description of reason task is not up - to - date,staticmethod def get_reasons reasons lines if reasons has_no_dependencies lines append The task has no dependencies if reasons uptodate_false lines append The following uptodate objects evaluate to false for utd utd_args utd_kwargs in reasons uptodate_false msg args kwargs lines append msg format utd utd_args utd_kwargs if reasons checker_changed msg The file_dep checker changed from 0 to 1 lines append msg format reasons checker_changed sentences missing_target The following targets do not exist changed_file_dep The following file dependencies have changed missing_file_dep The following file dependencies are missing removed_file_dep The following file dependencies were removed added_file_dep The following file dependencies were added for reason sentence in sentences items entries reasons get reason if entries lines append format sentence for item in entries lines append format item return n join lines
returns the environment at the head of the stack .,def get_env return ENVIRONMENTS_STACK 1
writes the user variables and also sets the write attributes for the output file,def write_additional_db_params self cmr_params self cmr_params cmr_params copy
adds a new event handler .,def subscribe self handler assert callable handler Invalid handler s handler self handlers append handler
p2p group formation with per - sta psks,def test_grpform_per_sta_psk dev dev 0 request P2P_SET per_sta_psk 1 i_res r_res go_neg_pin_authorized i_dev dev 0 i_intent 15 r_dev dev 1 r_intent 0 check_grpform_results i_res r_res pin dev 2 wps_read_pin dev 0 p2p_go_authorize_client pin c_res dev 2 p2p_connect_group dev 0 p2p_dev_addr pin timeout 60 check_grpform_results i_res c_res if r_res psk c_res psk raise Exception Same PSK assigned for both clients hwsim_utils test_connectivity_p2p dev 1 dev 2 dev 0 remove_group dev 1 wait_go_ending_session dev 2 wait_go_ending_session
return true if obj is an instance of a class .,def isclassinstance obj return hasattr obj __class__
creates a validator for checking that a string can be parsed as an integer .,def __init__ self errorMessage super IntegerValidator self __init__ errorMessage
sets the width of the object . negative number implies unspecified size ( terminal is free to set the size ) .,def setWidth self args raise NotImplementedError
paints the content of this component .,def paintContent self target super AbstractSplitPanel self paintContent target position str self _pos self UNIT_SYMBOLS self _posUnit target addAttribute position position if self isLocked target addAttribute locked True target addAttribute reversed self _posReversed if self _firstComponent is not None self _firstComponent paint target else temporaryComponent VerticalLayout temporaryComponent setParent self temporaryComponent paint target if self _secondComponent is not None self _secondComponent paint target else temporaryComponent VerticalLayout temporaryComponent setParent self temporaryComponent paint target
return the field of uncalibrated precipitation values .,def uncalibrated_precip self return self _read_scaled_masked_field 3
return relative path from start to end . warning : this is not the same as a relative url ; see relativeurl ( ) .,def relpath path start try return os path relpath path start except AttributeError if not path raise ValueError no path specified start_list os path abspath start split sep path_list os path abspath path split sep if start_list 0 lower path_list 0 lower unc_path rest os path splitunc path unc_start rest os path splitunc start if bool unc_path bool unc_start raise ValueError Cannot mix UNC and non UNC paths s and s path start else raise ValueError path is on drive s start on drive s path_list 0 start_list 0 for i in range min len start_list len path_list if start_list i lower path_list i lower break else i 1 rel_list pardir len start_list i path_list i if not rel_list return os path curdir return os path join rel_list
13 . if width and height are not null :,pytest mark parametrize rect width None height None width None height None x None y None x None y None width None x None width None y None height None x None height None Y None width None height None x None y None width 200 height 200 x 200 y 200 width 200 x 200 height 200 x 200 width 200 y 200 height 200 y 200 def test_no_change session rect original session window rect response set_window_rect session rect assert_success response original
return if the test suite should fail if an @expectedfailure unittest test passes .,def _is_unittest_unexpected_success_a_failure return sys version_info 3 4
create a field subclass instance corresponding to a given space .,staticmethod def from_args name dtype shape region approx_order 1 space H1 poly_space_base lagrange conf Struct name name dtype dtype shape shape region region name approx_order approx_order space space poly_space_base poly_space_base return Field from_conf conf region name region
"returns dictionary and key or none , none none - root node ( w/o "" node "" attribute ) /a / b / c - node /a / b/ - branch set returns '' or none as the key get returns '' or none as the key or none as the dict . used internally .",def _traversePath self node jid set_ 0 if jid in self _handlers cur self _handlers jid elif set_ self _handlers jid cur self _handlers jid else cur self _handlers if node is None node None else node node replace split for i in node if i and i in cur cur cur i elif set_ and i cur i dict cur str i cur cur i elif set_ or in cur return cur else return None None if 1 in cur or set_ return cur 1 raise Corrupted data
"convert sparql results dict to json , using json module .",def sparql_results_to_json self results vars_dict results_out for result in results result_json for var in result vars_dict var True value result var typ value type val unicode value value result_json var type typ value val results_out append result_json vars_out for var in vars_dict vars_out append var out head vars vars_out results bindings results_out return json dumps out indent 2
returns html of a specific example that is available online or locally,def getExampleHtml location print if location startswith http return urllib2 urlopen location read else f open location html f read f close return html
compute the density and store into a cube file,def test_cube_c self from pyscf tools cubegen import Cube from pyscf dft import numint gen_grid cc Cube mol nx 20 ny 20 nz 20 coords cc get_coords ngrids cc get_ngrids blksize min 8000 ngrids rho np empty ngrids ao None dm mf make_rdm1 for ip0 ip1 in gen_grid prange 0 ngrids blksize ao numint eval_ao mol coords ip0 ip1 out ao rho ip0 ip1 numint eval_rho mol ao dm rho rho reshape cc nx cc ny cc nz cc write rho h2o_den_cube_c cube comment Electron density in real space e Bohr 3
tdhf diagonalization with non - hermitian eigenvalue solver,def kernel self x0 None self check_sanity self dump_flags vind hdiag self get_vind self _scf precond self get_precond hdiag if x0 is None x0 self init_guess self _scf self nstates def pickeig w v nroots envs realidx numpy where abs w imag REAL_EIG_THRESHOLD w real POSTIVE_EIG_THRESHOLD 0 idx realidx w realidx real argsort return w idx real v idx real idx self converged w x1 lib davidson_nosym1 vind x0 precond tol self conv_tol nroots self nstates lindep self lindep max_space self max_space pick pickeig verbose self verbose mo_occ self _scf mo_occ e xy for i z in enumerate x1 xs ys z reshape 2 1 norm lib norm xs 2 lib norm ys 2 if norm 0 norm 1 numpy sqrt norm xs norm ys norm e append w i xy append _unpack xs mo_occ _unpack ys mo_occ self e numpy array e self xy xy return self e self xy
resolve variable references in a string,def ResolveReferences self var_dict args re_var re compile _a z0 9A Z 1 while True m re_var search args if not m break lookup m group 0 2 1 value var_dict get lookup args args m start 0 value args m end 0 return args
return an iterable list of all chunks . use this function if you only want to loop through the chunks once or have a very large world . use get_chunks ( ) if you access the chunk list frequently and want to cache the results . use iter_nbt ( ) if you are concerned about speed and do n't want to parse the block data .,def iter_chunks self for c in self iter_nbt yield self chunkclass c
return a tabbed string from an expanded one .,def re_tab s l p 0 for i in range 8 len s 8 if s i 2 i l append s p i rstrip t p i if p 0 return s else l append s p return join l
plot the key on a plotter .,def draw self posn phelper outerbounds None s self settings d self document if s hide return width s get width getFloatArray d height s get height getFloatArray d rotate s get rotate getFloatArray d if width is None or height is None or rotate is None return xpos ypos self _getPlotterCoords posn if xpos is None or ypos is None return isnotdataset not s get xPos isDataset d and not s get yPos isDataset d and not s get width isDataset d and not s get height isDataset d and not s get rotate isDataset d clip None if s clip clip qt4 QRectF qt4 QPointF posn 0 posn 1 qt4 QPointF posn 2 posn 3 painter phelper painter self posn clip clip with painter if not s Border hide painter setPen s get Border makeQPen painter else painter setPen qt4 QPen qt4 Qt NoPen index 0 dx dy posn 2 posn 0 posn 3 posn 1 x y w h r None for x y w h r in czip xpos ypos itertools cycle width itertools cycle height itertools cycle rotate wp hp dx w dy h painter save painter translate x y if r 0 painter rotate r self drawShape painter qt4 QRectF wp 0 5 hp 0 5 wp hp painter restore controlgraphitems if x is not None and isnotdataset cgi controlgraph ControlResizableBox self phelper x y wp hp r allowrotate True cgi index index cgi widgetposn posn index 1 controlgraphitems append cgi phelper setControlGraph self controlgraphitems
takes a simpleread object containing the data to be set .,def __init__ self simplereadobject self simplereadobject simplereadobject
detect any mistaken uses of single - blob deletion .,pytest fixture autouse True def never_use_single_delete monkeypatch def die assert False monkeypatch setattr storage Blob delete die monkeypatch setattr storage Bucket delete_blob die
compile a jitted function doing the hard part of the job,classmethod def callable cls nans False reverse False scalar False if scalar def _valgetter a i return a else def _valgetter a i return a i valgetter nb njit _valgetter if nans def _ri_redir i val Redirect any write access to the output array to it s first field if we encounter a nan value This first field was reserved in advance for dummy access Shift the index by 1 if we don t have a nan value return i 1 val val else def _ri_redir i val return i ri_redir nb njit _ri_redir inner _inner nb njit cls _inner def _loop group_idx a ret counter mean fill_value ddof rng range len group_idx 1 1 1 if reverse else range len group_idx for i in rng val valgetter a i ri ri_redir group_idx i val inner ri val ret counter mean loop nb njit _loop nogil True cache True _2pass cls _2pass if _2pass is None return loop _2pass nb njit _2pass nogil True cache True def loop_2pass group_idx a ret counter mean fill_value ddof loop group_idx a ret counter mean fill_value ddof _2pass ret counter mean fill_value ddof return loop_2pass
check http response status is expected .,def check_status status expected path headers None resp_headers None extras None if status in expected return msg Expect status r from Google Storage But got status d Path r Request headers r Response headers r Extra info r expected status path headers resp_headers extras if status httplib UNAUTHORIZED raise AuthorizationError msg elif status httplib FORBIDDEN raise ForbiddenError msg elif status httplib NOT_FOUND raise NotFoundError msg elif status httplib REQUEST_TIMEOUT raise TimeoutError msg elif status httplib REQUESTED_RANGE_NOT_SATISFIABLE raise InvalidRange msg elif status httplib OK and 308 in expected and httplib OK not in expected raise FileClosedError msg elif status 500 raise ServerError msg else raise FatalError msg
generates a dynamic api class for a given name .,def _MakeClass name def init self args Initializer for dynamically created classes Args self The instance of this class Listed to make the linter hush args Either a ComputedObject to be promoted to this type or arguments to an algorithm with the same name as this class Returns The new class klass globals name onlyOneArg len args 1 if onlyOneArg and isinstance args 0 klass result args 0 else ctor ApiFunction lookupInternal name firstArgIsPrimitive not isinstance args 0 ComputedObject shouldUseConstructor False if ctor if not onlyOneArg shouldUseConstructor True elif firstArgIsPrimitive shouldUseConstructor True elif args 0 func ctor shouldUseConstructor True if shouldUseConstructor ComputedObject __init__ self ctor ctor promoteArgs ctor nameArgs args else if not onlyOneArg raise EEException Too many arguments for ee s s name args elif firstArgIsPrimitive raise EEException Invalid argument for ee s s Must be a ComputedObject name args else result args 0 ComputedObject __init__ self result func result args result varName properties __init__ init name lambda self name new_class type str name ComputedObject properties ApiFunction importApi new_class name name return new_class
returns the number of restored runs .,def restore config optimizer_dir kwargs fh open optimizer_dir smac_restart out w smac_cmd re sub python os path dirname os path realpath __file__ config get SMAC algo_exec pwd kwargs cmd smac_cmd re sub outputDirectory optimizer_dir outputDirectory optimizer_dir restart_rungroups smac_cmd logger info smac_cmd process subprocess Popen smac_cmd stdout fh stderr fh shell True executable bin bash logger info RUNNING ret process wait fh close logger info Finished with return code str ret fh open optimizer_dir smac_restart out prog re compile Restored 0 9 1 100 runs restored_runs 0 for line in fh readlines match prog search line if match restored_runs int match group 2 state_run _get_state_run optimizer_dir state_run_path os path join os path dirname os path realpath __file__ os getcwd state_run state_runs glob glob state_run_path runs_and_results it csv state_run_iterations for state_run in state_runs match re search runs_and_results it 0 9 1 100 csv state_run if match state_run_iterations append float match group 2 run_and_results_fn state_runs np argmax state_run_iterations runs_and_results open run_and_results_fn lines runs_and_results readlines state_run_iters len lines 1 runs_and_results close fh close assert state_run_iters restored_runs 1 state_run_iters restored_runs restored_runs state_run_iters return restored_runs
encrypts the given turnover counter for the given receipt with the key . : param receipt : the receipt object in which the encrypted turnover counter will be used . : param turnovercounter : the turnover counter as an int . : param key : the key as a byte list . : param size : the number of bytes used to represent the turnover counter as an int . must be between 5 and 16 ( inclusive ) . : return : the encrypted turnover counter as a byte list .,def encryptTurnoverCounter self receipt turnoverCounter key size raise NotImplementedError Please implement this yourself
times how fast a framework can read a nifti file and convert it to numpy,def time_nifti_to_numpy N_TRIALS img_paths ants get_ants_data mni 10 def test_nibabel for img_path in img_paths array nib load img_path get_data def test_itk for img_path in img_paths array itk GetArrayFromImage itk imread img_path def test_ants for img_path in img_paths array ants image_read img_path pixeltype float numpy nib_start time time for i in range N_TRIALS test_nibabel nib_end time time print NIBABEL TIME 3f seconds nib_end nib_start itk_start time time for i in range N_TRIALS test_itk itk_end time time print ITK TIME 3f seconds itk_end itk_start ants_start time time for i in range N_TRIALS test_ants ants_end time time print ANTS TIME 3f seconds ants_end ants_start
""" the selectivity measure max(rate)/mean(rate ) of the cell . the more tightly concentrated the cell 's activity , the higher the selectivity . a cell with no spatial tuning at all will have a selectivity of 1 "" [ 2]_.",def selectivity rate_map px tmp_rate_map rate_map copy tmp_rate_map np isnan tmp_rate_map 0 avg_rate np sum np ravel tmp_rate_map px max_rate np max np ravel tmp_rate_map return max_rate avg_rate
"retrieves vm 's folder , dc and root parent object by traversing linked list of parents back to beginning .",def get_vm_datacenter_details self obj folder N A datacenter N A root_obj False if obj parent folder obj parent name obj_parent obj parent while obj_parent root_obj obj_parent if isinstance obj_parent vim Datacenter datacenter obj_parent name break obj_parent obj_parent parent return datacenter folder root_obj
insert a list of insert statements into the event and study_event tables .,def _execute_statements study_id sql_statement output_file open missing_event_data txt a csvout csv writer output_file try ip port sid username password gwas_data_sources get_db_properties DEV3 dsn_tns cx_Oracle makedsn ip port sid connection cx_Oracle connect username password dsn_tns cursor connection cursor new_id cursor var cx_Oracle NUMBER sql_event sql_statement returning id into new_id csvout writerow StudyID study_id csvout writerow sql_event cursor execute sql_event new_id new_id event_id int new_id getvalue sql_study_event INSERT INTO STUDY_EVENT VALUES str study_id str event_id csvout writerow sql_study_event n cursor execute sql_study_event if args mode production cursor execute COMMIT else cursor execute ROLLBACK cursor close connection close except cx_Oracle DatabaseError as exception print exception
search the address within the interface list .,def interface_lookup interfaces hwaddr address_type for interface in interfaces values if interface get hwaddr hwaddr for address in interface get addrs if address get type address_type return address get addr
"@respawn : if true , respawn if child dies abnormally",def start_plugin_helper name respawn display None argv sys executable argv extend sys argv argv append exec helper s name pretty print_debug __name__ Spawning argv return spawn_child argv respawn display display
"given a group element , extract a symmetric key : param g : : return :",def extract_key g g_in_hex hashPair g decode utf 8 return bytes bytearray fromhex g_in_hex
test that compcardataset.chips is the correct length,def test_compcar_chips_len compcar instantiated_class compcar 0 FILE_NAMES compcar 1 assert len FILE_NAMES assert len FILE_NAMES len instantiated_class chips
register a worker with this ioloop,def register_worker self worker def on_close worker def close_worker worker worker socket close self _workers discard worker self _pending_commands append lambda close_worker worker self pinger ping worker on_close on_close worker pinger self pinger self _pending_commands append lambda self _workers add worker self pinger ping
"normalizes string , converts to lowercase , removes non - alpha characters , and converts spaces to hyphens to have nice filenames .",def slugify value try unicode_type unicode except NameError unicode_type str if not isinstance value unicode_type value unicode_type value value unicodedata normalize NFKD value encode ascii ignore decode ascii value unicode_type _SLUGIFY_STRIP_RE sub value strip return _SLUGIFY_HYPHENATE_RE sub _ value
test if a called callback adds the node - host to the dict .,def test_callback_easy self lookup HostLookup for x in range 1 3 rstat RatedStatistics rstat host host1 rstat seuid n s s d SEUID_DELIMITER node x lookup callback_rated rstat test lookup get_host node1 host1 self assertTrue test
the decorator is used to pass model field names to create_post_model_field function for logging change .,def model_field_name field_name args kwargs u n The decorator is used to pass model field names to create_post_model_field function for logging change n def model_field_name_decorator f args kwargs def model_field_name_wrapper sender instance kwargs f sender instance field_name field_name kwargs return model_field_name_wrapper return model_field_name_decorator
yield address - location pairs in the given address range .,def iter_locations self low high query select addr loc from lines where addr and addr order by addr for addr lid in self query_db query low high yield addr self elf locations lid
initialise the object . opts is the parsed options . ui_file is the name of the .ui file .,def __init__ self opts ui_file if opts debug logger logging getLogger self LOGGER_NAME handler logging StreamHandler handler setFormatter logging Formatter name s message s logger addHandler handler logger setLevel logging DEBUG self _opts opts self _ui_file ui_file
do all necessary declarations for inner properties .,def declare_once self init_val None if self _declared return code if self _nbr_num 0 neighborhood self _bsca topology neighborhood lattice self _bsca topology lattice border self _bsca topology border dimensions self _bsca topology dimensions if not self _coords_declared code lattice index_to_coord_code i _x coord_vars _nx d i for i in range dimensions code int s n join coord_vars self _bsca declare_coords code neighborhood neighbor_coords self _nbr_num _x _nx is_cell_off_board lattice is_off_board_code _nx if hasattr border wrap_coords code if is_cell_off_board wrap_coords format is_cell_off_board is_cell_off_board wrap_coords border wrap_coords _nx else code type var if is_cell_off_board var off_board_cell else var neighbor_state format type self ctype var self var_name is_cell_off_board is_cell_off_board off_board_cell border off_board_state _nx neighbor_state init_val self _bsca append_code code self _bsca declare self return if init_val is None code s s n self ctype self var_name else code s s s n self ctype self var_name init_val self _bsca append_code code self _bsca declare self
"assert that any of the model types support "" less than or equal "" comparisons against expected types .",def test_model_supports_le_with_expected_types model_with_ordered_bytes model_type less_than_bytes greater_than_bytes model_with_ordered_bytes model model_type less_than_bytes assert model ulid MemoryView less_than_bytes assert model bytes less_than_bytes assert model bytearray less_than_bytes assert model memoryview less_than_bytes assert model int from_bytes less_than_bytes byteorder big assert model base32 encode less_than_bytes assert model ulid MemoryView greater_than_bytes assert model bytes greater_than_bytes assert model bytearray greater_than_bytes assert model memoryview greater_than_bytes assert model int from_bytes greater_than_bytes byteorder big assert model base32 encode greater_than_bytes
page : the page this controller appears on .,property def page self return self parent
collapse this ` beat ` into a single ` fraction ` and return it .,def to_fraction self if isinstance self numerator type self return Fraction self numerator collapsed_fraction self denominator return Fraction self numerator self denominator
induces rules for the given knowledge base .,def induce self kb self kb has_min_sup lambda pred kb get_members pred count self min_sup all_predicates filter has_min_sup kb predicates rules for depth in range 1 self depth 1 for attrs in combinations all_predicates depth rule Rule kb predicates self _labels_to_predicates attrs target self target rules append rule rules sorted rules key lambda r r score reverse True return rules self n
send a selector and a query string .,def send_query selector query host port 0 return send_selector selector t query host port
return an absolute path normalized but symbolic links not eliminated,def abspath path path _tostr path abspath return _abspath path
updates coefficient of a given output category with a new value .,def update_output_category_coefficient self current_output constraint obj_var output_category if output_category in self non_disc_outputs constraint changeRHS current_output else constraint obj_var current_output
"this method normalizes the file object by making `` path `` , `` name `` and `` handle `` properties consistent . it writes incoming data to the file object and points the `` data `` iterable to the contents of this file .",def rollover self if self data is not None if self path is None self handle tempfile NamedTemporaryFile self abspath self path self handle name self name basename self abspath else self handle open self path wb for d in self data self handle write d elif self handle is not None self data mmap self handle fileno 0 elif self path is not None if not isfile self path logger error File path in r not found self self handle open self path rb self data mmap self handle fileno 0 access ACCESS_READ self abspath abspath self path self name self path basename self path else raise ValueError Invalid file object passed in All of data handle and path are None
base_base_correlation function works when a sequence contains characters ( e.g. ns ) not included in alphabet .,def test_base_base_correlation_on_ambiguous_dna_k1 self dna CTAGGGAACATACCANNNNNNNN vec bbc base_base_correlation dna 1 utils ALPHABET_DNA exp 0 09531944216197286 0 08354249482243745 0 011648745118694886 0 03537936275852141 0 08354249482243745 0 07114045890800086 0 10696198320987654 0 07735938746326047 0 06569448291953908 0 10696198320987654 0 14092829842677065 0 05337075358024692 0 036771706024547365 0 0058396884306785996 0 02369886445107525 0 0355666929797287 self assertEqual vec shape 1 16 self assertEqual vec tolist exp
delete a key - value pair,def __delitem__ self key del self _mapping key
retrieve fasta files from s3 bucket,def pull_fasta_from_s3 lineage directory data bucket nextflu data Boto expects environmental variables AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY directory directory rstrip import boto conn boto connect_s3 b conn get_bucket bucket k boto s3 key Key b print Retrieving FASTA for lineage fasta lineage _gisaid_epiflu_sequence fasta k key fasta k get_contents_to_filename directory fasta print fasta retrieved
"return a prototype scanner instance for "" scanning "" directory nodes for their in - memory entries",def DirEntryScanner kw kw node_factory SCons Node FS Entry kw recursive None return SCons Scanner Base scan_in_memory DirEntryScanner kw
compute the limit of e(z ) at the point z0 .,def limit e z z0 dir e sympify e z sympify z z0 sympify z0 if e z return z0 if not e has z return e if z0 is_positive e e rewrite factorial gamma if e is_Mul if abs z0 is S Infinity ok lambda w z in w free_symbols and any a is_polynomial z or any z in m free_symbols and m is_polynomial z for m in Mul make_args a for a in Add make_args w if all ok w for w in e as_numer_denom u C Dummy positive z0 is S Infinity inve e subs z 1 u return limit inve as_leading_term u u S Zero if z0 is S Infinity else if e is_Order return C Order limit e expr z z0 e args 1 try r gruntz e z z0 dir if r is S NaN raise PoleError except PoleError ValueError r heuristics e z z0 dir return r
low - level implementation of gegenbauer polynomials .,def dup_gegenbauer n a K seq K one K 2 a K zero for i in xrange 2 n 1 f1 K 2 i a K one i f2 i K 2 a K 2 i p1 dup_mul_ground dup_lshift seq 1 1 K f1 K p2 dup_mul_ground seq 2 f2 K seq append dup_sub p1 p2 K return seq n
"returns a plotinterval if args can be interpreted as such , otherwise none .",staticmethod def try_parse args if len args 1 and isinstance args 0 PlotInterval return args 0 try return PlotInterval args except ValueError return None
create theano function from sympy expressions,def theano_function inputs outputs dtypes cache None kwargs cache if cache None else cache broadcastables dim_handling inputs kwargs dim_names inspect getargspec dim_handling 0 theano_kwargs dict k v for k v in kwargs items if k not in dim_names code partial theano_code cache cache dtypes dtypes broadcastables broadcastables tinputs list map code inputs toutputs list map code outputs toutputs toutputs 0 if len toutputs 1 else toutputs return theano function tinputs toutputs theano_kwargs
compute greatest factorial factorization of `` f `` in `` k[x ] `` .,def dmp_gff_list f u K if not u return dup_gff_list f K else raise MultivariatePolynomialError f
vehicles that are meant to stay in the ring are rerouted whenever they reach a new edge .,def additional_command self for veh_id in self ids if merge in self vehicles get_state veh_id type and self scenario net_params additional_params merge_out_length is not None continue route None if self vehicles get_route veh_id 1 self vehicles get_edge veh_id if self vehicles get_edge veh_id ring_0 route ring_0 ring_1 elif self vehicles get_edge veh_id ring_1 route ring_1 ring_0 if route is not None self vehicles set_route veh_id route self traci_connection vehicle setRoute vehID veh_id edgeList route
generate bus cycles from a button input this is a nonsensical module that creates memory - mapped bus cycles from a button press . it is used in simple examples and demonstrations .,myhdl block def button_controller glbl regbus btns led_addr 576 clock reset glbl clock glbl reset dbtns Signal intbv 0 len btns led_addr intbv led_addr 16 ctl regbus get_generic btn_inst button_debounce glbl btns dbtns ctl_inst controller_basic ctl regbus always_seq clock posedge reset reset def beh ctl write next False ctl read next False ctl per_addr next led_addr 16 8 ctl mem_addr next led_addr 8 0 if ctl done if btns 0 ctl write next True if dbtns 0 ctl write_data next 1 elif dbtns 1 ctl write_data next 2 elif dbtns 2 ctl write_data next 3 elif dbtns 3 ctl write_data next 4 return myhdl instances
test cases can load fixture objects into models defined in packages,def testClassFixtures self u self assertEqual Article objects count 3 self assertQuerysetEqual Article objects all u Django conquers world u Copyright is fine the way it is u Poker has no place on ESPN lambda a a headline
create a detached copy of this comment .,def __copy__ self clone self __class__ self content self author self height self width return clone
to add another frame to the call ; detectable because _ _ tracback_info _ _ is set to ` info `,def pass_through info inner args kw __traceback_info__ info return inner args kw
"stop the zookeeper session , but leaves the socket open .",def stop self self zk stop
get snapshot instance which holds the percentiles,def get_snapshot self return self sample get_snapshot
"return urlpatterns , if the panel has its own views .",classmethod def get_urls cls u n Return URLpatterns if the panel has its own views n return
verify the `` msg ` and `` sig `` using `` key `` .,def verify self key msg sig new_api hasattr key verify if not new_api verifier key verifier sig self padding self hash verifier update msg try if new_api key verify sig msg self padding self hash else verifier verify except cryptography exceptions InvalidSignature as error logger debug error exc_info True return False else return True
verifies that the given username and password was correct : param request : either the query part of a url a urlencoded body of a http message or a parse such . : param kwargs : catch whatever else is sent . : return : redirect back to where ever the base applications wants the user after authentication .,def verify self request kwargs if isinstance request six string_types _dict parse_qs request elif isinstance request dict _dict request else raise ValueError Wrong type of input try self _verify _dict password 0 _dict login 0 timestamp str int time mktime time gmtime info self aes encrypt join _dict login 0 timestamp self active info timestamp cookie make_cookie self cookie_name info self srv seed return_to create_return_url self return_to _dict query 0 self query_param true resp Redirect return_to headers cookie except AssertionError KeyError resp Unauthorized Unknown user or wrong password return resp
corresponds to the : attr:`partitionstate . failure ` state,property def failed self return self state PartitionState FAILURE
allow deletion of a setting in an overridden settings set ( # 18824 ),def test_override_settings_delete self previous_i18n settings USE_I18N previous_l10n settings USE_L10N with self settings USE_I18N False del settings USE_I18N with self assertRaises AttributeError getattr settings USE_I18N del settings USE_L10N with self assertRaises AttributeError getattr settings USE_L10N self assertNotIn USE_I18N dir settings self assertNotIn USE_L10N dir settings self assertEqual settings USE_I18N previous_i18n self assertEqual settings USE_L10N previous_l10n
shrink the range by the dimensions provided .,def shrink self right 0 bottom 0 left 0 top 0 u n Shrink the range by the dimensions provided n n type right int n param right shrink range from the right by this number of cells n type down int n param down shrink range from the top by this number of cells n type left int n param left shrink range from the left by this number of cells n type up int n param up shrink range from the bottown by this number of cells n self min_col left self min_row top self max_col right self max_row bottom
check that the current ptsa version is in the version - range described by the 2 argument strings .,def versionWithin str1 str2 if not ptsaVersion StrictVersion str1 and ptsaVersion StrictVersion str2 return False else return True
called before any tests are performed .,def setup_module print n __name__
set minimum values of study variables .,lower_bounds setter def lower_bounds self value if not isinstance value tuple list raise TypeError Lower bounds must be a tuple or a list self _lower_bounds value
report execution of some order quantity .,def send_order_execution self message return
ensure that all args are an indexable type .,def to_indexable args kwargs if kwargs get allow_scalars False indexable _maybe_indexable else indexable _indexable for x in args if x is None or isinstance x da Array yield x elif is_dask_collection x yield delayed indexable pure True x else yield indexable x
parses a dsrf report to block objects .,def parse_report self files_list dsrf_xsd_file avs_xsd_file human_readable False write_head True file_path_to_name_map file_path path basename file_path for file_path in files_list expected_components constants FILE_NAME_COMPONENTS self logger info Validating the report file names report_validator report_files_validators ReportFilesValidator file_name_validators FileNameValidator expected_components self logger report_validator validate_file_names file_path_to_name_map values blocks defaultdict set for file_path file_name in file_path_to_name_map iteritems file_parser dsrf_file_parser DSRFFileParser self logger dsrf_xsd_file avs_xsd_file file_path file_name_dict file_name_validators FileNameValidator split_file_name file_name expected_components file_number file_name_dict x self logger info Start parsing file number s file_number for block in file_parser parse_file int file_number if block type block_pb2 BODY for compared_file_number file_blocks in blocks iteritems if block number in file_blocks raise error ReportValidationFailure The block number s is not unique It appears in files number s and s block number min file_number compared_file_number max file_number compared_file_number blocks file_number add block number elif block type block_pb2 HEAD try self validate_head_block block file_name file_name_dict except error FileNameValidationFailure as e self logger error e if not write_head continue else continue self write_to_queue block self logger human_readable try self logger raise_if_fatal_errors_found except error ReportValidationFailure as e sys stderr write constants COLOR_RED constants BOLD n Cell validation str e constants ENDC return self logger
sets the enabled state of the plugin .,enabled setter def enabled self value value bool value if self enabled value return if value self load if not os path isfile self get_plugin_file os makedirs os path dirname self get_plugin_file exist_ok True with open self get_plugin_file a as fh fh write self name n else if os path isfile self get_plugin_file return result with open self get_plugin_file w as fh for line in fh line line strip if not line continue if line self name result append line fh seek 0 fh write n join result n
simulates an ansible run by creating the expected database objects . this roughly approximates the following playbook :,def ansible_run complete True failed False gather_facts True ara_record False playbook fakes Playbook complete complete path playbook yml model pb_file fakes File playbook playbook is_playbook True path playbook path model pb_content fakes FileContent content fakes FAKE_PLAYBOOK_CONTENT model play fakes Play playbook playbook model host fakes Host playbook playbook model tasks task_results task_file fakes File playbook playbook is_playbook False path some path main yml model task_content fakes FileContent content fakes FAKE_TASK_CONTENT model task fakes Task play play playbook playbook action fake_action file task_file file_id task_file id model tasks append task task_result fakes TaskResult task task host host status ok changed True result fake action result model task_results append task_result record_task fakes Task play play playbook playbook action ara_record file task_file file_id task_file id model tasks append record_task ctx dict playbook playbook pb_file pb_file pb_content pb_content play play host host task task task_file task_file task_content task_content result task_result items playbook pb_file pb_content task_file task_content play host skipped False if ara_record msg Data recorded in ARA for this playbook record_result fakes TaskResult task record_task host host status ok changed True skipped skipped result msg model data fakes Data playbook playbook model ctx data data items append data else skipped True msg Conditional check failed record_result fakes TaskResult task record_task host host status skipped changed False skipped skipped result msg model task_results append record_result failed_task fakes Task play play playbook playbook action fail file task_file file_id task_file id model tasks append failed_task if failed msg FAILED failed_result fakes TaskResult task failed_task host host status failed changed False failed True result msg model else skipped True msg Conditional check failed failed_result fakes TaskResult task failed_task host host status skipped changed False skipped skipped result msg model task_results append failed_result if gather_facts facts fakes HostFacts host host model ctx facts facts items append facts for item in items tasks task_results if hasattr item start item start if complete stats fakes Stats playbook playbook host host ok 1 skipped int skipped failed int failed model ctx stats stats items append stats for item in items tasks task_results if hasattr item stop item stop for item in items tasks task_results db session add item db session commit return ctx
assign to connectors hosted on grids[0 ] all connected links from grids[1 ] : return :,def connect_connectors_to_links self for i in range len self __grids 1 connectors for k in 0 1 for j in range len self __grids 1 connectors i immediate_connectors_id k self __grids 0 connectors self __grids 1 connectors i immediate_connectors_id k j immediate_connectors_id invert k append self __grids 1 connectors i id
output set statistics and prompt the user to add the set .,def user_add_set self set_score variables set_dict dict score set_score scoring_fn self score_expression items variables items message Set statistics n n join utils fmtkv k v for k v in set_dict items if self force or not self force and click confirm Add set to database default True min_set_id Set select fn Min Set _id scalar if min_set_id is None min_set_id 0 set_id min_set_id 1 add_set True else add_set False return add_set set_id
the maximum raw score of our problem .,def max_score self return sum max option points for option in criterion options if len criterion options 0 else 0 for criterion in self rubric_criteria
test to load serial pumi model and mesh,def test_meshLoadPUMI verbose 0 testDir os path dirname os path abspath __file__ cubeMdl testDir cube dmg cube670p1 testDir cube smb meshAdaptInstance MeshAdaptPUMI MeshAdaptPUMI meshAdaptInstance loadModelAndMesh cubeMdl cube670p1 mesh MeshTools TetrahedralMesh mesh cmesh cmeshTools CMesh meshAdaptInstance constructFromSerialPUMIMesh mesh cmesh mesh buildFromC mesh cmesh eq mesh nElements_global 670 eq mesh nNodes_global 190 eq mesh nEdges_global 977 eq mesh nElementBoundaries_global 1458
"wtf ! ? : there is an error when checking if a qlistwidgetitem is in a list of qlistwidgetitems via "" item in item_list "" : notimplementederror : operator not implemented . this uses a workaround getting the objects id()s .",def select_items self items if not items self clear_selection return item_ids id i for i in items last_item None for item in self iter_items if id item in item_ids item setSelected True last_item item else item setSelected False if last_item is not None self setCurrentItem last_item
decode a json document from `` s `` ( a `` str `` or `` unicode `` beginning with a json document ) and return a 2-tuple of the python representation and the index in `` s `` where the document ended .,def raw_decode self s idx 0 try obj end self scan_once s idx except StopIteration raise ValueError No JSON object could be decoded return obj end
convenience wrapper around joblib 's parallelization .,def parallel func inputs n_jobs expand_args False if expand_args return Parallel n_jobs n_jobs delayed func args for args in inputs else return Parallel n_jobs n_jobs delayed func arg for arg in inputs
"the * encoding * argument specifies the encoding to use for communications with the child . if an encoding is specified , the standard input and output handles provide text - based io , otherwise they provide bytes - based io .",def __init__ self encoding None timeout None super Process self __init__ StreamProtocol timeout self _encoding encoding self _process None self _child_exited Event self _closed Event self _stdin self _stdout self _stderr None self _exit_status None self _term_signal None self _callbacks None
return the name of the instrument and detector,property def det_name self return self _det_name
"parses an executor string of the form ssh : arg1,arg2,kwarg1=foo .",def _parse_executor self executor arguments args kwargs if in executor executor arguments executor split 1 for argument in arguments split argument argument strip if in argument key value argument split 1 key key strip value value strip kwargs key value else args append argument self executor self executor_args self executor_kwargs executor args kwargs
"on button press , set album popularity @param widget as gtk . eventbox @param event as gdk . event",def _on_button_press self widget event rate self __get_rate max_heart self __heart_from_rate rate event_heart widget get_children 0 if event_heart in self _hearts position self _hearts index event_heart else position 1 new_rate position 1 if new_rate 0 or new_rate max_heart El bookmarks set_popularity self __bookmark_id 0 self _on_leave_notify None None else avg_popularity El bookmarks get_avg_popularity best_popularity El bookmarks get_higher_popularity popularity int new_rate avg_popularity 5 0 5 if new_rate 5 popularity popularity best_popularity 2 El bookmarks set_popularity self __bookmark_id popularity return True
invoked for a new connection opened .,def on_open self args kwargs cls self __class__ SseHandler log info Incoming connection s to channels s self connection_id join self channels cls _connections self connection_id self self on_message ping for channel in self channels if channel not in cls _channels cls _channels channel cls _channels channel self connection_id self get_secure_cookie REMOTE_SESSION decode ascii event_id self request headers get Last Event ID None if event_id SseHandler log debug Client s last event ID s self connection_id event_id i 0 for i msg in enumerate cls _cache if msg id event_id break for msg in cls _cache i 1 if msg channel broadcast or msg channel in self channels self on_message msg body
generate a grammar function that will match ' expected_tokens ' only .,def match_tokens expected_tokens if isinstance expected_tokens Token def _grammar_func tokens try next_token next iter tokens except StopIteration return if next_token expected_tokens return TokenMatch None next_token value next_token elif isinstance expected_tokens tuple match_len len expected_tokens def _grammar_func tokens upcoming tuple itertools islice tokens match_len if upcoming expected_tokens return TokenMatch None None upcoming else raise TypeError expected_tokens must be an instance of Token or a tuple thereof Got r expected_tokens return _grammar_func
returns the generator and discriminator loss for a particular gan type .,def get_gan_losses gan_type if gan_type gan return gan_g_loss gan_d_loss elif gan_type wgan return wgan_g_loss wgan_d_loss elif gan_type lsgan return lsgan_g_loss lsgan_d_loss else raise ValueError Unrecognized GAN type s gan_type
@param topofiles : list of topology file names ( default all_*in in biskit / data / amber / residues ) @type topofiles : [ str ] @param log : optional logfile instance ( default stdout ) @type log : biskit . logfile @param verbose : add messages to log ( default false ) @type verbose : bool,def __init__ self topofiles F_RESTYPES log None verbose False self aindex self topoindex self log log or StdLog self verbose verbose for f in topofiles self addTopology f
get maximum membership value for each frame .,def maxMemberships self msm self memberships return map lambda x max msm x range 0 self traj lenFrames
the number of alleles for this call .,property def ploidy self if not self _ploidy self _ploidy Call _call_jobject ploidy self _call return self _ploidy
for a given p - cochain \omega there is a unique decomposition,def hodge_decomposition omega For a given p cochain omega there is a unique decomposition omega d lpha delta eta h for p 1 cochain lpha p 1 cochain eta and harmonic p cochain h This function returns non unique representatives eta gamma and h which satisfy the equation above Example decompose a random 1 cochain sc SimplicialComplex omega sc get_cochain 1 omega rand omega shape alpha beta h hodge_decomposition omega sc omega complex p omega k alpha sc get_cochain p 1 beta sc get_cochain p 1 A delta d sc get_cochain_basis p 1 v b delta omega v alpha v cg A b tol 1e 08 0 A d delta sc get_cochain_basis p 1 v b d omega v beta v cg A b tol 1e 08 0 h omega d alpha delta beta return alpha beta h
returns smallest bst around value .,def min_bst self value if not self splits return self choice self splits 0 if value self splitval else self splits 1 return choice min_bst value
returns a blue - red divergent palette,def div_palette_zero_centered values if len v for v in values if v 0 0 print no negative values if len v for v in values if v 0 0 print no positive values min_v min values max_v max values colors for v in values if v 0 alpha 1 v min_v colors append alpha alpha 1 else alpha 1 v max_v colors append 1 alpha alpha return colors
returns names of all the parameters,def get_param_names self return self parameters keys
registers an file path to be served by ctfd,def register_plugin_asset app asset_path admins_only False asset_path asset_path strip def asset_handler return send_file asset_path if admins_only asset_handler admins_only_wrapper asset_handler rule asset_path app add_url_rule rule rule endpoint asset_path view_func asset_handler
a function for determining which server the job is currently running on . this is meant to be run on a calculation node .,def get_server evars os environ server evars get LSB_EXEC_CLUSTER evars get SLURM_CLUSTER_NAME if server local False return server local else server evars get CLUSTER local True return server local
"get color [ r , g , b , a ] attributes by index .",def __getitem__ self index return 0 self getRed 1 self getGreen 2 self getBlue 3 self getAlpha index
evaluates the metric on a ranked list of targets .,def evaluate self qid targets raise NotImplementedError
must be overridden by all crawlers,def crawl self pub_date raise NotImplementedError
close the associated file descriptor . swallows raised exceptions .,def close self try os close self fd except Exception pass
sample from gumbel - softmax distribution,def gumbel_softmax_sample logits temperature y logits sample_gumbel tf shape logits return tf nn softmax y temperature
sample implementation of process ( ),def process self event self make_entry event self calculate_amount event
"get by package name necessary to access from conaninfo self.requires[""boost""].version = "" 2.x """,def __getitem__ self item return self _data self _get_key item
adding a parent milestone to a milestone object transforms it into a submilestone,def add_parent self milestone if not isinstance milestone int Milestone exp_types 0 or 1 format int Milestone raise TypeError const SETTER_ERR format exp_types type milestone parent_id milestone if isinstance milestone int else milestone id sub_milestone deepcopy self _content sub_milestone parent_id parent_id return SubMilestone self client sub_milestone
"return true if current run is successfully processed . if there are some files missing , remove output directory and rerun conversion .",def _isProcessed outdir sampleSheetFpath reportFn os path join outdir Reports html index html if not os path isdir outdir return elif not os path isfile reportFn sys stderr write WARNING Incomplete conversion detected s Remove it n outdir elif os path isfile sampleSheetFpath and os stat sampleSheetFpath st_mtime os stat outdir st_mtime sys stderr write WARNING Newer sampleSheet than outdir s Remove it n outdir return True
returns a key for an instancetemplate .,def get_instance_template_key base_name return ndb Key models InstanceTemplate base_name
post processes the stack trace through _ relative_path ( ) .,def _reformat_stack stack out stack splitlines True def replace l m re match RE_STACK_TRACE_FILE l re DOTALL if m groups list m groups groups 1 _relative_path groups 1 return join groups return l return join map replace out
get a generator of usbhandle for devices available .,classmethod def Devices cls return common UsbHandle FindDevices DeviceIsAvailable
stops saving content in memory . used to test large files .,def discard_content self self _server discard_content True
keyword arguments in from_serializable_dict take precedence .,def test_from_serializable_dict_kwargs_precedence self class Entity ndb Model serializable SerializableModelMixin prop ndb IntegerProperty entity Entity from_serializable_dict prop 123 prop 456 self assertEqual 456 entity prop
check that all things needed to run the admin have been correctly installed .,def check_dependencies self from django contrib contenttypes models import ContentType if not ContentType _meta installed raise ImproperlyConfigured Put django contrib contenttypes in your INSTALLED_APPS setting in order to use the admin application if not django contrib auth context_processors auth in settings TEMPLATE_CONTEXT_PROCESSORS or django core context_processors auth in settings TEMPLATE_CONTEXT_PROCESSORS raise ImproperlyConfigured Put django contrib auth context_processors auth in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application
returns the legendre polynomial shifted by a certain amount,def shift_legendre_polynomial l shift ls L cast l window l window shift return L ls coef
add all of the views of the given diva object to this one . this is useful for mutli - file projects,def extend self other_diva self reports extend other_diva reports
commit any side effects of adding this model element to a model . this is an abstract method that must be implemented for each subclass of modelelement .,def commit self raise NotImplementedError
launch moonlight scrollviewer with accessibility enabled and return a scrollviewer object . log an error and return none if something goes wrong,def launchScrollViewer exe None if exe is None exe s samples moonlight ScrollViewer ScrollViewerSample html uiaqa_path if not exists exe raise IOError Could not find file s exe args firefox_path exe app subproc cache launchApplication args args name Firefox wait config LONG_DELAY scrollviewer ScrollViewer app subproc cache addApplication scrollviewer scrollviewer scrollViewerFrame app scrollviewer return scrollviewer
"ensure that the order of the rows is correct . if is_reversed is true , the list should be in reverse order . otherwise , the list should be in descending order .",def assertSortedOrder self is_reversed procedurelogger action Ensure that the rows are in the correct order if is_reversed procedurelogger expectedResult The list is reversed procedurelogger expectedResult read2 and edit2 change position to s and s self top_read_position self top_edit_position read2_new_position self read_cells 2 _getAccessibleCenter edit2_new_position self edit_cells 2 _getAccessibleCenter assert read2_new_position self top_read_position and edit2_new_position self top_edit_position The list is not reversed and it should be else procedurelogger expectedResult The list is not reversed procedurelogger expectedResult read0 and edit0 change position to s and s self top_read_position self top_edit_position read0_new_position self read_cells 0 _getAccessibleCenter edit0_new_position self edit_cells 0 _getAccessibleCenter assert read0_new_position self top_read_position and edit0_new_position self top_edit_position The list is not in descending order and it should be
test post on the translate view .,def test_translate_post root_doc trans_doc_client data slug root_doc slug title root_doc title content root_doc current_revision content form type both toc_depth 1 url reverse wiki translate args root_doc slug url tolocale fr response trans_doc_client post url data assert response status_code 302 assert response X Robots Tag noindex assert_no_cache_header response doc_url reverse wiki document args root_doc slug locale fr assert doc_url rev_saved in response Location assert len Document objects filter locale fr slug root_doc slug 1 assert len Document objects filter title root_doc title Redirect 1 locale fr 0
default : can not load existing data from storage .,def load_and_validate_existing self storage u return False
split a cone into simplicial cones ; i.e. cones defined by exactly : math:`d ` rays where : math:`d ` is the dimensionality .,def triangulate cone normaliz normaliz workdir normaliz_tmp keep_workdir False switch_representation False cone np asarray cone assert len cone shape 2 cone must be two dimensional assert cone shape 0 cone shape 1 Must at least have as many rays as the dimensionality if cone shape 0 cone shape 1 and not switch_representation raise ValueError cone is simplicial already old_np_printoptions np get_printoptions np set_printoptions threshold np inf os mkdir workdir try run_card_as_str str cone shape 0 str cone shape 1 n run_card_as_str str cone replace replace replace n n if switch_representation False run_card_as_str nintegral_closure n else run_card_as_str ninequalities n run_card_file_prefix normaliz run_card_file_suffix in run_card_filename run_card_file_prefix run_card_file_suffix normaliz_args T verbose command_line_command normaliz normaliz_args run_card_filename with open os path join workdir run_card_filename w as f f write run_card_as_str with open os path join workdir run_info w as infofile infofile write Normaliz run card s n run_card_filename infofile write running s n join command_line_command with open os path join workdir stdout w as stdout with open os path join workdir stderr w as stderr try subprocess check_call command_line_command stdout stdout stderr stderr cwd workdir except OSError as error if normaliz not in str error error filename normaliz raise with open os path join workdir normaliz tgn r as f try shape int f readline int f readline except ValueError f seek 0 original_cone np loadtxt f dtype int with open os path join workdir normaliz tri r as f try shape int f readline int f readline except ValueError f seek 0 array_lines current_str f readline while re match 0 9 current_str is not None array_lines append current_str current_str f readline array_as_str join array_lines simplicial_cones_indices np fromstring array_as_str sep dtype int reshape len array_lines 1 1 1 return original_cone simplicial_cones_indices finally np set_printoptions old_np_printoptions if not keep_workdir shutil rmtree workdir
great k shortest paths of src to dst .,def k_shortest_paths self graph src dst weight weight k 1 generator nx shortest_simple_paths graph source src target dst weight weight shortest_paths try for path in generator if k 0 break shortest_paths append path k 1 return shortest_paths except self logger debug No path between s and s src dst
"returns true if "" e1 "" intersects any edge from "" edges "" .",def edge_intersects_edges e1 nodes edges for i in range len edges e2 edges i if e1 1 e2 0 or e1 0 e2 1 continue if two_edges_intersect nodes e1 e2 return True return False
graphical interface for starting this class .,classmethod def guiStart self parent None kwargs independent common _SimplePluginStart FileDetail startDisplay kwargs parent parent return self kwargs independent return self False
returns ` true ` if shell logger socket available .,def is_available path _get_socket_path if not path return False return os path exists path
aciyi star - charts'in istedigi formata cevirir,def angle_to_right_ascension angle return 1 angle 2 math pi 24
note : we could use logging ?,def Write self msg args pass
helper for remove_tree ( ) .,def _build_cmdtuple path cmdtuples for f in os listdir path real_f os path join path f if os path isdir real_f and not os path islink real_f _build_cmdtuple real_f cmdtuples else cmdtuples append os remove real_f cmdtuples append os rmdir path
get the status of some files in the wc .,def test_todo self self _change_to_pkg simple p osc core Package p todo test missing_added foo exp_st D foo missing_added st p get_status False self assertEqual exp_st st
"template method - initialize the state , called once the first time a state is selected .",def init self return
get cards for this list . returns a list of card objects,def get_cards self cards self get_cards_json self base_uri cards_list for card_json in cards cards_list append self create_card card_json return cards_list
run a statement on the database directly .,def query self query args kwargs if isinstance query six string_types query text query _step kwargs pop _step QUERY_STEP rp self executable execute query args kwargs return ResultIter rp row_type self row_type step _step
this will force this class to read the data type from data at the specified offset,def __init__ self buffer args kwargs if isinstance buffer str fd cStringIO StringIO buffer self buffer Buffer fd else self buffer buffer self parameters kwargs if self buffer self data self read else self buffer Buffer cStringIO StringIO
: returns : list of sources attached sandbox : rtype : list,property def sources self return self config sources
backlinks ( links to current page ),def get_links page_name try query Page select join Link on Link page Page name where Link link page_name order_by SQL mtime desc dicts for page in query yield page query Page select join Link on Link link Page name where Link page page_name order_by SQL mtime desc dicts for page in query yield page except OperationalError as e log warn e return
check creation of single - dimensional objects,def test_zerosSD self ua zeros 2 dtype U s self ulen self content_check ua ua 0 4 self ulen 2 self content_check ua ua 1 4 self ulen 2
test whether each element of a 1-d array is also present in a second array .,def in1d ar1 ar2 assume_unique False ar1 np asarray ar1 ravel ar2 np asarray ar2 ravel if len ar2 10 len ar1 0 145 mask np zeros len ar1 dtype np bool for a in ar2 mask ar1 a return mask if not assume_unique ar1 rev_idx np unique ar1 return_inverse True ar2 np unique ar2 ar np concatenate ar1 ar2 order ar argsort kind mergesort sar ar order equal_adj sar 1 sar 1 flag np concatenate equal_adj False indx order argsort kind mergesort len ar1 if assume_unique return flag indx else return flag indx rev_idx
run the given test case or test suite .,def run self test class_ test __class__ classname class_ __module__ class_ __name__ if self _stream None filename TEST s xml self _name or classname if self _filename filename self _filename stream file os path join self _path filename w stream write xml version 1 0 encoding utf 8 n else stream self _stream result _XMLTestResult classname start_time time time old_stdout sys stdout old_stderr sys stderr sys stdout StringIO sys stderr StringIO try test result try out_s sys stdout getvalue except AttributeError out_s try err_s sys stderr getvalue except AttributeError err_s finally sys stdout old_stdout sys stderr old_stderr time_taken time time start_time result print_report stream time_taken out_s err_s if self _stream None stream close return result
find a spec for the given module .,def find_spec modpath path None _path path or sys path modpath modpath submodule_path None module_parts modpath processed while modpath modname modpath pop 0 finder spec _find_spec_with_path _path modname module_parts processed submodule_path or path processed append modname if modpath submodule_path finder contribute_to_path spec processed if spec type ModuleType PKG_DIRECTORY spec spec _replace submodule_search_locations submodule_path return spec
send a multipart mail through smtp using given parameters,def send_mail_multipart self sender target subject content tracking_id None newpart None content s n n s n content self signature msg MIMEMultipart msg Subject Pyvac s subject msg From sender msg To target msg Date formatdate body MIMEText content encode utf 8 plain utf 8 msg attach body if newpart attachment MIMEText newpart encode utf 8 calendar utf 8 attachment add_header Content Disposition attachment filename invite ics msg attach attachment self _send_mail sender target msg
provides the implementation of p_hash function defined in section 5 of rfc 4346 ( and section 5 of rfc 5246 ) . two parameters have been added ( hm and req_len ) :,def _tls_P_hash secret seed req_len hm hash_len hm hash_alg hash_len n req_len hash_len 1 hash_len res a hm secret digest seed while n 0 res hm secret digest a raw seed a hm secret digest a n 1 return res req_len
return textual representation of domain name .,def text self escape True result_list for label in self labels result for c in label if isinstance c int c_int c_chr c chr c else c_int c_chr ord c c decode if c in result c_chr else result c_chr result_list append result if result_list return else return join result_list
attach a contiguity pysal w object to a layer,def addW2Layer w layer contiguity rook if contiguity upper ROOK layer Wrook w neighbors elif contiguity upper QUEEN layer Wqueen w neighbors else print Unsupported contiguity type contiguity return None
"dependencies are expressed as a dictionary whose keys are items and whose values are a set of dependent items . output is a list of sets in topological order . the first set consists of items with no dependencies , each subsequent set consists of items that depend upon items in the preceding sets .",def toposort data if len data 0 return data data copy for k v in data items v discard k extra_items_in_deps _reduce set union data values set data keys data update item set for item in extra_items_in_deps while True ordered set item for item dep in data items if len dep 0 if not ordered break yield ordered data item dep ordered for item dep in data items if item not in ordered if len data 0 raise ValueError Cyclic dependencies exist among these items format join repr x for x in data items
simply calls origin function with `` args `` argument values .,def call self args return self origin args
"same as frame.pack ( ) , but asserts that the payload size does not exceed 125 bytes .",def pack self if len self payload 125 raise ValueError control frames must not be larger than 125 bytes return Frame pack self
"collection , method , dict . of the parameters ( may be empty )",def askEachAgentInCollectionAndExecLocalCode collection method k setLocalCode for a in collection if common debug applyMethod a method k else try applyMethod a method k except SystemExit print method method raising an exit condition while acting on agent number a number of type a agType os sys exit 1 except BaseException print cannot apply case 1 method method to agent number a number of type a agType pass execLocalCode
"the shared library extension for the platform , e.g. `` dll `` for windows and `` so `` for other platforms .",def platform_shared_library_extension platform u n The shared library extension for the platform e g dll for windows and so for other n platforms n n param platform platform n type platform str FunctionType n returns shared library extension or None n rtype str n platform stringify platform if platform in u win64 u win32 return u dll return u so
"stop tweening an object , without completing the motion or firing the on_complete",def kill_tweens self obj None if obj try del self current_tweens obj except pass else self current_tweens collections defaultdict set
decodes a value to an integer .,def _dictunbaser self string ret 0 for index cipher in enumerate string 1 ret self base index self dictionary cipher return ret
map quotas hard_limit from null to -1,def upgrade migrate_engine _migrate_unlimited migrate_engine None 1
creation of this object should basically cover all time consuming collection . methods after that should not cause time delays due to network operations or lengthy cpu operations .,def __init__ self instance address None content extra_md None self instance instance self extra_md extra_md ctxt context get_admin_context services db service_get_all_by_host ctxt elevated instance host self availability_zone ec2utils get_availability_zone_by_host services instance host self ip_info ec2utils get_ip_info_for_instance ctxt instance self security_groups db security_group_get_by_instance ctxt instance id self mappings _format_instance_mapping ctxt instance if instance get user_data None is not None self userdata_raw base64 b64decode instance user_data else self userdata_raw None self ec2_ids self ec2_ids instance id ec2utils id_to_ec2_inst_id instance id self ec2_ids ami id ec2utils glance_id_to_ec2_id ctxt instance image_ref for image_type in kernel ramdisk if self instance get s_id image_type image_id self instance s_id image_type ec2_image_type ec2utils image_type image_type ec2_id ec2utils glance_id_to_ec2_id ctxt image_id ec2_image_type self ec2_ids s id image_type ec2_id self address address self launch_metadata for item in instance get metadata self launch_metadata item key item value self uuid instance get uuid self content self files ctxt context get_admin_context network_info network API get_instance_nw_info ctxt instance self network_config None cfg netutils get_injected_network_template network_info if cfg key 04i len self content self content key cfg self network_config name network_config content_path s s CONTENT_DIR key for path contents in content key 04i len self content self files append path path content_path s s CONTENT_DIR key self content key contents
update information about a host from its compute_node info .,def update_from_compute_node self compute all_ram_mb compute memory_mb least compute get disk_available_least free_disk_mb least if least is not None else compute free_disk_gb free_disk_mb 1024 self disk_mb_used compute local_gb_used 1024 self free_ram_mb compute free_ram_mb self total_usable_ram_mb all_ram_mb self total_usable_disk_gb compute local_gb self free_disk_mb free_disk_mb self vcpus_total compute vcpus self vcpus_used compute vcpus_used stats compute get stats statmap self _statmap stats self num_instances int statmap get num_instances 0 project_id_keys k for k in statmap keys if k startswith num_proj_ for key in project_id_keys project_id key 9 self num_instances_by_project project_id int statmap key vm_state_keys k for k in statmap keys if k startswith num_vm_ for key in vm_state_keys vm_state key 7 self vm_states vm_state int statmap key task_state_keys k for k in statmap keys if k startswith num_task_ for key in task_state_keys task_state key 9 self task_states task_state int statmap key os_keys k for k in statmap keys if k startswith num_os_type_ for key in os_keys os key 12 self num_instances_by_os_type os int statmap key self num_io_ops int statmap get io_workload 0
sets security setting ( iptables : port ) if needed .,def iptables_set self node_ip user_data if user_data open_ip base64 b64decode user_data utils execute tftpboot iptables_rule node_ip open_ip
gets the probability of the dependent variable given the independent ones . : param data : matrix of data . : param m : array of means . : param cov : covariance matrix . : param dep : index of dependent variable . : param given : array of indices of independent variables . : return : probabilities .,def dcmvnorm data m cov dep given col_selector x for x in range cov shape 1 if x in given X data col_selector y data dep cov_yy cov dep dep cov_yx __slice_acov__ cov dep given cov_xx inv __slice_scov__ cov dep given m_x m col_selector m_y m dep cov_yx_dot_cov_xx cov_yx dot cov_xx v_y cov_yy cov_yx dot cov_xx dot cov_yx transpose for i in range data shape 0 e_y m_y cov_yx_dot_cov_xx dot X i m_x d y i p_y list dnorm d e_y v_y 0 yield p_y
test add a new route with incomplete parameters,def testAddRouteError self self assertRaises IPROUTECommandError Route add self ip self cidr
create a field container that represents the device held in the non - dominant hand of the active user . see make_dominant_user_device ( ) for more information .,def make_non_dominant_user_device user 0 interface subdisplay return _selected_display make_non_dominant_user_device user interface subdisplay
store the camera intrinsics . we need this for the calibration matrices from the tango,def new_camera_intrinsics_callback self new_camera_info self camera_intrinsics new_camera_info self k_mat np matrix np array self camera_intrinsics K reshape 3 3 self k_inv self k_mat I
many ovs functions return an int which is one of : - 0 : no error yet - > 0 : errno value - eof : end of file ( not necessarily an error ; depends on the function called ),def ovs_retval_to_string retval if not retval return if retval 0 return os strerror retval if retval EOF return End of file return unknown return value s retval
called if no specific method for processing a trace event has been found .,def catchall self event rec pass
".dump ? table ? dumps a database into a sql string if table is specified , dump that table .",def do_dump self line try if not line for row in self conn iterdump self display row else conn sqlite3 connect memory cu conn cursor cu execute attach database self database as attached_db cu execute select sql from attached_db sqlite_master where type table and name line sql_create_table cu fetchone 0 cu execute sql_create_table cu execute insert into line select from attached_db line conn commit cu execute detach database attached_db self display n join conn iterdump except print Invalid table specified
this is not meant to be used,def write_geometry self args kwargs raise ValueError self __class__ __name__ can not write a geometry
removes all records from the report .,def clear self for record_id in self get_children self delete record_id
"2-d zoom interpolation using purely python - fast if compiled with numba . both the array to zoom and the output array are required as arguments , the zoom level is calculated from the size of the new array .",numba jit nopython True nogil True def zoom_numbaThread data chunkIndices zoomArray for i in range chunkIndices 0 chunkIndices 1 x i numba float32 data shape 0 1 zoomArray shape 0 0 99999999 x1 numba int32 x for j in range zoomArray shape 1 y j numba float32 data shape 1 1 zoomArray shape 1 0 99999999 y1 numba int32 y xGrad1 data x1 1 y1 data x1 y1 a1 data x1 y1 xGrad1 x x1 xGrad2 data x1 1 y1 1 data x1 y1 1 a2 data x1 y1 1 xGrad2 x x1 yGrad a2 a1 zoomArray i j a1 yGrad y y1 return zoomArray
create a dictionary of devices known to the user account .,timed_cached_property ttl 10 def devices self params access_token self access_token r self spark_api GET params params timeout self timeout self _check_error r json_list r json devices_dict if json_list allKeys functions variables api requires_deep_update status for device_json in json_list allKeys update device_json keys Device _BaseDevice make_device_class self allKeys timeout self timeout for d in json_list if d connected info self _get_device_info d id d functions info get functions d variables info get variables d api self spark_api d id d requires_deep_update d get requires_deep_update False d status info get status d setdefault key None for key in allKeys devices_dict d name Device d return devices_dict
detect the base and return a decimal equivalent,def parse_bases snum string False if snum startswith and snum endswith num ord snum 1 1 elif string and snum startswith and snum endswith AsmError_NO_RET 211 Error use single quotes for an ascii constant return elif snum endswith 2 num int snum 2 2 elif snum endswith 10 num int snum 3 10 elif snum endswith 16 num int snum 3 16 else num int snum 0 return num
"attempts adding a new block to the blockchain . median is good for weeding out liars , so long as the liars do n't have 51 % hashpower .",def add_block block DB def median mylist if len mylist 1 return 0 return sorted mylist len mylist 2 def block_check block DB def tx_check txs start copy deepcopy txs out start_copy while start start_copy if start return False start_copy copy deepcopy start if transactions tx_check start 1 type start 1 out DB out append start pop else return True return True if not isinstance block dict return False if error in block return False if length not in block return False length DB length if int block length int length 1 return False if block diffLength hexSum DB diffLength hexInvert block target return False if length 0 if tools detSha db_get length DB block prevHash return False a copy deepcopy block a pop nonce if u target not in block keys return False half_way u nonce block nonce u halfHash tools detSha a if tools detSha half_way block target return False if block target target DB block length return False earliest median recent_blockthings time DB custom mmm if time not in block return False if block time time time return False if block time earliest return False if tx_check block txs return False return True if block_check block DB print add_block str block db_put block length block DB DB length block length DB diffLength block diffLength orphans copy deepcopy DB txs DB txs for tx in block txs DB add_block True transactions update tx type tx DB for tx in orphans add_tx tx DB
usage : rsyncmatch.py [ --debug ] [ filter rules ... ] directory ...,def print_matches import getopt import logging loggingclass init_logging gl GlobChain options args getopt gnu_getopt sys argv 1 gl _known_options debug gl getopt options for x in options if x 0 debug GlobChain set_log_level loggingclass DEBUG RsyncGlob set_log_level loggingclass DEBUG for dir in args ls gl recurse dir print List of include files below s dir for x in ls print x
"this method pass exception from python into tcl as error , so we get stacktrace and reason : param text : text of error : return : raise exception",def raise_tcl_error self text raise self app TclErrorException text
@rtype : list[ert.enkf.enums . realizationstateenum ],def getCaseRealizationStates case_name state_map ERT ert getEnkfFsManager getStateMapForCase case_name return state for state in state_map
entry point for this component . overrides l{component.run },def run self while True for data in self receive_all in tokens parts data split self sep for i in self indicies try tokens append parts i 1 except pass this_string join tokens self send out this_string self yield_ctrl
return the rangeset that contains at most the first ' n ' integers .,def first self n if self size n return self out for s e in self if e s n out s s n break else out s e n e s return RangeSet data out
inverse of the softplus transform : .. math : :,def backward self y Inverse of the softplus transform math x log exp y 1 The bound for the input y is self _lower inf self _lower is subtracted prior to any calculations The implementation avoids overflow explicitly by applying the log sum exp trick math log exp y exp 0 ys log exp y ys exp ys ys log 1 exp ys ys max 0 y As y can not be negative ys could be replaced with y itself However in case math y 0 this results in np log 0 Hence the zero is replaced by a machine epsilon math ys max epsilon y ys np maximum y self _lower np finfo settings float_type eps return ys np log np expm1 ys
context manager that temporarily replaces stdout for tests that need to verify output,contextmanager def swap_stdout old_stdout sys stdout if PY3 fake_stream StringIO else fake_stream BytesIO try sys stdout fake_stream yield fake_stream finally sys stdout old_stdout
fetch a file from chroot to local,def fetch_file self in_path out_path super Connection self fetch_file in_path out_path display vvv FETCH s TO s in_path out_path host self chroot in_path shlex_quote self _prefix_login_path in_path try p self _buffered_exec_command dd if s bs s in_path BUFSIZE except OSError raise AnsibleError chroot connection requires dd command in the chroot with open to_bytes out_path errors surrogate_or_strict wb as out_file try chunk p stdout read BUFSIZE while chunk out_file write chunk chunk p stdout read BUFSIZE except traceback print_exc raise AnsibleError failed to transfer file s to s in_path out_path stdout stderr p communicate if p returncode 0 raise AnsibleError failed to transfer file s to s n s n s in_path out_path stdout stderr
updates the os with ` swupd update `,def update_os self if self module check_mode self module exit_json changed self _needs_update if not self _needs_update self msg There are no updates available return cmd self _get_cmd update self _run_cmd cmd if self rc 0 self changed True self msg Update successful return self failed True self msg Failed to check for updates
get the timestamp as a utc .,def get_datetime_utc self return self timestamp
tests the states of the node,def test_states assert root state state1 assert child2 state state3 assert grandchild1 state state4
intialize the reader and writer class .,def __init__ self alphabet None self _alphabet alphabet self separator
"sprot_search_de(text , swissprot=1 , trembl = none , cgi='http://www.expasy.ch / cgi - bin / sprot - search - de ' ) - > handle",def sprot_search_de text swissprot 1 trembl None cgi http www expasy ch cgi bin sprot search de variables SEARCH text if swissprot variables S on if trembl variables T on options urllib urlencode variables fullcgi s s cgi options handle urllib urlopen fullcgi return handle
calculate the position of the chart with blank space .,def _determine_position self start_x start_y end_x end_y x_padding self padding_percent end_x start_x y_padding self padding_percent start_y end_y new_x_start start_x x_padding new_x_end end_x x_padding if self chart_title new_y_start start_y y_padding self chart_title_size else new_y_start start_y y_padding new_y_end end_y y_padding return new_x_start new_x_end new_y_start new_y_end
* * additional input arguments * *,def _train self x y if self _xTx is None if self with_bias x_size self _input_dim 1 else x_size self _input_dim self _xTx numx zeros x_size x_size self _dtype self _xTy numx zeros x_size self _output_dim self _dtype if self with_bias x self _add_constant x self _xTx mult x T x self _xTy mult x T y self _tlen x shape 0
create a shake for user admin . should succeed and redirect to /short_name,def test_shake_create_success self self user stripe_plan_id mltshp double self user save arguments name yo description My little corner of the world title title response self post_url shake create arguments arguments s Shake get name s yo self assertEqual response effective_url self get_url yo self assertTrue s
open an image file in binary mode and return the handler,def hOpenImgBinary imgfileName try fHandler open imgfileName rb return fHandler except IOError raise SystemExit
calculate subset of points that make a convex hull around points,def convex_hull points points np asarray points points points T n_pts points shape 1 assert n_pts 1 centre points mean 1 angles np apply_along_axis _angle_to_point 0 points centre pts_ord points angles argsort pts x 0 for x in zip pts_ord transpose prev_pts len pts 1 while prev_pts n_pts prev_pts n_pts n_pts len pts i 2 while i n_pts 2 Aij area_of_triangle centre pts i pts i 1 n_pts Ajk area_of_triangle centre pts i 1 n_pts pts i 2 n_pts Aik area_of_triangle centre pts i pts i 2 n_pts if Aij Ajk Aik del pts i 1 i 1 n_pts len pts return np asarray pts
function to remove all file created by nemoh from the case directory inputs : none otuputs : none,def clean self rmd self dir os system rm self baseDir os path sep log try os remove self files ID dat except pass try os remove self mesh files Mesh cal except pass
check if cleanable vo status is cleanable .,def is_cleanable self pinned False if pinned obj_version self get_pinned_version else obj_version None return self _is_cleanable self status obj_version
creates a group from a group snapshot .,def test_create_group_from_group_snapshot self created_group self api post_group group group_type self group_type id volume_types self volume_type id self assertTrue created_group id created_group_id created_group id found_group self _poll_group_while created_group_id creating self assertEqual created_group_id found_group id self assertEqual self group_type id found_group group_type self assertEqual available found_group status created_volume self api post_volume volume size 1 group_id created_group_id volume_type self volume_type id self assertTrue created_volume id created_volume_id created_volume id found_volume self api get_volume created_volume_id self assertEqual created_volume_id found_volume id self assertEqual self _vol_type_name found_volume volume_type self assertEqual created_group_id found_volume group_id found_volume self _poll_volume_while created_volume_id creating self assertEqual available found_volume status created_group_snapshot self api post_group_snapshot group_snapshot group_id created_group_id self assertTrue created_group_snapshot id created_group_snapshot_id created_group_snapshot id found_group_snapshot self _poll_group_snapshot_while created_group_snapshot_id creating self assertEqual created_group_snapshot_id found_group_snapshot id self assertEqual created_group_id found_group_snapshot group_id self assertEqual available found_group_snapshot status created_group_from_snap self api post_group_from_src create from src group_snapshot_id created_group_snapshot_id self assertTrue created_group_from_snap id created_group_from_snap_id created_group_from_snap id found_volumes self api get_volumes self _poll_volume_while found_volumes 0 creating self _poll_volume_while found_volumes 1 creating found_group_from_snap self _poll_group_while created_group_from_snap_id creating self assertEqual created_group_from_snap_id found_group_from_snap id self assertEqual created_group_snapshot_id found_group_from_snap group_snapshot_id self assertEqual self group_type id found_group_from_snap group_type self assertEqual available found_group_from_snap status self api delete_group created_group_from_snap_id delete delete volumes True found_group_from_snap self _poll_group_while created_group_from_snap_id deleting self api delete_group_snapshot created_group_snapshot_id found_group_snapshot self _poll_group_snapshot_while created_group_snapshot_id deleting self api delete_group created_group_id delete delete volumes True found_volume self _poll_volume_while created_volume_id deleting found_group self _poll_group_while created_group_id deleting self assertFalse found_group_from_snap self assertFalse found_group_snapshot self assertFalse found_volume self assertFalse found_group
replace the contents of the given image with the new data .,def update self context image_id metadata data None purge_props False if not self images get image_id raise exception ImageNotFound image_id image_id if purge_props self images image_id copy deepcopy metadata else image self images image_id try image properties update metadata pop properties except Exception pass image update metadata return self images image_id
"checks if user has the admin role , the domain does not match sensitive domains and whitelisted domain patterns . : param domain : domain name ( str ) : return :",def sensitive_domain domain if SensitiveDomainPermission can return whitelist current_app config get LEMUR_WHITELISTED_DOMAINS if whitelist and not any re match pattern domain for pattern in whitelist raise ValidationError Domain 0 does not match whitelisted domain patterns Contact an administrator to issue the certificate format domain if any d sensitive for d in domain_service get_by_name domain raise ValidationError Domain 0 has been marked as sensitive Contact an administrator to issue the certificate format domain
identify nights with two well separated transits,def IDdoubleEclipses self axis color k ls doubleNights goodNights for time in range 0 len self allMidE for otherTime in range 0 len self allMidE if time otherTime and np abs self allMidE time self allMidE otherTime 0 5 doubleNights append self allMidE time if np abs self allMidE time self allMidE otherTime 0 16 goodNights append self allMidE time for time in goodNights axis axvline ymin 0 ymax 1 x time color color ls ls return np unique goodNights
returns the center of the cell in world coordinates,def to_world self return tuple to_world_coordinate c for c in self location
driver function for the computation of the mm algorithm,def main cand_set 0 1 2 votes 0 1 2 1 2 0 mmagg MMPLAggregator cand_set gamma mmagg aggregate votes epsilon 1e 07 max_iters 20 print mmagg alts_to_ranks mmagg ranks_to_alts assert mmagg get_ranking i for i in cand_set 1 0 2 print gamma
this test is an example of using the class variable ' nodes ' the prior test set the class variable to be used by this test . this test prints out the class variable,depends after test_get_nodes_rackhdapi def test_display_class_nodes self my_nodes self __class__ nodes logs info s dumps my_nodes indent 4
"generates list of documents using pmids and the restapi interface from tmtools . source : "" http://www.ncbi.nlm.nih.gov/cbbresearch/lu/demo/tmtools/ "" : param list_of_pmids : strings : return nalaf.structures.dataset : dataset",def generate_abstracts self list_of_pmids url_tmvar http www ncbi nlm nih gov CBBresearch Lu Demo RESTful tmTool cgi Mutation 0 JSON url_converter http www ncbi nlm nih gov pmc utils idconv v1 0 if os path exists cache json with open cache json r encoding utf 8 as f tm_var json load f else tm_var for pmid in list_of_pmids if pmid not in tm_var req requests get url_tmvar format pmid try tm_var pmid req json except ValueError pass with open cache json w as file json dump tm_var file indent 4 dataset Dataset for doc_id in list_of_pmids if doc_id in tm_var doc Document text tm_var doc_id text part Part text denotations tm_var doc_id denotations annotations for deno in denotations ann Entity class_id self mut_class_id offset int deno span begin text text deno span begin deno span end annotations append ann part annotations annotations doc parts abstract part dataset documents doc_id doc return dataset
generate a dataproxy from the given schema .,def data_proxy_factory basename schema strict True cls_name sDataProxy basename nmspc __slots__ schema schema _fields schema fields _fields_from_mongo_key v attribute or k v for k v in schema fields items data_proxy_cls type cls_name BaseDataProxy if strict else BaseNonStrictDataProxy nmspc return data_proxy_cls
get the number of pending reviews for given review step .,def get_step_count user step cache_key review_step_count_ d_ s user id step count cache get cache_key if count is None count Review objects filter reviewer user filter closed_on None filter role step count cache set cache_key count None return count
"takes : input : desired current axis number , int [ ]",current_axis setter def current_axis self input self _current_axis input
test interpolating with log x - scale .,def test_log_interpolate_1d x_log np array 1000 0 10000 0 100000 0 1000000 0 y_log np log x_log 2 3 x_interp np array 5000 0 50000 0 500000 0 y_interp_truth np array 20 0343863828 24 6395565688 29 2447267548 y_interp log_interpolate_1d x_interp x_log y_log assert_array_almost_equal y_interp y_interp_truth 7
return a string representation of the iobuffer .,def __str__ self return Size Offset format len self _data self _offset
create a new media item .,def make_media db return media_item db 2x233 gif
"function take an automaton object as argument , and return initialized numpy ndarray of type np.int32",def fld_init a fld np zeros a width a height dtype np int32 conway a str2genome 3 23 cx cy 360 360 fld 0 cx 1 cy conway fld 0 cx 2 cy conway fld 0 cx 3 cy conway fld 1 cx 0 cy conway fld 2 cx 0 cy conway life34 a str2genome 34 34 cx cy 870 360 fld 2 cx 0 cy life34 fld 0 cx 1 cy life34 fld 1 cx 1 cy life34 fld 1 cx 2 cy life34 fld 1 cx 3 cy life34 fld 2 cx 2 cy life34 fld 3 cx 2 cy life34 pseudolife a str2genome 357 238 c 150 for i in xrange 500 r i 58321 11113 fld r 1280 r 3 c pseudolife fld r 3 c r 720 pseudolife return fld
available batch ( line - search ) solvers,def batch_solvers self return gd cgd lbfgs
"execute command in a subshell , return status code .",def sh cmd return check_call cmd shell True
compute the wind direction given a u and v wind speed,def drct u v umps u value MPS vmps v value MPS val np arctan2 umps vmps 180 0 np pi 180 return dt direction val DEG
add an eclib . platebutton to the controlbar specified by cbarpos . @keyword lbl : button label @keyword bmp : bitmap or editraartprovider id @keyword align : button alignment @keyword cbarpos : controlbar position @return : platebutton instance,def AddPlateButton self lbl u bmp 1 align wx ALIGN_LEFT cbarpos wx TOP ctrlbar self GetControlBar cbarpos assert ctrlbar is not None No ControlBar at cbarpos if not isinstance bmp wx Bitmap assert isinstance bmp int bmp wx ArtProvider GetBitmap str bmp wx ART_MENU if bmp IsNull or not bmp IsOk bmp None btn eclib PlateButton ctrlbar wx ID_ANY lbl bmp style eclib PB_STYLE_NOBG ctrlbar AddControl btn align return btn
deletes files or directories at the provided paths . directories will be deleted recursively .,def delete self paths def _delete_path path Recursively delete the file or directory at the provided path try if os path isdir path shutil rmtree path else os remove path except OSError as err raise IOError err exceptions for path in paths try _delete_path path except Exception as e exceptions path e if exceptions raise BeamIOError Delete operation failed exceptions
description : adds a word in the trie data structure .,def add self word u n Description n Adds a word in the trie data structure n n Args n arg word str The word that you want to insert in the trie n n Raises n raises AssertionError if the word is None n n assert word is not None u Input word cannot be None node self root for i in range 0 len word letter word i if letter not in node children self _id 1 node add_child letter _id self _id node node letter if i len word 1 node eow True self _num_of_words 1
test observer handle_logs with logtype stderr,def test_handle_logs_with_stderr self process mock Mock mock_logs _ mock_ologs make_mocks base_path MOCK_BASE_PATH filename MOCK_FILENAME process process logtype stderr with contextlib nested mock patch apache thermos observer task_observer TaskObserver logs return_value mock_ologs mock patch apache thermos observer task_observer TaskObserver valid_path return_value MOCK_BASE_PATH MOCK_FILENAME ptfb PatchingTaskObserverFileBrowser actual_logs ptfb handle_logs MOCK_TASK_ID process 1 stderr assert mock_logs actual_logs assert actual_logs task_id MOCK_TASK_ID assert actual_logs filename MOCK_FILENAME assert actual_logs process process assert actual_logs run 1 assert actual_logs logtype stderr
checks if the platforms have a valid platform code,def check_platforms platforms if len platforms 0 return all platform in PLATFORM_IDS for platform in platforms return True
getpool - return the current members of a pool and its free list,def getPool self vmName self log debug Received getPool request s vmName try if not vmName or vmName return result self preallocator getPool vmName return pool_size d len result pool free_size d len result free pool s result pool free s result free except Exception as err self log error getPool request failed s err return
install a source file into a target using the function specified as the install construction variable .,def installFunc target source env try install env INSTALL except KeyError raise SCons Errors UserError Missing INSTALL construction variable assert len target len source Installing source s into target s target and source lists must have same length list map str source list map str target for t s in zip target source if install t get_path s get_path env return 1 return 0
"return a "" view "" of the meshsource , in the spirit of numpy 's ndarray view .",def view self view object __new__ MeshSource view base self return view __finalize__ self
_ merge_to_n_commands functions as expected ( even number of cmds ),def test_merge_to_n_commands_even self commands pick_otus py h mv somthing txt something_else txt pick_otus py g pick_otus py f pick_otus py w expected bin bash pick_otus py h mv somthing txt something_else txt pick_otus py g pick_otus py f pick_otus py w exit actual self pw _merge_to_n_commands commands 1 self assertEqual actual expected expected bin bash pick_otus py h mv somthing txt something_else txt pick_otus py g exit bin bash pick_otus py f pick_otus py w exit actual self pw _merge_to_n_commands commands 2 self assertEqual actual expected expected bin bash pick_otus py h mv somthing txt something_else txt pick_otus py g exit bin bash pick_otus py f pick_otus py w exit actual self pw _merge_to_n_commands commands 3 self assertEqual actual expected expected bin bash pick_otus py h mv somthing txt something_else txt exit bin bash pick_otus py g exit bin bash pick_otus py f exit bin bash pick_otus py w exit actual self pw _merge_to_n_commands commands 4 self assertEqual actual expected self assertRaises ValueError self pw _merge_to_n_commands commands 0 self assertRaises ValueError self pw _merge_to_n_commands commands 42 expected bin bash pick_otus py h mv somthing txt something_else txt exit bin bash pick_otus py g exit bin bash pick_otus py f exit bin bash pick_otus py w exit actual self pw _merge_to_n_commands commands 100 self assertEqual actual expected self assertRaises ValueError self pw _merge_to_n_commands commands 0 self assertRaises ValueError self pw _merge_to_n_commands commands 42
test correctly suppresses different plot types .,def test_make_distance_boxplots_suppress_plots self obs make_distance_boxplots self dm_f self map_f Bar suppress_all_within True self assertEqual len obs 1 self assertEqual obs 0 0 Bar self assertTrue isinstance obs 0 1 Figure self assertEqual len obs 0 2 4 self assertEqual len obs 0 3 4 self assertEqual obs 0 4 None None None None obs make_distance_boxplots self dm_f self map_f Bar suppress_all_within True suppress_all_between True self assertEqual len obs 1 self assertEqual obs 0 0 Bar self assertTrue isinstance obs 0 1 Figure self assertEqual len obs 0 2 3 self assertEqual len obs 0 3 3 self assertEqual obs 0 4 None None None obs make_distance_boxplots self dm_f self map_f Bar suppress_all_within True suppress_all_between True suppress_individual_within True self assertEqual len obs 1 self assertEqual obs 0 0 Bar self assertTrue isinstance obs 0 1 Figure self assertEqual len obs 0 2 1 self assertEqual len obs 0 3 1 self assertEqual obs 0 4 None obs make_distance_boxplots self dm_f self map_f Bar suppress_all_within True suppress_all_between True suppress_individual_between True self assertEqual len obs 1 self assertEqual obs 0 0 Bar self assertTrue isinstance obs 0 1 Figure self assertEqual len obs 0 2 2 self assertEqual len obs 0 3 2 self assertEqual obs 0 4 None None obs make_distance_boxplots self dm_f self map_f Bar suppress_individual_within True suppress_individual_between True self assertEqual len obs 1 self assertEqual obs 0 0 Bar self assertTrue isinstance obs 0 1 Figure self assertEqual len obs 0 2 2 self assertEqual len obs 0 3 2 self assertEqual obs 0 4 None None
selects samples on a message from the user,authenticated execute_as_transaction def on_message self msg msginfo loads msg default self current_user default_analysis default add_samples msginfo sel self write_message dumps sel len set chain from_iterable s for s in viewvalues msginfo sel
is desktop window manager compositing ( aero ) enabled .,def is_dwm_compositing_enabled import ctypes enabled ctypes c_bool try DwmIsCompositionEnabled ctypes windll dwmapi DwmIsCompositionEnabled except AttributeError WindowsError return False rval DwmIsCompositionEnabled ctypes byref enabled return rval 0 and enabled value
add a file to the ( python ) filesystem with the given static contents .,def add_static filename contents l len contents def do_open return l def do_read offset size return contents offset offset size pyfs_add filename do_open do_read
returns the worker 's worker 's identity,property def identity self if self _identity is None self _identity d s os getpid socket gethostname return self _identity
due tomorrow ( creation date + recurrence ),def test_progress16 self set_256_colors color progress_color Todo 2015 12 01 Foo due 2016 01 02 rec 1d self assertEqual color color 22
test that we raise the underlying exception when it 's not one of the expected exception types .,def test_unexpected_exception self with self assertRaises TestUnexpectedException self _get_wrapped 5 exception_class TestUnexpectedException self assertEqual 1 self num_calls
"helper function to get all * .simulation from the direction specified in --simulation_data_dir returns file with .simulation extensions , corresponding roots ( no extension ) of each file",def get_simulation_files simulation_files glob glob os path join simulation_data_dir simulation simulation_roots os path splitext os path split x 1 0 for x in simulation_files return simulation_files simulation_roots
"process surface magnetic field measurement time series with indices * dt * and components * bx * and * by*. output a : class:`dataframe ` with columns * c1 * and * c2 * associated with the processed output time series . if * despike_data * , remove outliers prior to filtering . if * remove_mean * , remove the mean from the output time series .",def process_timeseries dt Bx By c1 B_X c2 B_Y despike_data True remove_mean True warnings warn use process_df instead PendingDeprecationWarning n consecutive_nans Bx By interval dt 1 dt 0 total_seconds if n 0 logger warning longest contiguous gap 2f minutes format n interval 60 Bx nan_interp Bx By nan_interp By if despike_data df PD DataFrame index dt data Bx Bx By By df despike df dt df index to_pydatetime Bx df Bx values By df By values if interval 1 0 h second_interval_filter elif interval 60 0 h minute_interval_filter else raise ValueError 1 to 100 mHz filter not yet synthesized for s interval data format interval Bx_filtered dt_filtered lp_fir_filter h Bx mode valid index dt By_filtered lp_fir_filter h By mode valid if remove_mean Bx_filtered NP mean Bx_filtered By_filtered NP mean By_filtered return PD DataFrame index dt_filtered data c1 Bx_filtered c2 By_filtered
maps an enum value to an integer using an ` enum_mapper ` ( one of the objects in ` c2corg_common.sortable_search_attributes ` .,def map_enum_to_int enum_mapper s if s in enum_mapper return enum_mapper s else return None
does calling prime with 0 raise an indexerror ?,def test_zero self with self assertRaises IndexError primer prime 0
"this helper method verifies , for the provided filesystem , that the nodesets possibly set on command line , to restrain the node list , did not : - disabled all nodes - specified nodes which are not in filesystem configuration . return false if nothing was done .",def check_valid_list self fs_name fs_nodes action_txt do selected_nodes self options nodes excluded_nodes self options excludes if selected_nodes if excluded_nodes selected_nodes selected_nodes excluded_nodes if fs_nodes selected_nodes selected_nodes fs_nodes if selected_nodes print sys stderr WARNING Nothing to s on s for s action_txt selected_nodes fs_name if len fs_nodes 0 print sys stderr WARNING Nothing was done for s fs_name return False return True
the disassembly engine will stop on address in args if they are not at the block beginning,def add_disassembly_splits self args self split_dis update set args
creates random dna sequence in phylip format .,def phylip len num output_name bases A T C G file open output_name w file write str num str len n for i in range num file write seq str i for j in range len file write random choice bases file write n file close
"r2 is the region after the first non - vowel following a vowel in r1 , or the end of the word if there is no such non - vowel .",def R2 w if w startswith tuple overstemmed return R1 R1 R1 w return R1 R1 w
called when loss of leadership is detected,def on_leadership_lost self
returns a tuple containing the max value in the temperature series preceeded by its timestamp,def max_temperature self unit kelvin if unit not in kelvin celsius fahrenheit raise ValueError Invalid value for parameter unit maximum max self _purge_none_samples self temperature_series key itemgetter 1 if unit kelvin result maximum if unit celsius result maximum 0 temputils kelvin_to_celsius maximum 1 if unit fahrenheit result maximum 0 temputils kelvin_to_fahrenheit maximum 1 return result
"show target information for a specific module , next argument is module name",def cmd_xInfo self self loadDevice modName self _getcmd if not modName print sys stderr s xInfo requires a module name sys argv 0 sys exit 1 ext self device getApi modName ext load ext printStatus
takes a screen capture and saves it into the output file .,click command option_device click argument output click pass_context def screencap ctx device index output device __determine_device_id ctx params Adb screencap device output
read a graph from a path,def read_graph path formatting None writable extract_writable path formatting graph graph_from_writable writable return graph
parse a distcc hosts specification and count the number of hosts .,def count_hosts hosts num_hosts 0 for host in hosts split if host zeroconf raise ValueError Can t count hosts when zeroconf is in DISTCC_HOSTS if host startswith continue num_hosts 1 return num_hosts
create a runinstance in qc .,def make_test_run testinstance exec_date exec_time duration 0 status Passed run testinstance RunFactory AddItem Run format datetime now run Status status run SetField RN_DURATION duration run SetField RN_EXECUTION_DATE exec_date run SetField RN_EXECUTION_TIME exec_time run Post run Refresh run SetField RN_EXECUTION_DATE exec_date run SetField RN_EXECUTION_TIME exec_time run Post run Refresh return run
preprocess a file using cpp .,def preprocess text try CREATE_NO_WINDOW 134217728 pipe subprocess Popen PATH_LIST stdout subprocess PIPE stdin subprocess PIPE universal_newlines True creationflags CREATE_NO_WINDOW processed_text pipe communicate text 0 except OSError as e raise RuntimeError Unable to invoke cpp Make sure its path was passed correctly Original error s e return processed_text
adds a new row to the spill unit .,def addRow self row_vals rowdata_key u main index None kwargs u Adds a new row to the spill unit n n Ensures that certain requirements of the data rows such as the n chainage needing to increase for each row down are met then call the n addNewRow method in the row_collection n n Args n row_vals Dict keys must be datunits ROW_DATA_TYPES with a legal n value assigned for the DataType Chainage and Elevation MUST n be included n index None int the row to insert into The existing row at the n given index will be moved up by one n n Returns n False if the addNewRow method is unsuccessful n n Raises n IndexError If the index does not exist n ValueError If the given value is not accepted by the DataObjects n n See Also n ADataObject and subclasses for information on the parameters n keys row_vals keys if not rdt CHAINAGE in keys or not rdt ELEVATION in keys raise AttributeError u row_vals must include CHAINAGE and ELEVATION AUnit addRow self row_vals index index kwargs
returns an iterator which goes over edges by end nodes .,def iterateEdgesByEndNodes self return self endNodesToEdgeD keys
fetch the list of payment processor classes based on django settings .,def get_queryset self return self request site siteconfiguration get_payment_processors
tell sailthru when payment started .,receiver basket_addition silence_exceptions Failed to call Sailthru upon basket addition def process_basket_addition sender product None user None request None basket None is_multi_product_basket None kwargs if not waffle switch_is_active sailthru_enable return site_configuration request site siteconfiguration if not site_configuration enable_sailthru return if product is_seat_product course_id product course_id stock_record product stockrecords first if stock_record price stock_record price_excl_tax currency stock_record price_currency message_id request COOKIES get sailthru_bid if message_id and basket BasketAttribute objects update_or_create basket basket attribute_type get_basket_attribute_type defaults value_text message_id if price and not is_multi_product_basket update_course_enrollment delay user email _build_course_url course_id True mode_for_product product unit_cost price course_id course_id currency currency site_code site_configuration partner short_code message_id message_id
verify an error is shown if an exception is raised when requesting eligibility information from the credit api .,httpretty activate def test_eligibility_api_failure self u Verify an error is shown if an exception is raised when requesting n eligibility information from the Credit API n self _mock_eligibility_api body status 500 self _assert_error_without_deadline
regress on the differences to the observed summaries .,def _input_variables self model sample summary_names observed_summaries np stack model s observed for s in summary_names axis 1 summaries np stack sample outputs name for name in summary_names axis 1 return summaries observed_summaries
returns object of type c{bookiversion}. if version is none it returns latest version .,def getVersion book version book_ver None if not version book_ver book version elif version find 1 book_ver models BookVersion objects get book book name version else v version split book_ver models BookVersion objects get book book major int v 0 minor int v 1 return book_ver
force getting a unicode string from any object .,def to_unicode x encoding None errors strict if isinstance x unicode return x elif isinstance x bytes if encoding return unicode x encoding errors else return unicode x errors errors else return unicode x
saves the file to ' filename ' on the local machine,def save self filename log debug saving to s filename mp3 open filename wb r self request data r read 32 1024 while data mp3 write data data r read 32 1024 mp3 close r close log debug Done
returns a list of current caches,def get_cache_names self return cache_mapping keys
convert an integer to roman numerals .,def int_to_roman input if type input type 1 raise TypeError expected integer got s type input if not 0 input 4000 raise ValueError Argument must be between 1 and 3999 ints 1000 900 500 400 100 90 50 40 10 9 5 4 1 nums M CM D CD C XC L XL X IX V IV I result for i in range len ints count int input ints i result nums i count input ints i count return result
return ` _ _ doc _ _ ` of the given object as unicode,def get_obj_doc obj u doc getattr obj u __doc__ u or u if not isinstance doc text_type doc text_type doc u utf 8 return doc
"given a line from /proc / pid / maps , return true if the image name is in the blacklist .",def is_blacklisted_library self s_maps_line global GL_LIBRARY_BLACKLIST_NAMES for blacklisted in GL_LIBRARY_BLACKLIST_NAMES if re search blacklisted s_maps_line return True return False
converts all variables in a graph and checkpoint into constants .,def freeze_graph input_graph input_saver input_binary input_checkpoint output_node_names restore_op_name filename_tensor_name output_graph clear_devices initializer_nodes if not tf gfile Exists input_graph print Input graph file input_graph does not exist return 1 if input_saver and not tf gfile Exists input_saver print Input saver file input_saver does not exist return 1 if not tf gfile Glob input_checkpoint print Input checkpoint input_checkpoint doesn t exist return 1 if not output_node_names print You need to supply the name of a node to output_node_names return 1 input_graph_def tf GraphDef mode rb if input_binary else r with tf gfile FastGFile input_graph mode as f if input_binary input_graph_def ParseFromString f read else text_format Merge f read input_graph_def if clear_devices for node in input_graph_def node node device _ tf import_graph_def input_graph_def name with tf Session as sess if input_saver with tf gfile FastGFile input_saver mode as f saver_def tf train SaverDef if input_binary saver_def ParseFromString f read else text_format Merge f read saver_def saver tf train Saver saver_def saver_def saver restore sess input_checkpoint else sess run restore_op_name filename_tensor_name input_checkpoint if initializer_nodes sess run initializer_nodes output_graph_def graph_util convert_variables_to_constants sess input_graph_def output_node_names split with tf gfile GFile output_graph wb as f f write output_graph_def SerializeToString print d ops in the final graph len output_graph_def node
updates ssh daemon 's keys .,def UpdateSshDaemon data dry_run _runcmd_fn utils RunCmd _keyfiles None keys data get constants SSHS_SSH_HOST_KEY if not keys return if _keyfiles is None _keyfiles constants SSH_DAEMON_KEYFILES logging info Updating SSH daemon key files _UpdateKeyFiles keys dry_run _keyfiles if dry_run logging info This is a dry run not restarting SSH daemon else result _runcmd_fn pathutils DAEMON_UTIL reload ssh keys interactive True if result failed raise JoinError Could not reload SSH keys command s had exitcode s and error s result cmd result exit_code result output
return the list of nodegroups .,def GetNodegroupList self data self _ReadFile constants SS_NODEGROUPS nl data splitlines False return nl
see : meth : ` openquake.hazardlib.source.base.baseseismicsource.count_ruptures ` .,def count_ruptures self whole_fault_surface SimpleFaultSurface from_fault_data self fault_trace self upper_seismogenic_depth self lower_seismogenic_depth self dip self rupture_mesh_spacing whole_fault_mesh whole_fault_surface mesh mesh_rows mesh_cols whole_fault_mesh shape fault_length float mesh_cols 1 self rupture_mesh_spacing fault_width float mesh_rows 1 self rupture_mesh_spacing self _nr for mag mag_occ_rate in self get_annual_occurrence_rates if mag_occ_rate 0 continue rup_cols rup_rows self _get_rupture_dimensions fault_length fault_width mag num_rup_along_length mesh_cols rup_cols 1 num_rup_along_width mesh_rows rup_rows 1 self _nr append num_rup_along_length num_rup_along_width counts sum self _nr n_hypo len self hypo_list or 1 n_slip len self slip_list or 1 return counts n_hypo n_slip
raise a notfound if the parent region does not exist .,def _check_parent_region self session region_ref parent_region_id region_ref get parent_region_id if parent_region_id is not None self _get_region session parent_region_id
the beans are now in the machine ; save them .,_machine output def _save_beans self beans self _beans beans
adds a list of observed objects .,def add_all_objects self objs self __objects extend objs
return a relative file if it is embedded in a path .,def GetSourceFile file sourcepath for root in sourcepath if file find root 0 prefix_length len root if not root endswith prefix_length 1 relative_file file prefix_length return relative_file return None
test the submission of a survey anonymously .,def test_submit_survey_anonymously self survey_models config_model Config set anonymous_surveys True with mock patch object self question1 stream_to_bq autospec True as mock_stream self question1 submit selected_answer self answer1 acting_user loanertest USER_EMAIL self question1 selected_answer self answer1 mock_stream assert_called_once_with survey_models constants DEFAULT_ACTING_USER Filing survey question response with mock patch object self question2 stream_to_bq autospec True as mock_stream self question2 submit selected_answer self answer2 acting_user survey_models constants DEFAULT_ACTING_USER more_info_text More info self question2 selected_answer self answer2 mock_stream assert_called_once_with survey_models constants DEFAULT_ACTING_USER Filing survey question response
a generator for modules ( uses _ kpcr symbols ),def lsmod self for module in self session GetParameter PsLoadedModuleList list_of_type _LDR_DATA_TABLE_ENTRY InLoadOrderLinks if self plugin_args name_regex and not self plugin_args name_regex search utils SmartUnicode module FullDllName continue yield module
compiles a feature - matching regex .,def compileFeatureRE name featureRE list parser featureContentRE featureRE insert 2 name featureRE insert 6 name return re compile join featureRE
deprecates products in datastore that no longer exist in any catalogs .,classmethod def _DeprecateOrphanedProducts cls catalog_products set for os_version in applesus OS_VERSIONS for track in common TRACKS untouched key s_ s os_version track catalog_obj models AppleSUSCatalog get_by_key_name key if not catalog_obj logging error Catalog does not exist s key continue catalog_plist plist ApplePlist catalog_obj plist try catalog_plist Parse except plist Error logging exception Error parsing Apple Updates catalog s key continue for product in catalog_plist get Products catalog_products add product gc collect deprecated for p in models AppleSUSProduct all filter deprecated False if p product_id not in catalog_products p deprecated True p put deprecated append p return deprecated
loads the preferences from chrome profile stored in @p profile_dir .,def _LoadPreferences profile_dir _LOGGER info Reading preferences from s profile_dir with open _GetPreferencesFile profile_dir as f return json load f
zips up all files needed to run the game .,def main dir_name os path basename os getcwd zip_file_name dir_name zip try zip_file zipfile ZipFile zip_file_name w zipfile ZIP_DEFLATED except IOError as error sys stderr write Could not open s for writing s n zip_file_name str error return 1 for relative_path in EXPORT_DIRECTORIES for root _ filenames in os walk relative_path for filename in filenames input_path os path join root filename output_path os path join dir_name root filename try zip_file write input_path output_path except IOError as error handle_io_error error filename return 1 for filename in EXPORT_FILES output_path os path join dir_name filename try zip_file write filename output_path except IOError as error handle_io_error error filename return 1 try zip_binary zip_file bin zooshi dir_name zip_binary zip_file bin flatc dir_name if platform system Windows zip_binary zip_file bin SDL2 dll dir_name except MissingBinaryError as error sys stderr write Could not find s binary n error filename return 1 except IOError as error handle_io_error error error filename return 1 zip_file close return 0
uses price parsing utils to convert sales catalogs price fields into a paid_amount object .,def main mongo price_field price_amount_1 currency_field price_currency_1 for record in mongo db_collection find event make_processing_event event datetime str datetime utcnow event pathname __name__ event args price_field price_field currency_field currency_field derived parse_price record price_field currency_field event record derived file_name derived record log append event record flags file_name event status mongo db_collection replace_one _id record _id record pprint record derived pprint record log 1 print
"edit file in place , returns a list of modifications ( unified diff ) .",def edit_file self file_name with open file_name r as from_file from_lines from_file readlines to_lines self edit_line line for line in from_lines diffs difflib unified_diff from_lines to_lines fromfile file_name tofile new if not self dry_run bak_file_name file_name bak if os path exists bak_file_name raise EditorError 0 already exists format bak_file_name try os rename file_name bak_file_name with open file_name w as new_file new_file writelines to_lines os unlink bak_file_name except os rename bak_file_name file_name raise return list diffs
the api should not define any required parameters without a default,def test_api_params self parse_params API_PARAMS
perform one step of gradient descent on the provided batch of data .,def train_on_batch self sess inputs_batch labels_batch feed self create_feed_dict inputs_batch labels_batch labels_batch _ loss sess run self train_op self loss feed_dict feed return loss
is not quite sucessful right now,def loop_folder folder_name import glob i 0 start_port 40035 for pcap_file_name in glob glob os path join folder_name pcap print start to process pcap_file_nam pcap_file_name i 1 flowd_pid softflowd_pid flowreader_pid pcap2flow pcap_file_name 127 0 0 1 d start_port 30 i time sleep 1
raises exception if value is not a valid model species entry,def validate_species_names value must_have_length value species name sequence min_len 1 for species_count in value must_be_string_like species_count species name
just ... is this a valid unit entity_id .,def does_unit_exist db_conn entity_id query SELECT entity_id FROM units_entity_id WHERE entity_id entity_id s LIMIT 1 params entity_id convert_slug_to_uuid entity_id return get_row db_conn query params
loads attributes dictionary from ` data `,def load_attrs self data schema allow_partial False if isinstance data list set tuple return self load_attrs item schema allow_partial for item in data mapping self get_schema_mapping schema return mapping load_attrs data self allow_partial allow_partial
apply a ' null ' filter to the filename supplied .,def apply self filename return True
convert a dpid from a long into into the canonical string form .,def dpid_to_str dpid alwaysLong False if type dpid is long or type dpid is int dpid struct pack Q dpid assert len dpid 8 r join 02x ord x for x in dpid 2 if alwaysLong or dpid 0 2 x00 2 r str struct unpack H dpid 0 2 0 return r
perform a substitution on a task,def subs task key val if not istask task if task key return val elif isinstance task list return subs x key val for x in task else return task newargs for arg in task 1 if istask arg arg subs arg key val elif isinstance arg list arg subs x key val for x in arg elif type arg is type key and arg key arg val newargs append arg return task 1 tuple newargs
see : py : mod:`niprov.recording `,def record self command new None parents None transient False args None kwargs None user None opts None return niprov recording record command new parents transient args kwargs user opts self deps
removes a principal from an acl,event_or_id def remove_principal self event name principal u Removes a principal from an ACL n n param event Event or its ID n param name Setting name n param principal A class User or a class GroupProxy n self _check_name name EventSettingPrincipal remove_principal self module name principal event_id event self _flush_cache
builds the url of a css resource .,def get_css_url event force_theme None for_preview False u Builds the URL of a CSS resource n n param event The Event to get the CSS url for n param force_theme The ID of the theme to override the custom CSS resource n only if it exists n param for_preview Whether the URL is used in the CSS preview page n return The URL to the CSS resource n from indico modules events layout import layout_settings if force_theme and force_theme u _custom return _build_css_url force_theme elif for_preview and force_theme is None return None elif force_theme u _custom or layout_settings get event u use_custom_css if not event has_stylesheet return None return url_for u event_layout css_display event slug event stylesheet_metadata u hash elif layout_settings get event u theme return _build_css_url layout_settings get event u theme
looks at various hints to find the redirect target .,def get_redirect_target for target in request args get next request referrer if not target continue if is_safe_url target return target
initializes a connection to hdfs .,def __init__ self super HadoopFileSystem self __init__ self _hdfs_client HDFileSystem
ad a row to the table,def row2table soup table row tr Tag soup name tr table append tr for attr in row td Tag soup name td tr append td td append attr
update the session headers with the request ones while ignoring certain name prefixes .,def update_headers self request_headers for name value in request_headers items if value is None continue value value decode utf8 if name User Agent and value startswith HTTPie continue for prefix in SESSION_IGNORED_HEADER_PREFIXES if name lower startswith prefix lower break else self headers name value
"helper that reads the binary content of the specified file , or none if the file does n't exist . this returns a byte string .",def _read_binary self filename u n Helper that reads the binary content of the specified file or n None if the file doesn t exist This returns a byte string n with io open filename u rb as f return f read
"switch to math mode , main difference is that brackets are not interpreted as tree brackets : param feed : : param math_mode : new value for math mode , true / false : return :",def toggle_math_mode self self feed pop self math_mode not self math_mode
parse command - line arguments .,def parse_args p argparse ArgumentParser description __doc__ p add_argument v verbose action count help be more verbose p add_argument p patients help patients file p add_argument b nboot type int default 2000 help number of bootstraps p add_argument voxel default 0 help index of voxel to use or mean or median p add_argument m pmaps nargs required True help pmap files pairs grouped together p add_argument figdir help figure output directory return p parse_args
poll the server periodically until the action has either completed or errored out and return its final state .,def wait self wait_interval None wait_time None return next self doapi_manager wait_actions self wait_interval wait_time
returns the position of the parent node of the node at ` pos ` or ` none ` if none exists .,def parent_position self pos return None
when marking test case results inside a test run there is a ' report ' link . when the ` report ' link is clicked this method is called to help the user report an issue in the it .,def report_issue_from_testcase self caserun raise NotImplementedError
initialize the database and tables . args : connection : an sqliteconnectionmanager object .,def __init__ self connection_manager self __mgr connection_manager cert_repeated_field_tables issuer type TEXT name TEXT subject type TEXT name TEXT subject_alternative_names type TEXT name TEXT subject_names name TEXT root_issuer type TEXT name TEXT observations description TEXT reason TEXT details BLOB cert_single_field_tables version INTEGER serial_number TEXT with self __mgr get_connection as conn conn execute CREATE TABLE IF NOT EXISTS certs log INTEGER id INTEGER sha256_hash BLOB UNIQUE cert BLOB join s s column type_ for column type_ in cert_single_field_tables PRIMARY KEY log id for entry in cert_repeated_field_tables self __create_table_for_field conn entry conn execute CREATE INDEX IF NOT EXISTS certs_by_subject on subject_names name self __tables logs certs column for column _ in cert_repeated_field_tables
called from the network proxy thread main loop .,def run self self wallet synchronize with self lock addresses self new_addresses self new_addresses set self subscribe_to_addresses addresses up_to_date self is_up_to_date if up_to_date self wallet is_up_to_date self wallet set_up_to_date up_to_date self network trigger_callback updated
triggers an interrupt on the gpio name gpio_name,def send_interrupt self gpio_name msg zmq Frame GPIO encode ascii zmq Frame to_bytes gpio_name zmq Frame INT encode ascii self ipc_socket send_multipart msg
construct a series of period objects,def periods today None today today or pd Timestamp today def __f offset today return Period start today offset end today offset pd Series offset Two weeks pd DateOffset weeks 2 offset Month to Date pd offsets MonthBegin offset Year to Date pd offsets YearBegin offset One Month pd DateOffset months 1 offset Three Months pd DateOffset months 3 offset One Year pd DateOffset years 1 offset Three Years pd DateOffset years 3 offset Five Years pd DateOffset years 5 offset Ten Years pd DateOffset years 10 return offset apply __f today today
register an observer to a given rate,def register_to_rates self start None end None field None observer None start get_livedate start end get_livedate end if start end end start if end live r self get_or_make end field r attach observer if start end return self factory loadhistory start end field observer observer
handles an http get request .,def get self query lookup_query LookupQuery query initialize_from_http_request self request logging info Policy is s query policy lookup_resolver resolver new_resolver query policy sliver_tools lookup_resolver answer_query query if sliver_tools is None return util send_not_found self query response_format if query response_format message FORMAT_JSON self send_json_response sliver_tools query elif query response_format message FORMAT_HTML self send_html_response sliver_tools query elif query response_format message FORMAT_REDIRECT self send_redirect_response sliver_tools query elif query response_format message FORMAT_BT self send_bt_response sliver_tools query elif query response_format message FORMAT_MAP candidates lookup_resolver get_candidates query self send_map_response sliver_tools query candidates else self send_json_response sliver_tools query self log_request query sliver_tools
returns a list of args for the specified method in the class of a func module . this is useful when register_method_args is not defined ( or not properly ),def get self modname methodname vtuple pv pyver vtuple 0 vtuple 1 sys path append usr lib python pyver site packages func minion modules the_mod __import__ modname name data inspect getmembers the_mod inspect isclass 0 the_class modname name c getattr the_mod name return arg for arg in inspect getargspec eval c methodname 0 if arg self
set the parameters of this estimator .,def set_params self params if not params return self valid_params self get_params deep True for key value in six iteritems params split key split __ 1 if len split 1 name sub_name split if name not in valid_params raise ValueError Invalid parameter s for estimator s name self sub_object valid_params name sub_object set_params sub_name value else if key not in valid_params raise ValueError Invalid parameter s for estimator s key self __class__ __name__ setattr self key value return self
"return all fields that shall be pickled . walk the slots in the class hierarchy and add those to the state dictionary . if a ' _ _ dict _ _ ' slot is available , copy all entries to the dictionary . also include the version i d , which is fixed for all instances of a class .",def __getstate__ self state getattr self __dict__ copy for obj in type self mro for name in getattr obj __slots__ if hasattr self name state name getattr self name state _version_id self current_version_id try del state __weakref__ except KeyError pass return state
"returns -9999 if above top of system , + 9999 if below bottom of system , negative for in leaky layer . leaky layer -n is on top of aquifer n",def inWhichLayer self z if z self zt 0 return 9999 for i in range self naq 1 if z self zb i return i if z self zt i 1 return i 1 if z self zb self naq 1 return self naq 1 return 9999
get the path of numpy headers .,def numpy_include_dir try import numpy as np except ImportError print Cannot build mdtraj extensions without numpy installed sys exit 1 return np get_include
allocates the trajectory array for the recording of the trajectory of each tracked particle . the user has to specify for how many kmc steps the trajectory should be recorded .,def allocate_trajectory kmc_model nr_of_steps kmc_model base_acf allocate_trajectory nr_of_steps
list directory ' root ' appending the path separator to subdirs .,def _listdir self root res for name in os listdir root path os path join root name if os path isdir path name os sep res append name return res
users can explicitly set the config file using the ' --config ' option . allows users to specify a config other than the default ` mkdocs.yml ` .,def test_load_from_file self u n Users can explicitly set the config file using the config option n Allows users to specify a config other than the default mkdocs yml n temp_dir TemporaryDirectory config_file open os path join temp_dir name u mkdocs yml u w os mkdir os path join temp_dir name u docs try config_file write u site_name MkDocs Test n config_file flush config_file close cfg base load_config config_file config_file name self assertTrue isinstance cfg base Config self assertEqual cfg u site_name u MkDocs Test finally os remove config_file name
calculates the levenshtein distance between a and b.,def _levenshtein a b u n m len a len b if n m return _levenshtein b a current range n 1 for i in range 1 m 1 previous current current i 0 n for j in range 1 n 1 add delete previous j 1 current j 1 1 change previous j 1 if a j 1 b i 1 change 1 current j min add delete change return current n
generate an error record in the journal .,def j_error app src action msg instance None metadata None return Record objects log app app type_ RECORD_ERROR src src action action msg msg instance instance metadata metadata
returns an iterator that waits for one message at a time .,def consume self limit None for total_message_count in count if limit and total_message_count limit raise StopIteration if not self channel is_open raise StopIteration self channel conn drain_events yield True
args : model_input : a ' batch_size ' x ' max_frames ' x ' num_features ' matrix of input features . vocab_size : the number of classes in the dataset . num_frames : a vector of length ' batch ' which indicates the number of frames for each video ( before padding ) .,def create_model self model_input vocab_size num_frames unused_params num_frames tf cast tf expand_dims num_frames 1 tf float32 feature_size model_input get_shape as_list 2 denominators tf reshape tf tile num_frames 1 feature_size 1 feature_size avg_pooled tf reduce_sum model_input axis 1 denominators output slim fully_connected avg_pooled vocab_size activation_fn tf nn sigmoid weights_regularizer slim l2_regularizer 1e 08 with open frame_level data a as f_handle np savetxt f_handle avg_pooled return predictions output
retrieve message header of message number ' which ' and first ' howmuch ' lines of message body .,def top self which howmuch return self _longcmd TOP s s which howmuch
return true if the device is a frequency electrometer,def isFreqType self device _type device getType return _type 1 or _type 2 or _type 3 or _type 6
: apply this style to the given object using the supplied defaults .,def apply self obj defaults kwargs if not isinstance obj mplaxis Axis msg Unable to apply this sub style to the given element Expected a matplotlib Axis and instead received the following s obj raise Exception msg subKwargs kwargs get majorTicks subDefaults S lib resolveDefaults defaults majorTicks value self majorTicks grid getValue visible subDefaults subKwargs if value is not None obj grid value which major majorOn self majorTicks marks getValue visible subDefaults subKwargs majorOn2 self majorTicks secondaryMarks getValue visible subDefaults subKwargs if majorOn or majorOn2 if isinstance obj get_major_locator mticker NullLocator obj set_major_locator mticker AutoLocator elif majorOn is not None or majorOn2 is not None if not isinstance obj get_major_locator mticker NullLocator obj set_major_locator mticker NullLocator majorTicks obj get_major_ticks for tick in majorTicks self majorTicks apply tick subDefaults subKwargs subKwargs kwargs get minorTicks subDefaults S lib resolveDefaults defaults minorTicks value self minorTicks grid getValue visible subDefaults subKwargs if value is not None obj grid value which minor minorOn self minorTicks marks getValue visible subDefaults subKwargs minorOn2 self minorTicks secondaryMarks getValue visible subDefaults subKwargs if minorOn or minorOn2 if isinstance obj get_minor_locator mticker NullLocator obj set_minor_locator mticker AutoMinorLocator elif minorOn is not None or minorOn2 is not None if not isinstance obj get_minor_locator mticker NullLocator obj set_minor_locator mticker NullLocator minorTicks obj get_minor_ticks for tick in minorTicks self minorTicks apply tick subDefaults subKwargs subKwargs kwargs get label subDefaults S lib resolveDefaults defaults text labels label self label apply obj get_label subDefaults subKwargs subKwargs kwargs get offsetText subDefaults S lib resolveDefaults defaults text labels offsetText self offsetText apply obj get_offset_text subDefaults subKwargs axes obj axes if isinstance obj mplaxis XAxis autoOn self getValue autoscale defaults kwargs if autoOn is not None axes set_autoscalex_on autoOn value self getValue dataMargin defaults kwargs if value is not None axes set_xmargin value axes autoscale enable autoOn axis x elif isinstance obj mplaxis YAxis autoOn self getValue autoscale defaults kwargs if autoOn is not None axes set_autoscaley_on autoOn value self getValue dataMargin defaults kwargs if value is not None axes set_ymargin value axes autoscale enable autoOn axis y else msg An error happened while applying Axis style properties to the object s If this error happens it is a result of a coding error and should be reported immediately obj raise Exception msg
return true if and only if * value * is an element in the set .,def __contains__ self value return value in self _set
"function(value ) equals output . if output is none , function(value ) equals value .",def check_output self function value output None if output is None output value self assertEqual function value output
make sure the auth app only appears on the ' other ' db,def allow_migrate self db app_label hints if app_label auth return db other return None
testing envelope expand_to_include with point as parameter .,def test08_expand_to_include_point self self e expand_to_include TestPoint 1 1 self assertEqual 1 0 5 5 self e self e expand_to_include TestPoint 10 10 self assertEqual 1 0 10 10 self e
deleting the * proxy * instance bubbles through to its non - proxy and * all * referring objects are deleted .,def test_delete_proxy self self create_image Image objects all delete self assertEqual len Image objects all 0 self assertEqual len File objects all 0 self assertEqual len FooImage objects all 0 self assertEqual len FooFile objects all 0
saves the results of a bittorrent test,def bittorrent_store self message DATABASE connect if DATABASE readonly logging warning backend_neubot readonly database return table_bittorrent insert DATABASE connection message
return an iterator over the keys of a dictionary .,def iterkeys d return iter getattr d _iterkeys
build and return an * onion skin * to this handshake 's relay .,def createOnionSkin ntorstate ret ntorstate relay_identity ret ntorstate relay_ntor_onion_key ret bytes ntorstate public_key return ret
"returns a length limited version of a string , up to `` max_length `` characters .",def ellipsis string max_length 100 if len string max_length return string else return string max_length 3
"print a list of objects as a table , one row per object .",def print_list objs fields formatters None sortby_index 0 mixed_case_fields None field_labels None formatters formatters or mixed_case_fields mixed_case_fields or field_labels field_labels or fields if len field_labels len fields raise ValueError _ Field labels list labels s has different number of elements than fields list fields s labels field_labels fields fields if sortby_index is None kwargs else kwargs sortby field_labels sortby_index pt prettytable PrettyTable field_labels pt align l for o in objs row for field in fields if field in formatters row append formatters field o else if field in mixed_case_fields field_name field replace _ else field_name field lower replace _ data getattr o field_name row append data pt add_row row if six PY3 print encodeutils safe_encode pt get_string kwargs decode else print encodeutils safe_encode pt get_string kwargs
intercepts temporalmemory deserialization request in order to initialize ` temporalmemorymonitormixin ` state,classmethod def read cls proto tm super TemporalMemoryMonitorMixin cls read proto tm mmName None tm _mmTraces None tm _mmData None tm mmClearHistory tm _mmResetActive True return tm
returns radius for given speed .,def radiusForSpeed self speed overlap 1 5 coordinatesPerTimestep speed self timestep self scale radius int round float coordinatesPerTimestep 2 overlap minRadius int math ceil math sqrt self w 1 2 return max radius minRadius
parametrize a : class:`unittest . testcase ` .,def parametrize TestCase return builtin_types new_class TestCase __name__ dict metaclass _ParametrizedCollection base TestCase
adds a job to the queue .,def enqueue self job with self _queue_cv self _queue append job self _queue_cv notify
summarizes peak loads of underlying load_areas in kva .,def add_peak_demand self peak_load peak_load_satellites 0 for lv_load_area in self lv_load_areas peak_load lv_load_area peak_load if lv_load_area is_satellite peak_load_satellites lv_load_area peak_load self peak_load peak_load self peak_load_satellites peak_load_satellites
"this test compares the discrete finite - difference scheme against polynomials for a given order p , the finite difference scheme should be exact for polynomials of order p : param derivative : name of the derivative to be tested : param space_order : space order of the finite difference stencil",skipif_yask pytest mark parametrize space_order 2 4 6 8 10 12 14 16 18 20 pytest mark parametrize derivative dx dxl dxr dx2 def test_fd_space derivative space_order clear_cache nx 100 xx np linspace 1 1 nx dx xx 1 xx 0 grid Grid shape nx dtype np float32 x grid dimensions 0 u Function name u grid grid space_order space_order du Function name du grid grid space_order space_order coeffs np ones space_order dtype np float32 polynome sum coeffs i x i for i in range 0 space_order polyvalues np array polynome subs x xi for xi in xx np float32 u data polyvalues Dpolynome diff diff polynome if derivative dx2 else diff polynome Dpolyvalues np array Dpolynome subs x xi for xi in xx np float32 u_deriv getattr u derivative stencil Eq du u_deriv op Operator stencil subs x spacing dx op apply space_border space_order error abs du data space_border space_border Dpolyvalues space_border space_border assert np isclose np mean error 0 0 atol 0 001
returns an unreferenced dict with connection information .,def get_connection_info self token access_url ret dict self __dict__ ret token token ret access_url access_url return ret
returns the list of actions recorded for a given instance .,def index self req server_id context req environ nova context instance common get_instance self compute_api context server_id authorize_actions context target instance actions_raw self action_api actions_get context instance actions self _format_action action for action in actions_raw return instanceActions actions
bind cli arguments to a shell.py ` do_foo ` function .,def add_arg func args kwargs if not hasattr func arguments func arguments if args kwargs not in func arguments func arguments insert 0 args kwargs
"reboots , shuts down or powers up the host .",def _host_power_action self req host_name action context req environ nova context authorize context try result self api host_power_action context host_name host_name action action except NotImplementedError msg _ Virt driver does not implement host power management raise webob exc HTTPNotImplemented explanation msg except exception NotFound as e raise webob exc HTTPNotFound explanation e format_message except exception ComputeServiceUnavailable as e raise webob exc HTTPBadRequest explanation e format_message return host host_name power_action result
returns true if button num is now pressed . buttons are numbered 0 .. 3 .,def get_button num if num 0 or num 3 raise ValueError Illegal button number _time sleep 0 01 return _button_state num
sets the mount up to the current location . mount must be initialized first .,def _setup_location_for_mount self assert self is_initialized self logger warning Mount has not been initialized assert self location is not None self logger warning Please set a location before attempting setup self logger debug Setting up mount for location
< insert documentation for function >,def _branches self thisBranch if thisBranch is None thisBranch thisBranch append self _obj myBranches thisBranch for aChild in self _children myBranches extend aChild _branches thisBranch thisBranch pop return myBranches
writes the css file into to the directory that the file is in .,def writeCssForFile theFile return writeCssToDir os path dirname theFile
update attributes in interval class . here all these attributes have float datatype,def __update self if self __percent 0 raise ValueError parameter percent must be positive if self __center 0 self __percent 0 elif isinf self __center if isinf self __percent raise ValueError cannot construct interval with infinite center and infinite percent self __percent 0 elif isinf self __percent self __center 0
"_ _ call__(self , hx , xs )",def __call__ self hx xs kwargs hy ys self _call hx xs kwargs return hy ys
"from a list of strings , get all unique strings that start with tzid",def _get_TZIDs lines return sorted line for line in lines if line startswith TZID
return a dictionary mapping subreddits to their karma .,def karma self karma_map for row in self _reddit get API_PATH karma data subreddit Subreddit self _reddit row sr del row sr karma_map subreddit row return karma_map
write secret and private key to filename .,def write_keys_to_file filename keys config configparser ConfigParser config keys secret keys secret private keys private if not os path exists os path dirname filename os makedirs os path dirname filename mode 448 with open filename w as f config write f
return attrs that are not in ignored_attrs,def _filter_attrs attrs ignored_attrs return dict k v for k v in attrs items if k not in ignored_attrs
"places array back into the object , removing markers .",staticmethod def __place_arrays obj array_list if isinstance obj BaseObject for k v in vars obj iteritems setattr obj k BaseObject __place_arrays v array_list elif isinstance obj NumpyMarker return array_list obj id elif isinstance obj list or isinstance obj tuple for i in range len obj obj i BaseObject __place_arrays obj i array_list elif isinstance obj dict for k v in obj iteritems obj k BaseObject __place_arrays v array_list return obj
generetors of items to include in the sitemap,def items self request return
wire up the incoming lambda / api gateway request to an application .,def call_api event app_name app_swagger_path logger strict_validation True validate_responses True cache_app True app get_connexion_app app_name app_name app_swagger_path app_swagger_path strict_validation strict_validation validate_responses validate_responses cache_app cache_app return app call_api event
field ` outlet node name `,property def outlet_node_name self return self Outlet Node Name
use sklearn.external.tifffile.imread to read image.tiff .,def external_tifffile_imread self u n Use sklearn external tifffile imread to read image tiff n file_name os path join self data_dir u image tiff external tifffile imread file_name
add a word to the user 's personal exclude list .,def remove self word self _words remove word if self pwl is not None pwlF file self pwl wt for w in self _words pwlF write s n w strip pwlF close
if the repo has never been checked for an update .,def test_no_last_checked self config get_jigconfig self gitrepodir config remove_section jig set_jigconfig self gitrepodir config last_check last_checked_for_updates self gitrepodir self assertEqual 0 last_check
apply patches to histfactory xml output from printxml,def patch_xml files root_file None float_precision 3 if float_precision 0 raise ValueError precision must be greater than 0 def fix_path match path match group 1 if path head tail os path split path new_path os path join os path basename head tail else new_path return Input 0 Input format new_path for xmlfilename in files xmlfilename os path abspath os path normpath xmlfilename patched_xmlfilename 0 tmp format xmlfilename log info patching 0 format xmlfilename fin open xmlfilename r fout open patched_xmlfilename w for line in fin if root_file is not None line re sub InputFile InputFile 0 format root_file line line line replace StatError Activate True InputFile HistoName HistoPath StatError Activate True line re sub Combination OutputFilePrefix S Combination OutputFilePrefix hist2workspace line line re sub w line line re sub s line line re sub S s 1 line line re sub InputFileHigh S line line re sub InputFileLow S line line line replace ParamSetting Const True ParamSetting line re sub d d 0 d format float_precision 1 lambda x 0 format str round float x group 1 float_precision line line re sub s s S 1 line line re sub Input Input fix_path line fout write line fin close fout close shutil move patched_xmlfilename xmlfilename if not os path isfile os path join os path dirname xmlfilename HistFactorySchema dtd rootsys os getenv ROOTSYS None if rootsys is not None dtdfile os path join rootsys etc HistFactorySchema dtd target os path dirname xmlfilename if os path isfile dtdfile log info copying 0 to 1 format dtdfile target shutil copy dtdfile target else log warning 0 does not exist format dtdfile else log warning ROOTSYS is not set so cannot find HistFactorySchema dtd
writes a wall post to the given profile 's wall .,def put_wall_post self message attachment profile_id me return self put_object profile_id feed message message attachment
set the visibility of the window and the tray .,def setVisible self visible QtGui QMainWindow setVisible self visible if not options systray return self minimizeAction setEnabled visible self maximizeAction setEnabled not self isMaximized self restoreAction setEnabled self isMaximized or not visible self trayIcon setVisible not visible if not visible self showMessage GINI GINI is still running in the background
"reads the files at the given paths and returns the concatenated results . for unknown file types , the files are read in a default binary or text mode , which can be overridden via the binary flag .",def readfiles paths binary None return n join readfile path binary for path in paths
converts an image to grayscale and prints the locations of any faces found,def detectObjects image grayscale cvCreateImage cvSize image width image height 8 1 cvCvtColor image grayscale CV_BGR2GRAY storage cvCreateMemStorage 0 cvClearMemStorage storage cvEqualizeHist grayscale grayscale cascade cvLoadHaarClassifierCascade usr share opencv haarcascades haarcascade_frontalface_default xml cvSize 1 1 faces cvHaarDetectObjects grayscale cascade storage 1 2 2 CV_HAAR_DO_CANNY_PRUNING cvSize 50 50 if faces for f in faces print d d d d f x f y f x f width f y f height
derivative of mesigma with respect to the model,property def MeSigmaDerivMat self u n Derivative of MeSigma with respect to the model n if getattr self u _MeSigmaDerivMat None is None dsigma_dlogsigma Utils sdiag self sigma self etaDeriv self _MeSigmaDerivMat self mesh getEdgeInnerProductDeriv np ones self mesh nC np ones self mesh nE dsigma_dlogsigma return self _MeSigmaDerivMat
"arguments : - parent : the parent window of this ceframe . - title : the title as appearing in the title bar . - action : a tuple ( ' label ' , callback ) . - menu : the title of the right menu as a string if not none , the menu can be filled via the cb_menu attribute after ceframe initialization .",def __init__ self parent None title PocketPyGui action None menu None right_action None tab_traversal True visible True enabled True has_sip True has_toolbar False Frame __init__ self parent title tab_traversal tab_traversal visible visible enabled enabled self bind _activate self _on_activate _settingchanged self _on_setting_changed size self _on_size if has_toolbar self toolbar ToolBar self else self toolbar None self __create_menubar action menu right_action has_sip
verify s3 target url with params,mock patch luigi contrib s3 S3Target __init__ def test_s3_parse_param self s3_init_patch s3_init_patch return_value None local_file s3 zefr foo bar txt foo hello bar true OpenerTarget local_file s3_init_patch assert_called_with s3 zefr foo bar txt foo hello bar true
remove an inode from the dictionary,def unregister self inode del self files inode path
called when a connection is retrieved from the pool .,def checkout self dbapi_con con_record con_proxy
construct a tensorflow function to compute the likelihood .,def compute_log_likelihood self X None Y None Construct a tensorflow function to compute the likelihood log p Y theta assert X is None and Y is None does not support minibatch mode format str type self K self kern K self X Variable torch eye self X size 0 out self X data new self likelihood variance get L torch potrf K upper False m self mean_function self X return densities multivariate_normal self Y m L
the computation of a constant model based on a linear regression model .,def derived_const analysis const_ref _ analysis _filter_by_models analysis const_ref required if const_ref b1_threshold 0 const_ref b1_threshold _DEFAULT_THRESHOLD for result in analysis tools validate_dictionary_keys result r_square coeffs y_sum pts_num x_interval_start x_interval_end uid method const const_ref copy r 1 result r_square slope abs result coeffs 1 if slope const b1_threshold coeff slope const b1_threshold 10 if coeff 1 coeff 1 r coeff else coeff 1 const b1_threshold const b1_threshold slope 1 r coeff if r 1 r 1 elif r 0 r 0 const r_square r const x_interval_start result x_interval_start const x_interval_end result x_interval_end const coeffs result y_sum result pts_num 0 const uid result uid const method result method yield const
"checks whether the given minor version specification corresponds to the wrapped version control system , and is not in wrong format .",def check_minor_version_validity minor_version vcs_type vcs_path pcs get_vcs_type pcs get_vcs_path dynamic_module_function_call perun vcs vcs_type _check_minor_version_validity vcs_path minor_version
encode a uri string or string component .,def uriencode uristring safe encoding utf 8 errors strict if not isinstance uristring bytes uristring uristring encode encoding errors if not isinstance safe bytes safe safe encode ascii try encoded _encoded safe except KeyError encoded _encoded for i in _tointseq safe encoded i _fromint i _encoded safe encoded return join map encoded __getitem__ _tointseq uristring
correct travel times of taup for other ( crust ) model,def correct_ttt phase P slowness 6 4 newmodel iasp91 oldmodel iasp91 tpo tso xp xs oldmodel trace slowness tpn tsn xp xs newmodel trace slowness z min oldmodel z 1 newmodel z 1 if phase P return interpolate z newmodel z tpn interpolate z oldmodel z tpo else return interpolate z newmodel z tsn interpolate z oldmodel z tso
"checks all variables in the config . especially if all given binaries are actually executable , have the correct version and support everything needed",def check_config if not path isfile LLVMOPT or llvm bc bc modular optimizer not in __get_output_from LLVMOPT help raise Exception Config Invalid opt binary if LLVM version 3 4 2 not in __get_output_from LLVMOPT version raise Exception Config Invalid opt version if not path isfile LIBMACKEOPT raise Exception Config Invalid libmackeopt binary mhelp __get_output_from LLVMOPT load LIBMACKEOPT help if any t not in mhelp for t in extractcallgraph listallfuncstopologic encapsulatesymbolic preprenderror raise Exception Config limackeopt does not support all required passes if not path isfile KLEEBIN raise Exception Config Invalid KLEE binary kvers __get_output_from KLEEBIN version if KLEE not in kvers or LLVM version 3 4 2 not in kvers raise Exception Config Invalid klee version khelp __get_output_from KLEEBIN help if any t not in khelp for t in sonar sonar target sonar target info string raise Exception Config klee does not support sonar search if THREADNUM is not None and not 0 THREADNUM 128 raise Exception Config Invalid Number of threads
create a new hashing object and return it .,def new key msg None digestmod None return HMAC key msg digestmod
return an l{axiom.iaxiom . icomparison } ( an object that can be passed as the ' comparison ' argument to store.query/.sum/.count ) which will constrain a query against 2 attributes for ranges which contain the given argument . the range is half - open .,def contains startAttribute endAttribute value return AND startAttribute value value endAttribute
process a i{delete } change .,def _process_delete existing change if change type in u SOA u NS raise _error if existing change return discard raise _error
"gets a datetime object representing the job 's end time , or none if the string representation ca n't be converted .",property def end_datetime self return self _end_datetime
returns a pandas . period for a given growing season year and week number,def _period_for_week year week_number first_sunday _first_sunday year return pandas Period first_sunday freq W SAT week_number 1
sets the currently selected customer of the user .,def set_current_customer self customer c UserKey Name customer name ci CustomerInfo customer name self _raw_current_customer c self _current_customer ci
takes filenames out of queue and runs clang - tidy on them .,def run_tidy args tmpdir build_path queue while True name queue get invocation get_tidy_invocation name args clang_tidy_binary args checks tmpdir build_path args header_filter args extra_arg args extra_arg_before args quiet sys stdout write join invocation n subprocess call invocation queue task_done
send an alert email and restart the instance if needed .,def handle_collider_response self error_message status_code collider_instance result constants WSS_HOST_STATUS_CODE_KEY status_code memcache_key get_collider_probe_success_key collider_instance constants WSS_INSTANCE_NAME_KEY host collider_instance constants WSS_INSTANCE_HOST_KEY if error_message is not None logging warning Collider prober error error_message for host result constants WSS_HOST_ERROR_MESSAGE_KEY error_message result constants WSS_HOST_IS_UP_KEY False last_probe_success memcache get memcache_key if last_probe_success is None or last_probe_success is True logging info Restarting the collider instance compute_page enqueue_restart_task collider_instance constants WSS_INSTANCE_NAME_KEY collider_instance constants WSS_INSTANCE_ZONE_KEY error_message Restarting the collider instance automatically send_alert_email Collider s error host error_message else result constants WSS_HOST_IS_UP_KEY True memcache set memcache_key result constants WSS_HOST_IS_UP_KEY return result
performs mtd method . see func : teneto.derive.derive .,def temporal_derivative data params report report tdat data 1 data 1 tdat tdat np std tdat axis 0 coupling np array tdat i tdat j for i in np arange 0 tdat shape 1 for j in np arange 0 tdat shape 1 coupling np reshape coupling tdat shape 1 tdat shape 1 tdat shape 0 shape coupling shape 1 coupling shape 1 params windowsize 1 params windowsize strides coupling strides coupling strides 1 coupling_windowed np mean np lib stride_tricks as_strided coupling shape shape strides strides 1 report report method temporalderivative report temporalderivative report temporalderivative windowsize params windowsize return coupling_windowed report
returns script plus extension from an url . ie . http://www.localhost.com/kk/index.html?id=3 will return index.html,property def ffname self u self path split 1 0 return u
convert a dnssec algorithm value to text @rtype : string,def algorithm_to_text value text _algorithm_by_value get value if text is None text str value return text
"represent the surface as a mesh in local coordinates . for the triangular face this means twice the head vertex , and each of the other two vertices are returned in mesh form .",def mesh self resolution 2 if resolution 2 raise ValueError Resolution must be 2 alpha beta np meshgrid np linspace 0 1 resolution np linspace 0 1 resolution x y z alpha self _verts 1 None None 1 beta alpha self _verts 0 None None beta return x y z
helper to obtain a test binary for object file testing .,def get_test_binary self for d in POSSIBLE_TEST_BINARY_PATHS for lib in POSSIBLE_TEST_BINARIES path os path join d lib if os path exists path return path raise Exception No suitable test binaries available
this is run before each test,def setup_method self self rp runparams RuntimeParameters self rp params mesh nx 8 self rp params mesh ny 8 self rp params particles do_particles 0 self rp params eos gamma 1 4 self rp params compressible grav 1 0 self sim sn Simulation compressible test self rp self sim initialize
check the supplied email address against a list of known free webmail domains .,def clean_email self email_domain self cleaned_data email split 1 if email_domain in self bad_domains raise forms ValidationError _ Registration using free email addresses is prohibited Please supply a different email address return self cleaned_data email
"test that pushing to remote , when the local repos is ahead updates the remote .",def testPushToRemoteWhenAhead self pass
"parameters _ _ _ _ _ _ _ _ _ _ chunks_attr : str or none if provided , it specifies the name of a samples attribute in the training data , unique values of which will be used to identify chunks of samples , and to perform individual clustering within them . k : int or ndarray the number of clusters to form as well as the number of centroids to generate . if init initialization string is matrix , or if a ndarray is given instead , it is interpreted as initial cluster to use instead init : { k - means++ , random , points , matrix } method for initialization , defaults to k - means++:k - means++ : selects initial cluster centers for k - mean clustering in a smart way to speed up convergence . see section notes in k_init for more details . random : generate k centroids from a gaussian with mean and variance estimated from the data.points : choose k observations ( rows ) at random from data for the initial centroids.matrix : interpret the k parameter as a k by m ( or length k array for one - dimensional data ) array of initial centroids . n_init : int number of iterations of the k - means algrithm to run . note that this differs in meaning from the iters parameter to the kmeans function .",def __init__ self chunks_attr None k 8 init k means n_init 10 kwargs Mapper __init__ self kwargs self __chunks_attr chunks_attr self __k k self __init init self __n_init n_init
a fast implementation of the forward pass for a max pooling layer .,def max_pool_forward_fast x pool_param mode train N C H W x shape pool_height pool_width pool_param pool_height pool_param pool_width if pool_stride in pool_param stride pool_param pool_stride pool_param stride stride else stride pool_param stride same_size pool_height pool_width stride tiles H pool_height 0 and W pool_width 0 if same_size and tiles out reshape_cache max_pool_forward_reshape x pool_param mode mode cache reshape reshape_cache else out im2col_cache max_pool_forward_im2col x pool_param mode mode cache im2col im2col_cache return out cache
"check that if load_tests returns none , no tests are run .",def test_none_cancels self u n Check that if load_tests returns None no tests are run n with open os path join self basename u test_load_keys_none_cancels py u w as fh fh write textwrap dedent u n import unittest n class A unittest TestCase n def test_that_will_fail self n self fail n n def load_tests loader tests pattern n return None n module_name self basename u test_load_keys_none_cancels result Queue poolRunner module_name result 0 result get proto_test_result result get self assertEqual len proto_test_result errors 1 self assertEqual len proto_test_result passing 0 self assertEqual len proto_test_result failures 0
tests gitpub . profile.get_public_repos ( ) by loading public repository details of the user ` demfier ` ---------------------------------------------------------------------------- parameters : none,def test_get_public_repos correct gitpub Profile username demfier name Gaurav location Kharagpur West Bengal email sahu gaurav719 gmail com followers_count 14 repos_url https api github com users Demfier repos public_repo_count 40 correct get_public_repos profile gitpub Profile profile load_gh_profile demfier profile get_public_repos for idx _ in enumerate profile public_repos assert profile public_repos idx name correct public_repos idx name
extracts tablature string model ( textx ) and then parses it .,def parse_tablature_string self tab_string tab_strings_model self tab_metamodel model_from_str tab_string return self processor process_tablature_model tab_strings_model
go through responses and save any that timed out into the database,when u storing any new cases of responses timing out def step_impl context new_findings 0 for response in context responses if response get server_timeout is True if fuzzdb known_false_positive context response is False fuzzdb add_false_positive context response new_findings 1 if new_findings 0 context new_findings new_findings assert True
adds transmitter - specific options to the options parser,def add_options normal expert if not normal has_option bitrate normal add_option r bitrate type eng_float default 100000 0 help specify bitrate default default normal add_option tx amplitude type eng_float default 0 25 metavar AMPL help set transmitter digital amplitude 0 AMPL 1 default default normal add_option v verbose action store_true default False expert add_option S samples per symbol type float default None help set samples symbol default default expert add_option log action store_true default False help Log all parts of flow graph to file CAUTION lots of data
the hamiltonian dimension of a single site .,property def hndim self return self hl hndim
check that a codelist can turn itself into a type to use for validation .,def test_codelist_type_xsd self name_to_set code_value_to_set test Code value codelist iati Codelist name_to_set code iati Code code_value_to_set codelist codes add code type_tree codelist xsd_restriction assert isinstance type_tree etree _Element assert type_tree tag iati constants NAMESPACE simpleType assert type_tree attrib name name_to_set type assert type_tree nsmap iati constants NSMAP assert len type_tree 1 assert type_tree 0 tag iati constants NAMESPACE restriction assert type_tree 0 nsmap iati constants NSMAP assert len type_tree 0 1 assert type_tree 0 0 tag iati constants NAMESPACE enumeration assert type_tree 0 0 attrib value code_value_to_set assert type_tree 0 0 nsmap iati constants NSMAP
return the statsresult object for this statistic,def get_stats_result self request stats_datasets StatsMakerDatasets request GET dict pub_state self get_pub_state request if pub_state self PUB_STATE_ALL stats_result stats_datasets get_dataset_counts_by_create_date elif pub_state self PUB_STATE_UNPUBLISHED stats_result stats_datasets get_dataset_counts_by_create_date_unpublished else stats_result stats_datasets get_dataset_counts_by_create_date_published return stats_result
creates the ` rosterclient ` instance for the ` roster_client ` attribute .,def roster_client_factory self return RosterClient self settings
get the bounding box of a `` circle `` node .,def bounding_box_circle surface node cx size surface node get cx x cy size surface node get cy y r size surface node get r return cx r cy r 2 r 2 r
"sending a global variable , using a path .",def get_global_variable self user variable globs_file False r self project authenticate user if not r return False try node_path v for v in variable split if v except Exception logWarning Global Variable Invalid variable type for user format variable user return False var_pointer self _find_global_variable user node_path globs_file if not var_pointer node_path join node_path if globs_file logWarning Global Variable Invalid variable path in file for user format node_path globs_file user else logWarning Global Variable Invalid variable path for user format node_path user return False return var_pointer
"gets or sets the underlying data as a list of rows , each row being a list itself . the returned list - of - lists allows access to the data _ as if it were contiguous _ ( collapsed vectors removed ) . see class description",property def collapsed_data self if self _data is None self _allocate_empty_data_array return self _data
compiles the program object to ptx using the compiler options specified in ` options ` .,def compile self options try self _interface nvrtcCompileProgram self _program options ptx self _interface nvrtcGetPTX self _program return ptx except NVRTCException as e log self _interface nvrtcGetProgramLog self _program raise ProgramException log
transform camelcase - > snake_case .,def underscore name s1 re sub A Z a z 1_ 2 name return re sub a z0 9 A Z 1_ 2 s1 lower
"collect node information ( cpu , memory and disk space )",def collectWNInfo self diskpath with open proc meminfo r as fd mems fd readline while mems if mems upper find MEMTOTAL 1 self mem float mems split 1 1024 break mems fd readline with open proc cpuinfo r as fd lines fd readlines for line in lines if not string find line cpu MHz self cpu float line split 1 break diskpipe os popen df mP s diskpath disks diskpipe read if not diskpipe close self disk float disks splitlines 1 split 3 return self mem self cpu self disk
double click the file / folder by name .,def double_click_on_file self filename elem self d find_element_by_id filename self double_click elem return FileSystemPage self d
tests that the length of the predict dataframe is equal to no of steps h,def test_predict_length model ARIMAX formula y x1 data data ar 2 ma 2 family Skewt x model fit x summary assert model predict h 5 oos_data data_oos shape 0 5
tests that the in - sample predictions are not nans,def test_exponential_predict_is_nans model pf GAS data exponentialdata ar 2 sc 2 family pf Exponential x model fit x summary assert len model predict_is h 5 values np isnan model predict_is h 5 values 0
python 2.6 subprocess.check_output stand - in .,def check_output cmd if hasattr subprocess check_output return subprocess check_output cmd proc subprocess Popen cmd stdout subprocess PIPE stdout proc communicate 0 code proc returncode if code raise subprocess CalledProcessError code cmd return stdout
computes partial derivatives of power injection w.r.t . voltage . : param ybus : admittance matrix : param v : bus voltages array : param i : bus current injections array : return :,def dSbus_dV Ybus V I Computes partial derivatives of power injection w r t voltage Returns two matrices containing partial derivatives of the complex bus power injections w r t voltage magnitude and voltage angle respectively for all buses If C Ybus is a sparse matrix the return values will be also The following explains the expressions used to form the matrices Ibus Ybus V I S diag V conj Ibus diag conj Ibus V Partials of V Ibus w r t voltage magnitudes dV dVm diag V abs V dI dVm Ybus dV dVm Ybus diag V abs V Partials of V Ibus w r t voltage angles dV dVa j diag V dI dVa Ybus dV dVa Ybus j diag V Partials of S w r t voltage magnitudes dS dVm diag V conj dI dVm diag conj Ibus dV dVm diag V conj Ybus diag V abs V conj diag Ibus diag V abs V Partials of S w r t voltage angles dS dVa diag V conj dI dVa diag conj Ibus dV dVa diag V conj Ybus j diag V conj diag Ibus j diag V j diag V conj Ybus diag V conj diag Ibus j diag V j diag V conj diag Ibus Ybus diag V For more details on the derivations behind the derivative code used in PYPOWER information see TN2 R D Zimmerman AC Power Flows Generalized OPF Costs and their Derivatives using Complex Matrix Notation MATPOWER Technical Note 2 February 2010 U http www pserc cornell edu matpower TN2 OPF Derivatives pdf author Ray Zimmerman PSERC Cornell ib range len V if issparse Ybus Ibus Ybus V I diagV sparse V ib ib diagIbus sparse Ibus ib ib diagVnorm sparse V abs V ib ib else Ibus Ybus asmatrix V T I diagV asmatrix diag V diagIbus asmatrix diag asarray Ibus flatten diagVnorm asmatrix diag V abs V dS_dVm diagV conj Ybus diagVnorm conj diagIbus diagVnorm dS_dVa 1j diagV conj diagIbus Ybus diagV return dS_dVm dS_dVa
"loads fixtures specified in fixtures_dict . this method must be used for fixtures that do n't have associated data models . we simply want to load the meta into dict objects . fixtures_dict should be of the form : { ' actionchains ' : [ ' actionchain1.json ' , ' actionchain2.json ' ] , ' workflows ' : [ ' workflow.yaml ' ] } : param fixtures_dict : dictionary specifying the fixtures to load for each type . : type fixtures_dict : `` dict `` : rtype : `` dict ``",def load_fixtures fixtures_dict None if fixtures_dict is None fixtures_dict all_fixtures fixtures_base_path get_fixtures_base_path for fixture_type fixtures in six iteritems fixtures_dict loaded_fixtures for fixture in fixtures fixture_path fixtures_base_path fixture fixture_dict load_content fixture_path loaded_fixtures fixture fixture_dict all_fixtures fixture_type loaded_fixtures return all_fixtures
delete the key value pair .,def delete self api_key_id_or_key requester_user api_key_db ApiKey get_by_key_or_id api_key_id_or_key permission_type PermissionType API_KEY_DELETE rbac_utils assert_user_has_resource_db_permission user_db requester_user resource_db api_key_db permission_type permission_type ApiKey delete api_key_db extra api_key_db api_key_db LOG audit ApiKey deleted ApiKey id s api_key_db id extra extra return Response status http_client NO_CONTENT
@type ert : enkfmain @type case_name : str @type key : str @type report_step : int @rtype : dataframe,staticmethod def loadGenData ert case_name key report_step fs ert getEnkfFsManager getFileSystem case_name realizations fs realizationList RealizationStateEnum STATE_HAS_DATA config_node ert ensembleConfig getNode key gen_data_config config_node getModelConfig ensemble_data EnsemblePlotGenData config_node fs report_step data_size gen_data_config getDataSize report_step active_mask gen_data_config getActiveMask data_array numpy empty shape data_size len realizations dtype numpy float64 data_array fill numpy nan for realization_index realization_number in enumerate realizations realization_vector ensemble_data realization_number if len realization_vector 0 for data_index in range data_size if active_mask data_index value realization_vector data_index data_array data_index realization_index value return DataFrame data data_array columns realizations
testing for constructor involves checking if all needed,def test_constructor monkeypatch def job_consume return Thread Consuming Job monkeypatch setattr jobs JobConsumerThread job_consume manager Manager test assert manager _sds_sync_thread is test assert manager _message_handler_thread is None assert manager _job_consumer_thread Thread Consuming Job
select unassigned variable with with fewest legal values,def __select_unassigned_variable self assignment csp possible_bags unassigned_items item_name csp items item_name for item_name in csp items if item_name not in assignment unassigned_item_names list unassigned_items keys min_item_name unassigned_item_names 0 num_constraints self __get_num_constraints csp unassigned_items for item_name in unassigned_item_names 1 num_remaining_bag len possible_bags item_name num_min_item len possible_bags min_item_name if num_remaining_bag num_min_item min_item_name item_name elif num_remaining_bag num_min_item if num_constraints item_name num_constraints min_item_name min_item_name item_name return csp items min_item_name
return the direction of a control request .,def ctrl_direction bmRequestType return bmRequestType _CTRL_DIR_MASK
"load parameters ( weights , biases , scaling info ) of the network from an hdf5 file if reset_network is true , then the layers are re - created . if reset_network is false , then the layers are only updated",def load_parameters self h5file self n_in int get_h5file_attribute h5file n_in self n_out int get_h5file_attribute h5file n_out self load_parameters_virtual h5file for i l in enumerate self ls_layers l load_parameters h5file layer str i
returns the path to the default chromedriver binary to use .,staticmethod def GetDriverPath return ChromeDriverTest _driver_path
asserts that a set of extensions is expected .,def _AssertExtensionNamesAreExpected self expected_set actual_set ext_type full_expected_info full_actual_info for extension_name in Chrome Web Store Bookmark Manager actual_set discard extension_name def _GetSetDifferenceMessage expected_set actual_set strings for missing_item in expected_set difference actual_set strings append Missing item s missing_item located_ext_info info for info in full_expected_info if info name missing_item 0 strings append self pformat located_ext_info for extra_item in actual_set difference expected_set strings append Unexpected extra item s extra_item located_ext_info info for info in full_actual_info if info name extra_item 0 strings append self pformat located_ext_info return n join strings self assertEqual expected_set actual_set msg s names do not match the baseline n s n ext_type _GetSetDifferenceMessage expected_set actual_set
uses _ generatefield ( ) and address_construct to gen a random address .,def GenerateAddress self return self _GenerateField self address_construct
returns a json - formatted dict containing the nacl dependencies,def GetManifest self if not self manifest self _GenerateManifest return self manifest
test cases for lusmu.vector.vectoreq._value_eq ( ) with complex data types,def test_numpy_vector_equality_others parameterize def check value other_value expected Vector node value 0 1 2 vector VectorEq value assert expected vector _value_eq other_value yield check DIRTY np array 1 2 3 4 False yield check np array 1 2 3 4 np array 1 2 3 4 True yield check np array 1 2 3 4 np array 1 2 3 5 False yield check np array 1 2 3 4 1 2 3 4 False yield check np array 1 2 np array 1 2 1 2 False
get data from a file .,def get_data filename with open filename r as data return data read
sets the certificate serial number .,def serial_number self number if not isinstance number six integer_types raise TypeError Serial number must be of integral type if self _serial_number is not None raise ValueError The serial number may only be set once if number 0 raise ValueError The serial number should be non negative if utils bit_length number 160 raise ValueError The serial number should not be more than 160 bits return CertificateBuilder self _issuer_name self _subject_name self _public_key number self _not_valid_before self _not_valid_after self _extensions
tests that messages can be deleted,def test_that_messages_can_be_deleted self message Message self msg_stub message save self assertIsNotNone message id message delete self assertIsNone message id
indentation button clicked . show dialog,def _onClicked self document core workspace currentDocument if document is not None dialog _IndentationDialog self document dialog exec_ self _setIndentMode document qutepart indentWidth document qutepart indentUseTabs
checks if postgresql server version is higher than or equal to version identified by verstr .,def checkVersion self verstr return self _version util SoftwareVersion verstr
returns true if connection is closed .,locked def is_closed self return self status CLOSED
set up some items we can reuse .,def setUp self self backend DjangoORMBackend
"calculates the probability of something based on a manually specified probability distribution , where the probability distribution is a tuple specified as : :",def calc_prob_from_prob_dist prob_dist attribute binlims probs prob_dist n 0 for uplim in binlims 1 if attribute uplim break n 1 return probs n
a generator yielding all tokens in a given line .,def lex self data ignore t literals regex self regex match pos 0 length len data while pos length char data pos if char in ignore pos 1 continue match regex data pos if match value match group pos len value token match lastgroup func getattr self token ret func token value if ret yield Token ret elif char in literals yield Token char char pos 1 else raise FilterException filter Illegal character in filter format char
add a 64-bit int to the stream .,def add_int64 self n self packet write struct pack Q n return self
return the raw deserialized response as dict,def to_native self return self __data
! @brief get paradigm label . @return paradigm attribute ' paradigmlabel ' .,def get_paradigmLabel self return self paradigmLabel
overridable . check to see if the file object self.lib actually has a file we understand .,def checkmagic self self lib seek self start if self lib read len self MAGIC self MAGIC raise RuntimeError s is not a valid s archive file self path self __class__ __name__ if self lib read len self pymagic self pymagic print Warning pyz is from a different Python version self lib read 4
process job input to extend for the proper number of layers .,def layer_extend var default layers if type var list default var var var while len var layers var append default return var
"copy a dict recursively , but only if key does n't match regex pattern",def copy_dict_filter_key d regex out for k v in six iteritems d if not re match regex k if isinstance v dict out k copy_dict_filter_key v regex else out k v return out
append message and flush to disk,def log f msg if f f write msg n f flush os fsync f fileno
"given an identifier , returns the namespace that identifier is from .",def GetClosurizedNamespace self identifier parts identifier split for part in parts if part endswith _ return None if identifier startswith goog global return None for namespace in self __closurized_namespaces if identifier startswith namespace last_part parts 1 if not last_part return None if last_part in apply inherits call parts pop last_part parts 1 for i in xrange 1 len parts part parts i if part isupper return join parts i if part prototype return join parts i if last_part isupper or not last_part 0 isupper parts pop return join parts return None
test that the output of ' conan info --build ' is correct,def info_build_test self self _export H0 0 1 self _export H1a 0 1 deps H0 0 1 lu st private self _export H1b 0 1 deps H0 0 1 lu st self _export H1c 0 1 deps H0 0 1 lu st private self _export H2a 0 1 deps H1a 0 1 lu st self _export H2c 0 1 deps H1c 0 1 lu st self _export H3 0 1 deps H2a 0 1 lu st H2c 0 1 lu st self clients H3 run info build missing self assert_last_line self clients H3 H0 0 1 lu st H1a 0 1 lu st H1c 0 1 lu st H2a 0 1 lu st H2c 0 1 lu st self clients H0 run info conanfile py build missing self assert_last_line self clients H0 self clients H1a run info conanfile py build missing self assert_last_line self clients H1a H0 0 1 lu st self clients H3 run install H1a 0 1 lu st build self clients H3 run install H1c 0 1 lu st build self clients H3 run upload H1a 0 1 lu st all self clients H3 run upload H1c 0 1 lu st all self clients H3 run remove f self clients H3 run info build missing self assert_last_line self clients H3 H2a 0 1 lu st H2c 0 1 lu st self clients H3 run remove f self clients H3 run info conanfile py build self assert_last_line self clients H3 H0 0 1 lu st H1a 0 1 lu st H1c 0 1 lu st H2a 0 1 lu st H2c 0 1 lu st conanfile_path os path join self clients H1a current_folder CONANFILE conanfile load conanfile_path conanfile n MODIFIED save conanfile_path conanfile self clients H1a run export lu st self clients H1a run upload H1a 0 1 lu st self clients H3 run remove f self clients H3 run info conanfile py build missing self assert_last_line self clients H3 H2a 0 1 lu st H2c 0 1 lu st self clients H3 run remove f self clients H3 run info build outdated self assert_last_line self clients H3 H0 0 1 lu st H1a 0 1 lu st H2a 0 1 lu st H2c 0 1 lu st
register options_context for special ' commands ' that has no command context attached to them,def register_options_context_without_command self name context return self _options_registry register name context
": param start : optional parameter indicating , if given , the smallest key of the values in the view ( default `` none `` ) . : param stop : optional parameter , indicating , the smallest key that should be larger than all of the keys corresponding to the values in the view ( default `` none `` ) . : param bool reverse : whether to iterate in reverse order . : returns : a dynamic : py : class:`itemsview ` view of the dict 's items ( default `` false `` ) .",def items self args kwargs return ItemsView self args kwargs
adds a point to the path only if it is within the path resolution also trims the path if needed,def add_point self p if len self last_pos 0 self last_pos append p elif self dist self last_pos 1 p 1 0 conf PATH_RES self last_pos append p if conf PATH_LEN 0 and len self last_pos conf PATH_LEN del self last_pos 0
"this is a temporary hot - fix to handle the way metadata is encoded when we read data directly from bpch files . it removes the ' scale_factor ' and ' units ' attributes we encode with the data we ingest , converts the ' hydrocarbon ' and ' chemical ' attribute to a binary integer instead of a boolean , and removes the ' units ' attribute from the "" time "" dimension since that too is implicitly encoded .",def fix_attr_encoding ds def _maybe_del_attr da attr Possibly delete an attribute on a DataArray if it s present if attr in da attrs del da attrs attr return da def _maybe_decode_attr da attr Possibly coerce an attribute on a DataArray to an easier type to write to disk if attr in da attrs and type da attrs attr bool da attrs attr int da attrs attr return da for v in ds data_vars da ds v da _maybe_del_attr da scale_factor da _maybe_del_attr da units da _maybe_decode_attr da hydrocarbon da _maybe_decode_attr da chemical times ds time times _maybe_del_attr times units return ds
run a command on the lchroot,def exec_command self cmd in_data None sudoable False super Connection self exec_command cmd in_data in_data sudoable sudoable p self _buffered_exec_command cmd stdout stderr p communicate in_data return p returncode stdout stderr
"given a list of of [ < file_spec > , ... ] create the specified files under specified root .",def touch_files self root files_list record None def create location contents None Create this location with specified contents dirname filename os path split location if not os path exists dirname os makedirs dirname nxt record if nxt is not None and dirname nxt folder for part in os path relpath dirname nxt folder split os path sep if part in nxt nxt nxt part else nxt nxt part folder os path join nxt folder part if filename with open location w as fle if contents fle write contents else fle write if nxt nxt filename file os path join nxt folder filename for file_spec in files_list if isinstance file_spec six string_types create os path join root file_spec None else file_location file_contents file_spec create os path join root file_location file_contents
stages allow the same resource type to re - occur in an explosion,def test_staged_explosion self due_date datetime date today commitment self ct3_change create_commitment due_date self user visited process commitment generate_producing_process self user visited explode True prev process previous_processes 0 prev_prev prev previous_processes 0 process_start due_date datetime timedelta days 3 self assertEqual process start_date process_start prev_start due_date datetime timedelta days 6 self assertEqual prev start_date prev_start prev_prev_start due_date datetime timedelta days 9 self assertEqual prev_prev start_date prev_prev_start ordered_processes visited_resources all_prevs process all_previous_processes ordered_processes visited_resources 0 self assertEqual len ordered_processes 3 prev_next prev next_processes 0 self assertEqual prev_next process prev_prev_next prev_prev next_processes 0 self assertEqual prev_prev_next prev
creates a new config instance .,def __init__ self data default None Dict __init__ self default default if isinstance data dict self update data elif data self read data
"if clients have negative rdy values , distribute_ready is invoked",def test_low_ready self connection self client connections 0 with mock patch object connection ready 2 with mock patch object connection last_ready_sent 10 self assertTrue self client needs_distribute_ready
find the best position of all the particles in the list,def update_global_best self tmp self Particle global_best tmp_index self Particle best_index for p in self p_list if Q p x p y tmp 0 tmp Q p x p y p x p y tmp_index p index self Particle global_best tmp self Particle best_index tmp_index
invoke vaultier.org website api to get news if any,def _invoke_api self count use_etag True headers content type application json if use_etag and self etag headers update If None Match self etag try url urljoin self _url page_size format count return requests get url headers headers timeout self _connection_timeout except requests exceptions RequestException as e return None
returns true if string is a key string . key strings begin with underscore .,def is_key_string string return len string 1 and string 0 _
"this method is called when the plugin is stopped . it should perform any special clean up necessary to terminate the operation . the gui will be destroyed by the plugin manager so there is no need for the stop method to do that . this method may be called many times as the plugin is opened and closed for modal operations , and may be omitted if there is no special cleanup required when stopping .",def stop self pass
test zifa and block zifa under a variety of conditions to make sure projected dimensions and parameters do n't change .,def unitTests print Running unit tests IMPORTANT These unit tests pass with Python version 2 7 10 your version s numpy 1 13 1 your version s scipy 0 18 1 your version s sklearn 0 16 1 your version s platform python_version np __version__ scipy __version__ sklearn __version__ print Different versions of Python or those packages may yield slightly different results and fail to pass the asserts unless you increase the absolute_tolerance parameter set below print If your configuration yields significantly different results please contact emmap1 cs stanford edu absolute_tolerance 1e 08 random seed 35 np random seed 32 n 200 d 20 k 2 sigma 0 3 n_clusters 3 decay_coef 0 1 X Y Z ids generateSimulatedDimensionalityReductionData n_clusters n d k sigma decay_coef old_Y deepcopy Y Zhat params ZIFA fitModel Y k assert np allclose Y old_Y assert np allclose np abs Zhat 1 np abs 1 50067515 0 04742477 atol absolute_tolerance assert np allclose np abs params A 0 np abs 0 66884415 0 17173555 atol absolute_tolerance assert np allclose params decay_coef 0 10458794970222711 atol absolute_tolerance assert np allclose params sigmas 0 0 30219903 atol absolute_tolerance Zhat params block_ZIFA fitModel Y k assert np allclose Y old_Y assert np allclose np abs Zhat 1 np abs 1 49712162 0 05823952 atol absolute_tolerance assert np allclose np abs params A 0 np abs 0 66884415 0 17173555 atol absolute_tolerance assert np allclose params decay_coef 0 10458794970222711 atol absolute_tolerance assert np allclose params sigmas 0 0 30219903 atol absolute_tolerance Zhat params block_ZIFA fitModel Y k n_blocks 3 assert np allclose Y old_Y assert np allclose np abs Zhat 1 np abs 0 984455438 0 0450924335 atol absolute_tolerance n 50 d 60 k 3 sigma 0 3 n_clusters 3 decay_coef 0 1 X Y Z ids generateSimulatedDimensionalityReductionData n_clusters n d k sigma decay_coef old_Y deepcopy Y Zhat params block_ZIFA fitModel Y k n_blocks 3 assert np allclose Y old_Y assert np allclose np abs Zhat 1 np abs 1 69609638 0 5475882 0 08008015 atol absolute_tolerance X Y Z ids generateSimulatedDimensionalityReductionData n_clusters n d k sigma decay_coef old_Y deepcopy Y Zhat params ZIFA fitModel Y k print Zhat 1 assert np allclose np abs Zhat 1 np abs 0 63075905 0 77361427 0 11544281 atol absolute_tolerance assert np allclose Y old_Y print Tests passed with absolute tolerance 2 3e absolute_tolerance
"asciihexdecode filter : pdfreference v1.4 section 3.3.1 for each pair of ascii hexadecimal digits ( 0 - 9 and a - f or a - f ) , the asciihexdecode filter produces one byte of binary data . all white - space characters are ignored . a right angle bracket character ( > ) indicates eod . any other characters will cause an error . if the filter encounters the eod marker after reading an odd number of hexadecimal digits , it will behave as if a 0 followed the last digit .",def asciihexdecode data decode lambda hx chr int hx 16 out map decode hex_re findall data m trail_re search data if m out append decode c0 m group 1 return join out
a node that restarts after some transactions should eventually get the transactions which happened while it was down : return :,skipper def test_node_load_after_add sdk_new_node_caught_up txnPoolNodeSet looper sdk_pool_handle sdk_wallet_client capsys new_node sdk_new_node_caught_up logger debug Sending requests client_batches 300 txns_per_batch 25 for i in range client_batches s perf_counter sdk_send_random_and_check looper txnPoolNodeSet sdk_pool_handle sdk_wallet_client txns_per_batch with capsys disabled print executed client txns in 2f seconds format i 1 txns_per_batch perf_counter s logger debug Starting the stopped node format new_node sdk_send_random_and_check looper txnPoolNodeSet sdk_pool_handle sdk_wallet_client 5 waitNodeDataEquality looper new_node txnPoolNodeSet 4
: param x_var : : param dist_info : : return : log likelihood of the data,def logli self x_var dist_info raise NotImplementedError
@case : hrm004 @description : delete a prepop organisation . organisation id : 40 ( org / organisation/40/ ),def test_hrm004_delete_organisation self self login account normal nexturl org organisation 40 delete
combine multiple result dicts from l{pc_info } into one .,def combine_info args info define_macros include_dirs libraries library_dirs for a in args info define_macros extend a get define_macros info include_dirs extend a get include_dirs info libraries extend a get libraries info library_dirs extend a get library_dirs return info
keep trying the xmlrpc call until a timeout occurs on errors that are not xmlrpclib faults .,def wrap_xmlrpc_call func args kwargs timeout import time xmlrpclib for i in xrange timeout try r func args kwargs return r except xmlrpclib Fault raise except logger debug Trying to call func for the s th again i 1 time sleep 1 pass return func args kwargs
merge contents for specified rspec with current rspec,def merge self in_rspec if not in_rspec return from openflow optin_manager sfa rspecs rspec import RSpec if isinstance in_rspec RSpec rspec in_rspec else rspec RSpec in_rspec if rspec version type lower protogeni from openflow optin_manager sfa rspecs rspec_converter import RSpecConverter in_rspec RSpecConverter to_sfa_rspec rspec toxml rspec RSpec in_rspec current_networks self get_networks networks rspec version get_networks for network in networks current_network network get name if current_network and current_network not in current_networks self xml append network element current_networks append current_network
make packing list for product bundle item,def make_packing_list doc u if doc get u _action and doc _action u update_after_submit return parent_items for d in doc get u items if frappe db get_value u Product Bundle u new_item_code d item_code for i in get_product_bundle_items d item_code update_packing_list_item doc i item_code flt i qty flt d stock_qty d i description if d item_code d name not in parent_items parent_items append d item_code d name cleanup_packing_list doc parent_items
attempts to serialize an object value that is none,def test_serialize_none_object_issue_7 class Athlete object def __init__ self self name self age 0 processor xml dictionary race result xml floating_point time xml user_object athlete Athlete xml string name xml integer age required False value time 87 5 athlete None expected_xml strip_xml race result time 87 5 time race result actual_xml xml serialize_to_string processor value assert expected_xml actual_xml
return the definition of the inferred parameters .,def get_param_definitions self names alpha beta sigma shapes self J self D hiers 0 None None return names shapes hiers
returns imprinted container data of a tool,def parse_container tool data tool GetData avalon if not isinstance data dict return required schema id name namespace loader representation if not all key in data for key in required return container key data key for key in required container objectName tool Name container _tool tool return container
perform implementation - specific icmp_type and protocol transforms .,def _HandleIcmpTypes self icmp_types protocols u Perform implementation specific icmp_type and protocol transforms n n Note that icmp_types or protocols are passed as parameters in case they n are to be munged prior to this function call and may not be identical n to self term parameters n n Args n icmp_types a list of icmp types e g self term icmp_types n protocols a list of protocols e g self term protocols n n Returns n A pair of lists of icmp_types protocols n pass
add builders and construction variables for sun f90 compiler to an environment .,def generate env add_all_to_env env fcomp env Detect compilers or f90 env FORTRAN fcomp env F90 fcomp env SHFORTRAN FORTRAN env SHF90 F90 env SHFORTRANFLAGS SCons Util CLVar FORTRANFLAGS KPIC env SHF90FLAGS SCons Util CLVar F90FLAGS KPIC
create an empty network and add nodes to it .,classmethod def _start_topo cls subnet netaddr IPNetwork 10 0 0 0 24 hosts_iter subnet iter_hosts cls _net mininet net Mininet controller None cls _net addHost TARGET_NAME cls _net addHost CONTROLLER_NAME cls _net addHost DUMMY_NAME params1 ip get_ip_spec hosts_iter next subnet params2 ip get_ip_spec hosts_iter next subnet cls _net addLink TARGET_NAME CONTROLLER_NAME params1 params1 params2 params2 cls _net addLink TARGET_NAME DUMMY_NAME cls _net addLink TARGET_NAME DUMMY_NAME cls _target cls _net TARGET_NAME cls _ctrlr cls _net CONTROLLER_NAME cls _net start logger info Running target command s FLAGS target_cmd cls _target_popen cls _target popen FLAGS target_cmd if FLAGS emulator mininet cli CLI cls _net else time sleep 20
executes an oem command on the device .,def oem self command timeout_ms None info_cb DEFAULT_MESSAGE_CALLBACK return self _simple_command oem s command timeout_ms timeout_ms info_cb info_cb
test gradients of functions with binary tensor inputs .,def test_grad_tensor_broadcast func motion optimized preserve_result s t tfe_utils test_rev_tensor func motion optimized preserve_result 0 1 s t
write the test run end to the stream .,def stop_test_run self self stream writeln Tests Run Finished None BOLD
save the test data result as unexpected success .,def add_unexpected_success self test test data save
remove and return an item from the queue .,def get_nowait self self _consume_done_putters if self _putters assert self full queue not full why are putters waiting putter self _putters popleft putter set_result None return self _get elif self qsize return self _get else raise QueueEmpty
true if given day is weekend day .,def is_weekend datetime return datetime weekday 5 or datetime weekday 6
we use logging 's levels as an easy - to - use verbosity controller .,def create_log_config verbose quiet if verbose and quiet raise ValueError Supplying both quiet and verbose makes no sense elif verbose level logging DEBUG elif quiet level logging ERROR else level logging INFO return version 1 formatters click_formatter format message s handlers click_handler level level class doc2dash __main__ ClickEchoHandler formatter click_formatter loggers doc2dash handlers click_handler level level
check to see if we need to restart any processes,def check_restart self u n Check to see if we need to restart any processes n for idx proc in self processes items if proc get u need_restart False and proc u process poll is not None print u Starting new process on index s idx self start_proc idx proc u need_restart False
"look up the preferred version in the modules . @in , name , string , the name of the module @out , result , string , returns the version as a string or "" "" if unknown",def __lookUpPreferredVersion name optional False index modules_to_try if not optional else optional_test_libraries for i fv ev qa mv in index if name i return qa return
"calls finalizecodeoutput from bison mesh script interface to clean up files @ in , command , string , the command used to run the just ended job @ in , output , string , the output name root @ in , workingdir , string , current working dir @ out , output , string , optional , present in case the root of the output file gets changed in this method ( not present in this case )",def finalizeCodeOutput self command output workingDir u n Calls finalizeCodeOutput from Bison Mesh Script Interface to clean up files n In command string the command used to run the just ended job n In output string the Output name root n In workingDir string current working dir n Out output string optional present in case the root of the output file gets changed in this method not present in this case n self BisonMeshInterface finalizeCodeOutput command output workingDir
make a grid from images .,def mosaic w imgs imgs iter imgs img0 imgs next pad np zeros_like img0 imgs it chain img0 imgs rows grouper w imgs pad return np vstack map np hstack rows
"create new directory , remove old directory if it exists . : param str full_path : path to directory that should be created",def create_dir self full_path if os path exists full_path os remove full_path os makedirs full_path
checks if the folder structure exists,staticmethod def is_project_folder_present paths if paths project is None return False if not os path exists paths project return False return True
displays javascript and css to initialize holoviews widgets .,classmethod def load_hvjs cls logo False bokeh_logo False mpl_logo False plotly_logo False JS True message HoloViewsJS successfully loaded import jinja2 if JS widgetjs widgetcss Renderer html_assets extras False backends script True else widgetjs widgetcss templateLoader jinja2 FileSystemLoader os path dirname os path abspath __file__ jinjaEnv jinja2 Environment loader templateLoader template jinjaEnv get_template load_notebook html html template render widgetcss widgetcss logo logo bokeh_logo bokeh_logo mpl_logo mpl_logo plotly_logo plotly_logo message message publish_display_data data text html html if JS mimebundle MIME_TYPES js widgetjs MIME_TYPES jlab hv load widgetjs if os environ get HV_DOC_HTML False mimebundle text html mimebundle_to_html mimebundle publish_display_data data mimebundle
.g/.google < query > -- returns first google search result,hook command g hook command def google inp parsed api_get web inp if not 200 parsed responseStatus 300 raise IOError error searching for pages d s parsed responseStatus if not parsed responseData results return no results found result parsed responseData results 0 title http unescape result titleNoFormatting content http unescape result content if len content 0 content No description available else content http html fromstring content text_content out s x02 s x02 s result unescapedUrl title content out join out split if len out 300 out out out rfind return out
succeed iff str is the start of an invalid piece of code,def assertInvalid self str symbol single is_syntax 1 try compile_command str symbol symbol self fail No exception raised for invalid code except SyntaxError self assertTrue is_syntax except OverflowError self assertTrue not is_syntax
return true if var contains a valid python identifier,def is_valid_identifier var allow_unicode False flags re UNICODE if allow_unicode else re ASCII is_valid re match d W w Z var flags return is_valid and not keyword iskeyword var
add builders and construction variables for pdftex to an environment .,def generate env global PDFTeXAction if PDFTeXAction is None PDFTeXAction SCons Action Action PDFTEXCOM PDFTEXCOMSTR global PDFLaTeXAction if PDFLaTeXAction is None PDFLaTeXAction SCons Action Action PDFLATEXCOM PDFLATEXCOMSTR global PDFTeXLaTeXAction if PDFTeXLaTeXAction is None PDFTeXLaTeXAction SCons Action Action PDFTeXLaTeXFunction strfunction SCons Tool tex TeXLaTeXStrFunction env AppendUnique LATEXSUFFIXES SCons Tool LaTeXSuffixes import pdf pdf generate env bld env BUILDERS PDF bld add_action tex PDFTeXLaTeXAction bld add_emitter tex SCons Tool tex tex_pdf_emitter pdf generate2 env SCons Tool tex generate_common env
adapts the list of anillo urlmapping specs into a list of werkzeug rules or rules subclasses .,def _build_rules specs for spec in specs if context in spec yield Context spec context list _build_rules spec get routes else rulespec spec copy match rulespec pop match name rulespec pop name yield Rule match endpoint name rulespec
this tests the case where the same transaction is submitted twice on two separate blocks as part of a reorg . the former will vanish and the latter will appear as the true transaction ( with confirmations dropping as a result ) .,def test_double_send self self sync_all self split_network utxos self nodes 2 listunspent utxo utxos 0 change 8f float utxo amount 1 0003 recipientDict self nodes 0 getnewaddress 1 self nodes 2 getnewaddress change utxoDicts txid utxo txid vout utxo vout signedtxres self nodes 2 signrawtransactionwithwallet self nodes 2 createrawtransaction utxoDicts recipientDict assert signedtxres complete signedtx signedtxres hex txid1 self nodes 1 sendrawtransaction signedtx self nodes 2 generate 2 txid2 self nodes 2 sendrawtransaction signedtx assert_equal txid1 txid2 lastblockhash self nodes 1 generate 3 2 self nodes 2 generate 2 self join_network self sync_all self nodes 0 gettransaction txid1 lsbres self nodes 0 listsinceblock lastblockhash assert any tx txid txid1 for tx in lsbres transactions assert any tx txid txid1 for tx in lsbres removed for tx in lsbres transactions if tx txid txid1 assert_equal tx confirmations 2 for tx in lsbres removed if tx txid txid1 assert_equal tx confirmations 2
return a byte array deep copy of 188 byte ts packet payload,staticmethod def get_payload packet adaptation_field_len TS get_adaptation_field_length packet header_size 4 adaptation_field_len return packet header_size
replaces functools.wraps in order to undo wrapping when generating sphinx documentation,def no_op_wraps func import sys if func __module__ is None or blessed not in func __module__ return functools orig_wraps func def wrapper decorator sys stderr write patched for function signature 0 r n format func return func return wrapper
"check if a message is likely to be bds code 2,0",def is20 msg if allzeros msg return False d hex2bin data msg if d 0 8 00100000 return False cs cs20 msg if in cs return False return True
return a * copy * ( we hope ) of the parameters . danger : altering properties directly does n't call model._cache,property def params self params odict for key model in self models items params update model params return params
"fit a broken power law ( a line in log - space ) to data as a function of x differs from ' plfit ' because plfit fits a power law distribution , this code simply fits a power law",def brokenpowerfit xax data err None alphaguess1 0 0 alphaguess2 2 0 scaleguess 1 0 breakpoint None quiet True logdata np log10 data if err is None err np ones data shape dtype float def brokenpowerlaw p lowerhalf np log10 p 0 np log10 xax p 2 xax p 1 scale2loc np argmin np abs xax p 1 scale2 np log10 xax scale2loc p 2 p 3 np log10 p 0 upperhalf scale2 np log10 xax p 3 xax p 1 return lowerhalf upperhalf def mpfitfun data err def f p fjac None return 0 np ravel brokenpowerlaw p data err return f if breakpoint is None breakpoint np median xax parinfo mpminstep xax min mpmaxstep xax max step xax min mp mpfit mpfit mpfitfun logdata err xall scaleguess breakpoint alphaguess1 alphaguess2 quiet quiet parinfo parinfo fitp mp params scale2loc np argmin np abs xax fitp 1 scale2 10 np log10 xax scale2loc fitp 2 fitp 3 np log10 fitp 0 fitp np array fitp 0 scale2 fitp 1 tolist return fitp mp
eval cifar-10 for a number of steps .,def evaluate with tf Graph as_default as g with tf device USE_DEVICE eval_data FLAGS eval_data test images labels cifar10 inputs eval_data eval_data logits cifar10 inference images top_k_op tf nn in_top_k logits labels 1 variable_averages tf train ExponentialMovingAverage cifar10 MOVING_AVERAGE_DECAY variables_to_restore variable_averages variables_to_restore saver tf train Saver variables_to_restore summary_op tf merge_all_summaries summary_writer tf train SummaryWriter FLAGS eval_dir g while True eval_once saver summary_writer top_k_op summary_op if FLAGS run_once break time sleep FLAGS eval_interval_secs
putfh which nolonger exists should return nfs4err_stale,def testStaleHandle t env c env c1 c init_connection stale_fh stateid c create_confirm t code res c close_file t code stale_fh stateid check res ops c use_obj c homedir c remove_op t code res c compound ops check res res c compound c putfh_op stale_fh check res NFS4ERR_STALE Using a stale fh
verify with an unsupported attribute should return nfs4err_attrnotsupp,def testUnsupportedLink t env _try_unsupported env env opts uselink
enable all the widgets in this container,def enable self self _enabled True for child in self children if isinstance child Container Widget child enable
multiplication with a scalar or dot product .,def __mul__ self other T type other if T types FloatType or T types IntType or T types LongType return vec3 self x other self y other self z other if isinstance other vec3 return self x other x self y other y self z other z elif getattr other __rmul__ None None return other __rmul__ self else raise TypeError unsupported operand type for
returns the log of the pdf at the given values . the keyword arguments must contain all of parameters in self 's params . unrecognized arguments are ignored .,def _logpdf self kwargs if kwargs in self return numpy log self _pdf kwargs else return numpy inf
"> > > app = make_simple_application(project_dir= ' . ' ) > > > import uliweb.orm as orm > > > b = get_model('blog ' ) > > > r = b.all().remove ( ) > > > a = b(title='1 ' , content='1 ' ) > > > a.save ( ) true > > > b1 = get_model('blog ' , ' b ' ) > > > b2 = b.use('b ' ) > > > id(b1 ) = = id(b2 ) true > > > b = b.use('b')(title='2 ' , content='2 ' ) > > > b.save ( ) true > > > b.get(1 ) < blog { ' title':u'1','content':u'1','id':1 } >",def test_3
make 100 % sure that specan has stopped,def teardown self self pyrpl spectrumanalyzer stop
purges cached auth token / cookie .,subcommand usage options def CMDlogout parser args options args parser parse_args args process_auth_options parser options service AuthService options service service logout return 0
"constructs a composable layout element that will be rendered automatically by ipython notebooks . it can also be saved in html , pdf , png or jpeg formats .",def Block contents None title None title_level 3 title_wrap False inherit_cfg True kwargs block_cls None for key value in _block_types items if isinstance contents key block_cls value break if block_cls is None if isinstance contents string_types block_cls Raw elif isinstance contents BaseBlock if title is None return contents class _NestedBlock BaseBlock container_tag None def __init__ self super _NestedBlock self __init__ title title title_level title_level title_wrap title_wrap inherit_cfg inherit_cfg kwargs def _to_static self return contents _to_static def _write_contents self sub_args sub_kwargs contents _write_block sub_args sub_kwargs return _NestedBlock elif contents is None block_cls Raw contents else raise ValueError Unrecognized argument type s type contents return block_cls contents title title title_level title_level title_wrap title_wrap inherit_cfg inherit_cfg kwargs
split_embeddings splits the embeddings and distributes into several different files .,def split_embeddings X P path dname init_variance 0 0 perm None N X shape 0 Q X shape 1 if perm is None perm np random permutation N for p in xrange 1 P 1 name path embeddings dname _ str p embedding npy var_name path embeddings dname _ str p variance npy x X perm P p 1 np save name x np save var_name np ones N np sum perm P p 1 init_variance return perm
": param chunkposition : : type chunkposition : ( int , int ) : return : : rtype :",def __init__ self chunkPosition super ChunkNode self __init__ self chunkPosition chunkPosition cx cz chunkPosition self translate Translate self translate translateOffset cx 4 0 cz 4 self addState self translate self name str chunkPosition
input a tag and header from the url 's source to output a scraped list of of matching elements .,def header_weatherlist tag header url search make_soup url find_all tag headers header values x get_text replace n for x in search return values
"find the stack frame of the caller so that we can note the source file name , line number and function name .",def findCaller f currentframe f_back rv unknown file 0 unknown function while hasattr f f_code co f f_code filename os path normcase co co_filename if filename _srcfile f f f_back continue rv filename f f_lineno co co_name break return rv
transform an inertia tensor to a new frame .,def transform_inertia transform inertia_tensor transform np asanyarray transform dtype np float64 if transform shape 4 4 rotation transform 3 3 elif transform shape 3 3 rotation transform else raise ValueError transform must be 3 3 or 4 4 inertia_tensor np asanyarray inertia_tensor dtype np float64 if inertia_tensor shape 3 3 raise ValueError inertia_tensor must be 3 3 transformed util multi_dot rotation inertia_tensor negate_nondiagonal rotation T transformed negate_nondiagonal return transformed
clean the form skipping the add - to - form checks .,def clean self return super AddToCartForm self clean
create a locked session for the test_vm machine,def test_lock_vm self vbox virtualbox VirtualBox vm vbox find_machine test_vm s virtualbox Session vm lock_machine s virtualbox library LockType shared self assertTrue s state virtualbox library SessionState locked self assertRaises library VBoxErrorInvalidObjectState vm lock_machine s virtualbox library LockType shared s2 virtualbox Session self assertRaises library VBoxErrorInvalidObjectState vm lock_machine s2 virtualbox library LockType write vm lock_machine s2 virtualbox library LockType shared self assertTrue s2 state virtualbox library SessionState locked s unlock_machine self assertTrue s state virtualbox library SessionState unlocked self assertTrue s2 state virtualbox library SessionState unlocked vm lock_machine s virtualbox library LockType write self assertRaises library VBoxErrorInvalidObjectState vm lock_machine s2 virtualbox library LockType write s unlock_machine self assertRaises library VBoxError s unlock_machine
used when the entire index for model is updated .,def index_queryset self return self get_model live_objects filter show_in_lists True
msb shall never be greater then 32,def testTooLargeField self self assertRaises Exception A429MsgStructureError MessageField Field 1 33 Test Field
stalls control endpoint ( 0 ),def stall_ep0 self self app event_handler handle_event StallEp0Event
whether this node was set for data parallelism .,def AllowParallel global _parallel_groups world_rank Rank for idx g in enumerate _parallel_groups if world_rank in g return idx g return 1
"load image in bgr , subtract mean , and make dims c x h x w for caffe",def read_img_cv2 fpath mean None img_dat cv2 imread fpath if mean is not None img_dat img_dat astype np float32 img_dat mean img_dat img_dat astype np float img_dat mu hwc_to_chw img_dat return img_dat
called as the app dies - too late to prevent it here !,def ExitInstance self win32ui OutputDebug Application shutdown n try win32ui InstallCallbackCaller self oldCallbackCaller except AttributeError pass if self oldCallbackCaller del self oldCallbackCaller self frame None self idleHandlers if self _obj_ self _obj_ AttachObject None self _obj_ None global App global AppBuilder App None AppBuilder None return 0
return a list of groups .,def listGroups self ret filter None self _groups keys self logd listGroup return s str ret return ret
attach a lot of summaries to a tensor .,def variable_summaries var name with tf name_scope summaries mean tf reduce_mean var tf summary scalar mean name mean with tf name_scope stddev stddev tf sqrt tf reduce_sum tf square var mean tf summary scalar sttdev name stddev tf summary scalar max name tf reduce_max var tf summary scalar min name tf reduce_min var tf summary histogram name var
return an iterable of model . alarmchange objects .,staticmethod def query_alarm_history filter_expr None orderby None limit None raise aodh NotImplementedError Complex query for alarms history is not implemented
"derive the keystone userid , stored in the user resource_id .",def _get_user self return self stack resource_by_refid self properties self USER_NAME
: param host : local address to listen on : param port : local port to listen on : param security_proxy : instance of nova.console.securityproxy.base.securityproxy,def proxy host port security_proxy None if CONF ssl_only and not os path exists CONF cert exit_with_error SSL only and s not found CONF cert if CONF web and not os path exists CONF web exit_with_error Can not find html js files at s CONF web logging setup CONF nova gmr TextGuruMeditation setup_autorun version conf CONF websocketproxy NovaWebSocketProxy listen_host host listen_port port source_is_ipv6 CONF source_is_ipv6 cert CONF cert key CONF key ssl_only CONF ssl_only daemon CONF daemon record CONF record traffic not CONF daemon web CONF web file_only True RequestHandlerClass websocketproxy NovaProxyRequestHandler security_proxy security_proxy start_server
convert image to other format .,def convert_image source dest in_format out_format run_as_root False if in_format is None raise RuntimeError convert_image without input format is a security risk _convert_image source dest in_format out_format run_as_root
return vbd refs for all nova / cinder volumes .,def _get_all_volume_vbd_refs self vm_ref vbd_refs self _session VM get_VBDs vm_ref for vbd_ref in vbd_refs other_config self _session VBD get_other_config vbd_ref if other_config get osvol yield vbd_ref
this function checks if incoming value in http response codes range .,def is_valid_code code_value return code_value in http_client responses
"prints the centroid configurations , into a binary file .",def print_bin atoms cell filedesc sys stdout title buff filedesc cell h tofile buff nat np asarray atoms natoms nat tofile buff atoms names tofile buff atoms q tofile buff
unescapes html . taken from https://wiki.python.org/moin/escapinghtml,def unescape s s s replace lt s s replace gt s s replace amp return s
get playlist position skipping file with path equal to autopath . try to secure that there are some time ( securesec ) to complete all operations in time : if xmms change song during operation will be a big problem,def get_playlist_posauto self autopath securesec 10 try pos self get_playlist_securepos securesec securesec if pos is None return pos pos 1 metadata self tracklist GetMetadata pos try file metadata URI except return pos filepath os path dirname file while os path commonprefix filepath file autopath file autopath pos 1 metadata self tracklist GetMetadata pos try file metadata URI except return pos filepath os path dirname file return pos except return None
symmetry transformation n for position r.,def transform self r n if n 0 n 1 0 return r copy eps 1e 10 a b self angle1 n 0 self angle2 n 1 R1 R2 self R1 self R2 R a R1 2 b R2 2 a 2 R1 b 2 R2 assert abs R eps min abs R1 abs R2 A np array 0 0 abs R1 abs R2 rot self rotation n if R 0 return np dot rot r else if R 0 B 0 0 R1 R else B A 0 0 R return B np dot rot r B
"returns ` vec2d(radius , theta ) ` for this vector , where ` radius ` is the length and ` theta ` is the angle .",def to_polar self return Vec2D self get_length self get_angle
convert itunes media kind to api representation .,def media_kind kind if kind in 1 return const MEDIA_TYPE_UNKNOWN elif kind in 3 7 11 12 13 18 32 return const MEDIA_TYPE_VIDEO elif kind in 2 4 10 14 17 21 36 return const MEDIA_TYPE_MUSIC elif kind in 8 64 return const MEDIA_TYPE_TV raise exceptions UnknownMediaKind Unknown media kind str kind
transfer the statements in this context over to the main store .,def save self if self parent buffered query INSERT DATA GRAPH s s query query self identifier n3 self graph serialize format nt self parent graph update query self flush else self meta generate
override protected - member - access check .,def _override_check_protected_attribute_access old_check_protected_attribute_access ClassChecker _check_protected_attribute_access def _check self node attrname node attrname klass node_frame_class node if klass is None or attrname not in klass instance_attrs and attrname not in m name for m in klass methods old_check_protected_attribute_access self node ClassChecker _check_protected_attribute_access _check
get attribute ' _ slope ',def do_get_slope self return self _slope
return list of files in the database,def get_database self search_paths Path var opt eset esets lib database_patterns dat return self locate database_patterns search_paths syspath False
"checks that the gsmmodem automatically retries commands that fail with a cms 515 error , and does not retry those that fail with other errors .",def testRetryCommands self class MockBusyDevice MockDevice def __init__ self MockDevice __init__ self self last_cmd None self retried def at_test self one return True def process self cmd if self last_cmd cmd self _output CMS ERROR 515 self last_cmd cmd return None self retried append cmd return False device MockBusyDevice n len device retried gsm pygsm GsmModem device device self assert_ len device retried n n len device retried gsm command AT TEST 1 self assertEqual len device retried n
initialize the variables from some text,def initVariablesFromText self text s StringIO text scan Scanner self lexicon s while 1 tok scan read print tok if tok 0 declare v StringIO tok 1 inner_scan Scanner self sub_lex v while 1 inner_tok inner_scan read print inner_tok if inner_tok 0 is None break if tok 0 is None break
assert that a string matches a particular pattern,def assert_re_match self pattern s if not re match pattern s raise AssertionError string does not match regexp n string s n re s s pattern
exports the volume . can optionally return a dictionary of changes to the volume object to be persisted .,def create_export self ctx volume pass
"return a complete pretty print representation of the file and all its groups , datasets and attributes .",def __repr__ self filename os path realpath self filename s HDF5 file 0 s 1 s n format filename format_size os path getsize filename s super File self __repr__ return s
return the list of versions which have eggs stored ( for the given project ) in order ( the latest version is the currently used ) .,def list project
send an arp from each host to aid controller 's host discovery ; fallback to ping if necessary,def gratuitousArp self hosts if not hosts hosts self hosts self verifyHosts hosts for host in hosts info s host name info host cmd ARP_PATH info n
test a package for which remote versions should be available .,pytest mark network def test_remote_versions versions zlib
"return the current user name , or none if getuser ( ) does not work in the current environment ( see # 1010 ) .",def get_user import getpass try return getpass getuser except ImportError KeyError return None
makes sure that virtual providers ( in the hierarchy ) always include a hash . make sure that the module file for the spec does not include a hash if hash_length is 0 .,def test_no_hash self factory patch_configuration patch_configuration no_hash module spec factory mpileaks_spec_string path module layout filename mpi_spec spec mpi mpiElement 0 1 2 format mpi_spec name mpi_spec version mpi_spec dag_hash length 7 assert mpiElement in path mpileaks_spec spec mpileaks_element 0 1 lua format mpileaks_spec name mpileaks_spec version assert path endswith mpileaks_element
returns the hop ips from the textfsm returned data,def extract_path_from_parsed_traceroute header routes hop_id Hop hop_index header index hop_id return item hop_index for item in routes
read in optimal mapping parameters for marker genes ; override if user has provided cutoff,def get_markers args marker_cutoffs inpath join args db marker_genes phyeco mapping_cutoffs if not os path isfile inpath sys exit File not found s inpath for line in open inpath marker_id min_pid line rstrip split if args mapid marker_cutoffs marker_id args mapid else marker_cutoffs marker_id float min_pid return marker_cutoffs
find the position of an item . raise valueerror if not found .,def index self item k self _key item i bisect_left self _keys k j bisect_right self _keys k return self _items i j index item i
activate a user 's account .,def activate request backend template_name registration activate html success_url None extra_context None kwargs Activate a user s account The actual activation of the account will be delegated to the backend specified by the backend keyword argument see below the backend s activate method will be called passing any keyword arguments captured from the URL and will be assumed to return a User if activation was successful or a value which evaluates to False in boolean context if not Upon successful activation the backend s post_activation_redirect method will be called passing the HttpRequest and the activated User to determine the URL to redirect the user to To override this pass the argument success_url see below On unsuccessful activation will render the template registration activate html to display an error message to override thise pass the argument template_name see below Arguments backend The dotted Python import path to the backend class to use Required extra_context A dictionary of variables to add to the template context Any callable object in this dictionary will be called to produce the end result which appears in the context Optional success_url The name of a URL pattern to redirect to on successful acivation This is optional if not specified this will be obtained by calling the backend s post_activation_redirect method template_name A custom template to use This is optional if not specified this will default to registration activate html kwargs Any keyword arguments captured from the URL such as an activation key which will be passed to the backend s activate method Context The context will be populated from the keyword arguments captured in the URL and any extra variables supplied in the extra_context argument see above Template registration activate html or template_name keyword argument backend get_backend backend account backend activate request kwargs if account if success_url is None to args kwargs backend post_activation_redirect request account return redirect to args kwargs else return redirect success_url if extra_context is None extra_context context RequestContext request for key value in extra_context items context key callable value and value or value return render_to_response template_name kwargs context_instance context
delete permissions from a user when she is removed as a meetup location moderator,receiver m2m_changed sender MeetupLocation moderators through dispatch_uid delete_moderators def delete_meetup_location_moderators sender kwargs instance kwargs pop instance None action kwargs pop action None pk_set kwargs pop pk_set None if action pre_remove systersuser SystersUser objects get pk list pk_set 0 moderators_group get_object_or_404 Group name COMMUNITY_MODERATOR format instance name if systersuser is_group_member moderators_group name systersuser leave_group moderators_group
method for getting metadata value ( returned as string ) .,def get_value self metadata if metadata in self data data if metadata authors or metadata authors_short value and join self data data metadata 0 elif metadata emails or metadata affiliations or metadata affiliations_short or metadata dirs_to_copy value join self data data metadata 0 else value str self data data metadata 0 return value
method for striping theme raw data from source .,def strip self source strip_source self canvas strip source if len self headings 0 for hds in self headings strip_source hds strip strip_source strip_source self slide strip strip_source if len self selectors 0 for sls in self selectors strip_source sls strip strip_source strip_source self toc strip strip_source strip_source Figure strip_theme strip_source strip_source Note strip_theme strip_source strip_source Table strip_theme strip_source return strip_source strip
upgrade name type of this user .,def upgrade_name self user_ if user_ name_type self name_type self full_name user_ full_name self first_name user_ first_name self name_type user_ name_type logger debug Added s name to User s s self name_type name lower self full_name self
pads the input along the spatial dimensions independently of input size .,def fixed_padding inputs kernel_size data_format channels_first pad_total kernel_size 1 pad_beg pad_total 2 pad_end pad_total pad_beg if data_format channels_first padded_inputs tf pad inputs 0 0 0 0 pad_beg pad_end pad_beg pad_end else padded_inputs tf pad inputs 0 0 pad_beg pad_end pad_beg pad_end 0 0 return padded_inputs
squeeze out some annoying extra space from an html string .,def spaceless html html re sub s p n p html return html
"implement isinstance(inst , cls ) .",def __instancecheck__ cls inst return any cls __subclasscheck__ c for c in set type inst inst __class__
"succeed iff pyclbr.readmodule_ex(modulename ) corresponds to the actual module object , module . any identifiers in ignore are ignored . if no module is provided , the appropriate module is loaded with _ _ import__.",def checkModule self moduleName module None ignore if module is None module __import__ moduleName globals silly dict pyclbr readmodule_ex moduleName def ismethod oclass obj name classdict oclass __dict__ if isinstance obj FunctionType if not isinstance classdict name StaticMethodType return False else if not isinstance obj MethodType return False if obj im_self is not None if not isinstance classdict name ClassMethodType or obj im_self is not oclass return False elif not isinstance classdict name FunctionType return False objname obj __name__ if objname startswith __ and not objname endswith __ objname _ s s obj im_class __name__ objname return objname name for name value in dict items if name in ignore continue self assertHasattr module name ignore py_item getattr module name if isinstance value pyclbr Function self assertIsInstance py_item FunctionType BuiltinFunctionType if py_item __module__ moduleName continue self assertEqual py_item __module__ value module else self assertIsInstance py_item ClassType type if py_item __module__ moduleName continue real_bases base __name__ for base in py_item __bases__ pyclbr_bases getattr base name base for base in value super try self assertListEq real_bases pyclbr_bases ignore except print sys stderr class s py_item raise actualMethods for m in py_item __dict__ keys if ismethod py_item getattr py_item m m actualMethods append m foundMethods for m in value methods keys if m 2 __ and m 2 __ foundMethods append _ name m else foundMethods append m try self assertListEq foundMethods actualMethods ignore self assertEqual py_item __module__ value module self assertEqualsOrIgnored py_item __name__ value name ignore except print sys stderr class s py_item raise def defined_in item module if isinstance item ClassType return item __module__ module __name__ if isinstance item FunctionType return item func_globals is module __dict__ return False for name in dir module item getattr module name if isinstance item ClassType FunctionType if defined_in item module self assertHaskey dict name ignore
return a list of all header values .,def values self return v for k v in self _headers
test whether name has a version file associated .,def isvalid self name namev self rcsname name return os path isfile namev or os path isfile os path join RCS namev
search path for a binary .,def which name path None exts path os environ get PATH path for dir in path split os pathsep for ext in exts binpath os path abspath os path join dir name ext if os path isfile binpath return binpath return None
"fringe : list of abstractnode objects , found_nodes : map of path - > abstractnode",def _build_graph fringe found_nodes while fringe an fringe 0 fringe fringe 1 if an path in found_nodes pass else fringe fringe an parents found_nodes an path an return graph_pb2 Graph nodes _build_node an for an in found_nodes values
return the string expression of this object .,def __str__ self if self pretty is None return str self val return self pretty
checks whether a func has been decorated with @add_arg_scope or not .,def has_arg_scope func key_op func __module__ func __name__ return key_op in _DECORATED_OPS
returns a string describing the current git head version as descriptively as possible .,def describe directory try return command_output git describe directory rstrip decode except try return command_output git rev parse HEAD directory rstrip decode except timestamp int os environ get SOURCE_DATE_EPOCH time time formatted datetime date fromtimestamp timestamp isoformat return unknown hash format formatted
transforms a key in sparse representation to a sequence which can be used as key in the trie .,def _sparse2seq self key seq for d v in key seq append d seq append v return seq
template tag used to sum its two arguments .,register filter def sum value args if value is None return if args is None return value return value args
extract the user applications . returns : the user applications list .,property def apps self from models import ApplicationModel return appli for appli in ApplicationModel objects developer self
passes the new default language i d through to the current session .,property def default_language_id self return self registry default_language_id
returns a single float value .,def get_value self return self get_values 1 0
tests svm classifier with real valued features .,def testRealValuedFeaturesPerfectlySeparable self def input_fn return example_id constant_op constant 1 2 3 feature1 constant_op constant 0 0 1 0 3 0 feature2 constant_op constant 1 0 1 2 1 0 constant_op constant 1 0 1 feature1 feature_column real_valued_column feature1 feature2 feature_column real_valued_column feature2 svm_classifier svm SVM feature_columns feature1 feature2 example_id_column example_id l1_regularization 0 0 l2_regularization 0 0 svm_classifier fit input_fn input_fn steps 30 metrics svm_classifier evaluate input_fn input_fn steps 1 loss metrics loss accuracy metrics accuracy self assertAlmostEqual loss 0 0 places 3 self assertAlmostEqual accuracy 1 0 places 3
verifies file_io 's object manipulation methods .,def create_object_test starttime int round time time 1000 dir_name s tf_gcs_test_ s FLAGS gcs_bucket_url starttime print Creating dir s dir_name file_io create_dir dir_name file_name s test_file txt dir_name print Creating file s file_name file_io write_string_to_file file_name test file creation list_files_pattern s test_file txt dir_name print Getting files matching pattern s list_files_pattern files_list file_io get_matching_files list_files_pattern print files_list assert len files_list 1 assert files_list 0 file_name print Deleting file s file_name file_io delete_file file_name print Deleting directory s dir_name file_io delete_recursively dir_name
static check of the ` matrix ` argument .,def _check_matrix self matrix allowed_dtypes dtypes float32 dtypes float64 dtypes complex64 dtypes complex128 matrix ops convert_to_tensor matrix name matrix dtype matrix dtype if dtype not in allowed_dtypes raise TypeError Argument matrix must have dtype in s Found s allowed_dtypes dtype if matrix get_shape ndims is not None and matrix get_shape ndims 2 raise ValueError Argument matrix must have at least 2 dimensions Found s matrix
this use case used to cause a missing argument error to be reported in module ' ( builtin ) ' in line -1 when the input file did not contain a trailing newline .,def test_error_missing_argument eof t BoostBuild Tester pass_toolset False t write file jam rule f param nf s __trailing_newline eof t run_build_system ffile jam status 1 t expect_output_lines file jam 2 in module scope t expect_output_lines file jam 1 see definition of rule f being called t cleanup
return the entire last flash page,def getLastCODEPage self return self readCODE self flashSize self flashPageSize self flashPageSize
1ad vtr translate 1 - > 1 1q test,def test_1ad_vtr_translate_1_1q self self pg1 sub_if set_vtr L2_VTR_OP L2_TRANSLATE_1_1 tag 300 push1q 1 self vtr_test self pg1 Tag dot1 DOT1Q vlan 300 Tag dot1 DOT1Q vlan 100
"alternative to the common request method , which sends the body with chunked encoding and not as one block",def request_chunked self method url body None headers None headers HTTPHeaderDict headers if headers is not None else skip_accept_encoding accept encoding in headers self putrequest method url skip_accept_encoding skip_accept_encoding for header value in headers items self putheader header value if transfer encoding not in headers self putheader Transfer Encoding chunked self endheaders if body is not None stringish_types six string_types six binary_type if isinstance body stringish_types body body for chunk in body if not chunk continue if not isinstance chunk six binary_type chunk chunk encode utf8 len_str hex len chunk 2 self send len_str encode utf 8 self send r n self send chunk self send r n self send 0 r n r n
try creating a key using an empty dictionary .,def test_create_dictionary_key_with_empty_dict with pytest raises ValueError utils create_dictionary_key dict
get all lines with certain data .,def lines_data self data data_hex data_to_hex data return self match_data_fts format data_hex
the dsaparameters object associated with this private key .,abc abstractmethod def parameters self
display the syntax error that just occurred .,def showsyntaxerror self filename None type value sys last_traceback sys exc_info sys last_type type sys last_value value if filename and type is SyntaxError try msg dummy_filename lineno offset line value except pass else value SyntaxError msg filename lineno offset line sys last_value value list traceback format_exception_only type value map self write list
returns the text from a query node .,def GetPhraseQueryNodeText node text GetQueryNodeText node text RemoveSurroundingQuotes text return text
return the database of ground - truth regions of interest .,def gt_roidb self cache_file os path join self cache_path self name _gt_roidb pkl if os path exists cache_file with open cache_file rb as fid roidb cPickle load fid print gt roidb loaded from format self name cache_file return roidb gt_roidb self _load_shapenet_annotation index for index in self image_index for i in xrange 1 self num_classes print Total number of boxes d format self classes i self _num_boxes_all i print Number of boxes covered d format self classes i self _num_boxes_covered i print Recall f format self classes i float self _num_boxes_covered i float self _num_boxes_all i with open cache_file wb as fid cPickle dump gt_roidb fid cPickle HIGHEST_PROTOCOL print wrote gt roidb to format cache_file return gt_roidb
read all messages from the queue and persist them to s3 . messages are stored in the s3 bucket using a naming scheme of : :,def save_to_s3 self bucket raise BotoClientError Not Implemented
this function will handle the file extension manipulation,def Filename_Handler url Like adding tar zip etc to the file name file_name file_ext file_noext alter_filename url files file_name s tar file_noext s rar file_noext s zip file_noext s txt file_noext files s old file_name s file_name s bak file_name s tar gz file_noext files s backup s file_noext file_ext s bkp s file_noext file_ext backup s s file_noext file_ext files s s swp file_noext file_ext s s file_noext file_ext s _ s s file_noext file_ext files s2 s file_noext file_ext s s_ file_noext file_ext s s gz file_noext file_ext files s_old s file_noext file_ext return files Assume that you submitted upload php here is the output then
"get the path for steam from the steam process . if that fails , it uses the registry on windows . returns : str : the path to steam . if the path could not be found , the current directory is returned instead ( os.curdir )",def get_steam_path if psutil for pid in psutil process_iter try if pid name lower steam exe or pid name lower steam return os path dirname pid exe except psutil Error logger exception Could not get Steam path from its process if winreg try reg_key winreg OpenKey winreg HKEY_CURRENT_USER Software Valve Steam return os path normpath winreg QueryValueEx reg_key SteamPath 0 except WindowsError logger exception Could not query registry for Steam path return os curdir
returns the agent for the provided index .,def getAgent self index util raiseNotDefined
"provide a recorded response , or record a response for replay .",def request self http_request request http_request _copy _scrub_request request if self real_client is None self last_request_was_live False for recording in self _recordings if _match_request recording 0 request return recording 1 else self real_client debug self debug self last_request_was_live True response self real_client request http_request scrubbed_response _scrub_response response self add_response request scrubbed_response status scrubbed_response reason dict scrubbed_response getheaders scrubbed_response read return self _recordings 1 1 raise NoRecordingFound No recoding was found for request s s request method str request uri
this example illustrates loading a kinetic model defined in genesis format into moose using loadmodel function and using writesbml function one can save the model into sbml format .,def main moose loadModel genesis Kholodenko g Kholodenko written moose mooseWriteSBML Kholodenko genesis Kholodenko_tosbml xml print written
create a compartment with hodgkin - huxley type ion channels ( na and k ) .,def create_hhcomp parent library name hhcomp diameter 3e 05 length 0 0 comp sarea create_passive_comp parent name diameter length if moose exists library na moose copy library na comp path na else create_na_chan parent comp path na moose element s na comp path na Gbar 0 12 sarea 10000 0 na Ek 0 115 EREST_ACT moose connect comp channel na channel if moose exists library k moose copy library k comp path k else create_k_chan parent comp path k moose element s k comp path k Gbar 0 036 sarea 10000 0 k Ek 0 012 EREST_ACT moose connect comp channel k channel return comp na k
updates current image must be implemented in subclass .,def _update_image self if self current_image is None self current_image cv LoadImage resources camera_disconnected png return cv CloneImage self current_image
"give me data points yerr is the 1sigma error of each y i return a function : you pass an array of new x , the func returns ( newy , newyerr )",def regression x y yerr verbose True kwargs x np atleast_2d x T mykwargs theta0 100 0 nugget 0 001 mykwargs update kwargs gp GaussianProcess corr squared_exponential random_start 1 verbose verbose mykwargs gp fit x y def outfct xgrid ygrid MSE gp predict np atleast_2d xgrid T eval_MSE True sigmas np sqrt MSE return ygrid sigmas return outfct
: return : a list(mandatory ) contains solutions,abc abstractmethod def _request_journeys self from_coord to_coord period_extremity limit None u n return a list mandatory contains solutions n pass
returns content of specified authfile as bytes . none if file is not in default booth directory or there was some io error .,def read_authfile reporter path if not path return None if os path dirname os path abspath path BOOTH_CONFIG_DIR reporter process reports booth_unsupported_file_location path return None try with open path rb as file return file read except EnvironmentError as e reporter process lib_reports file_io_error file_roles BOOTH_KEY path reason format_environment_error e operation read severity ReportItemSeverity WARNING return None
get all data for the light .,def get_data self response requests get self hue_url if response status_code HTTPStatus OK raise RuntimeError error requesting data from bridge 0 format response return response json
create a subsublogger and create a logrecord,def test_01getSubSubLogger self log gLogger getSubLogger log sublog log getSubLogger sublog sublog always message self assertIn Framework log sublog self buffer getvalue self buffer truncate 0 self oldbuffer truncate 0
obtain the summary of the stage task from the db .,def export_getTaskSummary self taskID res storageDB getTaskSummary taskID if not res OK gLogger error getTaskSummary Failed to get task summary res Message return res
handler for eof ( ctrl d ) signal - perform quit,def do_EOF self args self do_quit args
"get seconds , with microsecond precission , since 2 k",def to2K dateTimeObject None if not dateTimeObject dateTimeObject dateTime delta dateTimeObject dt return delta days 86400 delta seconds delta microseconds 1000000 0
to get the list of the policies available in the rss.policy . configurations,def listAvailablePolicies policiesMeta Configurations POLICIESMETA for pm in policiesMeta print 3 pm args policiesMeta pm args description policiesMeta pm description
gets all computing elements from /resources / sites/<>/<>/ce,def getComputingElements _basePath Resources Sites ces domainNames gConfig getSections _basePath if not domainNames OK return domainNames domainNames domainNames Value for domainName in domainNames domainSites gConfig getSections s s _basePath domainName if not domainSites OK return domainSites domainSites domainSites Value for site in domainSites siteCEs gConfig getSections s s s CEs _basePath domainName site if not siteCEs OK gLogger error siteCEs Message continue siteCEs siteCEs Value ces extend siteCEs ces list set ces return S_OK ces
responds to user 's request to create a new repository .,require_http_methods GET POST login_required def new_repository request if request method POST form RepositoryCreationForm data request POST user request user if form is_valid form save return redirect view_repository username request user username repository form cleaned_data name elif request method GET form RepositoryCreationForm return render request repository new html form form
test whether the data set parameter units are successfully loaded .,def test_parameter_units self ds self _create_dataset self assertEqual ds col_units K kg m3 J kg K kg m s m2 s W m K m2 s None
register a function to be called when this entry is accepted .,def on_accept self func kwargs u n Register a function to be called when this entry is accepted n n param func The function to call n param kwargs Keyword arguments that should be passed to the registered function n self add_hook u accept func kwargs
starting point when module is the main routine .,def vp_start_gui global val w root root Tk root title CPU_Information root geometry 498x433 1309 473 w CPU_Information root cpu_info_support init root w root mainloop
recover deleted key for a domain .,keys command name recover click argument fqdn click argument key pass_gandi def keys_recover gandi fqdn key result gandi dns keys_recover fqdn key gandi echo Recover successful return result
create a ` gxdbwrite < geosoft.gxapi.gxdbwrite > ` object for a xy - located data . add channels using the ` add_channel < geosoft.gxapi.gxdbwrite.add_channel > ` method .,classmethod def create_xy cls db ret_val gxapi_cy WrapDBWRITE _create_xy GXContext _get_tls_geo db return GXDBWRITE ret_val
adds a face to a patch in a mesh,def add_face self mesh_name patch_id v0 v1 v2 ret_val self _add_face mesh_name encode patch_id v0 v1 v2 return ret_val
returns the correct upload file type .,def to_python self value try raw json loads value except raw ret defaultdict list for datum in raw cls UPLOADERS datum get source prefix self get_prefix datum id ret datum bucket append cls build_upload prefix datum return ret
stub out gevent.sleep to only yield briefly .,pytest fixture autouse True def gevent_fastsleep monkeypatch old_sleep gevent sleep def fast_sleep tm old_sleep 0 1 monkeypatch setattr gevent sleep fast_sleep
"publishes payload to topic , returns true if successfull",def topic_pub self topic payload url http arg arg format self host self port api_urls pub topic payload with request urlopen url payload encode utf 8 as response if response getcode 200 return True else return False
% reduce randomaction expr scalar exprattrs,def reduceRandomAction self cmd source text attrs text cmd script_parser parse_text text val cmd script_parser _ Random actions list for k v in attrs val iteritems if not re_valid_attribute_code match k raise Parsing SyntaxError cmd script_parser _ obj has no attribute attr format obj randomaction attr k self val randomaction source val text attrs val
save a dictionary as a config file .,def save_config fname config pattern None f open fname w if pattern is None for key t val in sorted config items f write s s s n t key str val else for line in pattern if len line 1 and line 0 key line 1 t val config key f write s s s n t key str val else f write line n f close
simply swap 2 indices in a the specified list .,def _swapListIndices inputList oldIndex newIndex if oldIndex 1 oldIndex len inputList 1 if newIndex 1 newIndex len inputList value inputList oldIndex inputList pop oldIndex inputList insert newIndex value
return device specific tracklog folder or none if default should be used,def getTracklogFolderPath self return None
check if identifier is registerd with manager instance .,Pyro4 expose def valid_ident self ident if ident in self idents return True else return False
check whether a pyramid was successfully built or a new one was started .,def run self bot user msg tag_info msgType msgCount emote self getInfo msg tag_info if msgType EmoteType INVALID self reset elif self validNextLevel msgType msgCount emote self processNextLevel msgType msgCount emote user bot elif self validNewStart msgType msgCount self reset self processNextLevel msgType msgCount emote user bot else self reset
called immediately after a task finishes .,def _post_run self args kwargs self _end_time time time self _task_latency_sec self _end_time self _start_time if self target_runtime if self _task_latency_sec self target_runtime self _alert_runtime_exceeded
test that the inactive_ads method on a provider returns the correct amount,def test_inactive_ads_returns_correct_amounts self self assertEqual self provider inactive_ads 20
test that the equality operator returns true when comparing two intervals .,def test_equal_on_equal_and_empty self a primitives Interval b primitives Interval self assertTrue a b self assertTrue b a
get an object bound to the twitter api using your own credentials .,classmethod def from_oauth_file cls filepath None if filepath is None home os environ get HOME os environ get USERPROFILE filepath os path join home twitter_oauth oauth_token oauth_token_secret read_token_file filepath twitter cls auth OAuth oauth_token oauth_token_secret CONSUMER_KEY CONSUMER_SECRET api_version 1 1 domain api twitter com return twitter
returns a dict with he artist if we can find it on the download page,def getArtistFromDlPage self download_page opener self getOpener try response opener open download_page read except urllib2 URLError return None try return artist re search labels w s response group 1 except AttributeError return None
shutdown all active connections and then terminate protocol .,def shutdown self for connection in self _active_connections values connection shutdown if hasattr self transport loseConnection self transport loseConnection
get a host object by ip address,def get_host self ipaddr return self __hosts get ipaddr
create num openstack instances running os_type os_version and return their names . each instance has at least the resources described in resources_hint .,def create self num os_type os_version arch resources_hint log debug ProvisionOpenStack create if arch is None arch self get_default_arch resources_hint self interpret_hints machine config openstack machine volumes config openstack volumes resources_hint self init_user_data os_type os_version image self image os_type os_version arch if network in config openstack net nic net id str self net_id config openstack network else net flavor self flavor resources_hint machine arch keypair config openstack keypair or teuthology worker_group config openstack worker_group or teuthology worker cmd flock close timeout 28800 tmp teuthology server create lock openstack quiet server create config openstack get server create f json image str image flavor str flavor key name s keypair user data str self user_data net min str num max str num security group s worker_group property teuthology self property property ownedby config openstack ip wait self basename try self run cmd type compute except CalledProcessError as exc if quota exceeded in exc output lower raise QuotaExceededError message exc output raise instances filter lambda instance self property in instance Properties self list_instances instances OpenStackInstance i ID for i in instances fqdns try network config openstack get network for instance in instances ip instance get_ip network name self ip2name self basename ip OpenStack run server set name name instance ID fqdn name config lab_domain if not misc ssh_keyscan_wait fqdn raise ValueError ssh_keyscan_wait failed for fqdn time sleep 15 if not self cloud_init_wait instance raise ValueError cloud_init_wait failed for fqdn self attach_volumes name resources_hint volumes fqdns append fqdn except Exception as e log exception str e for id in instance ID for instance in instances self destroy id raise e return fqdns
returns the users sasview config dir,staticmethod def _get_home_dir return os path join os path expanduser sasview
create an xml element for writing to file,def create_element self name attrib None nsmap None if attrib is None attrib return etree Element name attrib nsmap
encode a folder name using imap modified utf-7 encoding .,def encode s u Encode a folder name using IMAP modified UTF 7 encoding n n Despite the function s name the output is still a unicode string n if not isinstance s text_type return s r _in def extend_result_if_chars_buffered if _in r extend u modified_utf7 u join _in u del _in for c in s if ord c in PRINTABLE extend_result_if_chars_buffered r append c elif c u extend_result_if_chars_buffered r append u else _in append c extend_result_if_chars_buffered return u join r
check if the values of the observations correspond to the values assumed by the likelihood function .,def _preprocess_values self Y Y_prep Y copy Y1 Y Y flatten 1 size Y2 Y Y flatten 0 size assert Y1 Y2 Y size Bernoulli likelihood is meant to be used only with outputs in 0 1 Y_prep Y flatten 0 1 return Y_prep
"fetches log , possibly requesting multiple pages to do so .",def fetch_log_with_paging query_params limit fetch last_result fetch query_params commits last_result log while last_result get next and len commits limit query_params s last_result get next last_result fetch query_params commits extend last_result log last_result log commits logging debug fetched d commits next s len commits last_result get next return last_result
"parses a lfmm results file to extract any significant associations between a marker and a covariate . returns a list of associations tuples : [ ( ' marker ' , ' covariate ' ) , ( ' marker ' , ' covariate ' ) ... ]",def lfmm_results_parser lfmm_results_filename assoc_threshold immutables associations snp 0 imut_indeces int x for x in immutables results open lfmm_results_filename r for lines in results snp 1 lines float x for x in lines split try snp_assocs str snp str i for i in line_index if lines i assoc_threshold except NameError line_index list range len lines for index in sorted imut_indeces reverse True del line_index index snp_assocs str snp str i for i in line_index if lines i assoc_threshold associations snp_assocs results close return associations
test if content repository returns expected top torrents .,def test_get_top_torrents self def get_fake_torrents limit return chr x 20 x 0 1525704192 for x in range limit self content_repository torrent_db getRecentlyCheckedTorrents get_fake_torrents limit 10 self assertEqual self content_repository get_top_torrents limit limit get_fake_torrents limit
test whether items are not parsed anymore when the parse feeder is stopped,deferred timeout 10 def test_parse_feed_stopped self self channel_rss rss_url http localhost d test_rss xml self file_server_port self channel_rss _url_cache SimpleCache os path join self session_base_dir cache txt self channel_rss _to_stop True def verify_rss items self assertEqual len items 0 return self channel_rss parse_feed addCallback verify_rss
encode a reply @param int version : socks5 version @param int rep : the response @param int rsv : reserved bytes @param address_type : the address type of the bind address @param bind_address : the bind address host @param bind_port : the bind address port @return :,def encode_reply version rep rsv address_type bind_address bind_port data struct pack BBBB version rep rsv address_type data __encode_address address_type bind_address data struct pack H bind_port return data
add some scheme standard procedures .,def add_globals self import math cmath operator as op self update vars math self update vars cmath self update op add op sub op mul op div not op not_ op gt op lt op ge op le op eq equal op eq eq op is_ length len cons cons car lambda x x 0 cdr lambda x x 1 append op add list lambda x list x list lambda x isa x list null lambda x x symbol lambda x isa x Symbol boolean lambda x isa x bool pair is_pair port lambda x isa x file apply lambda proc l proc l eval lambda x eval expand x load lambda fn load fn call cc callcc open input file open close input port lambda p p file close open output file lambda f open f w close output port lambda p p close eof object lambda x x is eof_object read char readchar read read write lambda x port sys stdout port write to_string x display lambda x port sys stdout port write x if isa x str else to_string x return self
"get a new furious context and add it to the registry . if a batch size is specified , use an autocontext which inserts tasks in batches as they are added to the context .",def new batch_size None options if batch_size new_context AutoContext batch_size batch_size options else new_context Context options _local get_local_context registry append new_context return new_context
"` input_specs ` follows the format of featurespec from schema . to be more precise it 's a namedtuple that should have : ' feature_type ' , ' feature_names ' , ' feature_ids '",def __init__ self model input_record input_specs name u feature_sparse_to_dense kwargs u n input_specs follows the format of FeatureSpec from schema To be more n precise it s a namedtuple that should have n feature_type feature_names feature_ids n super FeatureSparseToDense self __init__ model name input_record kwargs self input_specs input_specs outputs for field feature_specs in self input_specs assert len feature_specs feature_names len feature_specs feature_ids if feature_specs feature_type u FLOAT outputs append field schema Scalar np float32 len feature_specs feature_ids self get_next_blob_reference field u _output elif feature_specs feature_type u ID_LIST outputs append field schema Struct u ranges schema Scalar np int32 len feature_specs feature_ids 2 self get_next_blob_reference field u _ranges u values schema Scalar np int64 self get_next_blob_reference field u _values elif feature_specs feature_type u ID_SCORE_LIST outputs append field schema Struct u ranges schema Scalar np int32 len feature_specs feature_ids 2 self get_next_blob_reference field u _ranges u ids schema Scalar np int64 self get_next_blob_reference field u _ids u scores schema Scalar np float32 self get_next_blob_reference field u _scores elif feature_specs feature_type u EMBEDDING outputs append field schema Struct u ranges schema Scalar np int32 len feature_specs feature_ids 2 self get_next_blob_reference field u _ranges u values schema Scalar np float32 self get_next_blob_reference field u _values else raise TypeError u Unsupported input type 0 format feature_specs feature_type self output_schema schema Struct outputs for field feature_specs in input_specs schema attach_metadata_to_scalars self output_schema field schema Metadata feature_specs feature_specs self zero model global_constants u ZERO self zero_range model global_constants u ZERO_RANGE
renames interval name field ( and second column because are working on gff files ) to the parent gene generally takes a dict { transcript : gene } and converts transcript names to gene names,def rename_to_gene_from_dict interval transcript_gene_dict interval 2 transcript_gene_dict interval attrs Parent interval name transcript_gene_dict interval attrs Parent return interval
sends a transaction to be refunded ( partially or fully ),def credit self amount trans_id credit_card self charge_setup super FirstDataLegacy self set self REQUEST_FIELDS trans_type Credit super FirstDataLegacy self set self REQUEST_FIELDS trans_id trans_id super FirstDataLegacy self set self REQUEST_FIELDS number credit_card number if amount super FirstDataLegacy self set self REQUEST_FIELDS amount amount response response_time self request return self parse response response_time
return a dictionary suitable for use in `` package_data `` in a distutils `` setup.py `` file .,def find_package_data where package exclude standard_exclude exclude_directories standard_exclude_directories only_in_packages True show_ignored False out stack convert_path where package only_in_packages while stack where prefix package only_in_packages stack pop 0 for name in os listdir where fn os path join where name if os path isdir fn bad_name False for pattern in exclude_directories if fnmatchcase name pattern or fn lower pattern lower bad_name True if show_ignored print Directory s ignored by pattern s fn pattern file sys stderr break if bad_name continue if os path isfile os path join fn __init__ py and not prefix if not package new_package name else new_package package name stack append fn new_package False else stack append fn prefix name package only_in_packages elif package or not only_in_packages bad_name False for pattern in exclude if fnmatchcase name pattern or fn lower pattern lower bad_name True if show_ignored print File s ignored by pattern s fn pattern file sys stderr break if bad_name continue out setdefault package append prefix name return out
return the bond in the string if it has the same properties as the given bond .,def get_existing_bond self bond existing_bond self get_bond bond from_object bond to_object if existing_bond if existing_bond bond_category bond bond_category and existing_bond direction_category bond direction_category return existing_bond
returns a mask of the same size of the image with true on the skin - color pixel . note : this function expects the image color representation to be ycrcb .,def get_skin_mask image image_in_ycbcr return np logical_and np logical_and np logical_and np abs image take 2 axis 2 image take 1 axis 2 15 squeeze image take 2 axis 2 image take 1 axis 2 squeeze np logical_and np logical_and np all image 20 40 95 axis 2 np amax image axis 2 np min image axis 2 15 image take 2 axis 2 image take 0 axis 2 squeeze np all np logical_and 0 133 80 image_in_ycbcr image_in_ycbcr 255 173 120 axis 2
get a random task of the specified type .,staticmethod def get_assignment_context request request_data request GET if request method GET else request POST worker_id request_data get worker_id task_type request_data get task_type eligible_tasks InternalCrowdInterface get_eligible_tasks worker_id filter task_type task_type order_by create_time task_index min geometric ORDER_WEIGHT 1 eligible_tasks count 1 assignment_id uuid uuid4 return task_id eligible_tasks task_index task_id if task_index 0 else None worker_id worker_id is_accepted True assignment_id assignment_id
: param api_key : api key or username to used ( required ) : type api_key : `` str ``,def __init__ self api_key api_secret
create a container cluster ( a namespace ),def create_cluster self name location None request metadata name name result self connection request ROOT_URL v1 namespaces method POST data json dumps request object return self _to_cluster result
test conversion from color name to percent rgb triplet .,def test_name_to_rgb_percent self test_pairs u white u 100 u 100 u 100 u navy u 0 u 0 u 50 u goldenrod u 85 49 u 64 71 u 12 5 for pair in test_pairs self assertEqual pair 1 webcolors name_to_rgb_percent pair 0
return only non - blank lines that start with the comment regexp . for these lines strip out the matching characters and leading / trailing whitespace .,def process_lines self lines re_comment re compile self comment for line in lines line line strip if not line continue match re_comment match line if match out line match end if out yield out else return
"context manager to temporarily override individual column info.serialize_method dict values . the serialize_method attribute is an optional dict which might look like `` { ' fits ' : ' jd1_jd2 ' , ' ecsv ' : ' formatted_value ' , .. } `` .",contextmanager def serialize_method_as tbl serialize_method def get_override_sm col Determine if the serialize_method str or dict specifies an override of column presets for col Returns the matching serialize_method value or None if isinstance serialize_method str return serialize_method if col info name in serialize_method return serialize_method col info name for key in serialize_method if isclass key and isinstance col key return serialize_method key return None if serialize_method original_sms for col in tbl itercols if hasattr col info serialize_method override_sm get_override_sm col if override_sm original_sms col info name col info serialize_method col info serialize_method fmt override_sm for fmt in col info serialize_method try yield finally if serialize_method for name original_sm in original_sms items tbl name info serialize_method original_sm
destroys arts c api agenda object associated with this agenda object .,def __del__ self try arts_api destroy_agenda self ptr except pass
upload a file to a google drive folder .,run_if GOOGLE_APPS def upload_file parent_id file_path title description mimetype service Service settings GOOGLE_P12_PATH settings GOOGLE_SERVICE_EMAIL file_metadata service insert_file title description parent_id mimetype file_path return file_metadata
build a block of testing data from numpy.arange .,with_default_shape def arange_data self shape dtype np float64 return arange prod shape dtype dtype reshape shape
"from a dictionary of vectors that give weights , pull the vectors that correspond to each kernel , as stored in the ` weight_names ` attribute . a none vector will result in none weights",def get_weights self vectors mask vectors get self mask_name slice None wghts for w in self weight_names if vectors w is None wghts None else wghts append vectors w mask return wghts
solves tsp exactly by checking all pathes ( o(n!*n ) ) .,def solve_stupid_brute_force self ans self path_weight for i in permutations range self N w self path_weight i if w ans ans w self path i
load a font for rendering .,def load name None size None bold False italic False dpi None if size is None size 12 if dpi is None dpi 96 if type name in tuple list for n in name if _font_class have_font n name n break else name None shared_object_space gl current_context object_space if not hasattr shared_object_space pyglet_font_font_cache shared_object_space pyglet_font_font_cache weakref WeakValueDictionary shared_object_space pyglet_font_font_hold list font_cache shared_object_space pyglet_font_font_cache font_hold shared_object_space pyglet_font_font_hold descriptor name size bold italic dpi if descriptor in font_cache return font_cache descriptor font _font_class name size bold bold italic italic dpi dpi font name name font size size font bold bold font italic italic font dpi dpi font_cache descriptor font del font_hold 3 font_hold insert 0 font return font
builds and display the window for editing block of times,def __init__ self parent okclicked_cb super EditBlockTimesWin self __init__ Gtk WindowType TOPLEVEL self okclicked_cb okclicked_cb self modify_bg Gtk StateType NORMAL fstimer gui bgcolor self set_transient_for parent self set_modal True self set_title fsTimer Edit times self set_position Gtk WindowPosition CENTER self set_border_width 20 self connect delete_event lambda b jnk self hide label0 Gtk Label label label0 set_markup span color red WARNING Changes to times cannot be automatically undone span If you change the times and forget the old values they will be gone forever label1 Gtk Label label Time h mm ss to be added or subtracted from all selected times self radiobutton Gtk RadioButton group None label ADD self radiobutton set_active True radiobutton2 Gtk RadioButton group self radiobutton label SUBTRACT self entrytime Gtk Entry self entrytime set_max_length 7 self entrytime set_text 0 00 00 hbox1 Gtk HBox False 10 hbox1 pack_start self radiobutton False False 0 hbox1 pack_start radiobutton2 False False 0 hbox1 pack_start self entrytime False False 0 btnOK GtkStockButton ok OK btnOK connect clicked self okclicked btnCANCEL GtkStockButton close Cancel btnCANCEL connect clicked lambda b self hide cancel_algn Gtk Alignment new 0 0 0 0 cancel_algn add btnCANCEL hbox2 Gtk HBox False 10 hbox2 pack_start cancel_algn True True 0 hbox2 pack_start btnOK False False 0 vbox Gtk VBox False 10 vbox pack_start label0 False False 10 vbox pack_start label1 False False 10 vbox pack_start hbox1 False False 0 vbox pack_start hbox2 False False 0 self add vbox self show_all
login the user to the system,view_config route_name login renderer auth login mako def login request login_url route_url login request referrer request url if referrer login_url referrer u came_from request params get came_from referrer message u login u password u if form submitted in request params login request params login lower password request params password LOG debug login auth UserMgr get username login LOG debug auth LOG debug UserMgr get_list if auth and auth validate_password password and auth activated headers remember request auth id max_age 60 60 24 30 auth last_login datetime utcnow AuthLog login login True return HTTPFound location request route_url user_bmark_recent username auth username headers headers if auth and not auth validate_password password message Your login attempt has failed AuthLog login login False password password elif auth and not auth activated message User account deactivated Please check your email AuthLog login login False password password AuthLog disabled login elif auth is None message Failed login AuthLog login login False password password if isinstance request user User and request user activated return HTTPFound location request route_url user_bmark_recent username request user username return message message came_from came_from login login password password
distance from point3 to line defined by point1 and point2 . distance is always positive .,def distance_to_line point1 point2 point3 norm line_orthogonal point1 point2 return abs norm dot point3 point1 norm length
returns the calling class ' name and dictionary,def class_space classlevel 3 frame sys _getframe classlevel classname frame f_code co_name classdict frame f_locals return classname classdict
returns the linear trend in previous trades for each data point in dataframe of book data,def get_trend books trades def trend x trades_n trades iloc x indexes 0 x indexes 1 if len trades_n 3 return 0 else return linregress trades_n index values trades_n price values 0 return books apply trend axis 1
"wait for the cloudstack simulator to return credentials . : rtype : dict[str , str ]",def _get_credentials self client HttpClient self args always True endpoint s admin json self endpoint for _ in range 1 30 display info Waiting for CloudStack credentials s endpoint verbosity 1 response client get endpoint if response status_code 200 try return response json except HttpError as ex display error ex time sleep 30 raise ApplicationError Timeout waiting for CloudStack credentials
convert string into a list of texts and numbers in order to support a natural sorting .,def numsplit text result for group in re split d text if group try group int group except ValueError pass result append group return result
block until remote process finishes .,def wait self for greenlet in self greenlets greenlet get status self _get_exitstatus for stream in stdout stderr if hasattr self stream stream_obj getattr self stream if hasattr stream_obj seek and not isinstance stream_obj ChannelFile stream_obj seek 0 self _raise_for_status return status
"initialise with a starting graph , and number of iterations k. note that the starting graph must have self edges on every vertex . only the adjacency matrix of the starting graph is used .",def __init__ self initialGraph k Parameter checkInt k 1 float inf W initialGraph getWeightMatrix if numpy diag W numpy zeros W shape 0 any raise ValueError Initial graph must have all self edges self initialGraph initialGraph self k k
return the integer corresponding to the current frame in the trajectory .,def current_frame return viewer traj_controls current_index
initialize a biomart object by connecting to a biomart service .,def __init__ self biomart ensembl dataset hsapiens_gene_ensembl host None version None verbose False self base importr biomaRt if version self mart self base useEnsembl biomart dataset version version verbose verbose elif host self mart self base useEnsembl biomart dataset host host verbose verbose else self mart self base useEnsembl biomart dataset verbose verbose
: param field_count : how many fields to omit in each mutation : type fields : field or iterable of fields : param fields : enclosed field(s ) ( default : [ ] ) : type delim : field : param delim : delimiter between elements in the list ( default : none ) : type encoder : bitsencoder : param encoder : encoder for the container ( default : enc_bits_default ) : param fuzzable : is container fuzzable ( default : true ) : param name : ( unique ) name of the container ( default : none ),def __init__ self field_count fields delim None encoder ENC_BITS_DEFAULT fuzzable True name None if field_count 1 raise KittyException field_count s 1 field_count super FieldRangeMutator self __init__ fields fields encoder encoder fuzzable fuzzable name name self _field_count field_count self _orig_fields self _delim delim
"@param target : { tuple(ip , prt ) } @param privatekeyfilepath : { str } file contain server private key ( if none - > back to standard rdp security ) @param certificatefilepath : { str } file contain server certificate ( if none - > back to standard rdp security ) @param clientsecurity : { str(ssl|rdp ) } security layer use in client connection side",def __init__ self target ouputDir privateKeyFilePath certificateFilePath clientSecurity rdp ServerFactory __init__ self 16 privateKeyFilePath certificateFilePath self _target target self _ouputDir ouputDir self _clientSecurity clientSecurity self _uniqueId 0
return the standard deviation of a numeric iterable .,def calculate_stddev values avg calculate_avg values return math sqrt calculate_avg val avg 2 for val in values
test to verify that an exact representation of the desired decimal type is maintained .,def test_exact self vector precision scale vector get_value decimal_type if vector get_value cast_from decimal pytest skip Casting between the same decimal type isn t interesting for i in xrange self iterations val self _gen_decimal_val precision scale cast self _normalize_cast_expr val precision vector get_value cast_from format val precision scale res Decimal self execute_scalar cast self _assert_decimal_result cast res val
gets the dungeon_level the entity is currently in .,property def value self return self _value
encode configuration data . return json object for koan .,def gen_config_data_for_koan self json_config_data json JSONEncoder sort_keys True indent 4 encode self gen_config_data return json_config_data
decorator to warn users if tracepoint by required api is in missing in trace # todo : keep _ _ doc _ _,def requires tracepoints global msg notified def wrapper func wraps func def wrapped args kwargs cls args 0 missing join tp for tp in tracepoints if tp not in cls _trace tracepoints if missing and missing not in notified log warn msg format tp missing notified add missing if not getattr cls _initialized True cls _initialize cls _initialized True return func args kwargs return wrapped return wrapper
create a file containing |text| and assign it to the key .,EntryLock def AssignText self text self _AssignText text
get the record for the given uri .,def get self uri urilib validate uri return self _collection get uri
: param host : statsd host : type host : str,def __init__ self host 127 0 0 1 port 8125 self host host self port port
"sets the resolution of this camera for all future captures from it , if the provided resolution is valid .",def set_resolution self x y with self lock self camera resolution x y
set_client_dh_params#f5045f1f nonce : int128 server_nonce : int128 encrypted_data : bytes = set_client_dh_params_answer,def get_bytes self ret struct pack I16s16s set_client_DH_params constructor self nonce self server_nonce bytes_io BytesIO bytes_io write ret serialize_string bytes_io self encrypted_data return bytes_io getvalue
calculate the gate size from the gate_style .,def _calculate_gate_size self if self _gate_style unit return self _mem_size elif self _gate_style memory return 1 else return 0
"attempt to determine the real path of a file i d or path through successive checking of candidate paths . if the real path is stored with an extension , the path is considered a match if the basename matches the expected file path of the i d .",def realpath self file if os path isfile file return file relpath os path join self root file if os path isfile relpath return relpath filepath self idpath file if os path isfile filepath return filepath paths glob glob 0 format filepath if paths return paths 0 return None
returns a generator yielding all currently registered conditionset instances .,def get_condition_sets self return self _registry itervalues
"yield up to ` max_executors ` expanded jobsteps to be run , based on the collection phase 's data .",def expand self job max_executors kwargs raise NotImplementedError
"if holiday falls on saturday or sunday , use previous friday instead .",def previous_friday dt if dt weekday 5 return dt timedelta 1 elif dt weekday 6 return dt timedelta 2 return dt
wrapper function for the gabp module which resolves a gaussian propagation problem using graphlab,def runGaBP convergence A y sigma_y None x None sigma_x None square False file input tempfile mkstemp dir save_c_gl input A y x x sigma_y sigma_y sigma_x sigma_x square square args gabp data input threshold str convergence algorithm 0 scheduler round_robin square if not square args append false else args append true print Running join args ret subprocess Popen args stdout sys stdout stderr subprocess STDOUT wait if ret 0 sys exit GaBP did not complete os remove input x2 diag load_c_gl input out len x return x2 diag
"uses the filepath parameter to construct a set of potential language suffixed file names , and return the template_name of the first template matching the current language , default language if otherwise , or if neither the base path requested . throws a templatenotfound exception if none are found .",register filter name translate_file_path def translate_file_path filepath paths construct_file_language_names filepath get_language return select_template paths origin template_name
""" run full analysis on class c",def run self class_result name self c_name source None xref_from xref_to fields methods component_type None if self c_analysis is_external access_flags EXTERNAL class_result component_type NonComponentType EXTERNAL else access_flags self c_analysis orig_class get_access_flags_string converted convert_to_dot_notation class_result name if converted in self activities class_result component_type ComponentType ACTIVITY elif converted in self receivers class_result component_type ComponentType RECEIVER elif converted in self services class_result component_type ComponentType SERVICE elif converted in self providers class_result component_type ComponentType PROVIDER else class_result component_type NonComponentType INTERNAL class_result access_flags access_flags if self c_analysis xrefs_from self c_analysis get_xref_from for ref_class in xrefs_from ref_class_name None if isinstance ref_class get_vm_class ExternalClass ref_class_name ref_class get_vm_class name else ref_class_name ref_class get_vm_class get_name if ref_class_name self c_name continue for ref_kind ref_method ref_offset in xrefs_from ref_class ref class ref_method get_class_name method ref_method get_name if not self duplicate_edges and ref in class_result xref_from continue class_result xref_from append ref xrefs_to self c_analysis get_xref_to for ref_class in xrefs_to ref_class_name None if isinstance ref_class get_vm_class ExternalClass ref_class_name ref_class get_vm_class name else ref_class_name ref_class get_vm_class get_name if ref_class_name self c_name continue for ref_kind ref_method ref_offset in xrefs_to ref_class ref class ref_method get_class_name method ref_method get_name if not self duplicate_edges and ref in class_result xref_to continue class_result xref_to append ref for f_a in self c_analysis get_fields field f_a get_field has_init_value True if field get_init_value else False class_field name field get_name access_flags field get_access_flags_string class_name field get_class_name init_value_type field get_init_value get_value_type if has_init_value else None init_value_arg field get_init_value get_value_arg if has_init_value else None init_value field get_init_value get_value if has_init_value else None xref_read xref_write if f_a xrefs_read f_a get_xref_read for ref_class ref_method in xrefs_read ref_class_name None if isinstance ref_class get_vm_class ExternalClass ref_class_name ref_class get_vm_class name else ref_class_name ref_class get_vm_class get_name ref class ref_class_name method ref_method get_name if not self duplicate_edges and ref in class_field xref_read continue class_field xref_read append ref xrefs_write f_a get_xref_write for ref_class ref_method in xrefs_write ref_class_name None if isinstance ref_class get_vm_class ExternalClass ref_class_name ref_class get_vm_class name else ref_class_name ref_class get_vm_class get_name ref class ref_class_name method ref_method get_name if not self duplicate_edges and ref in class_field xref_write continue class_field xref_write append ref class_result fields append class_field for m_a in self c_analysis get_methods method m_a get_method info access_flags EXTERNAL if not isinstance method ExternalMethod info append method get_information access_flags method get_access_flags_string class_method name method get_name access_flags access_flags xref_from xref_to info info source None if m_a xrefs_from m_a get_xref_from for ref_class ref_method _ in xrefs_from ref_class_name None if isinstance ref_class get_vm_class ExternalClass ref_class_name ref_class get_vm_class name else ref_class_name ref_class get_vm_class get_name ref class ref_class_name method ref_method get_name if not self duplicate_edges and ref in class_method xref_from continue class_method xref_from append ref xrefs_to m_a get_xref_to for ref_class ref_method _ in xrefs_to ref_class_name None if isinstance ref_class get_vm_class ExternalClass ref_class_name ref_class get_vm_class name else ref_class_name ref_class get_vm_class get_name ref class ref_class_name method ref_method get_name if not self duplicate_edges and ref in class_method xref_to continue class_method xref_to append ref class_result methods append class_method return class_result
send a direct muc invitation to an xmpp entity .,def send_invitation self jid roomjid password None reason None ifrom None msg self xmpp Message msg to jid if ifrom is not None msg from ifrom msg groupchat_invite jid roomjid if password is not None msg groupchat_invite password password if reason is not None msg groupchat_invite reason reason return msg send
publishes a message on the wall,def comment self message id None self _client push id comments message message
"remove paired device by mac address , return success of the operation .",def remove self mac_address try out self get_output remove mac_address 3 except BluetoothctlError as e print e return None else res self child expect not available Device has been removed pexpect EOF success True if res 1 else False return success
"add a new player connection . this should only be invoked from the "" connect "" and "" playeropen "" commands .",def add self connid uidstr email stream assert connid not in self map Connection ID already in use conn PlayerConnection self connid ObjectId uidstr email stream self map connid conn uset self uidmap get conn uid None if uset uset add conn else self uidmap conn uid set conn self disconnectedmap pop conn uid None return conn
"given a list of files , call isolateserver_archive.py with them . then verify they are all on the server .",def _archive_given_files self files args sys executable os path join ROOT_DIR isolateserver_archive py remote ISOLATE_SERVER namespace self namespace if v in sys argv args append verbose args extend os path join TEST_DATA_DIR filename for filename in files self assertEqual 0 subprocess call args file_hashes isolateserver_archive sha1_file os path join TEST_DATA_DIR f for f in files for i in range len files download_url scontent retrieve s s ISOLATE_SERVER self namespace file_hashes i downloaded_file isolateserver_archive url_open download_url retry_404 True self assertTrue downloaded_file is not None File s was missing from the server files i contains_hash_url scontent contains s token s from_smoke_test 1 ISOLATE_SERVER self namespace self token body join binascii unhexlify h for h in file_hashes expected chr 1 len files MAX_ATTEMPTS 10 for i in xrange MAX_ATTEMPTS response isolateserver_archive url_open contains_hash_url data body content_type application octet stream read if response expected break if i MAX_ATTEMPTS 1 print Visible datastore inconsistency retrying time sleep 0 1 self assertEqual expected response
get the top die ( which is either a dw_tag_compile_unit or dw_tag_partial_unit ) of this cu,def get_top_DIE self return self _get_DIE 0
write header entry or package entry to packages file .,def _WritePkgIndex self pkgfile entry lines s s k v for k v in sorted entry items if v pkgfile write s n n n join lines
lint webkit 's testexpectation files .,def RunWebkitLint target buildbot_report PrintNamedStep webkit_lint RunCmd webkit tools layout_tests run_webkit_tests py lint test files chromium target target
handle the output of a block of text from the subprocess .,def Output self stream data Handle the output of a block of text from the subprocess n n All subprocess output should be sent through this method It is split into n lines which are processed separately using the _Out method n n Args n stream Which file the output come in on n sys stdout stdout n sys stderr stderr n None Our own internal output n data Output data as a big string potentially containing many lines of n text Each line should end with r n There is no requirement to send n whole lines this method happily handles fragments and tries to n present then to the user as early as possible n n TODO sjg Just use a list as the input parameter to avoid the split n lines data split r n for line in lines 1 self _Out stream line display self verbose newline True if lines 1 self _Out stream lines 1 display self verbose sys stdout flush
"produce a checksum for the file specified by ' filename ' . ' filename ' is a string path to a file that is opened and read in this function . the checksum algorithm is specified by ' digest ' and is a valid openssl algorithm . if the digest used is not valid or python 's hashlib does n't work , the none object will be returned instead . the size of blocks that this function will read from the file object it opens based on ' filename ' can be specified by ' chunk_size ' , which defaults to 1 k",def digest_file filename digest chunk_size 1024 assert not os path isdir filename this function only works with files logger logging getLogger checksums py if hashlib is not None logger debug Creating new s object digest h hashlib new digest with open filename rb as f while True data f read chunk_size if not data logger debug Finished reading in file break h update data hash h hexdigest logger debug Hash for s is s filename hash return hash else logger warn The python module for hashlib is missing return None
": param dirs : dict of the form , { < dir > : < num tests >",def generate_tests self dirs i 0 for d num in dirs iteritems for j in range num i 1 name test i i test name name path os path join d name yield test
generator of all tests in the collection,property def tests self return t for t in self
@param u : the first vertex . @type u : c{object } @param v : the second vertex . @type v : c{object } @return : a set of @rtype : c{set } of l{edge },def adjacent self u v if u v return set return set edge for edge in self edges if u in edge and v in edge
"note : if the event exists , it will not do anything",def add_event self fd eventmask if not self __is_register get fd False return is_read eventmask EV_TYPE_READ EV_TYPE_READ is_write eventmask EV_TYPE_WRITE EV_TYPE_WRITE if is_read self __add_ev_read fd if is_write self __add_ev_write fd
round the corners of this polygon and fractures it into polygons with less vertices if necessary .,def fillet points radius points_per_2pi 128 max_points 199 precision 0 001 points np asarray points two_pi 2 np pi vec points astype float np roll points 1 0 length np sqrt np sum vec 2 1 ii np flatnonzero length if len ii len length points points ii vec points np roll points 1 0 length np sqrt np sum vec 2 1 vec 0 vec 0 length vec 1 vec 1 length dvec np roll vec 1 0 vec norm np sqrt np sum dvec 2 1 ii np flatnonzero norm dvec ii 0 dvec ii 0 norm ii dvec ii 1 dvec ii 1 norm ii theta np arccos np sum np roll vec 1 0 vec 1 ct np cos theta 0 5 tt np tan theta 0 5 if not isinstance radius list radius radius len points if not len points len radius raise ValueError GDSPY Fillet radius list length does not match the number of points in the polygon new_points for ii in range 1 len points 1 if theta ii 0 and radius ii 0 a0 vec ii tt ii dvec ii ct ii a0 np arctan2 a0 1 a0 0 a1 vec ii 1 tt ii dvec ii ct ii a1 np arctan2 a1 1 a1 0 if a1 a0 np pi a1 two_pi elif a1 a0 np pi a1 two_pi n max int np ceil abs a1 a0 two_pi points_per_2pi 0 5 2 a np linspace a0 a1 n l radius ii tt ii if l 0 49 length ii r 0 49 length ii tt ii l 0 49 length ii else r radius ii if l 0 49 length ii 1 r 0 49 length ii 1 tt ii new_points list r dvec ii ct ii points ii np vstack r np cos a r np sin a transpose else new_points append points ii points np array new_points if len points max_points print Error max points reached else return points
instantiate a new : obj:`lap `,def __init__ self index super _Lap self __init__ index
"builds the petlib distribution , ready to be uploaded to pypi .",task def build quiet True tell Build dist sh python setup py sdist capture quiet
edidms2deg converts the lat / lon information within given edi files from / to the degree / deg : min : sec format .,def edidms2deg invert 0 args sys argv usage n usage n t edidms2deg edi file s optional i for inverted transformation n if len args 2 sys exit usage lo_files_raw args 1 try if lo_files_raw 1 lower i invert 1 lo_files_raw pop except sys exit usage n last argument must be filename or the letter i lo_files for listarg in lo_files_raw tmp_list glob glob listarg for arg in tmp_list try fn op abspath arg lo_files append fn except print s is no valid file arg for fn in lo_files out_string latlon 0 F open fn r try for curr_line_raw in F readlines curr_line curr_line_raw strip out_line curr_line raw_line1 curr_line split if len raw_line1 1 if raw_line1 0 strip 3 lower lat lat_in raw_line1 1 if check_format lat_in dms and invert 0 lat_out dms2deg lat_in out_line LAT s lat_out latlon 1 elif check_format lat_in deg and invert 1 lat_out deg2dms lat_in out_line LAT s lat_out latlon 1 elif raw_line1 0 strip 3 lower lon lon_in raw_line1 1 if check_format lon_in dms and invert 0 lon_out dms2deg lon_in out_line LON s lon_out latlon 1 elif check_format lon_in deg and invert 1 lon_out deg2dms lon_in out_line LON s lon_out latlon 1 out_string out_line out_string n F close if latlon 2 F2 open op basename fn w F2 write out_string F2 close else print s did not contain proper lat lon information maybe it s just not an EDI file or it s in the correct form already file left unchanged fn continue except F close print t could not parse file s maybe it s not an EDI file n fn continue
returns the wait interval in seconds .,def get_wait_seconds self return self _wait_seconds
returns singleton or empty dictionary to be included in the resulting entity .,def map_form_to_entity self formvals entityvals if self e k self f get_field_value_key entityvals v formvals get self i None self f field_value_mapper decode_store v entityvals k return entityvals
"returns true if the string matches the card regexp , or false",def is_card_list self string if not string return False return re match self CARD_REGEXP string is not None
"return preferred width @return ( int , int )",def do_get_preferred_width self if self _widget is None return 0 0 width Gtk FlowBoxChild do_get_preferred_width self 0 return width width
two non - similar sets should not be clustered,def test_dissimilar_sets cluster Cluster cluster add_set 12345abcdef cluster add_set 1234567890z print cluster get_sets assert len cluster get_sets 2
returns a mapparser to parse filespasswd cache .,def GetParser self return ConsulPasswdMapParser
send forms and method page to user .,def get self params forms_path self request path rstrip hostname self request host registry_path self __registry_path service_path self request get path None method_name self request get method None if service_path and method_name form_template _METHODS_TEMPLATE params service_path service_path params method_name method_name else form_template _FORMS_TEMPLATE self response out write template render form_template params
"calculate(self , time , delta_time )",accepts 1 2 int float def calculate self time delta_time raise NotImplementedError Abstract method called
remove dots(if any ) that mark calculated aesthetics,def strip_dots value with suppress TypeError value DOTS_RE sub 1 value return value
"param : round_string is expected to be list of integers separated by spaces . the integers are interpreted as pairs ( agent_id , bet ) .",def deserialize_round round_string log debug round_string s round_string last_round dict parts round_string strip split if len parts 1 for i in range 0 len parts 2 last_round int parts i int parts i 1 return last_round
* virtual*. return a list of names in which we 'll search .,def _generate_lookup_names self return
returns a sorted list of part numbers and descriptions : param like : database matching string . use % as a wild card : return : list of part numbers and descriptions,def get_parts self like None if like None self cur execute SELECT Partnumber Description FROM pndesc WHERE Description LIKE ORDER BY PartNumber ASC like else self cur execute SELECT Partnumber Description FROM pndesc ORDER BY PartNumber ASC return self cur fetchall
"given a dictionary of coefs , create a k array to multiply against model fls",def update self p if self fix_c0 c0 1 0 cns p else c0 10 p 0 cns p 1 Tc np dot self T T cns k c0 1 Tc self k_last self k self k k
"< purpose > calls securesystemslib.interface.generate_and_write_ed25519_keypair with a default password of "" "" so as to prevent the library from prompting for password . if prompting is needed , it 's already handled here and then forwarded .",def generate_and_write_ed25519_keypair filepath password securesystemslib interface generate_and_write_ed25519_keypair filepath password
identify files that might contain data,def identify_datafiles root extensions_to_ignore None directories_to_ignore None files_to_ignore None for dirpath dirnames filenames in walk root for ignore in directories_to_ignore if ignore in dirnames dirnames remove ignore for filename in filenames ignore False for ext in extensions_to_ignore if filename endswith ext ignore True if filename in files_to_ignore ignore True if ignore is False yield dirpath filename
convert a date to julian day .,def date_to_jd year month day if month 1 or month 2 yearp year 1 monthp month 12 else yearp year monthp month if year 1582 or year 1582 and month 10 or year 1582 and month 10 and day 15 B 0 else A math trunc yearp 100 0 B 2 A math trunc A 4 0 if yearp 0 C math trunc 365 25 yearp 0 75 else C math trunc 365 25 yearp D math trunc 30 6001 monthp 1 jd B C D day 1720994 5 return jd
"within this context , all queries go to the master .",contextlib contextmanager def use_master old getattr multidb pinning _locals pinned False multidb pinning pin_this_thread try yield finally multidb pinning _locals pinned old
returns a dict with parts of the raw sql query .,def base_query self return
returns the value from the event . @return : the value of this event,def GetValue self return self _value
train with the specified score function . @param x0 : the initial vector for long - term memory . @param funct : the score function . we attempt to minimize or maximize this . @return : the trained long - term memory vector .,def train self x0 funct iteration_number 1 self position list x0 self best_score funct self position while not self should_stop iteration_number self best_score trial_position list self position self perform_randomization trial_position trial_score funct trial_position if self better_than trial_score self best_score self best_score trial_score self position trial_position current funct self position if self display_iteration print Iteration str iteration_number Score str self best_score iteration_number 1 if self display_final print Finished after str iteration_number iterations final score is str self best_score return self position
"given a number returns its string format with the specified length , adding ' 0 ' if necessary @param num : a number ( int ) @param numdigits : length of the output string ( int ) @return : a tuple ( status , statuscontent ) , where statuscontent is a number in string format in case status = 0 or an error in case status = -1",def numToString num numDigits if not isinstance num int return 1 Bad number strNum str num if numDigits len strNum return 1 Bad digit number for i in range numDigits len strNum strNum 0 strNum return 0 strNum
the main method for this script .,def main name options server config _config_value general server options server if server is None raise ValueError server must be supplied on command line or in configuration file username config _config_value general username options username if username is None raise ValueError username must be supplied on command line or in configuration file password config _config_value general password options password if password is None raise ValueError password must be supplied on command line or in configuration file vm_template None if options template is not None try vm_template template load_template options template except TemplateNotFoundError print ERROR Template s could not be found options template sys exit 1 expected_opts compute_resource datastore disksize nics memory num_cpus guest_id host vm_opts for opt in expected_opts vm_opts opt getattr options opt if vm_opts opt is None if vm_template is None raise ValueError s not specified on the command line and you have not specified any template to inherit the value from opt try vm_opts opt vm_template opt except AttributeError raise ValueError s not specified on the command line and no value is provided in the specified template opt client Client server server username username password password create_vm client name vm_opts compute_resource vm_opts datastore vm_opts disksize vm_opts nics vm_opts memory vm_opts num_cpus vm_opts guest_id host vm_opts host client logout
least squares minimization using tikhonov regularization .,def rlstsq coef_mat ordinate order 1 alpha None cross False coef_mat np array coef_mat ordinate np array ordinate dim1 dim2 coef_mat shape if cross out np empty dim1 dim2 ordinate shape 1 coef_mat_ np empty dim1 1 dim2 ordinate_ np empty dim1 1 ordinate shape 1 for i in range dim1 coef_mat_ i coef_mat i coef_mat_ i coef_mat i 1 ordinate_ i ordinate i ordinate_ i ordinate i 1 out i rlstsq coef_mat_ ordinate_ order alpha False return np median out 0 if order 0 tikhmat np eye dim2 elif order 1 tikhmat np zeros dim2 1 dim2 tikhmat 1 np eye dim2 1 tikhmat 1 np eye dim2 1 elif order 2 tikhmat np zeros dim2 2 dim2 tikhmat 2 np eye dim2 2 tikhmat 1 1 2 np eye dim2 2 tikhmat 2 np eye dim2 2 elif order is None tikhmat np zeros 1 else tikhmat np array order assert tikhmat shape 1 dim2 or tikhmat shape in 1 if alpha is None and order is not None gamma 0 1 def rgcv_error alpha Calculate Tikhonov dampening parameter if alpha 0 return np inf coef_mat_ np dot coef_mat T coef_mat alpha np dot tikhmat T tikhmat try coef_mat_ np dot linalg inv coef_mat_ coef_mat T except linalg LinAlgError return np inf abscissas np dot coef_mat_ ordinate res2 np sum np dot coef_mat abscissas ordinate 2 coef_mat_2 np dot coef_mat coef_mat_ skew dim1 res2 np trace np eye dim1 coef_mat_2 2 mu2 np sum coef_mat_2 coef_mat_2 T dim1 return gamma 1 gamma mu2 skew alphas 10 0 np arange 0 16 evals np array rgcv_error alpha for alpha in alphas alpha alphas np argmin evals out linalg inv np dot coef_mat T coef_mat alpha np dot tikhmat T tikhmat out np dot out np dot coef_mat T ordinate return out
transform data by mapping it into the latent space . taken from https://jmetzen.github.io/2015-11-27/vae.html,def transform self sess inputs inputs self normalize inputs feed_dict self inputs inputs return sess run self z_mean_test feed_dict feed_dict
takes subtracts last time logged in from current date and if the difference in minutes is greater than 90 minutes the session has expired . : return :,def session_is_expired self if not self last_login return True session_limit 90 session_duration datetime datetime now self last_login return session_duration seconds 60 session_limit
return true if in a venv and no system site packages .,def virtualenv_no_global site_mod_dir os path dirname os path abspath site __file__ no_global_file os path join site_mod_dir no global site packages txt if running_under_virtualenv and os path isfile no_global_file return True
create a new user . default role is admin,cli command create user click argument username nargs 1 click argument password nargs 1 click argument email nargs 1 click option role default admin type click Choice admin developer installer maintainer def create_user username password email role from extrapypi extensions import db from extrapypi import models pwd custom_app_context hash password user models User username username password_hash pwd email email role role db session add user try db session commit click echo User s created username except Exception click echo Cannot create user s username err True db rollback
transforms a job exception from one of several forms into something more obvious and manageable .,def transform_job_exception e if isinstance e NJSServerError return NarrativeException e code e message e name njs elif isinstance e UJSServerError return NarrativeException e code e message e name ujs elif isinstance e HTTPError code e response status_code if code 404 or code 502 or code 503 msg A KBase service is currently unavailable elif code 504 or code 598 or code 599 msg There was a temporary network connection error elif code 500 msg An internal error occurred in the KBase service else msg An untracked error occurred return NarrativeException e response status_code msg HTTPError network else return NarrativeException 1 str e Exception unknown
in - order traversal of the tree,def in_order_traverse self result if not self node return result result extend self node left in_order_traverse result append self node key result extend self node right in_order_traverse return result
returns the reference datetime as a date object .,classmethod def reference_date cls return cls _get_reference date
analyze a function 's signature and return a data structure suitable for passing in as arguments to an argparse parser 's add_argument ( ) method .,def describe_arguments func argspec inspect getargspec func if argspec defaults positional_args argspec args len argspec defaults keyword_names argspec args len argspec defaults for arg default in zip keyword_names argspec defaults yield format arg default default else positional_args argspec args for arg in positional_args yield arg if argspec varargs yield argspec varargs nargs
"unlike the real reactor , clock.calllater does n't raise an exception when the time is negative .",def callLater self when what a kw u n Unlike the real reactor Clock callLater doesn t raise an exception n when the time is negative n n https twistedmatrix com trac ticket 9166 comment n n Until that s fixed upstream emulate the behavior here n assert when 0 u s is not greater than or equal to 0 seconds when return Clock callLater self when what a kw
"create new indextable object . args : preread : func , pre - processing , applied to each field as it is read . precompile : func , pre - compilation , applied to each field before compiling . file_path : string , location of file to use as input .",def __init__ self preread None precompile None file_path None self index None self compiled None if file_path self _index_file file_path self _index_handle open self _index_file r self _ParseIndex preread precompile
use of default_args kwarg can be used to nuke e.g. -v,def test_overriding_default_args self r self rsync 2 default_opts pthrz for x in rsync_sources assert not re search s x r stdout re M s was found in s x r stdout
test the origin keyword for raster .,def test_origin graph DualRadialGraph 1 4 spacing 2 0 origin 1 0 2 assert_array_almost_equal graph xy_of_node 2 0 3 0 0 0 1 0 2 0 1 0 4 0 1 0 2 0 1 0 assert_array_almost_equal graph xy_of_corner 1 0 2 0 3 0 2 0 1 0 0 0 3 0 0 0
finds unique entries in hsd_upstr.values ( ),def find_unique_upstream_hsd_ids_and_fractions hsd_upstr unique_ids C fractions for ke in hsd_upstr keys cnt Counter for num in hsd_upstr ke cnt num 1 unique_ids update ke cnt keys buf for k in cnt keys buf append cnt k C update ke buf e s float sum buf for s in buf fractions update ke e return unique_ids fractions
load model using xxxnet.py and xxxnet.npy,def load_model exe place net_file net_name net_weight debug fluid import_fluid net input_map build_model net_file net_name feed_names input_map keys feed_shapes v for k v in input_map items prediction net get_output startup_program fluid default_startup_program exe run startup_program if net_weight find npy 0 net load data_path net_weight exe exe place place else raise ValueError not found weight file test_program fluid default_main_program clone fetch_list_var fetch_list_name if debug is False fetch_list_var append prediction else for k v in net layers items fetch_list_var append v fetch_list_name append k return program test_program feed_names feed_names fetch_vars fetch_list_var fetch_names fetch_list_name feed_shapes feed_shapes
"> > > r = reader('t1_template.xlsx ' , ' sheet2 ' , [ ' t1_data.xlsx ' ] ) > > > print r.result[0]['items ' ] [ { u'status ' : u's1 ' , u'name ' : u'a1 ' , u'id ' : u'id1 ' } , { u'status ' : u's2 ' , u'name ' : u'a2 ' , u'id ' : u'id2 ' } , { u'status ' : u's4 ' , u'name ' : u'a4 ' , u'id ' : u'id4 ' } , { u'status ' : u's8 ' , u'name ' : u'a8 ' , u'id ' : u'id8 ' } ]",def test_read_2
check that we can add a dictionary of pegs,def test_add_pegs self self assertRaises TypeError self enz add_pegs peg1 self assertRaises TypeError self enz add_pegs peg1 peg2 self enz add_pegs p1 a p2 b self assertRaises KeyError self enz add_pegs p3 role not present
discover all modules in |start_dir| which match |pattern| .,def DiscoverModules start_dir top_level_dir pattern import_error_should_raise True modules for dir_path _ filenames in os walk start_dir for filename in filenames if filename startswith or filename startswith _ continue if os path splitext filename 1 py continue if not fnmatch fnmatch filename pattern continue module_rel_path os path relpath os path join dir_path filename top_level_dir module_name re sub os path splitext module_rel_path 0 try module __import__ module_name fromlist True except ImportError if import_error_should_raise raise logging error While importing s n module_name traceback print_exc continue modules append module return modules
"returns the str |data| as a unicode object . it 's expected to be utf8 , but there are also latin-1 encodings in there for some reason . fall back to that .",def ToUnicode data try return unicode data utf 8 except return unicode data latin 1
get the list of disabled java test matchers .,def GetDisabledJavaTestMatchers self return _EXPECTATIONS GetDisabledTestMatchers self GetOS self _chrome_version
returns whether |obj| is a unittest . testcase .,staticmethod def _IsTestClass obj return isinstance obj type types ClassType and issubclass obj unittest TestCase
test that login is successful with valid credentials for a domain .,def testGoodLoginForTransitionedDomainAccount self credentials self _ValidCredentials account_type test_domain_account self Login credentials username credentials password login_info self GetLoginInfo self assertTrue login_info is_logged_in msg Login failed
checks whether this is a valid test method .,def _IsTestMethod attrname test_case_class attr getattr test_case_class attrname return callable attr and attrname startswith test
create the initial files in the project .,def create self raise NotImplementedError Projects must implement create
tests that recipe_name only uses allowed imports .,def ImportsTest recipe_path recipe_name whitelist universe_view recipe universe_view load_recipe recipe_name for _ val in sorted recipe globals iteritems if isinstance val types ModuleType module_name val __name__ for pattern in whitelist if pattern match val __name__ break else yield In s n Non whitelisted import of s recipe_path module_name
"delete a file , if possible .",def remove self path return SFTP_OP_UNSUPPORTED
take a transition that involves consuming a symbol,def feed self x assert self idle self i 1 if isinstance self pc Accept or not self pc comparison_function x self pc None else self pc self pc succ
"work can not be created without a category , the ` work.save ` method will throw an integrityerror .",def test_work_creation self with self assertRaises IntegrityError Work objects create title a cool work
tests that a combined model class still has datastore properties .,def testDatastoreModelProperties self self assertEqual 3 len TestModelWithProperties properties
was something modified since the user last downloaded it ?,def was_modified_since header None mtime 0 size 0 try if header is None raise ValueError matches re match length 0 9 header re IGNORECASE header_mtime mktime_tz parsedate_tz matches group 1 header_len matches group 3 if header_len and int header_len size raise ValueError if mtime header_mtime raise ValueError except AttributeError ValueError return True return False
"this decorator activates commit on response . this way , if the view function runs successfully , a commit is made ; if the viewfunc produces an exception , a rollback is made . this is one of the most common ways to do transaction control in web apps .",def commit_on_success func def _commit_on_success args kw try enter_transaction_management managed True try res func args kw except if is_dirty rollback raise else if is_dirty commit return res finally leave_transaction_management return wraps func _commit_on_success
"reset a core . after a call to this function , the core is running",def resetn self self reset
"compute the orbit of each satellites by sampling 200 positions of a satellites during one period : param name : the names of the satellites : param sioi : the "" satellites_in_orbit_info "" file used to get the period of a satellite : param dict_tle : the tle file as a dict : return : an 3 dimensional array representing the orbit of each satellites . the array is of dimension [ nb_satellites x 200 x 2 ] , where 200 is the sampling number and 2 is the position ( latitude , longitude )",def satellite_orbit name sioi dict_tle orbit_point nb_point 200 period int sioi sioi OBJECT_NAME name PERIOD values 0 delta_t int period 60 nb_point delta_t timedelta seconds delta_t time datetime 2017 10 12 l1 l2 dict_tle name temp ephem readtle name l1 l2 for i in range 0 200 time time delta_t temp compute time try lat temp sublat 180 pi long temp sublong 180 pi orbit_point append lat long except print ERROR return orbit_point
confirm we can use the iterator protocol,def test_iterator_access self self protocol answers append info names something one a documentation string something two a second documentation string info TorInfo self protocol self assertTrue len info 1 all for x in info all append x self assertTrue len all 1 self assertTrue len info something 2 all for x in info something all append x self assertTrue len all 2
iterate : func:`sample ` for `` n `` iterations and return the result .,def run_mcmc self pos0 M Madapt delta 0 6 kwargs print Running HMC with dual averaging and trajectory length 0 2f delta return self sample pos0 M Madapt delta kwargs
return data from a cont record in an endf-6 file .,def get_cont_record file_obj skipC False line file_obj readline if skipC C1 None C2 None else C1 float_endf line 11 C2 float_endf line 11 22 L1 int line 22 33 L2 int line 33 44 N1 int line 44 55 N2 int line 55 66 return C1 C2 L1 L2 N1 N2
update all data in the table from a dict of newsletter data,def refresh self new_data curr_data self serialize if new_data curr_data return None self all delete count 0 for slug data in new_data iteritems self create slug slug data data count 1 return count
a validated : class:`~ichnaea.api.locate.schema . fallbacklookup ` instance .,property def fallback self return self _fallback
verify caching headers of search forms and search results,def test_headers self response self client get reverse search q audio eq_ max age s settings SEARCH_CACHE_PERIOD 60 response Cache Control assert Expires in response response self client get reverse search eq_ max age s settings SEARCH_CACHE_PERIOD 60 response Cache Control assert Expires in response
unset the thread - local var we set during ` process_request ` .,def process_response self request response set_url_prefixer None return response
the finder class under test .,property def finder self from moztrap view runtests finders import RunTestsFinder return RunTestsFinder
the form class under test .,property def form self from moztrap view manage products forms import AddProductForm return AddProductForm
"try to add a non - existent case to a tag , get exception .",def test_add_bad_case self cv self F CaseVersionFactory t self F TagFactory product cv productversion product f self form product str t product id name t name description t description caseversions str cv id 1 cc_version str t cc_version instance t self assertFalse f is_valid self assertEqual f errors caseversions u Not a valid caseversion for this tag
"details includes description , markdownified safely .",def test_description self cv self F CaseVersionFactory create description _Valmorphanize_ script self rcv self F RunCaseVersionFactory create caseversion cv res self get ajax True res mustcontain em Valmorphanize em lt script gt
"load the source resource , modify it with changes made to this resource instance , and save it over the locale - specific resource .",def save self locale if not self source_resource raise SyncError Cannot save FTL resource 0 No source resource given format self path with codecs open self source_resource path r utf 8 as resource structure parser parse resource read entities structure body for obj in list entities if isinstance obj localizable_entries index entities index obj entity self entities obj id name if entity strings message parser parse_entry entity strings None message comment obj comment entities index message else del entities index create_parent_directory self path with codecs open self path w utf 8 as f log debug Saving file s self path f write serializer serialize structure
derived classes must override this function with business logic,def main self raise NotImplementedError A definition of main in a derived class is required
"returns a comma - separated list of valid keys , useful for exception messages .",property def _invalid_key self return Invalid key s Valid s join self _valid_keys
create a handler calling @callback when activated,def __init__ self callback super Handler self __init__ self callback callback
add keys to dictionary merging with another dictionary object,def __add__ self other self json update other return self
return the name of this node in the tree .,def getName self pass
i will write a welcomemessage and loginprompt to the client .,def connectionMade self self write self welcomeMessage self loginPrompt
"returns all books that are part of this collection , including subcollections .",def get_books self filter_string None books for collection in self self get_all_collections sql SELECT book id book name book path book pages book format book size book added FROM book JOIN contain ON contain book book id AND contain collection sql_args collection id if filter_string sql WHERE book name LIKE sql_args append filter_string cursor self get_backend execute sql sql_args rows cursor fetchall cursor close books extend _Book cols for cols in rows return books
ui and model updates at the end of a drag,def drag_stop_cb self tdw self _drag_update_idler_srcid None if self _cmd is not None assert tdw is self _drag_active_tdw tdw set_sensitive False window tdw get_window cursor Gdk Cursor new_for_display window get_display Gdk CursorType WATCH tdw set_override_cursor cursor self final_modifiers self current_modifiers GLib idle_add self _finalize_move_idler else self _drag_cleanup return super LayerMoveMode self drag_stop_cb tdw
the _ i d of the inserted document if an upsert took place . otherwise `` none `` .,property def upserted_id self self _raise_if_unacknowledged upserted_id return self __raw_result get upserted
this function creates a collection of spherical templates of different sizes .,def create_synth_dict radii box_radius u n This function creates a collection of spherical templates of different sizes n n Copyright c 2016 UChicago Argonne LLC n n Parameters n n radii int n radii coubld be 1xN vector but currently is an integer n box_radius float n Returns n n ndarray n dictionary of template vectors of size box_length 3 x length radii where n box_length box_radius 2 1 and radii is an input to the function which contains a vector n of different sphere sizes n import numpy as np from numpy import linalg as LA from scipy import ndimage as ndi from skimage morphology import ball box_length int box_radius 2 1 dict np zeros box_length 3 np size radii dtype u float32 cvox int box_length 1 2 1 for i in range len radii template np zeros box_length box_length box_length template cvox cvox cvox 1 dict i np reshape ndi binary_dilation template ball radii i 1 2 box_length 3 dict i dict i LA norm dict i return dict
tests that a pre - task successfully determines the correct error,def test_determine_error self u scale_errors ScaleDatabaseError ScaleIOError ScaleOperationalError MissingSetting u for scale_error in scale_errors config ExecutionConfiguration config create_tasks u pre config set_task_ids self job_exe get_cluster_id task PreTask u agent_1 self job_exe self job_exe job_type config update job_test_utils create_task_status_update task id task agent_id TaskStatusUpdate RUNNING now task update update update job_test_utils create_task_status_update task id task agent_id TaskStatusUpdate FAILED now exit_code scale_error exit_code error task determine_error update self assertEqual scale_error error_name error name
see : meth:`storage.brokers.broker . broker.get_file_system_paths `,def get_file_system_paths self volume_path files u See meth storage brokers broker Broker get_file_system_paths n paths for scale_file in files paths append os path join volume_path scale_file file_path return paths
edits an existing error and returns the updated model,def patch self request error_id u Edits an existing error and returns the updated model n n param request the HTTP PATCH request n type request class rest_framework request Request n param error_id The id of the error n type error_id int encoded as a str n rtype class rest_framework response Response n returns the HTTP response to send back to the user n try error Error objects get pk error_id except Error DoesNotExist raise Http404 if error category u SYSTEM raise BadParameter u System level errors cannot be edited title rest_util parse_string request u title required False description rest_util parse_string request u description required False category rest_util parse_string request u category required False accepted_values c for c _ in Error CATEGORIES if category u SYSTEM raise BadParameter u Errors cannot be changed to system level error title title or error title error description description or error description error category category or error category error save serializer self get_serializer error return Response serializer data
"returns the state of the given mesos task status , possibly none",def get_status_state status u Returns the state of the given Mesos task status possibly None n n param status The task status n type status class mesos_pb2 TaskStatus n returns The task status state n rtype string n return mesos_pb2 TaskState Name status state
tests calling scanconfiguration.validate ( ) successfully with all information,def test_validate_successful_all self u config u workspace self workspace name u scanner u type u dir u recursive True u files_to_ingest u filename_regex u txt u data_types u one u two u new_file_path os path join u my u path u new_workspace self new_workspace name ScanConfiguration config validate
send list of all links pass in the chan,def send_links self for chan in self chans links list schema Link select where schema Link created_at datetime datetime utcnow datetime timedelta hours 23 schema Link created_at datetime datetime utcnow datetime timedelta minutes 10 if not links self taemin log LOTD No links to display for chan s chan continue self privmsg chan Link of the day s links today len links for link in links self privmsg chan s s link url link title
args : app(flask . flask ) request(flask . request ),def __init__ self app request None self app app self request request self request_id uuid4 hex self bucket_name None self _permissions_validator None self _permissions_loader None self _cloud_factory None self _artifact_manager None self _search None self _link_mapper None self _context None self _context_response_mapper None self _link_manager None self _artifact_path_builder None self _search_portal None self _search_parser None self _resource_identity None self _resource_identity_factory None self _metadata None self _schema_validator None self _path_converter None self _silent_logger None self _silent_cloud_factory None self _hook None self _hook_manager None self _list_shelves_manager None
"draw vectors , north , then horizon",def render self displayImage cv CloneImage self cImage for vector in self polarArray a m vector cv Line displayImage self center addVector self center a self cardinalOffset self north m 255 0 0 point self center offset self cardinalOffset cv Line displayImage point addVector point offset self radius 0 0 255 cv Line displayImage point addVector point offset 180 360 self radius 255 255 255 cv Circle displayImage self center self radius 255 255 255 return displayImage
"this will invoke fun(driver ) , chaining implicitly_wait for time of execution warning : this will change implicit_wait time on global selenium object ! returns the result of fun invocation",def change_implicit_wait driver fun wait_time try driver implicitly_wait wait_time result fun driver finally driver implicitly_wait SELENIUM_IMPLICIT_WAIT return result
api to update various interfaces ( only some pon interfaces as of now ) in the devices,def update_interface self device data self log debug update interface data data handler self devices_handlers get device id if handler is not None handler xpon_update data
installs acl check on application .,def install app conf app wsgi_app auth_token AuthProtocol app wsgi_app conf dict conf get OPT_GROUP_NAME app before_request check
convert plain lists to mutablelist .,classmethod def coerce cls key value if not isinstance value MutableList if isinstance value list return MutableList value return mutable Mutable coerce key value else return value
"returns a 503 response with "" disabled by file "" in the body .",def DISABLED self req return Response request req status 503 body DISABLED BY FILE content_type text plain
test the creation failure of a new agent heartbeat record,def test_create_invalid_model_error self instance Mock instance errors instance is_valid Mock return_value False with patch object AgentHeartBeat save return_value instance self assertRaises exception InvalidModelError AgentHeartBeat create
resize the filesystem on the specified device .,def resize_fs self mount_point self _check_device_exists if self _wait_for_mount mount_point timeout 2 LOG debug Unmounting s before resizing mount_point self unmount mount_point try utils execute e2fsck f p self device_path run_as_root True root_helper sudo utils execute resize2fs self device_path run_as_root True root_helper sudo except exception ProcessExecutionError log_fmt Error resizing the filesystem with device s exc_fmt _ Error resizing the filesystem with device s log_and_raise log_fmt exc_fmt self device_path
returns request body for message - posting tests .,def create_message_body_v1_1 messagecount kwargs return messages single_message_body kwargs for i in range messagecount
return the hessian of the objective at x in dense format .,def dense_hess self x z kwargs return adolc hessian self _obj_trace_id x
"int nfq_set_verdict ( struct nfq_q_handle * qh , u_int32_t i d , u_int32_t verdict , u_int32_t data_len , const unsigned char * buf )",classmethod def cb_set_verdict cls qh packet_id verdict LOG debug Calling nfq_set_verdict ret cls dll nfq_set_verdict qh packet_id verdict 0 0 LOG debug Called nfq_set_verdict return ret
ensure that a a given value is a unicode string .,def ensure_unicode val if isinstance val six binary_type return val decode utf 8 return val
get the next error message .,def get_error self block True timeout None return self _error_queue get block block timeout timeout
test case with no weights at all .,def test_weights_in_out_none self scope MyScope targets tf constant 0 1 2 0 9 23 dtype tf int32 predictions tf constant 0 1 2 0 9 23 dtype tf int32 values tf constant 5 6 7 dtype tf float32 func mock Mock func side_effect values None avg streaming StreamingAverage avg compute mock MagicMock metric metrics StreamingMetric func avg metric compute targets predictions scope scope func assert_called_once_with targets predictions None avg compute assert_called_once args kwargs avg compute call_args act_values act_weights_out args self assertEqual act_values values self assertEqual act_weights_out None self assertIn scope kwargs self assertEqual kwargs pop scope name scope
can i put a lambda at x ?,def can_abstract_at self x return len self insertable_rules x returntype 0
returns a function that the neighbors of a tip within d. exclusion_distance -- the units of branchlength from which neighbors should be excluded,def make_distance_based_exclusion_fn exclusion_distance def exclude_tip_neighbors tip tree verbose False max_dist tree maxTipTipDistance 0 tips_to_delete tip tipsWithinDistance exclusion_distance tips_to_delete t Name for t in tips_to_delete if verbose print Tips to delete len tips_to_delete tips_to_keep t Name for t in tree tips if t Name not in tips_to_delete if float exclusion_distance float max_dist or len tips_to_delete len tree tips raise ValueError specified tree would be entirely excluded because branch lengths are too short holdout_tip tip Name if holdout_tip in tips_to_keep tips_to_keep remove holdout_tip if verbose print Will remove our tip of interest from the tree 0 format holdout_tip if verbose print Tips to keep len tips_to_keep subtree get_sub_tree tree tips_to_keep del tree return subtree new_fn exclude_tip_neighbors new_fn_doc Exclude neighbors of tip within f branch length units exclusion_distance new_fn __doc__ new_fn_doc return new_fn
this is the generic method to initialize the dynamic dispatcher,v on node def visit self node
decorator that blocks the call until the service is ready,def require_ready func functools wraps func def wrapped self args kwargs try self state wait ready self ready_timeout except Exception as e pass if not self ready raise RuntimeWarning Service must be ready to call this method return func self args kwargs return wrapped
"draw index from an array of values , filtering out illegal moves .",def _legalizeIt self a if not min a 0 print a print min a print self module params print self module inputbuffer print self module outputbuffer raise Exception No positve value in array legals self game getLegals self color vals ones len a 100 1 self temperature for i in map self _convertPosToIndex legals vals i a i drawn self _convertIndexToPos drawGibbs vals self temperature assert drawn in legals return drawn
see simplegenomemanipulation._manipulatevalue ( ) for more information,def _manipulateValue self value return self _uniform_variate getSample
returns the gameno of the game in which user is currently playing this is only set when status = = status_playing,def getGameno self return self __gameno
trakt do n't support this method .,def notify_git_update self new_version u pass
return true if the source object has changes from an old to a new value on the given synchronize pairs,def source_modified uowcommit source source_mapper synchronize_pairs for l r in synchronize_pairs try prop source_mapper _columntoproperty l except exc UnmappedColumnError _raise_col_to_prop False source_mapper l None r history uowcommit get_attribute_history source prop key attributes PASSIVE_NO_INITIALIZE if bool history deleted return True else return False
remove and return an item from the queue .,def get self timeout None future Future try future set_result self get_nowait except QueueEmpty self _getters append future _set_timeout future timeout return future
test that a summary is stored under the correct key and most recent objects are included .,def test_stracker_store_summary self stracker tracker SummaryTracker key 1 stracker store_summary key s stracker summaries key self assert_ s None key 2 tmp self _get_indicator stracker store_summary key s stracker summaries key self assertEqual self _contains_indicator s 1
make the field ' project_id ' of the table tokens be nullable .,def upgrade op alter_column tokens project_id nullable True existing_nullable False
helper function for plotting the displacement,def plot_static_los_result result target 0 import matplotlib pyplot as plt N result request targets target coords5 2 E result request targets target coords5 3 synth_disp result results_list 0 target result components synth_disp keys fig _ plt subplots int len components 2 int len components 2 vranges synth_disp k max synth_disp k min for k in components for comp ax vrange in zip components fig axes vranges lmax num abs num min vrange num max vrange max cmap ax scatter E N c synth_disp comp s 10 0 marker s edgecolor face cmap seismic vmin 1 5 lmax vmax 1 5 lmax ax set_title comp m ax set_aspect equal ax set_xlim obs_size obs_size ax set_ylim obs_size obs_size n e rect_source outline cs xy T ax fill e n color 0 5 0 5 0 5 alpha 0 5 fig colorbar cmap ax ax aspect 5 plt show
tests that the splitting of the data by a cv splitter node is deterministic given the run_number,def test_cv_reproducibility self second_cv_splitter CrossValidationSplitterNode splits 3 second_cv_splitter register_input_node self source second_cv_splitter set_run_number 7 self cv_splitter set_run_number 7 train_data1 list self cv_splitter request_data_for_training False train_data2 list second_cv_splitter request_data_for_training False all_contained True for datapoint1 label1 in train_data1 this_contained False for datapoint2 label2 in train_data2 this_contained datapoint1 view numpy ndarray datapoint2 view numpy ndarray all and label1 label2 if this_contained break all_contained this_contained if not all_contained break self assert_ all_contained CV Splitter generated different splits for the same run numbers
read catchmod timeseries input / outputs,def read_results wb sh wb sheet_by_name Input Parameters assert sh cell 32 3 ctype xlrd XL_CELL_NUMBER num_areas int sh cell 32 3 value for area_id in range 0 num_areas rain_col sh cell 26 8 value pet_col sh cell 27 8 value if rain_col 1 raise ValueError Unable to read input rainfall as column is not 1 area format area_id if pet_col 1 raise ValueError Unable to read input PET as column is not 1 area format area_id sh wb sheet_by_name Catchment Timeseries assert sh cell 4 1 value Date assert sh cell 4 10 value strip AE row 6 datemode wb datemode while True try date_num sh cell row 1 value except IndexError break if not date_num break row 1 max_row row length max_row 6 dates np empty length dtype M8 D recharge np empty length dtype np float64 smd_upper np empty length dtype np float64 smd_lower np empty length dtype np float64 flow_sim np empty length dtype np float64 rain np empty length dtype np float64 pet np empty length dtype np float64 flow_obs np empty length dtype np float64 for n in range 0 length row n 6 date_num sh cell row 1 value year month day hour minute second xlrd xldate_as_tuple date_num datemode date np datetime64 04d 02d 02d format year month day dates n date recharge n sh cell row 2 value smd_upper n sh cell row 3 value smd_lower n sh cell row 4 value flow_sim n sh cell row 5 value rain n sh cell row 8 value if sh cell row 8 ctype xlrd XL_CELL_NUMBER warnings warn Invalid rainfall data rain n 0 pet n sh cell row 9 value if sh cell row 9 ctype xlrd XL_CELL_NUMBER warnings warn Invalid PET data pet n 0 if sh cell row 12 ctype xlrd XL_CELL_NUMBER flow_obs n np nan else flow_obs n sh cell row 12 value row 1 units sh cell 5 6 value strip if units Mld pass elif units cumecs print Converting from cumecs to Ml d flow_sim 86 4 flow_obs 86 4 return dates dates rainfall rain pet pet recharge recharge smd_upper smd_upper smd_lower smd_lower flow_sim flow_sim flow_obs flow_obs
add an addressassignment record for every primarynameassociation,def add_addresses session q session query PrimaryNameAssociation q q join System DnsDomain q q filter System ip None q q filter exists where AddressAssignment ip System ip q q options contains_eager dns_record q q options contains_eager dns_record dns_domain q q options subqueryload_all hardware_entity interfaces vlans assignments q q options subqueryload_all hardware_entity interfaces _vlan_ids count 0 pnas q all for pna in pnas hw pna hardware_entity if len hw interfaces 1 print 0 has an unexpected number of interfaces skipping 1 format hw len hw interfaces continue iface hw interfaces 0 if len iface vlans 0 addresses print 0 already has addresses skipping format iface continue iface vlans 0 addresses append pna dns_record ip count 1 session flush print Added d AddressAssignment records count
computes euclidean distance between atoms in self.df and a 3d point .,def distance self xyz 0 0 0 0 0 0 return np sqrt np sum self df x y z subtract xyz axis 1 2 axis 1
get variables inside a scope the scope can be specified as a string,def _scope_vars scope trainable_only False return tf get_collection tf GraphKeys TRAINABLE_VARIABLES if trainable_only else tf GraphKeys VARIABLES scope scope if isinstance scope str else scope name
parser : argparse . argumentparser return a parser added with args required by fit,def add_fit_args parser train parser add_argument_group Training model training train add_argument network type str help the neural network to use train add_argument num layers type int help number of layers in the neural network required by some networks such as resnet train add_argument gpus type str help list of gpus to run e g 0 or 0 2 5 empty means using cpu train add_argument kv store type str default device help key value store type train add_argument num epochs type int default 100 help max num of epochs train add_argument lr type float default 0 1 help initial learning rate train add_argument lr factor type float default 0 1 help the ratio to reduce lr on each step train add_argument lr step epochs type str help the epochs to reduce the lr e g 30 60 train add_argument initializer type str default default help the initializer type train add_argument optimizer type str default sgd help the optimizer type train add_argument mom type float default 0 9 help momentum for sgd train add_argument wd type float default 0 0001 help weight decay for sgd train add_argument batch size type int default 128 help the batch size train add_argument disp batches type int default 20 help show progress for every n batches train add_argument model prefix type str help model prefix train add_argument save period type int default 1 help params saving period parser add_argument monitor dest monitor type int default 0 help log network parameters every N iters if larger than 0 train add_argument load epoch type int help load the model on an epoch using the model load prefix train add_argument top k type int default 0 help report the top k accuracy 0 means no report train add_argument loss type str default help show the cross entropy or nll loss ce strands for cross entropy nll loss stands for likelihood loss train add_argument test io type int default 0 help 1 means test reading speed without training train add_argument dtype type str default float32 help precision float32 or float16 train add_argument gc type type str default none help type of gradient compression to use takes 2bit or none for now train add_argument gc threshold type float default 0 5 help threshold for 2bit gradient compression train add_argument macrobatch size type int default 0 help distributed effective batch size train add_argument warmup epochs type int default 5 help the epochs to ramp up lr to scaled large batch value train add_argument warmup strategy type str default linear help the ramping up strategy for large batch sgd return train
the : meth:`main ` method for worker processes .,def main settings identity worker s s socket gethostname os getpid ctx zmq Context io_loop IOLoop instance log_pub ctx socket zmq PUB log_pub connect settings ZEROMQ_LOGGING zmq_logging_handler PUBHandler log_pub zmq_logging_handler root_topic spyder worker logger logging getLogger logger addHandler zmq_logging_handler logger setLevel settings LOG_LEVEL_WORKER logger info process Starting up another worker mgmt create_worker_management settings ctx io_loop logger debug process Initializing fetcher extractor and scoper fetcher create_worker_fetcher settings mgmt ctx zmq_logging_handler io_loop fetcher start extractor create_worker_extractor settings mgmt ctx zmq_logging_handler io_loop extractor start def quit_worker raw_msg When the worker should quit stop the io_loop after 2 seconds msg MgmtMessage raw_msg if ZMQ_SPYDER_MGMT_WORKER_QUIT msg data logger info process We have been asked to shutdown do so DelayedCallback io_loop stop 2000 io_loop start ack MgmtMessage topic ZMQ_SPYDER_MGMT_WORKER identity identity data ZMQ_SPYDER_MGMT_WORKER_QUIT_ACK mgmt _out_stream send_multipart ack serialize mgmt add_callback ZMQ_SPYDER_MGMT_WORKER quit_worker mgmt start msg MgmtMessage topic ZMQ_SPYDER_MGMT_WORKER identity identity data ZMQ_SPYDER_MGMT_WORKER_AVAIL mgmt _out_stream send_multipart msg serialize def handle_shutdown_signal _sig _frame Called from the os when a shutdown signal is fired msg MgmtMessage data ZMQ_SPYDER_MGMT_WORKER_QUIT quit_worker msg serialize io_loop start signal signal signal SIGINT handle_shutdown_signal signal signal signal SIGTERM handle_shutdown_signal logger info process waiting for action try io_loop start except ZMQError logger debug Caught a ZMQError Hopefully during shutdown logger debug traceback format_exc for mod in fetcher extractor mgmt mod close logger info process Houston Worker down ctx term
called when the process 's standard input is ready for writing .,def handle_stdin self fd iomap try start self byteswritten if start len self inputbuffer chunk self inputbuffer start start BUFFER_SIZE self byteswritten start os write fd chunk else self close_stdin iomap except OSError IOError _ e _ sys exc_info if e errno EINTR self close_stdin iomap self log_exception e
we implement a function which only raises methodnotallowed in order to return the correct response for methods not defined for a given flump_view .,def _meth_not_allowed args kwargs raise MethodNotAllowed
explicity flip operator for readability returns self for convenience,def F self self V self active_idx self V self active_idx return self
compute matches when text is a simple name .,def global_matches self text def get_item obj attr return obj attr a for dict_with_comps in __builtin__ __dict__ self namespace self global_namespace a update dict_with_comps filter _StartsWithFilter text return dir2 a a keys get_item filter
"get the app 's parser , have it inherit from this parser ( which may inherit from other parsers ) return the a new parser that inherits from app 's parser , from this parser , and implicitly from this parser 's parents ( if it has any )",def build_arg_parser parents _build_arg_parser _ns _ parents 0 parse_known_args _app get_pymodule _ns app_name if hasattr _app build_arg_parser parents append _app build_arg_parser return at build_arg_parser parents parents
verify that if a guard is not satisfied the call is rejected .,def test_guard_block scenarios service router router guards variable_sofia_profile_name doggy service apps load_app router app_id default service run block False assert service is_alive with dial_all scenarios doggy router pool evals client host expect False pass
journals - param : kwargs - field queries work as expected,vcr use_cassette test vcr_cassettes journals_field_queries yaml def test_journals_field_queries res cr journals ids 2167 8359 works True query_title fish filter type journal article titles x get title 0 for x in res message items assert dict res __class__ assert 5 len res message assert list titles __class__ assert str str titles 0 __class__
only has the ' all ' attribute,def test_attribute_error self self assertRaises AttributeError lambda self client config foo
should convert to iso strings where numpy or pandas datetimes are found .,def test_odd_dates self dt64 np datetime64 2002 06 28T01 00 00 source dict datetime64 dt64 timestamp pd Timestamp dt64 output json dumps source cls ComplexJsonEncoder self assertIsInstance output str self assertEqual 2 output count 2002 06 28T01 00 00
"given an object of unknown type , return a string that can be used in the database .",staticmethod def clean_input argument if type argument is str return DB2_Query clean_string argument if type argument is str return DB2_Query clean_unicode argument if type argument is Unescaped return argument if type argument is int return DB2_Query clean_int argument if type argument is datetime datetime return DB2_Query clean_datetime argument if type argument is semester Semester return DB2_Query clean_int argument if type argument is list return DB2_Query clean_list argument else raise UnknownArgumentType str argument is of type str type argument
join two or more pathname components for the filesystem,def join self basepath paths if not basepath startswith GCSFileSystem GCS_PREFIX raise ValueError Basepath r must be GCS path basepath path basepath for p in paths path path rstrip p lstrip return path
returns the element type of a composite type .,def element_type hint hint Const unwrap hint if isinstance hint typehints SequenceTypeConstraint return hint inner_type elif isinstance hint typehints TupleHint TupleConstraint return typehints Union hint tuple_types return Any
this function mark duplicates of the sorted bam file,def markduplicates picard sortBams if not os path exists tmp os makedirs tmp dedup_files cmd for bam in sortBams dedup bam 8 dedup bam dedup_files append dedup cmd cmd java Djava io tmpdir tmp jar picard MarkDuplicates I input O output CREATE_INDEX true METRICS_FILE metrics txt MAX_RECORDS_IN_RAM 8000000 MAX_FILE_HANDLES_FOR_READ_ENDS_MAP 1000 VALIDATION_STRINGENCY LENIENT format picard picard input bam output dedup subprocess check_call cmd 3 shell True return dedup_files
thermal state for this dynamical model,abstractmethod def thermal_state self liouville_subspace
implementation of the regularized least squares solver .,def ridge_regression data labels mu 0 0 n p data shape if n p tmp np dot data data T if mu tmp mu n np eye n tmp la pinv tmp return np dot np dot data T tmp labels reshape 1 1 else tmp np dot data T data if mu tmp mu n np eye p tmp la pinv tmp return np dot tmp np dot data T labels reshape 1 1
compare analytic steady state with numerical steady state .,def test_steady_state eps 0 1 for g in np linspace eps 0 05 4 for n in np linspace eps 0 05 4 for s in np linspace eps 1 eps 4 for alpha in np linspace eps 1 eps 4 for delta in np linspace eps 1 eps 4 tmp_params A0 1 0 g g L0 1 0 n n s s alpha alpha delta delta model params tmp_params actual_ss model steady_state expected_ss model find_steady_state 1e 12 1000000000000 0 nose tools assert_almost_equals actual_ss expected_ss
gets the cloudwatch log associated with the given job .,def get_job_log job_info log_group_name aws batch job write_file True verbose False job_name job_info jobName job_id job_info jobId logs boto3 client logs batch boto3 client batch job_description batch describe_jobs jobs job_id log_stream_name job_description jobs 0 container logStreamName stream_resp logs describe_log_streams logGroupName log_group_name logStreamNamePrefix log_stream_name streams stream_resp get logStreams if not streams logger warning No streams for job return None elif len streams 1 logger warning More than 1 stream for job returning first log_stream_name streams 0 logStreamName if verbose logger info Getting log for s s job_name job_id out_file s_ s log job_name job_id if write_file else None lines get_log_by_name log_group_name log_stream_name out_file verbose return lines
test of hashandlers ( ) functionality .,def test_hashandlers self self assertTrue self adapter hasHandlers self logger removeHandler self handler self assertFalse self adapter hasHandlers self logger addHandler self handler self assertTrue self adapter hasHandlers
transforms a tool name like copy - info - plist to copyinfoplist,def _CommandifyName self name_string return name_string title replace
: param subparsers : : return :,def create_parser subparsers return cli_helper create_parser subparsers kill Kill a topology
possibly cache out the internal cache .,classmethod def load_internal_cache cls pex pex_info internal_cache os path join pex pex_info internal_cache with TRACER timed Searching dependency cache s internal_cache V 2 if os path isdir pex for dist in find_distributions internal_cache yield dist else for dist in itertools chain cls write_zipped_internal_cache pex pex_info yield dist
print updates to the user . everybody is happy .,def __status_check self k energy temps None start_time None if start_time elapsed time time start_time print Step 6d Energy 4f Elapsed time 2f secs format k energy elapsed else print Step 6d Energy 4f format k energy if temps print Updated acceptance temp 6f format temps 0 print Updated generation temp 6f format temps 1 print
check if ` event_assign ` correctly assigns selected user to the event .,def test_assign_user_to_event self event Event objects first user Person objects first assert event assigned_to is None self client get reverse event_assign args event slug user pk event refresh_from_db assert event assigned_to user
each sweep is a ramp ( of set size ) which builds on the last sweep . used for detection of ap properties from first few aps .,def proto_01_11_rampStep abf exampleABF standard_inspect abf swhlab ap detect abf swhlab ap check_sweep abf swhlab plot save abf tag check swhlab ap check_AP_raw abf swhlab plot save abf tag raw resize False swhlab ap check_AP_deriv abf swhlab plot save abf tag deriv swhlab ap check_AP_phase abf swhlab plot save abf tag phase for feature in downslope freq swhlab ap plot_values abf feature continuous True swhlab plot save abf tag feature
"create a new , empty counter object . and if given , count elements from an input iterable . or , initialize the count from another mapping of elements to their counts .",def __init__ self iterable None kwds self update iterable kwds
updates the available command list .,def update self pass
pattern constructor for matching tf.nn.batch_normalization subgraphs .,def BatchNorm in_pattern Tensor in scale_name scale offset_name offset output_name out inv_pat Tensor inv In choice Rsqrt Mul In Tensor In Rsqrt Tensor scale_name without_offset_pat Mul In Tensor Tensor inv with_offset_pat Sub In Tensor offset_name Tensor In Mul In Tensor Tensor inv return Tensor output_name In Add In Tensor In Mul In in_pattern inv_pat Tensor In choice with_offset_pat without_offset_pat
"looks at all tags covering the position of iter in the text view , and if one of them is a link , follow it by showing the page identified by the data attached to it .",def follow_if_link self text_view iter tags iter get_tags for tag in tags href tag get_data href if href self emit link activated href return True
tries to resolve the widget from tk and create it .,def _create_widget self name parent desc position weight padding opt self _get_options desc try widget_factory getattr tkinter name if self preferTk else getattr ttk name except AttributeError try widget_factory getattr ttk name if self preferTk else getattr tkinter name except AttributeError traceback print_exc raise AttributeError Neither Tkinter nor ttk have a widget named name while True try widget widget_factory parent opt break except Exception as e if len opt 0 break del opt str e split 2 2 1 widget grid row position 0 column position 1 columnspan weight 0 rowspan weight 1 sticky padding 2 padx padding 0 pady padding 1 if width in opt or height in opt widget grid_propagate 0 if weight 2 0 parent rowconfigure position 0 weight weight 2 if weight 3 0 parent columnconfigure position 1 weight weight 3 self widgets widget _name widget return widget
generates and returns compound regular expression,def get_regex self regex for flag in self compound if flag or flag regex flag else regex join self flags flag return regex
makes the decorated function terminate silently on ctrl+c.,def graceful_ctrlc func def wrapper args kwargs try func args kwargs except KeyboardInterrupt pass return wrapper
runs device validations on each router object that is returned by getrouterdetails,def validateRouterDetails result for device results in result items routers device results results routers device validate return None
"given a format string , construct a parser .",def __init__ self format_string if not isinstance format_string Compatibility string raise TypeError format_string should be a string instead got s type format_string self _re_pattern self _applicators self _preprocess_format_string format_string self _re re compile self _re_pattern
make sure feature function gets 1d and 2d io correct .,pytest mark parametrize func features mean_absolute_value features waveform_length features zero_crossings features slope_sign_changes features root_mean_square features integrated_emg features logvar def test_feature_io func n 10 c 3 x_n np random randn n x_cn np random randn c n x_nc np random randn n c assert not isinstance func x_n np ndarray assert func x_n keepdims True shape 1 assert func x_cn shape c assert func x_cn keepdims True shape c 1 assert func x_nc axis 0 shape c assert func x_nc axis 0 keepdims True shape 1 c
check that tables are at least version 3.0,def _check_versions import tables if tables __version__ 3 0 sys exit FATAL PyTables version 3 0 or above is required installed version is format tables __version__
< website > -- checks the website against google 's safe browsing list .,hook command def issafe text if urlparse text scheme not in https http return Check your URL it should be a complete URI parsed requests get API_SB params url text client cloudbot key dev_key pver 3 1 appver str cloudbot __version__ parsed raise_for_status if parsed status_code 204 condition x02 x02 is safe format text else condition x02 x02 is known to contain format text parsed text return condition
compute the cyclotomic cosets of the galois field .,def cosets self coset_list x self tuple_to_power elements mark_list zeros len x coset_count 1 for idx in range len x if mark_list idx 0 a x idx mark_list idx coset_count i 1 while a 2 i 2 self m 1 a for idx2 in range len x if mark_list idx2 0 and x idx2 a 2 i 2 self m 1 mark_list idx2 coset_count i 1 coset_count 1 for counts in range 1 coset_count coset_list append GF self elements mark_list counts self m return coset_list
prepares the `` form_class `` form for writing a reply to a given message ( specified via `` message_id `` ) . uses the `` format_quote `` helper from `` messages.utils `` to pre - format the quote .,login_required def GET self message_id form_class ComposeForm template_name messages compose html success_url None recipient_filter None parent get_object_or_404 Message id message_id if parent sender username self request user username and parent recipient username self request user username raise Http404 form form_class body _ u sender s wrote n body s sender parent sender body format_quote parent body subject _ u Re subject s subject parent subject recipient parent sender return self context_response template_name form form current_tab messages subtab new
this function solves the complex - valued time - dependent gross - pitaevskii equation :,def GPE time phi This function solves the complex valued time dependent Gross Pitaevskii equation i dot phi t H t phi t U phi t 2 phi t phi_dot 1j H static dot phi U np abs phi 2 phi for Hd f f_args in H dynamic phi_dot 1j f time f_args Hd dot phi return phi_dot
reads netcdf files and returns a dictionary with corresponding structure .,def read_generic_netcdf fname ncid nc Dataset fname r out read_netcdf_group ncid ncid close return out
inputs to be fed to the graph .,def _add_placeholders self hps self _hps self _articles tf placeholder tf int32 hps batch_size hps enc_timesteps name articles self _abstracts tf placeholder tf int32 hps batch_size hps dec_timesteps name abstracts self _targets tf placeholder tf int32 hps batch_size hps dec_timesteps name targets self _article_lens tf placeholder tf int32 hps batch_size name article_lens self _abstract_lens tf placeholder tf int32 hps batch_size name abstract_lens self _loss_weights tf placeholder tf float32 hps batch_size hps dec_timesteps name loss_weights
creates option string based on parameters provided,def getMountOptions self options sec ntlm cache loose vers 3 0 actimeo 0 if self dconf has_key username and self dconf has_key password or self dconf has_key password_secret dom_username self dconf username split if len dom_username 1 domain None username dom_username 0 elif len dom_username 2 domain dom_username 0 username dom_username 1 else raise SMBException A maximum of 2 tokens are expected domain username were given format len dom_username domain util to_plain_string domain username util to_plain_string username if self dconf has_key password_secret password util get_secret self session self dconf password_secret else password self dconf password password util to_plain_string password cred_str username npassword n format username password if domain cred_str domain n format domain try with open self credentials w as f f write cred_str except IOError as e raise SMBException Failed to create credentials file options append credentials s self credentials else options append guest return options
"parse the given xml input and convert it into a dictionary . ` xml_input ` can either be a ` string ` or a file - like object . if ` xml_attribs ` is ` true ` , element attributes are put in the dictionary among regular child elements , using ` @ ` as a prefix to avoid collisions . if set to ` false ` , they are just ignored . simple example : : > > > import xmltodict > > > doc = xmltodict.parse ( "" "" "" ... < a prop=""x "" > ... < b>1</b > ... < b>2</b > ... < /a > ... "" "" "" ) > > > doc['a']['@prop ' ] u'x ' > > > doc['a']['b ' ] [ u'1 ' , u'2 ' ] if ` item_depth ` is ` 0 ` , the function returns a dictionary for the root element ( default behavior ) . otherwise , it calls ` item_callback ` every time an item at the specified depth is found and returns ` none ` in the end ( streaming mode ) . the callback function receives two parameters : the ` path ` from the document root to the item ( name - attribs pairs ) , and the ` item ` ( dict ) . if the callback 's return value is false - ish , parsing will be stopped with the : class:`parsinginterrupted ` exception . streaming example : : > > > def handle(path , item ) : ... print ' path:%s item:%s ' % ( path , item ) ... return true ... > > > xmltodict.parse ( "" "" "" ... < a prop=""x "" > ... < b>1</b > ... < b>2</b > ... < /a > "" "" "" , item_depth=2 , item_callback = handle ) path:[(u'a ' , { u'prop ' : u'x ' } ) , ( u'b ' , none ) ] item:1 path:[(u'a ' , { u'prop ' : u'x ' } ) , ( u'b ' , none ) ] item:2 the optional argument ` postprocessor ` is a function that takes ` path ` , ` key ` and ` value ` as positional arguments and returns a new ` ( key , value ) ` pair where both ` key ` and ` value ` may have changed . usage example : : > > > def postprocessor(path , key , value ) : ... try : ... return key + ' : int ' , int(value ) ... except ( valueerror , typeerror ) : ... return key , value > > > xmltodict.parse('<a><b>1</b><b>2</b><b>x</b></a > ' , ... postprocessor = postprocessor ) ordereddict([(u'a ' , ordereddict([(u'b : int ' , [ 1 , 2 ] ) , ( u'b ' , u'x ' ) ] ) ) ] ) you can pass an alternate version of ` expat ` ( such as ` defusedexpat ` ) by using the ` expat ` parameter . e.g : > > > import defusedexpat > > > xmltodict.parse('<a>hello</a > ' , expat = defusedexpat.pyexpat ) ordereddict([(u'a ' , u'hello ' ) ] )",def parse xml_input encoding None expat expat process_namespaces False namespace_separator kwargs Parse the given XML input and convert it into a dictionary xml_input can either be a string or a file like object If xml_attribs is True element attributes are put in the dictionary among regular child elements using as a prefix to avoid collisions If set to False they are just ignored Simple example import xmltodict doc xmltodict parse a prop x b 1 b b 2 b a doc a prop u x doc a b u 1 u 2 If item_depth is 0 the function returns a dictionary for the root element default behavior Otherwise it calls item_callback every time an item at the specified depth is found and returns None in the end streaming mode The callback function receives two parameters the path from the document root to the item name attribs pairs and the item dict If the callback s return value is false ish parsing will be stopped with the class ParsingInterrupted exception Streaming example def handle path item print path s item s path item return True xmltodict parse a prop x b 1 b b 2 b a item_depth 2 item_callback handle path u a u prop u x u b None item 1 path u a u prop u x u b None item 2 The optional argument postprocessor is a function that takes path key and value as positional arguments and returns a new key value pair where both key and value may have changed Usage example def postprocessor path key value try return key int int value except ValueError TypeError return key value xmltodict parse a b 1 b b 2 b b x b a postprocessor postprocessor OrderedDict u a OrderedDict u b int 1 2 u b u x You can pass an alternate version of expat such as defusedexpat by using the expat parameter E g import defusedexpat xmltodict parse a hello a expat defusedexpat pyexpat OrderedDict u a u hello handler _DictSAXHandler namespace_separator namespace_separator kwargs if isinstance xml_input _unicode if not encoding encoding utf 8 xml_input xml_input encode encoding if not process_namespaces namespace_separator None parser expat ParserCreate encoding namespace_separator try parser ordered_attributes True except AttributeError pass parser StartElementHandler handler startElement parser EndElementHandler handler endElement parser CharacterDataHandler handler characters parser buffer_text True try parser ParseFile xml_input except TypeError AttributeError parser Parse xml_input True return handler item
this method does almost nothing .,def method self return 1
os - specific conversion from a file system path to a relative url of the ' file ' scheme ; not recommended for general use .,def pathname2url pathname return urllib quote pathname translate __slash_dot
method defined in a and b.,def AB_method self
does the node represent a tuple literal ?,def is_tuple node if isinstance node Node and node children LParen RParen return True return isinstance node Node and len node children 3 and isinstance node children 0 Leaf and isinstance node children 1 Node and isinstance node children 2 Leaf and node children 0 value and node children 2 value
field : : = i d ? i d,def p_field_3 self type _ name return Field type name opt 1
return consistent ' i d 's ' given a name . subclasses will typically trim and prefix this to get something like i - abcd1234 .,def make_id self name return sha1 force_bytes name hexdigest
parse my config files and returns a config dictionary args : cfg_file : configuration filename,def parseConfig cfg_file assert exists cfg_file Cannot read s No such file cfg_file config try config_lines open cfg_file r readlines for line in config_lines if line find 0 continue if line rstrip key value line strip split key key strip value value strip if key in config config key append value else config key value except raise parseConfigError Incorrect format in s n cfg_file return config
transform a category name to an i d number alphabetically .,def cat_name_to_cat_id cat_name cat_list list_image_sets cat_id_dict dict zip cat_list range len cat_list return cat_id_dict cat_name
tests whether the converted coreml model 's preds are equal to mxnet preds for a given model or not .,def _test_model self model_name epoch_num input_shape 1 3 224 224 files None if files is not None print Downloading files from urls s files for url in files mx test_utils download url print Downloaded s url module self _load_model model_name model_name epoch_num epoch_num input_shape input_shape coreml_model mxnet_converter convert module input_shape data input_shape div for _ in xrange 1 np random seed 1993 input_data data np random uniform 0 1 input_shape astype np float32 Batch namedtuple Batch data module forward Batch mx nd array input_data data is_train False mxnet_pred module get_outputs 0 asnumpy flatten coreml_pred coreml_model predict _mxnet_remove_batch input_data values 0 flatten self assertEqual len mxnet_pred len coreml_pred div append _kl_divergence mxnet_pred coreml_pred print Average KL divergence is s np mean div self assertTrue np mean div 0 0001
sets the current read pointer position .,def seek self idx assert not self writable pos ctypes c_size_t self idx idx check_call _LIB MXRecordIOReaderSeek self handle pos
make sure we have the directory where we want to log,def create_log_directory self logdir try os makedirs logdir except OSError as detail if detail errno 17 pass else self logger error error creating log directory exc_info True except self logger error error creating log directory exc_info True
an exception handling idiom using decorators,def ExpHandler pargs def wrapper f if pargs handler li pargs t ex handler for ex in li t reverse else t Exception None def newfunc t args kwargs ex handler t 0 try if len t 1 f args kwargs else newfunc t 1 args kwargs except ex as e if handler handler e else print e __class__ __name__ e return functools partial newfunc t return wrapper
yields the sequence of prime numbers via the sieve of eratosthenes,def eratosthenes yield 2 D for q in count start 3 step 2 if q not in D yield q D q q q else for p in D q D setdefault 2 p q append p del D q
converts the given class into a c struct .,def __call__ self cls fields for k v in vars cls items if not k startswith _ if v startswith field_type ctypes POINTER self types v 1 else field_type self types v new_field k field_type fields append new_field bases ctypes Structure tuple base for base in cls __bases__ class_attrs _fields_ fields __doc__ cls __doc__ return type cls __name__ bases class_attrs
get the length of a lazylist 's computed data .,def __len__ self return len self _data
yield each message found in a `` input `` in `` mboxcl `` / `` mboxcl2 `` format,def mboxcl_generator input parser email parser Parser assert type input is file content_length None length 0 in_header None data for line in input if in_header is None if line n continue in_header True data append line if in_header if line n assert content_length is not None header Content Lenght not found not an mboxcl file in_header False elif line 16 Content Length content_length int line 16 rstrip else length len line assert not length content_length if length content_length yield parser parsestr join data data in_header None content_length None length 0 assert not length
this returns all currently processed data and empties the output buffer .,def push self data self outfile self outfile return data
using the permutation of all functions to generate sequences @param fromposition start position / index / value @param toposition end position / index / value,def createSequences self fromPosition toPosition self sequences set for r in range 1 len self registeredFunctions for functions in itertools permutations self registeredFunctions r position fromPosition sequence while position toPosition value position for function in functions value function value sequence append value position 1 self sequences add Sequence sequence 0 self combineFunctions functions
pickle and encrypt a python object,def dumps self obj pickler pickle return self encrypt self PICKLE_PAD pickler dumps obj
check every 100 ms if there is something new in the queue .,def periodicCall self self gui processIncoming if not self running import sys sys exit 1 self master after 100 self periodicCall
"send a token to the app engine login , again stating the name of the application to gain authentication for . returned is a cookie that may be used to authenticate http traffic to the application at app engine .",def get_gae_cookie appname auth_token continue_location http localhost args continue continue_location auth auth_token host s appspot com appname url https s _ah login s host urllib urlencode args opener get_opener req urllib2 Request url try response opener open req except urllib2 HTTPError as e response e if response code 302 or response info location continue_location raise urllib2 HTTPError req get_full_url response code response msg response headers response fp cookie response headers get set cookie assert cookie and cookie startswith ACSID return cookie replace HttpOnly
normalize the values of d to sumto . the returned dict will have value sum = sumto,def normDictSumTo d sumTo 1 ks d keys vs d values sum reduce lambda x y x y vs vs x sum 1 0 sumTo for x in vs return dict zip ks vs
construct a verse reference from the final three parameters .,def __addr self book chap vers return format self BOOKS book 1 chap vers
serialize xml data to a string,def dumps stream xmlfile try p make_parser p setContentHandler h XMLDictionaryHandler p parse open xmlfile return marshal dumps h d stream except Exception as e sys exit e return None
"popn(n ) : pops and return the n smallest items from the heap , maintaining the heap invariant . if the heap becomes empty , indexerror is raised .",def __popn_normal self n self__heap self _heap return heappop self__heap for _ in xrange n
returns total number of items in bag .,def _size self return sum self values
tests retrieving file from localfile storage .,def test_get_file setup with file examples telco resources cave png rb as infile stored_filename media set_file infile assert stored_filename cave png retrieved_file media get_file cave png assert filecmp cmp retrieved_file name examples telco resources cave png
calculate the parameters of a fit of a distribution to a data set,def fit data distribution norm params getattr _st distribution fit data return FitResults params _st kstest data distribution params distribution
execute a fabric task against the provisioned vagrant box .,def run_fabric_task self fabric_task env hosts self vagrant user_hostname_port env key_filename self vagrant keyfile env disable_known_hosts execute fabric_task
nearest neighbour imputations which weights samples using the mean squared difference on features for which two rows both have observed data .,staticmethod def impute_knn df k 3 imputed_matrix KNN k k complete df values imputed_df pd DataFrame imputed_matrix df index df columns return imputed_df
creates a docker container for this component and returns it .,def createContainer self client command self getCommand if not command fail No command defined in either gantry config or docker image for component self getName component self self logger debug Starting container for component s with command s self getName command container client create_container self config getFullImage command user self config getUser volumes self config getVolumes ports str p for p in self config getContainerPorts environment self calculateEnvForComponent return container
"join([],global_join , option(none,[abstract ] ) )",def iverb2_49_join self interp subject name ctx self get_context interp if name is None name default else name action abstract_string name if name empty or name all ctx name name ctx setup_empty print joining all return t self __find_value name if not t return async failure no such conversation auto li lu logic parse_clause t ctx name name ctx setup auto set li set lu
compute conjugate transpose multiplication : math:`a^*(z1 ) `,def dotH self z1 raise NotImplementedError
"analyzes all data evaluated during the optimization , and return an optimizeresult . outputs of constraints are used to remove all infeasible points .",def _create_bo_result self success message X Y self acquisition data valid self acquisition feasible_data_index if not np any valid return OptimizeResult success False message No evaluations satisfied the constraints valid_X X valid valid_Y Y valid valid_Yo valid_Y self acquisition objective_indices if valid_Y shape 1 1 _ dom non_dominated_sort valid_Yo idx dom 0 else idx np argmin valid_Yo return OptimizeResult x valid_X idx success success fun valid_Yo idx message message
"makes sure that value is within a specific range . if not , then the lower or upper bounds is returned",def clipValue self value minValue maxValue return min max value minValue maxValue
reads in raw data directly from color_sensor .,def read_data self bias_color bias_constant 0 if not self testing valid self registers STATUS read AVALID c self registers CDATA read r self registers RDATA read g self registers GDATA read b self registers BDATA read if bias_color green g 1 bias_constant 100 elif bias_color red r 1 bias_constant 100 elif bias_color blue b 1 bias_constant 100 self c c self r r self g g self b b return valid c r g b else return 1 1 1 1 1
delete metadata associated with the given i d return : none,app route ThreatKB metadata int id methods DELETE auto doc login_required admin_only def delete_metadata id entity metadata Metadata query get id if not entity abort 404 entity active False db session add entity db session commit return jsonify 204
"iterate over the edges in the graph and yield ( edge , insuffix ) .",def edges_in_suffix builder suffix predicate seqan traverse suffixpredicate suffix for edge in builder graph edges index_it builder index_iterators edge target yield edge predicate index_it
run eslint on javascript content inside html files .,def lint_javascript_in_html files_to_lint files lintutil filter files_to_lint prefix templates suffix html lint_inputs for f in files contents_of_f lintutil file_contents f js_contents_iter js_in_html extract_js_from_html contents_of_f jinja2 file_name f try for js_contents in js_contents_iter lint_inputs append f js_contents except Exception as why yield f 1 HTML parse error s why continue errors run_eslint lint_inputs errors sorted set errors key lambda l l 0 int l 1 l 2 for fname bad_linenum msg in errors yield fname int bad_linenum msg
create a ' forwarding ' script .,def create_forwarding_script filepath module func_name nargs kwargs doc dict module module func_name func_name if nargs doc nargs nargs if kwargs doc kwargs kwargs body dump_yaml doc create_executable_script filepath body _rez_fwd
path to test transposon features .,pytest fixture def features_path data_path return pytest helpers data_path features txt relative_to data_path
notifier : notifier - liked instance,def detach_notifier self notifier notifier detach_observer self _notifiers notifier del self _notifiers notifier
"converts an x , y value in original resolution to current frame size",def convert self xy return tuple int xy i float self _size i self _resolution i for i in range 2
"arguments ---------- 0 : int resolution of input coordinates 1 : list input x0,x1 coordinates 2 : list input y0,y1 coordinates 3 : list input z0,z1 coordinates",def neuron_ids self args return self request neuron_ids args
"extracts user aggregate information from the given collection of tweets , prints basic data and outputs a csv . fields : screenname , name , userid , lang , friendscount , followerscount , location , numtweets . takes optional date ranges to constrain query ( gte start , lte end . ie , inclusive ) . if only one term specified , take everything before end or after start .",def extract_user_data collection outfile start_date None end_date None update 10000 csv_header ScreenName Name UserId Lang FriendsCount FollowersCount Location NumTweets if start_date and not end_date tweets collection find timestamp gte start_date elif not start_date and end_date tweets collection find timestamp lte end_date elif start_date and end_date tweets collection find timestamp gte start_date lte end_date else tweets collection find user_tweet_count defaultdict int user_data counter 1 num_tweets tweets count print Total collection tweets 0 format collection count print Total tweets considered 0 format num_tweets print Compiling user data for tweet in tweets if counter update print Progress 0 2 r format float counter num_tweets counter 1 if user not in tweet or id_str not in tweet user continue uid tweet user id_str user_tweet_count uid 1 user_data uid tweet user screen_name encode utf8 tweet user name replace replace n encode utf8 tweet user id_str tweet user lang tweet user friends_count tweet user followers_count tweet user location replace replace n encode utf8 user_tweet_count uid print Writing aggregate data to file 0 format outfile with open outfile wb as out_handle csv_handle csv writer out_handle csv_handle writerow csv_header for uid udata in user_data items csv_handle writerow udata print Complete
refresh the localestore with locales for the given language .,def _refresh_locale_store self lang self _localeStore clear locales localization get_language_locales lang for locale in locales self _add_locale self _localeStore localization get_native_name locale locale set_treeview_selection self _localeView locales 0 col 1
move chuck relative to actual position in um,def move_position self dx dy speed None if speed self _intf write MoveChuckPosition 1 1f 1 1f R Y d dx dy speed else self _intf write MoveChuckPosition 1 1f 1 1f R Y dx dy
"specifies that targets with suffix from ' suffixes ' have the type ' type ' . if a different type is already specified for any of syffixes , issues an error .",def register_suffixes suffixes type for s in suffixes if __suffixes_to_types has_key s old_type __suffixes_to_types s if old_type type raise BaseException Attempting to specify type for suffix s Old type s New type s s old_type type else __suffixes_to_types s type
converts a list of dictionaries into a csv - formatted flat table ( including a header row ) .,def formatCsv dicts dicts basic align dicts output Str writer csv DictWriter output dicts 0 keys writer writeheader for d in dicts writer writerow d return output getvalue
return eldoc format documentation string or '' .,script_method def eldoc script u signatures script call_signatures if len signatures 1 signature signatures 0 return u name signature name u index signature index u params param description for param in signature params
returns 1 if sequence has more items than number and 0 if not .,def more_than sequence number i 0 for item in sequence i 1 if i number return 1 return 0
builds an array of experiments to run in parallel ( the array can contain more than one experiment ),staticmethod def get_experiments return ExperimentSetup boston_data __name__
test that singleton arguments to neuron getters work as either scalar or singleton list .,def test_get_neuron_scalar self def check x x get_neuron_state 0 0 x get_neuron_state 0 0 x get_neuron_parameter 0 0 x get_neuron_parameter 0 0 net sim self simple_network check net check sim
"merge files from different pt - hard bins , weighted by the cross section , into one file",def MergePtHardBins outputfile basedir firstbin lastbin merger MonteCarloFileMerger for pthardbin in range firstbin lastbin 1 merger AddFile s 02d AnalysisResults root basedir pthardbin pthardbin merger MergeAndWrite outputfile
read the environment from buffer .,def read_env src expr contents if expr name in SKIP_ENVS contents src forward_until lambda s s end while src hasNext and not src startswith end s expr name contents append read_tex src if not src startswith end s expr name end src peek 0 5 explanation Instead got s end if end else Reached end of file raise EOFError Expecting end s s expr name explanation else src forward 4 expr add_contents contents return expr
for old - style classes !,def save_inst self obj cls obj __class__ memo self memo write self write save self save if hasattr obj __getinitargs__ args obj __getinitargs__ len args _keep_alive args memo else args write MARK if self bin save cls for arg in args save arg write OBJ else for arg in args save arg write INST cls __module__ n cls __name__ n self memoize obj try getstate obj __getstate__ except AttributeError stuff obj __dict__ else stuff getstate _keep_alive stuff memo if self delay obj self save_later obj stuff else save stuff write BUILD
script entry point for the command line tool,def cassback_main args arg_parser parse_args init_logging args log logging getLogger __name__ log info Got command args args s vars cassandra set_version args cassandra_version try sub_command args func args endpoints validate_args args if callable sub_command rv out sub_command else rv 0 out sub_command sys stdout write str out n except Exception as exc print Error traceback print_exc sys exit 1 sys exit rv
"returns a socket where the addresses are converted by inet_ntoa into human - friendly strings . sock is in tuple format , like ( ( sip , sport),(dip , sport ) )",def friendly_socket sock return s d s d inet_ntoa sock 0 0 sock 0 1 inet_ntoa sock 1 0 sock 1 1
add a new tracking target .,def add_target self image rect data None x0 y0 x1 y1 rect raw_points raw_descrs self detect_features image points descs for kp desc in zip raw_points raw_descrs x y kp pt if x0 x x1 and y0 y y1 points append kp descs append desc descs np uint8 descs self matcher add descs target PlanarTarget image image rect rect keypoints points descrs descs data data self targets append target
returns a tuple containing the result code and a pre - formatted result label,def execute configurations parameters host_name None if configurations is None return RESULT_CODE_UNKNOWN There were no configurations supplied to the script flume_conf_directory None if FLUME_CONF_DIR_KEY in configurations flume_conf_directory configurations FLUME_CONF_DIR_KEY if flume_conf_directory is None return RESULT_CODE_UNKNOWN The Flume configuration directory is a required parameter if host_name is None host_name socket getfqdn flume_run_directory FLUME_RUN_DIR_DEFAULT if FLUME_RUN_DIR_KEY in parameters flume_run_directory parameters FLUME_RUN_DIR_KEY processes get_flume_status flume_conf_directory flume_run_directory expected_agents find_expected_agent_names flume_conf_directory alert_label alert_state RESULT_CODE_OK if len processes 0 and len expected_agents 0 alert_label No agents defined on 0 format host_name else ok critical text_arr for process in processes if not process has_key status or process status NOT_RUNNING critical append process name else ok append process name if len critical 0 text_arr append 0 1 NOT running format join critical is if len critical 1 else are if len ok 0 text_arr append 0 1 running format join ok is if len ok 1 else are plural len critical 1 or len ok 1 alert_label Agent 0 1 2 format s if plural else and join text_arr on host_name alert_state RESULT_CODE_CRITICAL if len critical 0 else RESULT_CODE_OK return alert_state alert_label
returns a base directory for hooks,def get_hook_base_dir self command server_url_prefix try hooks_subpath command commandParams hooks_folder except KeyError return None subpath os path join self STACKS_CACHE_DIRECTORY hooks_subpath return self provide_directory self cache_dir subpath server_url_prefix
return the list of absolute paths to jars in classpath . raise fatalexception ( ) if classpath is n't set,def _find_all_jars self classpath if classpath jars for wildcard in classpath split os pathsep for path in glob glob wildcard if os path isfile path and path endswith jar jars append path return jars else raise FatalException 1 No classpath specified pass
extract the modrm tuple out of the provided instruction,def decode instruction modrm instruction 2 if len modrm 0 modrm decoder decodeInteger modrm return decoder extractsib modrm return None
determines if all of the elements in x are a subset of y,def is_in self x y return set x issubset set y
receive notification of the end of a document .,def endDocument self
"implement this method in a subclass such that it returns a serializable object for `` o `` , or calls the base implementation ( to raise a `` typeerror `` ) .",def default self o raise TypeError repr o is not JSON serializable
loads an opml file into the mongo database ; returns the count of the number of documents added to the database .,def load_opml path opml OPML path rows 0 for feed in opml feed pop type feed pop text feed link feed pop xmlUrl feed urls xmlUrl feed link htmlUrl feed pop htmlUrl feed db Feed feed try feed save rows 1 except NotUniqueError continue return rows
"wrapper around rpy2.robjects.packages.importr , adding the following features :",def importr packname newname None verbose False assert isinstance packname str packinstance _importr packname on_conflict warn if newname is None newname packname replace _ Packages __dict__ newname packinstance p_latex_code re compile code p_latex_link re compile link p_latex_any_curly re compile p_latex_any re compile p_latex_usage re compile method P method P class P signature doc rhelp Package packname for obj_name in packinstance __dict__ obj packinstance __dict__ obj_name if hasattr type packinstance obj_name continue try p doc fetch obj __rname__ except rhelp HelpNotFoundError as hnfe if verbose print Pydoc generator no help for s obj_name continue except AttributeError as ae print Pydoc generator oddity with s obj_name continue except print Pydoc generator oddity with s s obj_name obj __rname__ continue if obj_name in packinstance _exported_names exported True else exported False docstring p title s s exported p _type not if not exported else Experimental dynamic conversion of the associated R documentation tmp p description tmp re sub p_latex_any_curly 1 tmp docstring append tmp docstring append tmp_usage p usage split linesep for i row in enumerate tmp_usage tmp_m p_latex_usage match row if tmp_m is not None tmp_usage i s_ s s tmp_m group method tmp_m group class tmp_m group signature tmp_usage linesep join tmp_usage docstring extend tmp_usage if obj_name not in packinstance _exported_names tmp p seealso tmp re sub p_latex_code 1 tmp tmp re sub p_latex_any_curly 1 tmp tmp re sub p_latex_any 1 tmp docstring extend See Also tmp docstring linesep join docstring obj __doc__ docstring continue try arguments p arguments except KeyError as ke arguments tuple arguments OrderedDict arguments if hasattr obj _prm_translate docstring extend Parameters for k v in obj _prm_translate items try tmp arguments v tmp re sub p_latex_code 1 tmp tmp re sub p_latex_any_curly 1 tmp tmp re sub p_latex_any 1 tmp docstring append s s k tmp except KeyError if verbose print Pydoc generator no help for parameter s in s k obj_name docstring append s error fetching the documentation k tmp p value tmp re sub p_latex_code 1 tmp tmp re sub p_latex_any 1 tmp docstring extend Returns tmp tmp p seealso tmp re sub p_latex_code 1 tmp tmp re sub p_latex_any_curly 1 tmp tmp re sub p_latex_any 1 tmp docstring extend See Also tmp docstring linesep join docstring obj __doc__ docstring return packinstance
find if the token exists in the line . @param line : line of code @param searchtoken : token to look for @return : bool @note : use sparingly as this can be slow,def HasToken line searchToken searchValue None for token value in line if token searchToken if searchValue None if searchValue value strip return True else return True return False
load the html document from a python file - like object .,def LoadStream self stream if self ctrl Document is None self LoadUrl about blank doc self ctrl Document for line in stream doc write line doc close
yield all the tests in the modules found by get_tests_modules .,def get_tests text True gui True packages None attrs if text attrs append tests_nogui if gui attrs append tests_gui for module in get_tests_modules gui gui packages packages for attr in attrs for test in getattr module attr yield test
create a logmsg object @param msg : the log message string @keyword msrc : source of message @keyword level : priority of the message,def __init__ self msg msrc unknown level info super LogMsg self __init__ self _msg dict mstr msg msrc msrc lvl level tstamp time time self _ok True
get the environmental info / header of error report @return : string,def GetEnvironmentInfo self info list info append Notes info append Please provide additional information about the crash here info extend info append System Information info append self GetProgramName info append Operating System s wx GetOsDescription if sys platform darwin info append Mac OSX s platform mac_ver 0 info append Python Version s sys version info append wxPython Version s wx version info append wxPython Info s join wx PlatformInfo info append Python Encoding Default s File s sys getdefaultencoding sys getfilesystemencoding info append wxPython Encoding s wx GetDefaultPyEncoding info append System Architecture s s platform architecture 0 platform machine info append Byte order s sys byteorder info append Frozen s str getattr sys frozen False info append End System Information info append return os linesep join info
derive the language names from the lexer identifier list @return : list of strings,def deriveLanguageNames lexlist rlist list for item in lexlist lang item rsplit _ 1 1 rlist append lang return rlist
processes the provided bytes and returns nothing .,abc abstractmethod def update self data
mark the parts of the domain which are in the core,def core_mask R Z psi opoint xpoint mask zeros psi shape nx ny psi shape Ro Zo psi_axis opoint 0 _ _ psi_bndry xpoint 0 psin psi psi_axis psi_bndry psi_axis xpt_inds for rx zx _ in xpoint ix argmin abs R 0 rx jx argmin abs Z 0 zx xpt_inds append ix jx for i in ix 1 ix ix 1 for j in jx 1 jx jx 1 mask i j 2 rind argmin abs R 0 Ro zind argmin abs Z 0 Zo stack rind zind while stack i j stack pop if j 0 and psin i j 1 1 0 and mask i j 1 0 5 stack append i j 1 while True mask i j 1 if i nx 1 and psin i 1 j 1 0 and mask i 1 j 0 5 stack append i 1 j if i 0 and psin i 1 j 1 0 and mask i 1 j 0 5 stack append i 1 j if j ny 1 break if psin i j 1 1 0 or mask i j 1 0 5 break j 1 for ix jx in xpt_inds for i in ix 1 ix ix 1 for j in jx 1 jx jx 1 if psin i j 1 0 mask i j 1 else mask i j 0 return mask
take literal loglevel return loglevel defined in logging module : param string : : return :,def get_loglevel string if string info return logging INFO if string warn return logging WARN if string debug return logging DEBUG return logging INFO
setup pressure laplacian ksp based on velocity mass matrix `` mu `` and discrete gradient `` bt `` and assemble matrix,def setup_ksp_Rp self ksp Mu Bt mat ksp getOperators 0 prefix ksp getOptionsPrefix const self assembler get_pcd_form mu is_constant and self assembler get_pcd_form gp is_constant if mat type is None or not mat isAssembled or not const mat self _build_approx_Ap Mu Bt mat mat setOption PETSc Mat Option SPD True mat setOptionsPrefix prefix ksp setOperators mat mat assert ksp getOperators 0 isAssembled with Timer FENaPack setup format prefix ksp setUp
creates an invoice item from posted form data,def update_invoice_from_form dbo username post dbo update clinicinvoiceitem post integer itemid ClinicAppointmentID post integer appointmentid Description post description Amount post integer amount username update_appointment_total dbo post integer appointmentid
scans paths for known bots and dumps information from them,def scan_paths paths only_detect recursive module_filter while len paths 0 file_path abspath paths 0 del paths 0 if isfile file_path for fp r in handle_file file_path module_filter only_detect yield fp r elif isdir file_path for p in iglob join file_path p join file_path p if isdir p and recursive paths append p if isfile p for fp r in handle_file p module_filter only_detect yield fp r
deep residual network that keeps the size of the input throughout the whole network,def keepsize nx ny noise depth activation relu n_filters 64 l2_reg 1e 07 def residual inputs n_filters x ReflectionPadding2D inputs x Conv2D n_filters 3 3 padding valid kernel_initializer he_normal kernel_regularizer l2 l2_reg x x BatchNormalization x x Activation activation x x ReflectionPadding2D x x Conv2D n_filters 3 3 padding valid kernel_initializer he_normal kernel_regularizer l2 l2_reg x x BatchNormalization x x add x inputs return x inputs Input shape nx ny 1 x GaussianNoise noise inputs x ReflectionPadding2D x x Conv2D n_filters 3 3 padding valid kernel_initializer he_normal kernel_regularizer l2 l2_reg x x0 Activation activation x x residual x0 n_filters for i in range depth 1 x residual x n_filters x ReflectionPadding2D x x Conv2D n_filters 3 3 padding valid kernel_initializer he_normal kernel_regularizer l2 l2_reg x x BatchNormalization x x add x x0 x UpSampling2D x x ReflectionPadding2D x x Conv2D n_filters 3 3 padding valid kernel_initializer he_normal kernel_regularizer l2 l2_reg x x Activation activation x final Conv2D 1 1 1 padding same kernel_initializer he_normal kernel_regularizer l2 l2_reg x return Model inputs inputs outputs final
repo files need special care in that a whole line should not be present if there is no value for it . because we were using ` format ( ) ` we could not conditionally add a line for a repo file . so the end result would contain a key with a missing value ( say if we were passing ` none ` ) .,def custom_repo kw lines tmpl reponame s name name s baseurl baseurl s enabled enabled s gpgcheck gpgcheck s _type type s gpgkey gpgkey s proxy proxy s priority priority s for line in tmpl tmpl_key tmpl_value line if tmpl_key in kw and kw get tmpl_key not in None lines append tmpl_value kw get tmpl_key return n join lines
extract array of event tree : param branchname : name of event branch / leaf : param selector : root section string : return : numpy array of data,def getNumpyBranch self branchname selector nSelected self _tree Draw branchname selector goff dat self _tree GetV1 dat SetSize nSelected datArray _np array dat return datArray
coarse grain ui locking to avoid glitchy ui updates,contextmanager def transactUI obj obj Freeze try yield finally obj Layout obj Thaw
"traverse your thunderbird tree , converting each message file found into a claws - mail message directory .",def convert_tree in_treepath out_treepath for path subs files in os walk in_treepath if files for f in x for x in files if not x endswith msf if path endswith sbd outpath path 4 else outpath path print path f process_file os path join path f os path join out_treepath outpath f
retrieves the version number from the latest tagged release .,task def get_latest_geckodriver_version_number self import feedparser latest_url feedparser parse self env geckodriver_feed entries 0 link self vprint latest_url latest_url version latest_url split 1 1 self vprint version version return version
freeze.get_module_path ( ) should return the file path of a module without importing it,patch u curdling freeze imp patch u curdling freeze sys def test_get_module_path sys imp u sys path u u l p site packages imp find_module return_value u u u l p site packages sure module u sure path freeze get_module_path module path should equal u sure
returns server port on which it is listening,def getServerPort self raise NotImplementedError Sending client does not provide port info
place a and b side by side to be plotted .,def compose_imgs a b is_a_binary True is_b_binary False ap convert_to_rgb a is_binary is_a_binary bp convert_to_rgb b is_binary is_b_binary if ap shape bp shape raise Exception A and B must have the same size 0 1 format ap shape bp shape h w ch ap shape composed np zeros h 2 w ch composed w ap composed w bp return composed
"this routine can be overridden by subclasses to try and remove logs left over from a prior run . this routine should log warnings if the files can not be deleted , but should not fail unless failure to delete the logs will actually cause start ( ) to fail .",def _remove_stale_logs self pass
convenience method to add an argument as an integer to the array,def put_int self arg return self put arg I
"return a list of structural attributes ( encoded as [ structure].[attribute ] e.g. "" doc.id "" ) required by the plug - in to be able to trigger request for information about structure ( instead of a common token which is simply identified by its numeric token id ) .",def get_required_structattrs self return
add builders and construction variables for acc & cc to an environment .,def generate env cc generate env env CXX aCC env SHCCFLAGS SCons Util CLVar CCFLAGS Z
test whether this task is in sync with the stored state and needs to be executed,def in_sync self if not os path exists os path join self root_directory self creates return False return self state_in_sync and all resource state_in_sync for resource in self depends_resources
"for successful runs , postprocessing on db",def postprocessing self db name cur props self name_split name props state 2 db update_healpix_frame_state props state 3 cur cur
returns the idx'th parameter byte .,def param_byte self idx return ord self param idx
check project settings file for required options,def validate_settings try django_backend x for x in settings TEMPLATES if x BACKEND django template backends django DjangoTemplates 0 except IndexError raise ImproperlyConfigured django CMS requires django template context_processors request in django template backends django DjangoTemplates context processors context_processors django_backend get OPTIONS get context_processors if django core context_processors request not in context_processors and django template context_processors request not in context_processors raise ImproperlyConfigured django CMS requires django template context_processors request in django template backends django DjangoTemplates context processors
reduce a list of [ sentence [ word [ syllable ] ] ] to [ sentence [ syllable ] ] . : param syllables_words : elided text : return : text tokenized only at the sentence and syllable level : rtype : list,def _syllable_condenser self words_syllables sentences_syllables for sentence in words_syllables syllables_sentence for word in sentence syllables_sentence word sentences_syllables append syllables_sentence return sentences_syllables
the type of transaction relative to this person .,property def transaction_type self return charge if self credited else payment
overload property access to interpret them as matchers .,def __getattr__ self name if name 0 2 __ raise AttributeError obj self clone if self factory else self if obj matcher obj _init_matcher if not obj deferred obj resolve obj value name re sub a z A Z 1_ 2 name parts name lower split _ expr if parts 0 and expr append OPERATOR AND parts pop 0 elif parts 0 or expr append OPERATOR OR parts pop 0 elif parts 0 but expr append OPERATOR BUT parts pop 0 elif len obj expr expr append obj def_op if not in parts expr append OPERATOR NOT parts pop parts index not if len parts name _ join parts else name obj last_matcher or obj def_matcher try obj matcher obj _find_matcher name obj last_matcher name obj expr extend expr except KeyError as ex raise AttributeError str ex return obj
returns the memory value in gb from a given string in kb,register filter name get_memory_in_GB def get_memory_in_GB memory_str try return 0 GB format int memory_str 2 1000000 except ValueError TypeError return
"returns an analytics i d for this tool , used for eventing .",classmethod def analytics_id cls return edx updates
endpoint for all requests to embed edx content via the lti protocol . this endpoint will be called by a post message that contains the parameters for an lti launch ( we support version 1.2 of the lti specification ) : http://www.imsglobal.org/lti/ltiv1p2/ltiimgv1p2.html,csrf_exempt add_p3p_header def lti_launch request course_id usage_id if not settings FEATURES ENABLE_LTI_PROVIDER return HttpResponseForbidden params get_required_parameters request POST if not params return HttpResponseBadRequest params update get_optional_parameters request POST try lti_consumer LtiConsumer get_or_supplement params get tool_consumer_instance_guid None params oauth_consumer_key except LtiConsumer DoesNotExist return HttpResponseForbidden if not SignatureValidator lti_consumer verify request return HttpResponseForbidden try course_key usage_key parse_course_and_usage_keys course_id usage_id except InvalidKeyError log error Invalid course key s or usage key s from request s course_id usage_id request raise Http404 params course_key course_key params usage_key usage_key authenticate_lti_user request params user_id lti_consumer store_outcome_parameters params request user lti_consumer return render_courseware request params usage_key
reset django urls before tests and after tests,def setUp self super UrlResetMixin self setUp self reset_urls self addCleanup self reset_urls
"given a token string , return the matching accesstoken object .",def get_access_token self token_string return models AccessToken objects get token token_string
return true if the ccx due date is set and is in the past,def has_ended self u if self due is None return False return datetime now utc self due
make sure a badge is n't created before a user 's reached any checkpoint .,def test_no_match self user UserFactory course CourseFactory GeneratedCertificate user user course_id course location course_key status CertificateStatuses downloadable save self assertFalse user badgeassertion_set all
contacts the backend to have a badge assertion created for this badge class for this user .,def award self user evidence_url None return self backend award self user evidence_url evidence_url
test render_to_string ( ) when makomiddleware has not initialized the threadlocal request_context.context . this is meant to run in cms .,unittest skipUnless settings ROOT_URLCONF cms urls Test only valid in cms def test_render_to_string_when_no_global_context_cms self self assertIn We re having trouble rendering your component render_to_string html_error html None
add the user to the instructor group of the course so they will have the permissions to see it in studio,def add_course_author user course global_admin AdminFactory for role in CourseStaffRole CourseInstructorRole auth add_users global_admin role course id user
check if age limit message is present .,property def age_limit_message_present self self wait_for_ajax return self q css u field message account_privacy visible
returns the dynamic tab types for the current user .,def _get_dynamic_tabs course user dynamic_tabs list for tab_type in CourseTabPluginManager get_tab_types if getattr tab_type is_dynamic False tab tab_type dict if tab is_enabled course user user dynamic_tabs append tab dynamic_tabs sort key lambda dynamic_tab dynamic_tab name return dynamic_tabs
add a comment to this entry,def add_comment self text author assert text and isinstance text six text_type text not str or empty assert author and isinstance author User second argument not an instance of User doc text text author author name created datetime utcnow self add_to_set comments doc self save return text
the second and main pass of the assembler - translate the compiled procedure int a codeobject .,def _assemble_to_code self proc label_offsets co CodeObject co name proc name co args proc args for instr in proc code if isinstance instr CompiledLabel continue if instr opcode OP_CONST if isinstance instr arg Pair co constants append instr arg arg len co constants 1 else arg list_find_or_append co constants instr arg elif instr opcode in OP_LOADVAR OP_STOREVAR OP_DEFVAR arg list_find_or_append co varnames instr arg value elif instr opcode OP_FUNCTION co constants append self assemble instr arg arg len co constants 1 elif instr opcode in OP_FJUMP OP_JUMP arg label_offsets instr arg name elif instr opcode OP_CALL arg instr arg elif instr opcode in OP_POP OP_RETURN arg None else assert False Unexpected opcode s instr opcode co code append Instruction instr opcode arg return co
creates and fills the table with user agent data,def data_filler_user_agent self number_of_rows db try user_agent db data_list list for i in range 0 number_of_rows post_uo_reg id rnd_id_generator self ip self faker ipv4 countrycode self faker country_code useragent self faker user_agent user_agent save post_uo_reg logger warning user_agent Commits are successful after write job extra d except Exception as e logger error e extra d
list ( : http : get:`get < /node/(hostname)/storage/(zpool)/image > ` ) all images imported on a compute node storage or remove ( : http : delete:`delete < /node/(hostname)/storage/(zpool)/image > ` ) all unused images imported on a compute node storage .,api_view GET DELETE request_data_defaultdc permissions IsSuperAdmin def node_image_list request hostname zpool data None ns get_object request NodeStorage node__hostname hostname zpool zpool exists_ok True noexists_fail True sr node images ns images select_related owner dc_bound order_by NodeImageView get_order_by data node_image_view NodeImageView request ns images data if request method DELETE return node_image_view cleanup else return node_image_view get many True
return cached size sum obtained from queryset,def get_cached_size key qs timeout 300 size cache get key if size is None size qs aggregate models Sum size get size__sum if size size b_to_mb size else size 0 cache set key size timeout return size
"sets any non - user authentication information associated with the request , such as an authentication token .",auth setter def auth self value u n Sets any non user authentication information associated with the n request such as an authentication token n self _auth value self _request auth value
set the the array at the index to the given value .,def __setitem__ self index value if index self _size if self _size self _capacity self _capacity 2 new_data np zeros self _capacity new_data self _size self _data self _data new_data self _size 1 self _data index value
set a variable in the planout environment,def set self name value self _env name value return self
calculate flow timeouts for learning on a port .,def learn_host_timeouts self port if port permanent_learn learn_timeout 0 else learn_timeout self _jitter_learn_timeout src_rule_idle_timeout learn_timeout src_rule_hard_timeout 0 dst_rule_idle_timeout learn_timeout self CACHE_UPDATE_GUARD_TIME return src_rule_idle_timeout src_rule_hard_timeout dst_rule_idle_timeout
": param cmd : command name . attributes must have annotations ! : param reg : regexp without command name . : param on_private : param on_channel : param name alternative name of event . if is not defined then name is function name : param next : if is true , accepting another matching commands : param priority : 0 is a smallest priority : param first_char : char before command name : param admin_required : if is true - check permissions",def __init__ self kwargs self kwargs self default_kwargs copy event_type kwargs get event msg reg kwargs get reg None if reg kwargs compiled_reg re compile reg kwargs is_reg True if event_type msg if not reg or kwargs get cmd None raise ValueError Must be cmd or reg argument else raise ValueError event argument is invalid self kwargs update kwargs
[ parallel | layer | multiprocessing | blend | no proba | no prep ] test feature prop fit,def test_fit_fp args get_layer fit multiprocessing blend False False feature_prop 2 run_layer args
fail if the given ( partial ) line is not in the log .,def assertInLog self line marker None data self _read_marked_region marker for logline in data if line in logline return msg r not found in log line self _handleLogError msg data marker line
create frames availables in the jpl files,def create_frames until None now Date now if until get_body until now else for body in list_bodies get_body body name now
reset all the configs back to their default values,def clear_config from GangaCore Utility Config import allConfigs for package in allConfigs values package _user_handlers package _session_handlers package revertToDefaultOptions
called by the monitoring thread . base class just calls update on each transform,def update self if self status new return for trf in self transforms if trf status running continue if trf update and not self check_all_trfs break self updateStatus
performs a make on the application . the unix exit code is returned . any arguments given are passed onto as in dv.make('clean ' ) .,def make self argument None import GangaLHCb Lib Applications FileFunctions return FileFunctions make self argument
return a tuple containing the target and host package symbol .,def _get_package_symbols self package_name u Return a tuple containing the target and host package symbol n n symbols re sub u u _ package_name symbols symbols upper symbols tuple prefix symbols for prefix in self package_prefixes return symbols
keep permission action and change content type to `` dest_obj `` .,def change_perm_ctype perm dest_obj action get_perm_action perm return get_full_perm action dest_obj
returns a dict containing the config for a project for the sentry relay,def get_project_options self project_keys ProjectKey objects filter project self project all public_keys for project_key in list project_keys public_keys project_key public_key project_key status 0 now datetime utcnow replace tzinfo utc return disabled self project status 0 slug self project slug lastFetch now lastChange self project get_option sentry relay rev lastchange now rev self project get_option sentry relay rev uuid uuid4 hex publicKeys public_keys config allowedDomains self project get_option sentry origins
update an organization release 's file `` `` `` `` `` `` `` `` `` ` `` `` `` `` `` `` `` `` ``,def put self request organization version file_id try release Release objects get organization_id organization id version version except Release DoesNotExist raise ResourceDoesNotExist if not self has_release_permission request organization release raise PermissionDenied try releasefile ReleaseFile objects get release release id file_id except ReleaseFile DoesNotExist raise ResourceDoesNotExist serializer ReleaseFileSerializer data request DATA if not serializer is_valid return Response serializer errors status 400 result serializer object releasefile update name result name return Response serialize releasefile request user
return an iterator that 's filtered by which flags are set on a key .,def filter self flag None if flag is None return self all if flag is DEFAULT_FLAGS return k for k in self all if k flags is DEFAULT_FLAGS return k for k in self all if k flags flag
process one inference and return data to visualize,override def process_data self input_id input_data output_data class_data output_data output_data keys 0 astype float32 class_data np argmax class_data axis 0 astype uint8 found_classes np unique class_data if self map fill_data self map to_rgba class_data 255 astype uint8 else fill_data np ndarray class_data shape 0 class_data shape 1 4 dtype uint8 for x in xrange 3 fill_data x class_data copy mask np greater class_data 0 fill_data 3 mask 255 mask_data np zeros fill_data shape dtype uint8 mask_data 3 1 mask 255 if len found_classes 1 line_mask np zeros class_data shape dtype bool for c in x for x in found_classes if x 0 c_mask np equal class_data c distance skfmm distance c_mask astype float32 0 5 line_width 3 line_mask c_mask np less distance line_width for x in xrange 3 input_data x input_data x 1 line_mask fill_data x line_mask input_max input_data max input_min input_data min input_range input_max input_min if input_range 255 input_data input_data input_min 255 0 input_range elif input_min 0 input_data input_min input_image PIL Image fromarray input_data astype uint8 input_image format png fill_image PIL Image fromarray fill_data fill_image format png mask_image PIL Image fromarray mask_data mask_image format png legend self get_legend_for found_classes skip_classes 0 return input_id input_id input_image input_image fill_image fill_image mask_image mask_image legend legend class_data class_data
this is the main method that should be called each time an event is to occur . it will block internally until it is time for the next event to occur .,def eventRatePause self if not hasattr self _curRate self _runningCount 1 if self _runningCount self _maxRate 0 7 return self _curRate 0 self _timeMark Timer self _goodMarks 0 return self _curRate 1 deltaT self _timeMark elapsed if deltaT timedelta seconds 1 return rate self _curRate timePeriodSeconds deltaT if rate self _maxRate delay 0 1 self _goodMarks 0 return self _goodMarks 1 if self _goodMarks self _maxRate delattr self _curRate self _runningCount 0 return
format the base path name .,def _format_base_path self api_name name self app_name if self app_name api_name name 0 1 format self app_name api_name return name
returns the candidate that most closely matches |target| .,def closest_candidate target candidates return min candidates key lambda candidate distance target candidate
truncate product name + supplier to less than 40 char,def show_title self o u n T truncate o product name 40 v o product vendor name r html format_html u a href o get_absolute_url n r u br if len n len v 37 else u r html format_html u a v return html mark_safe r
add dynamically calculated setup params to static ones .,def get_dynamic_setup_params return long_description read_file README rst install_requires substitute_crypto_to_req read_requirements requirements txt extras_require read_extras
returns a pileup column at the specified position . unclear if a function like this is hiding somewhere in pysam api .,def pileup_reads_at_position samfile chromosome base0_position for column in samfile pileup chromosome start base0_position end base0_position 1 if column pos base0_position continue return column pileups return
adds a new : class:`traversalpathnode ` constructed from the given arguments to this traversal path .,def push self proxy key attribute relation_operation node TraversalPathNode proxy key attribute relation_operation self nodes append node self __keys add key
sets the specified representer configuration option to the given value .,def set_option self option value self __config option value
power spectrum reconstruction for the spectral index field .,def mf_resolve_pspec_a a Da k_space alpha_prior params logger logger header1 Run total MF RESOLVE spectral index power spectrum iteration cycle psloop True M0 params M0_start_a while psloop Sk projection_operator domain k_space if params ftmode wsclean logger message Calculating Dhat for pspec reconstruction D_hathat Da hathat domain k_space loop True logger message Success else logger message Calculating Dhat for pspec reconstruction D_hathat Da hathat domain k_space ncpu params ncpu nrun params nrun logger message Success pspec infer_power a domain k_space Sk Sk D D_hathat q 1e 42 alpha alpha_prior perception 1 0 smoothness True var params smoothing bare True if np any pspec False logger message D not positive definite try increasing M0 if M0 0 M0 0 1 M0 1000000 0 Da para Da para 0 Da para 1 Da para 2 Da para 3 M0 Da para 5 Da para 6 Da para 6 logger message Current M0 str Da para 4 n else psloop False return pspec
send a post must keep get_form attribute as ' none ',def test_no_get_method self data dict date 2017 12 21 money 10 00 description test category test payment principal query_user Extract objects user_logged teste RQST method POST RQST GET data response MethodGet RQST query_user self assertEqual response get_form None
set a fixture file with ' name ' that will contain the contents specified by data,def fixtureData self name data assert name not in self files self files name FixtureRawFile data
"after a successfully validated authentication request , build an authentication assertion",def build_assertion request login now datetime datetime utcnow notBefore now datetime timedelta 0 60 notOnOrAfter now datetime timedelta 0 60 login buildAssertion lasso LIB_AUTHN_CONTEXT_CLASS_REF_PREVIOUS_SESSION now isoformat Z unused notBefore isoformat Z notOnOrAfter isoformat Z assertion login assertion fill_assertion request login request assertion login remoteProviderId
make sure we can create a sparsememory and use it,def test_sparsememory_basicusage mem SparseMemory mem add_segment 4096 bytearray 4096 assert mem 4096 0 dataslice mem 4096 5120 assert len dataslice 1024 with pytest raises ArgumentError mem 2304 with pytest raises ArgumentError mem 8192 with pytest raises ArgumentError mem 2048 4608 with pytest raises ArgumentError mem 4096 4608 2
create the argument parser for iotile .,def create_parser u parser argparse ArgumentParser description DESCRIPTION formatter_class argparse RawDescriptionHelpFormatter parser add_argument u v u verbose action u count default 0 help u Increase logging level goes error warn info debug parser add_argument u l u logfile help u The file where we should log all logging messages parser add_argument u i u include action u append default help u Only include the specified loggers parser add_argument u e u exclude action u append default help u Exclude the specified loggers including all others parser add_argument u q u quit action u store_true help u Do not spawn a shell after executing any commands parser add_argument u t u timeout type float help u Do not allow this process to run for more than a specified number of seconds parser add_argument u commands nargs argparse REMAINDER help u The command s to execute return parser
"create test data on given pattern . @param n1 : size of first part of array at base address 0 . @param offset : offset for second part of array . @param n2 : size of second part of array at given offset . @return : ( overall size , hex file , intelhex object )",def get_test_data n1 offset n2 ih intelhex IntelHex addr 0 for i in range_g n1 ih addr addr 256 addr 1 addr offset for i in range_g n2 ih addr addr 256 addr 1 sio StringIO ih write_hex_file sio hexstr sio getvalue sio close return n1 n2 hexstr ih
return the number of free output connections .,property def free_outputs self return self max_outputs self num_outputs
test formatting of top output .,def test_top_formatting u n Test formatting of top output n data u Processes u root u 27390 u 2347 u 0 u Jun02 u u 00 00 21 u bin sh c while true do echo Hello boo sleep 1 done u root u 32694 u 27390 u 0 u 21 52 u u 00 00 00 u sleep 1 u Titles u UID u PID u PPID u C u STIME u TTY u TIME u CMD formatted format_top data print u n print u n join formatted
return a configurationmanipulator for this representation .,abc abstractmethod def manipulator pass
: param item : a host response from gcp : return the privateip of this instance or none,def _get_privateip self item for interface in item u networkInterfaces if networkIP in interface return interface u networkIP
get season - level pitching data aggregated by team .,def team_pitching start_season end_season None league all ind 1 if start_season is None raise ValueError You need to provide at least one season to collect data for Try team_pitching season or team_pitching start_season end_season if end_season is None end_season start_season soup get_soup start_season start_season end_season end_season league league ind ind table get_table soup ind table postprocessing table return table
"compares two peaks , and returns 1 , 0 or -1 if the first has a greater amplitude than the second , they have the same amplitude , or the second has a greater amplitude than the first respectively . can be used to sort lists of peaks .",def compare_peak_amps peak_x peak_y if peak_x amplitude peak_y amplitude return 1 elif peak_x amplitude peak_y amplitude return 1 else return 0
"copy libcapnp into source dir , and patch it if necessary .",def copy_and_patch_libcapnp capnp libcapnp if sys platform startswith win return local localpath capnp libcapnp if not capnp and not os path exists local fatal Please specify capnp prefix via setup py configure capnp path to capnp or copy libcapnp into capnp manually prior to running bdist try lib os path realpath pjoin capnp lib libcapnp print copying s s lib local shutil copy lib local except Exception if not os path exists local fatal Could not copy libcapnp into capnp which is necessary for bdist Please specify capnp prefix via setup py configure capnp path to capnp or copy libcapnp into capnp manually if sys platform darwin mode os stat local st_mode os chmod local mode stat S_IWUSR cmd install_name_tool id loader_path s libcapnp local try p Popen cmd stdout PIPE stderr PIPE except OSError fatal install_name_tool not found cannot patch libcapnp for bundling out err p communicate if p returncode fatal Could not patch bundled libcapnp install_name s err p returncode
"sets a key in the current instance key , value , expiry seconds till it expires",def set key value expiry DEFAULT_CACHING_TIME if ACTIVE is False return None if expiry None expiry time time int expiry try with _CACHE_LOCK _CACHE key value expiry except MemoryError logging info s memory error setting key s __name__ key
"get number of downloads for a single release . : param release : release statistics from github api . : param quiet : if true , print nothing . : return : number of downloads for a release .",def get_release_downloads release quiet False downloads_total 0 if not quiet encoding sys stdout encoding or ascii title release name or release tag_name encode encoding ignore decode encoding published time strftime c time strptime release published_at Y m dT H M SZ if release published_at else Unpublished print print _Text HEADER title _Text END n print Tag release tag_name print Author release author login print URL _Text UNDERLINE release html_url _Text END print Published at published print if assets in release indent 13 len _Text BOLD _Text END for package in release assets downloads_release package download_count downloads_total downloads_release if not quiet print 1 0 2 format indent _Text BOLD str downloads_release _Text END package label if package label else package name if not quiet print 1 0 Total format indent _Text BOLD str downloads_total _Text END return downloads_total
"optimizes the objective function . returns two objects : a tuple of the optimal variables and optimal value , and an object detailing the best and average score at each iteration .",def GA self Fitness self Objective self InitialSolutions Sol_Fit zip self InitialSolutions Fitness Iterations 0 self SolMetrics while Iterations self maxIterations Sol_Fit sort key lambda x x 1 if self Crossover Quadratic if self Sense min Sol_Fit Sol_Fit self num_sols 4 else Sol_Fit Sol_Fit self num_sols 4 IndexPairs self CreatePairs range self num_sols self num_sols 4 3 NextGenSols numpy empty self num_sols 4 len self InitialSolutions 0 for i Index1 Index2 Index3 in enumerate IndexPairs Child self Crossover_Quadratic Sol_Fit Index1 Sol_Fit Index2 Sol_Fit Index3 MutatedChild self Mutate_Random Child NextGenSols i MutatedChild elif self Crossover in Weighted Average Heuristic if self Sense min Sol_Fit Sol_Fit self num_sols 2 else Sol_Fit Sol_Fit self num_sols 2 IndexPairs self CreatePairs range self num_sols 2 2 NextGenSols numpy empty self num_sols 2 len self InitialSolutions 0 i 0 for Index1 Index2 in IndexPairs if self Crossover Weighted Average Child1 self Crossover_WeightedAverage Sol_Fit Index1 0 Sol_Fit Index2 0 Child2 self Crossover_WeightedAverage Sol_Fit Index1 0 Sol_Fit Index2 0 elif self Crossover Heuristic Child1 self Crossover_Heuristic Sol_Fit Index1 Sol_Fit Index2 Child2 self Crossover_Heuristic Sol_Fit Index1 Sol_Fit Index2 if self MutationType Random MutatedChild1 self Mutate_Random Child1 MutatedChild2 self Mutate_Random Child2 elif self MutationType Sum Constraint MutatedChild1 self Mutate_SumConstraint Child1 MutatedChild2 self Mutate_SumConstraint Child2 NextGenSols i MutatedChild1 NextGenSols i 1 MutatedChild2 i 2 Fitness self Objective NextGenSols if self Sense min self SolMetrics append min Fitness numpy mean Fitness else self SolMetrics append max Fitness numpy mean Fitness New_Sol_Fit zip NextGenSols Fitness Sol_Fit extend New_Sol_Fit Iterations 1 if self Sense min return min Sol_Fit key lambda x x 1 self SolMetrics else return max Sol_Fit key lambda x x 1 self SolMetrics
: param data_type : edam ontology for the data type with uri and term . : type data_type : dict : param formats : edam ontology for data formats with uri and term . : type formats : list of dict : param description : description of the data ( deprecated ) : type description : string,def __init__ self data_type formats description None Data __init__ self data_type formats description
generate a random dna sequence .,def random_dna n return coral DNA join random choice ATGC for i in range n
"return true if the node has children or text , false otherwise",def hasContent self raise NotImplementedError
"given the name of a tk named font , returns a font representation .",def nametofont name return Font name name exists True
converts tile indices to a pygame . rect,def get_tile_rect x y return Rect x SIZE y SIZE SIZE SIZE
iterates the dumped nginx content .,def __iter__ self blocks None current_indent 0 spacer blocks blocks or self blocks for key values in blocks indentation spacer current_indent if isinstance key list if current_indent yield yield indentation spacer join key for parameter in values dumped self __iter__ parameter current_indent self indentation for line in dumped yield line yield indentation elif key yield spacer current_indent key values elif values is None yield spacer current_indent key else yield spacer current_indent key spacer values
tries to find shellpy file on filesystem . given a filename without extension it tries to locate it with .spy extension in pythonpath,def locate_spy_file file_name for python_path in sys path possible_file_path os path join python_path file_name spy if os path exists possible_file_path return possible_file_path return None
"test that if soledad already has a local secret , it emits no signals .",def test_stage1_bootstrap_signals self soledad client signal reset_mock sol self _soledad_instance self assertEqual soledad client signal mock_calls sol close
"templatedatasource is not instantiated directly , rather , its methods are invoked through a subclass of it , which has as its only data the directory in which templatedatasource methods should act on . thus , we test templatedatasource indirectly through the testdatasource class",def _CreateTestDataSource base_dir return TestDataSource ServerInstance ForLocal stest_data template_data_source s SERVER2 base_dir
constructor with following specific arguments .,def __init__ self store_revisions_url good_revision_steps None use_getname False check_revisions True base StatusReceiverMultiService __init__ self self good_revision_steps good_revision_steps or self store_revisions_url store_revisions_url self use_getname use_getname self check_revisions check_revisions self succeeded_steps self failed_revisions self last_known_good_revision 0 self status None self password get_password Password status_password GetPassword
"a decorator which can be optionally applied to the compilation function passed to compiledfilesystem . create , indicating that the function processes the file 's data as unicode text .",def Unicode fn def convert_args args args list args args 1 ToUnicode args 1 return args return lambda args fn convert_args args
does a ' make clean ',def AddClean self build_target clean description Clean timeout None cmd make s build_target if not timeout timeout self default_timeout self factory addStep shell ShellCommand description description timeout timeout command cmd workdir self workdir env self environment_variables
test for failure on double @ signs .,def test_doubleAt self self assertRaises jid InvalidFormat jid parse user host
delete all files in dir matching pattern .,def DeleteFiles dir pattern n 0 regex re compile pattern for root _ files in os walk dir for f in files if regex match f os remove os path join root f n 1 return n
"hook.removepre(klass , name , func ) - > none",def removePre klass name func _removeHook klass name PRE func
register / unregister an fd with the poller .,def _updateRegistration self fd try self _poller unregister fd except KeyError pass mask 0 if fd in self _reads mask mask POLLIN if fd in self _writes mask mask POLLOUT if mask 0 self _poller register fd mask elif fd in self _selectables del self _selectables fd
returns the oauth 2.0 client secret for the client of the given name .,def GetClientSecret client_name return _GetToken GOOGLE_CLIENT_SECRET_ s client_name
set build arch and reset files_dict to reflect new build criteria .,def _SetArch self value self _arch value self files_dict clear self files_dict update self _FilterFilesCfg
returns the absolute version of path .,def abspath self path path self normpath path if path 0 return self api slave_build path else return path
returns the parts of the message . you may modify parts if you wish . note that you must not call getid ( ) on this object until you have finished modifying the contents .,def GetContent self self dirty True return self parts
"like l{errorpagetests.test_errorpagerendering } , but flush the deprecation warning emitted by instantiating l{error . errorpage}.",def test_errorPageRendering self ErrorPageTests test_errorPageRendering self self _assertWarning ErrorPage self errorPage
"resolve $ ref |ref| in namespace |namespace| , or globally if none . if it can not be resolved , pretend like it is a link to a type .",def SafeGetLink self ref namespace None title None ref_data self GetLink ref namespace namespace title title if ref_data is not None return ref_data logging error ref s could not be resolved in namespace s ref namespace type_name ref rsplit 1 1 return href type s type_name text title or ref name ref
get layouttest names from svn .,staticmethod def GetLayoutTestNamesFromSVN parent_location_list layouttest_root_path recursion client pysvn Client name_map for parent_location in parent_location_list if parent_location endswith full_path layouttest_root_path parent_location try file_list client list full_path recurse recursion for file_name in file_list if sys stdout isatty default_encoding sys stdout encoding else default_encoding locale getpreferredencoding file_name file_name 0 repos_path encode default_encoding file_name file_name replace trunk LayoutTests if file_name endswith html name_map file_name True except print Unable to list tests in s full_path return name_map
steps to upload the symbols and symbol - sources for official builds .,def AddUploadSymbols self script_path self PathJoin self _repository_root syzygy internal scripts archive_symbols py asan_rtl_dll self PathJoin self _build_dir self _target asan_rtl dll client_dlls self PathJoin self _build_dir self _target client dll command self _syzygy_python_exe script_path s b asan_rtl_dll client_dlls self _factory addStep _UrlStatusCommand command command name upload_symbols description Upload Symbols
stop the named process and remove it from the list of monitored processes .,def removeProcess self name self stopProcess name del self processes name
sync a flavor of the nacl toolchain,def SyncFlavor flavor urls dst hashes min_time keep False force False verbose False if isinstance flavor tuple flavor_name flavor 0 else flavor_name flavor toolchain_dir os path join PARENT_DIR toolchain if not os path exists toolchain_dir os makedirs toolchain_dir download_dir os path join toolchain_dir tars prefix tmp_unpacked_toolchain_ suffix tmp for path in os listdir toolchain_dir if path startswith prefix and path endswith suffix full_path os path join toolchain_dir path try print Cleaning up s full_path pynacl file_tools RemoveDir full_path except Exception as e print Failed cleanup with str e if force stamp_dir None else stamp_dir dst filepaths need_sync False index 0 for url hash_val in zip urls hashes filepath ext url split 1 split 1 if SHA1_IN_FILENAME match filepath is not None filepath filepath rsplit _ 1 0 filepath os path join download_dir join filepath ext filepaths append filepath if pynacl download_utils SyncURL url filepath stamp_dir stamp_dir min_time min_time hash_val hash_val stamp_index index keep keep verbose verbose need_sync True index 1 if not need_sync return False new_hashes for filepath in filepaths new_hashes append pynacl download_utils HashFile filepath untar_dir tempfile mkdtemp suffix suffix prefix prefix dir toolchain_dir try if verbose tar_file os path basename filepath rel_dest os path relpath dst toolchain_dir print s Extracting s s flavor_name tar_file rel_dest for filepath in filepaths tar cygtar CygTar filepath r verbose verbose curdir os getcwd os chdir untar_dir try tar Extract tar Close finally os chdir curdir if not keep os remove filepath if bionic in flavor src os path join untar_dir flavor elif isinstance flavor tuple or arm in flavor or pnacl in flavor src os path join untar_dir elif newlib in flavor src os path join untar_dir sdk nacl sdk else src os path join untar_dir toolchain flavor pynacl file_tools MoveDirCleanly src dst finally try pynacl file_tools RemoveDir untar_dir except Exception as e print Failed cleanup with str e print Continuing on original exception pynacl download_utils WriteSourceStamp dst n join urls pynacl download_utils WriteHashStamp dst n join new_hashes return True
add dependencies created by from - imports,def add_from_depend self node from_module mod_name node root name obj self module mod_name if from_module not in obj node depends obj node depends append from_module
starts profiling using |profiler_name| . results are saved to |base_output_file|.<process_name>.,def StartProfiling self profiler_name base_output_file assert not self _active_profilers Already profiling Must stop first profiler_class profiler_finder FindProfiler profiler_name if not profiler_class is_supported self _browser_backend browser_type raise Exception The s profiler is not supported on this platform profiler_name if not profiler_class in self _profilers_states self _profilers_states profiler_class self _active_profilers append profiler_class self _browser_backend self _platform_backend base_output_file self _profilers_states profiler_class
decide the architecture of a nexe .,def NexeArchitecture filename fh open filename rb head fh read 20 if len head 20 print ERROR header too short return None if head 0 4 x7fELF print ERROR no elf header return None machine struct unpack H head 18 0 return 3 x86 32 62 x86 64 get machine
join a multicast group . returns deferred of success .,def joinGroup self addr interface return self reactor resolve addr addCallback self _joinAddr1 interface 1
returns true if the current platform is cygwin .,def isCygwin return _isCygwin
get a hostname of broker to induce failure on args : none return : hostname,def get_random_node self failure random choice self plan if failure get_node_type RANDOM_BROKER if failure get_topic is None topic self helper get_topic partition self helper get_partition topic self logger_instance logit INFO Selecting a random broker for a Random Topic 0 Random Partition 1 format topic partition log_level VERBOSE isr_list self helper get_isr topic partition return random choice isr_list else topic failure get_topic if failure get_partition is not None partition failure get_partition self logger_instance logit INFO Selecting a random broker for a Specified Topic 0 Specified Partition 1 format topic partition log_level VERBOSE else partition self helper get_partition topic self logger_instance logit INFO Selecting a random broker for a Specified Topic 0 Random Partition 1 format topic partition log_level VERBOSE isr_list self helper get_isr topic partition return random choice isr_list elif failure get_node_type RANDOM_LEADER topic self helper get_topic partition self helper get_partition topic self logger_instance logit INFO Selecting a Leader for a Random Topic 0 Random Partition 1 format topic partition log_level VERBOSE return self helper get_leader topic partition elif failure get_node_type LEADER topic failure get_topic if failure get_partition is not None partition failure get_partition self logger_instance logit INFO Selecting a Leader for a Specified Topic 0 Specified Partition 1 format topic partition log_level VERBOSE else partition self helper get_partition topic self logger_instance logit INFO Selecting a Leader for a Specified Topic 0 Random Partition 1 format topic partition log_level VERBOSE return self helper get_leader topic partition elif failure get_node_type CONTROLLER self logger_instance logit INFO Selecting Controller log_level VERBOSE return self helper get_controller
using multiple styles results in correct output .,def test_multiple_styles assert ansi_format bold True underline True x1b 1 4m x1b 0m
blocks until the first matching fibre node is connected and then returns that node,def find_any path usb serial_number None search_cancellation_token None channel_termination_token None timeout None logger Logger verbose False result None done_signal Event search_cancellation_token def did_discover_object obj result 0 obj done_signal set find_all path serial_number did_discover_object done_signal channel_termination_token logger try done_signal wait timeout timeout finally done_signal set return result 0
"reads a wildcard property from conf and returns its string value , if not set then default .",def get_wildcard self key values default None orig_key key keys key for wild in values key key replace wild 1 keys append key keys reverse for key in keys try return self cf get self main_section key except ConfigParser NoOptionError pass if default None raise Exception Config value not set orig_key return default
performs apriori algorithm on ` listofsequences ` with ` support ` as a threshold .,def __init__ self listOfSequences support super Apriori self __init__ self data listOfSequences self thres support len self data 100 0 self primitives self getPrimitives self apriori del self data
asserts a sample matches a probability density distribution,def eq_sample_pdf samples pdf ndivs 20 start util INF end util INF pval 0 05 step None if step is None step max samples min samples float ndivs cdf lambda x params integrate pdf x x step step 10 0 chi2 p stats chi_square_fit cdf samples ndivs ndivs start start end end assert p pval p
od.clear ( ) - > none . remove all items from od .,def clear self try for node in self __map itervalues del node root self __root root root root None self __map clear except AttributeError pass dict clear self
"add headers to both force latest ie rendering engine or chrome frame , and also to cache the rendered page for 10 minutes .",app after_request def add_header r r headers Cache Control no cache no store must revalidate r headers Pragma no cache r headers Expires 0 r headers Cache Control public max age 0 return r
close the connection to redis .,def close self if self _connection is not None self _connection connection disconnect self _connection None
post the flag view : actually flag the view ( nice for xhr ),def testFlagPost self comments self createSomeComments pk comments 0 pk self client login username normaluser password normaluser response self client post flag d pk self assertEqual response Location http testserver flagged c d pk c Comment objects get pk pk self assertEqual c flags filter flag CommentFlag SUGGEST_REMOVAL count 1 return c
calculates a security hash for the given form instance .,def form_hmac form data for bf in form if form empty_permitted and not form has_changed value bf data or else value bf field clean bf data or if isinstance value basestring value value strip data append bf name value pickled pickle dumps data pickle HIGHEST_PROTOCOL key_salt django contrib formtools return salted_hmac key_salt pickled hexdigest
logs out the user and displays ' you are logged out ' message .,def logout request next_page None template_name registration logged_out html redirect_field_name REDIRECT_FIELD_NAME current_app None extra_context None auth_logout request redirect_to request REQUEST get redirect_field_name if redirect_to netloc urlparse urlparse redirect_to 1 if not netloc and netloc request get_host return HttpResponseRedirect redirect_to if next_page is None current_site get_current_site request context site current_site site_name current_site name title _ Logged out if extra_context is not None context update extra_context return TemplateResponse request template_name context current_app current_app else return HttpResponseRedirect next_page or request path
we do not support update on already sliced query sets .,def test_update_slice_fail self method DataPoint objects all 2 update self assertRaises AssertionError method another_value another thing
"returns the 1-based index of the last object on this page , relative to total objects found ( hits ) .",def end_index self if self number self paginator num_pages return self paginator count return self number self paginator per_page
render the comment list ( as returned by `` { % get_comment_list % } `` ) through the `` comments / list.html `` template,register tag def render_comment_list parser token return RenderCommentListNode handle_token parser token
retrieve a project `` `` `` `` `` `` `` `` ``,attach_scenarios get_project_scenario def get self request project active_plugins name plugin get_title id plugin slug for plugin in plugins configurable_for_project project version None if plugin is_enabled project and plugin has_project_conf data serialize project request user data options sentry origins n join project get_option sentry origins or sentry resolve_age int project get_option sentry resolve_age 0 sentry scrub_data bool project get_option sentry scrub_data True sentry scrub_defaults bool project get_option sentry scrub_defaults True sentry sensitive_fields project get_option sentry sensitive_fields sentry csp_ignored_sources_defaults bool project get_option sentry csp_ignored_sources_defaults True sentry csp_ignored_sources n join project get_option sentry csp_ignored_sources or sentry default_environment project get_option sentry default_environment feedback branding project get_option feedback branding 1 1 data activePlugins active_plugins data team serialize project team request user data organization serialize project organization request user include set filter bool request GET get include split if stats in include data stats unresolved self _get_unresolved_count project return Response data
"spherical "" quadrangular "" interpolation of rotors with a cubic spline",def squad R_in t_in t_out if R_in size 0 or t_out size 0 return np array dtype np quaternion i_in_for_out t_in searchsorted t_out side right 1 A R_in np exp np log R_in np roll R_in 1 np log np roll R_in 1 R_in np roll t_in 1 t_in t_in np roll t_in 1 0 25 B np roll R_in 1 np exp np log np roll R_in 1 np roll R_in 2 np roll t_in 1 t_in np roll t_in 2 np roll t_in 1 np log R_in np roll R_in 1 0 25 A 0 R_in 0 A 1 R_in 1 B 2 R_in 1 B 1 R_in 1 R_in 2 R_in 1 R_ip1 np roll R_in 1 R_ip1 1 R_in 1 R_in 2 R_in 1 R_ip1 np array R_ip1 i_in_for_out t_inp1 np roll t_in 1 t_inp1 1 t_in 1 t_in 1 t_in 2 tau t_out t_in i_in_for_out t_inp1 t_in i_in_for_out R_out np squad_vectorized tau R_in i_in_for_out A i_in_for_out B i_in_for_out R_ip1 return R_out
get the bytecode for the specified module .,def get_code self fullname info None u if info is None info self _get_module_info fullname path type ispkg info code self fs getbytes path if type imp PY_SOURCE code n join code splitlines try path self fs getsyspath path except NoSysPath pass return compile code path u exec elif type imp PY_COMPILED if code 4 imp get_magic return None return marshal loads code 8 return code
transfer a file from local to chroot,def put_file self in_path out_path if not out_path startswith os path sep out_path os path join os path sep out_path normpath os path normpath out_path out_path os path join self chroot normpath 1 vvv PUT s TO s in_path out_path host self chroot if not os path exists in_path raise errors AnsibleFileNotFound file or module does not exist s in_path try shutil copyfile in_path out_path except shutil Error traceback print_exc raise errors AnsibleError failed to copy s and s are the same in_path out_path except IOError traceback print_exc raise errors AnsibleError failed to transfer file to s out_path
"set the handler to call when a listener raises an exception during a sendmessage ( ) . without a handler , the send operation aborts , whereas with one , the exception information is sent to it ( where it can be logged , printed , whatever ) , and sendmessage ( ) continues to send messages to remaining listeners . the handler must adhere to the pubsub.utils.exchandling.iexchandler api .",def setListenerExcHandler self handler self __treeConfig listenerExcHandler handler
extrapolates a set of modified midpoint estimates using rational function extrapolation .,def rati_extrapolate ki t0 tsav x0 p0 g0 Tx Tp Tg tsav ki t0 if ki 0 vx np copy Tx 0 vp np copy Tp 0 vg np copy Tg 0 Tx 0 np copy x0 Tp 0 np copy p0 Tg 0 np copy g0 if ki 0 cx Tx 0 cp Tp 0 cg Tg 0 for k in range 1 ki 1 fac tsav ki k t0 b1x fac vx b1p fac vp b1g fac vg bx b1x cx bp b1p cp bg b1g cg bx bx 0 cx bx 0 vx bx 0 bx bx 0 bp bp 0 cp bp 0 vp bp 0 bp bp 0 bg bg 0 cg bg 0 vg bg 0 bg bg 0 ddx cx bx ddp cp bp ddg cg bg ddx bx 0 vx bx 0 ddp bp 0 vp bp 0 ddg bg 0 vg bg 0 cx b1x bx cp b1p bp cg b1g bg if k ki vx Tx k vp Tp k vg Tg k Tx k ddx Tp k ddp Tg k ddg
test for bind version . this acts as a pretty decent ping .,def TestBindVersion self unused_response duration error_msg self RequestVersion return False None duration
saves the running configuration to memory,def write_mem self request commands writemem return self _post request
reads config values from zget.cfg or zget.ini,def config config configparser SafeConfigParser defaults port 0 interface None allow_no_value True config read zget cfg os path expanduser zget cfg os path join os getenv APPDATA zget zget ini return config
derive the path for a conf template file .,def _get_template_conf_path service extension return confs s s service extension
return a list of all available application instances ordered by name .,def generate_values self sessions filters return list Application objects all order_by name
"obtain the image plane for the given index as a numpy array , or a list of numpy arrays in the rgb case .",def save_bytes_simple self plane buf u Obtain the image plane for the given index as a numpy array or a n list of numpy arrays in the RGB case n copy None if type buf is list shape None dtype None for planebuf in buf if planebuf ndim 2 raise RuntimeError u Invalid number of dimensions for RGB plane if shape is None shape planebuf shape elif shape planebuf shape raise RuntimeError u Inconsistent dimension shapes for RGB planes if dtype is None dtype planebuf dtype elif dtype planebuf dtype raise RuntimeError u Inconsistent datatypes for RGB planes copy np ndarray shape shape 0 shape 1 len buf dtype dtype order u C for i in range 0 len buf copy i buf i else if buf ndim 2 raise RuntimeError u Invalid number of dimensions for plane copy np array buf copy True copy np expand_dims copy axis 2 copy np swapaxes copy 0 1 copy np expand_dims copy axis 2 copy np expand_dims copy axis 3 copy np expand_dims copy axis 4 copy np expand_dims copy axis 6 copy np expand_dims copy axis 7 copy np expand_dims copy axis 8 self save_bytes plane copy
construct a policy object from database record .,classmethod def _from_db_record cls record kwargs id record id rules record rules is_default record is_default metadata record meta_data created_at record created_at updated_at record updated_at deleted_at record deleted_at return cls record name kwargs
verify that the backup exists on the backend .,def verify self backup
parse is_public into something usable .,def _parse_is_public self is_public if is_public is None return True elif utils is_none_string is_public return None else try return strutils bool_from_string is_public strict True except ValueError msg _ Invalid is_public filter s is_public raise exc HTTPBadRequest explanation msg
create messages to test pagination functionality,def create_message_for_tests self utils create_message self ctxt action message_field Action ATTACH_VOLUME utils create_message self ctxt action message_field Action SCHEDULE_ALLOCATE_VOLUME utils create_message self ctxt action message_field Action COPY_VOLUME_TO_IMAGE utils create_message self ctxt action message_field Action COPY_VOLUME_TO_IMAGE
load extensions specified on the command line .,def _load_extensions self extensions list self cls_list for ext_factory in extensions try self load_extension ext_factory except Exception as exc LOG warning Failed to load extension ext_factory s exc s ext_factory ext_factory exc exc
validate user configured ' location_strategy ' option value .,def verify_location_strategy conf None strategies _available_strategies if not conf conf CONF location_strategy if conf not in strategies msg _ Invalid location_strategy option name s The valid strategy option s is are strategies s name conf strategies join strategies keys LOG error msg raise RuntimeError msg
it validates if the boot device is supported by xclarity .,def _validate_supported_boot_device self task boot_device if boot_device not in SUPPORTED_BOOT_DEVICES raise exception InvalidParameterValue _ Unsupported boot device device s for node node s device boot_device node task node uuid
versioning information for a single method,def __init__ self name start_version end_version func self name name self start_version start_version self end_version end_version self func func
fake implementation of a periodic hook action .,def _execute_periodic_hook self context periodic_hook_data args kwargs
return versions supported after the start of microversions .,wsgi Controller api_version 2 0 def index self req builder views_versions get_view_builder req known_versions copy deepcopy _KNOWN_VERSIONS known_versions pop v1 0 return builder build_versions known_versions
remove search options that are not valid for non - admin api / context .,def remove_invalid_options context search_options allowed_search_options if context is_admin return unknown_options opt for opt in search_options if opt not in allowed_search_options bad_options join unknown_options LOG debug Removing options bad_options s from query bad_options bad_options for opt in unknown_options del search_options opt
resolve placeholders in the data source url,plugins_base required_with_default def construct_url self url job_exec_id def _randstr match random_len int match group 1 return join random choice string ascii_lowercase for _ in six moves range random_len url url replace JOB_EXEC_ID job_exec_id url re sub RANDSTR d _randstr url return url
callback function when cluster membership is about to change .,def pre_op self cluster_id action count self _get_count cluster_id action if count 0 return expand True if count 0 expand False count count cluster cm Cluster load action context cluster_id nc self nova cluster user cluster project zones_good nc validate_azs self zones keys if len zones_good 0 action data status base CHECK_ERROR action data reason _ No availability zone found available LOG error No availability zone found available return zones for z w in self zones items if z in zones_good zones z w current cluster get_zone_distribution action context zones keys result self _create_plan current zones count expand if not result action data status base CHECK_ERROR action data reason _ There is no feasible plan to handle all nodes LOG error There is no feasible plan to handle all nodes return if expand if creation not in action data action data creation action data creation count count action data creation zones result else if deletion not in action data action data deletion action data deletion count count action data deletion zones result
context : - committee - abbr - metadata - sources - nav_active - events,ensure_csrf_cookie def committee request abbr committee_id committee db committees find_one _id committee_id if committee is None raise Http404 events db events find settings LEVEL_FIELD abbr participants id committee_id sort when 1 events list events if len events EVENT_PAGE_COUNT events events EVENT_PAGE_COUNT popularity counter inc committees committee_id abbr abbr return render request templatename committee dict committee committee abbr abbr metadata Metadata get_object abbr sources committee sources nav_active committees events events
reads the table entries from all tables on the switch .,def readTableRules p4info_helper sw print n Reading tables rules for s sw name for response in sw ReadTableEntries for entity in response entities entry entity table_entry table_name p4info_helper get_tables_name entry table_id print s table_name for m in entry match print p4info_helper get_match_field_name table_name m field_id print r p4info_helper get_match_field_value m action entry action action action_name p4info_helper get_actions_name action action_id print action_name for p in action params print p4info_helper get_action_param_name action_name p param_id print r p value print
graft many identical tether into a system at the given points .,def stamp_tethers system pts kwargs ids list for pt in pts tether_info dict kwargs tether_info pos pt id_ system add_tether tether_info ids append id_ return ids
"parse the arguments given into a list of ( app_name , model_name , field_name ) tuples",def parse_args self args if not args args APP_MAP keys rv for app_name in args for composite_field_name in APP_MAP app_name rv append app_name composite_field_name split return rv
turn a feature collection into an iterator over polygons .,def feature_collection_polygons featureCollection for feature in featureCollection features tzname feature properties TZID if feature geometry type Polygon exterior feature geometry coordinates 0 interior feature geometry coordinates 1 yield tzname exterior interior
just make sure it does n't blow up .,def test_repr self str self ss
return a nice html document describing a given traceback .,def html etype evalue etb context 5 import os types time traceback linecache inspect pydoc if type etype is types ClassType etype etype __name__ from Sycamore import version try osinfo join os uname except osinfo Platform s s sys platform os name pyver Python sys version split 0 sys executable date time ctime time time versinfo strong Please include this information in your bug reports strong br Python s br pyver osinfo br Sycamore Release s Revision s version release version revision head body bgcolor f0f0f8 pydoc html heading big big strong s strong s big big str etype str evalue ffffff 6622aa versinfo br date p A problem occurred in a Python script Here is the sequence of function calls leading up to the error in the order they occurred indent tt small nbsp 5 nbsp tt frames records inspect getinnerframes etb context for frame file lnum func lines index in records file file and os path abspath file or link a href file s s a file pydoc html escape file args varargs varkw locals inspect getargvalues frame call if func call in strong func inspect formatargvalues args varargs varkw locals formatvalue lambda value pydoc html repr value highlight def reader lnum lnum highlight lnum 0 1 try return linecache getline file lnum 0 finally lnum 0 1 vars scanvars reader frame locals rows tr td bgcolor d8bbff s s s td tr big nbsp big link call if index is not None i lnum index for line in lines num small nbsp 5 len str i str i nbsp line tt s s tt num pydoc html preformat line if i in highlight rows append tr td bgcolor ffccee s td tr line else rows append tr td s td tr grey line i 1 done dump for name where value in vars if name in done continue done name 1 if value is not __UNDEF__ if where global name em global em strong name elif where local name strong name else name where strong name split 1 dump append s nbsp s name pydoc html repr value else dump append name em undefined em rows append tr td s td tr small grey join dump frames append p table width 100 cellspacing 0 cellpadding 0 border 0 s table n join rows exception p s s strong str etype str evalue if type evalue is types InstanceType for name in dir evalue value pydoc html repr getattr evalue name exception append n br s s nbsp n s indent name value import traceback return head join frames join exception The above is a description of an error in a Python program formatted for a Web browser because the cgitb module was enabled In case you are not reading this in a Web browser here is the original traceback s join traceback format_exception etype evalue etb
"the ' color ' property is a color and may be specified as : - a hex string ( e.g. ' # ff0000 ' ) - an rgb / rgba string ( e.g. ' rgb(255,0,0 ) ' ) - an hsl / hsla string ( e.g. ' hsl(0,100%,50 % ) ' ) - an hsv / hsva string ( e.g. ' hsv(0,100%,100 % ) ' ) - a named css color : aliceblue , antiquewhite , aqua , aquamarine , azure , beige , bisque , black , blanchedalmond , blue , blueviolet , brown , burlywood , cadetblue , chartreuse , chocolate , coral , cornflowerblue , cornsilk , crimson , cyan , darkblue , darkcyan , darkgoldenrod , darkgray , darkgrey , darkgreen , darkkhaki , darkmagenta , darkolivegreen , darkorange , darkorchid , darkred , darksalmon , darkseagreen , darkslateblue , darkslategray , darkslategrey , darkturquoise , darkviolet , deeppink , deepskyblue , dimgray , dimgrey , dodgerblue , firebrick , floralwhite , forestgreen , fuchsia , gainsboro , ghostwhite , gold , goldenrod , gray , grey , green , greenyellow , honeydew , hotpink , indianred , indigo , ivory , khaki , lavender , lavenderblush , lawngreen , lemonchiffon , lightblue , lightcoral , lightcyan , lightgoldenrodyellow , lightgray , lightgrey , lightgreen , lightpink , lightsalmon , lightseagreen , lightskyblue , lightslategray , lightslategrey , lightsteelblue , lightyellow , lime , limegreen , linen , magenta , maroon , mediumaquamarine , mediumblue , mediumorchid , mediumpurple , mediumseagreen , mediumslateblue , mediumspringgreen , mediumturquoise , mediumvioletred , midnightblue , mintcream , mistyrose , moccasin , navajowhite , navy , oldlace , olive , olivedrab , orange , orangered , orchid , palegoldenrod , palegreen , paleturquoise , palevioletred , papayawhip , peachpuff , peru , pink , plum , powderblue , purple , red , rosybrown , royalblue , saddlebrown , salmon , sandybrown , seagreen , seashell , sienna , silver , skyblue , slateblue , slategray , slategrey , snow , springgreen , steelblue , tan , teal , thistle , tomato , turquoise , violet , wheat , white , whitesmoke , yellow , yellowgreen",property def color self return self color
"sets the maximum number of points to keep on the plots from an incoming stream . if ` maxpoints ` is set to * 50 * , only the newest 50 points will be displayed on the plot .",property def maxpoints self return self maxpoints
process the transform and convert data to figure or data coordinates,staticmethod def process_transform transform ax None data None return_trans False force_trans None if isinstance transform transforms BlendedGenericTransform warnings warn Blended transforms not yet supported Zoom behavior may not work as expected if force_trans is not None if data is not None data transform force_trans transform data transform force_trans code display if ax is not None for c trans in data ax transData axes ax transAxes figure ax figure transFigure display transforms IdentityTransform if transform contains_branch trans code transform c transform trans break if data is not None if return_trans return code transform transform data transform else return code transform transform data elif return_trans return code transform else return code
"html font family - the typeface that will be applied by the web browser . the web browser will only be able to apply a font if it is available on the system which it operates . provide multiple font families , separated by commas , to indicate the preference in which to apply fonts if they are n't available on the system . the plotly service ( at https://plot.ly or on- premise ) generates images on a server , where only a select number of fonts are installed and supported . these include * arial * , * balto * , * courier new * , * droid sans * , , * droid serif * , * droid sans mono * , * gravitas one * , * old standard tt * , * open sans * , * overpass * , * pt sans narrow * , * raleway * , * times new roman*.",property def family self return self family
"the ' size ' property is a number and may be specified as : - an int or float in the interval [ 1 , inf ] - a tuple , list , or one - dimensional numpy array of the above",property def size self return self size
"starts the http server , and returns the port object that the server is listening on",inlineCallbacks def startService self super JunebugService self startService self api JunebugApi self self config yield self api setup self _port reactor listenTCP self config port Site self api app resource interface self config interface log msg Junebug is listening on s s self config interface self config port
return the intersection of 2 lists .,def intersection set1 set2 return s for s in set1 if s in set2
"when implemented , returns an empty instance of drived : class:`.mergable ` class .",classmethod abc abstractmethod def empty cls raise NotImplementedError
get the command function * name *,def get_command name command global_commands_table get name lower if not command raise CommandNotFound name return command
"replace the summary and body of the notification , and optionally its icon . you should call show ( ) again after this to display the updated notification .",def update self summary message icon None self summary summary self message message if icon is not None self icon icon
set current execution environment for whatever parallel mechanism is used .,def push env with _lock ident identifier _current_envs setdefault ident if _current_envs ident current _current_envs ident 1 current deactivate _current_envs ident append env env activate
"computes func(x , sel ) , with sel sampled from [ 0 ... num_cases-1 ] . args : x : input tensor . func : python function to apply . num_cases : python int32 , number of cases to sample sel from . returns : the result of func(x , sel ) , where func receives the value of the selector as a python integer , but sel is sampled dynamically .",def apply_with_random_selector x func num_cases sel tf random_uniform maxval num_cases dtype tf int32 return control_flow_ops merge func control_flow_ops switch x tf equal sel case 1 case for case in range num_cases 0
"converts time into a "" score "" . this is the inverse of the time with an arbitrary scale applied to get the number in a nice range . the goal here is to have benchmark results where faster = bigger number .",def get_score time return 1000 0 time
returns the path to the users 's grade file for the given assignment,def submission_results_grade cur_submission_root result_dir dir_submission_results cur_submission_root return os path join result_dir grade vmr
the bs with the best link,property def BS self return self _BS
create keyword with mkheader iraf tool i.e. without opening the whole file,def mkheader file keyword value comment verbose logfile status 0 message SALTKEY MKHEADER Created keyword keyword in file try tmpfile status saltio tmpfile False logfile tmp status saltio openascii tmpfile w logfile tmp write 8s 18s s n keyword value comment status saltio closeascii tmp logfile iraf noao artdata mkheader file tmpfile append y verbose n saltio delete tmpfile False logfile saltprint log logfile message verbose except message ERROR SALTKEY MKHEADER Cannot edit keyword keyword message in file status saltprint err logfile message return status
"install a library , taking account of the different rpath varients",feature cshlib after apply_implib before apply_vnum def apply_soname self if self env SONAME_ST and getattr self soname self env append_value LINKFLAGS self env SONAME_ST self soname self env SONAME_ST
get an instance of a browser that already logged in .,yield_fixture scope session def browser with _create_browser admin False as browser yield browser
"creating a new user populates the correct data , and sets the user 's account inactive .",def test_user_creation self new_user RegistrationProfile objects create_inactive_user site Site objects get_current self user_info self assertEqual new_user username alice self assertEqual new_user email alice example com self failUnless new_user check_password swordfish self failIf new_user is_active
get individual addresses for every cell in a range . yields one row at a time .,def cols_from_range range_string min_col min_row max_col max_row range_boundaries range_string for col in range min_col max_col 1 yield tuple s d get_column_letter col row for row in range min_row max_row 1
initialize an instance of loader .,def __init__ self parser self log logging getLogger web claims views Loader self parser parser
cube is z - rotated either through setrotation method or through particle layout . additional translation is applied if necessary . the result is compared with unrotated cube .,def testRotationX self box FormFactorBox 10 10 10 data_to_test box None None None None box RotationX 90 0 degree kvector_t 0 0 5 0 None None box None None RotationX 90 0 degree kvector_t 0 0 5 0 box RotationX 90 0 degree None None kvector_t 0 0 5 0 box RotationX 45 0 degree kvector_t 0 0 0 0 RotationX 45 0 degree kvector_t 0 0 5 0 reference_data self get_result data_to_test 0 isSuccess True for i in range 1 len data_to_test diff self get_difference reference_data data_to_test i print 0 1 diff 2 2e format self testRotationX __name__ i diff if diff 1e 10 isSuccess False self assertTrue isSuccess
gets the user_access_code attribute of this securitysettings instance .,property def user_access_code self return self _user_access_code
gets the allow_manage_account attribute of this hierarchyprivilege instance .,property def allow_manage_account self return self _allow_manage_account
logs the user out and returns the status,def logout request pass
trivial constructor just defining the fields that will store data,def __init__ self self homer_user self homer_password self homer_database_name homer self homer_database_host localhost self homer_webserver_type
uploads a part from a file object .,def upload_part_from_file self fp part_num length None md5 None close False rewind True extra_headers if length is not None extra_headers Content Length length if md5 is not None extra_headers Content MD5 md5 req UploadPartRequest self conn self key self bucket fp part_num self uploadId close rewind extra_headers rep self conn run req return rep
print a message to console based on logging level,def log self message level None level level or self INFO if level self DEBUG self debug message elif level self INFO self info message elif level self WARNING self warning message elif level self ERROR self error message else self none message
test the simulation approach vs exmp approach vs one - step approach,def test_sim_methods self a_matrix 0 0 1 0 1 0 0 0 b_vector 0 0 0 0 step_time 0 1 max_steps 10 sim_bundle SimulationBundle a_matrix b_vector make_settings step_time expm_settings make_settings step_time expm_settings sim_mode SimulationSettings MATRIX_EXP expm_bundle SimulationBundle a_matrix b_vector expm_settings vals None for s in xrange max_steps 1 vals_sim center_sim sim_bundle get_vecs_origin_at_step s max_steps vals_expm center_expm expm_bundle get_vecs_origin_at_step s max_steps vals vals_sim vals_expm centers center_sim center_expm for index in xrange len centers 0 self assertAlmostEquals centers 0 index centers 1 index places 5 self assertEquals vals 0 shape 0 vals 1 shape 0 for x in xrange 2 for y in xrange 2 self assertAlmostEqual vals 0 x y vals 1 x y places 5
create a global logger with given name .,def create_custom_logger name formatter logging Formatter fmt asctime s levelname s name s message s handler logging StreamHandler handler setFormatter formatter logger logging getLogger name logger setLevel logging DEBUG logger addHandler handler return logger
return the reverse and complementary of the give sequence,def rc_seq seq alphabetsInString ACGTNRMKWYSBDHVTGCANYKMWRSVHDBacgtnrmkwysbdhvtgcanykmwrsvhdb alphabets alphabetsInString i alphabetsInString i 15 for i in range 60 if i 15 or 30 i 44 return join alphabets base for base in seq 1
"since dictionaries in python are unsorted make sure that our outputs are correctly ordered . note : comparing strings to get "" correct order "" is based on the fact that p2sh_1 string is < p2sh_2 string in this particular case .",def swap_outputs_in_rawtx rawtx outputs inputnum outputs_unordered json dumps outputs cls DecimalEncoder outputs_ordered json dumps outputs sort_keys True cls DecimalEncoder if outputs_ordered outputs_unordered first_rawoutput rawtx 12 82 inputnum 12 82 inputnum 64 second_rawoutput rawtx 12 82 inputnum 64 12 82 inputnum 64 64 rawtx rawtx 0 12 82 inputnum second_rawoutput first_rawoutput rawtx 12 82 inputnum 64 64 return rawtx
set configuration items using a string of type ' a.b.param ',def set_config_item self config_item_string value config_item_path config_item_string split if len config_item_path 1 self config_item_path 0 value elif len config_item_path 2 and config_item_path 1 startswith item current_value self config_item_path 0 int config_item_path 1 replace item if hasattr current_value unit self config_item_path 0 int config_item_path 1 replace item u Quantity value current_value unit else self config_item_path 0 int config_item_path 1 replace item value else self config_item_path 0 set_config_item join config_item_path 1 value
does this filetracer have dynamic source file names ?,def has_dynamic_source_filename self return False
gets bjd from returned result at :,def GetBJD iJD 0 iRA 0 iDEC 0 iLAT 0 iLON 0 iALT 0 FF False assert FF True or FF False URL http astroutils astronomy ohio state edu time utc2bjd html if not isinstance iJD list ndarray iJD iJD JD_send for i e in enumerate iJD if i len iJD JD_send n format e else JD_send format e if FF is False driver webdriver PhantomJS elif FF is True driver webdriver Firefox driver get URL ra driver find_element_by_name ra ra send_keys iRA dec driver find_element_by_name dec dec send_keys iDEC jd driver find_element_by_name jds jd send_keys JD_send lat driver find_element_by_name lat lat send_keys iLAT lon driver find_element_by_name lon lon send_keys iLON alt driver find_element_by_name elevation alt send_keys iALT submit driver find_element_by_name submit click source driver page_source split n driver close try assert pre The 0th date not in source 5 except AssertionError as e e args BAD JD Error in input check JDs for validity are they all capable of being cast to floats JDs inputed iJD JDs sent JD_send raise index_val source index pre The following are the BJD_TDBs for each of your input dates close_val source index pre body html BJDs source index_val 2 close_val 3 BJDs float x for x in BJDs return BJDs
test binding in / out with set input sizes defined ( by type ),def testBindInOutSetInputSizesByType self vars self cursor setinputsizes p_Value cx_Oracle STRING self cursor execute u n begin n p_Value p_Value TSI n end p_Value u InVal self failUnlessEqual vars p_Value getvalue u InVal TSI
always uses ' setup.py test ' as args,def test_always_uses_setup_py_test_as_args self self subprocess call assert_called_once_with python setup py test
"will return either a buy , sell or wait signal for the given market",def signal self chart raise NotImplementedError
removes the timer including the callback from the internal storage .,def stop_timer self timer_id pass
returns the total on - sky time for this image .,def parse_tautime self subtables origin_table subtables LOFAR_ORIGIN startcol origin_table col START endcol origin_table col END series int start int end for start end in zip startcol endcol tau_time LofarCasaImage non_overlapping_time series return tau_time
: param texture : : return : three_min_filter value,_texture def min_filter texture logger debug texture min_filter s texture try val texture THREE_min_filter except AttributeError logger debug No THREE_min_filter attribute found val MIN_FILTER return val
@param name : a loader name .,def getDocFactory self name default None return self loaders get name default
l{createtechnician } returns an instance of a type which declares that it implements l{iofferingtechnician } and has all of the methods and attributes defined by the interface .,def test_interface self technician self createTechnician technicianType type technician self assertTrue ixmantissa IOfferingTechnician implementedBy technicianType self assertTrue verifyClass ixmantissa IOfferingTechnician technicianType self assertTrue verifyObject ixmantissa IOfferingTechnician technician
begin loading all pop - accessible messages into an in - memory list .,def kickoff self def _ ignored return self messageList return self coiterate _transactionally self _buildMessageList self store transact self pagesize addCallback _
zone list should be empty when no zones are defined,def test_zones_list_empty self register clear url reverse api zones list response self client get url format json self assertEqual response status_code status HTTP_200_OK self assertEqual response data count 0 self assertEqual len response data results 0
get named configuration option from git repository .,def git_config_get option default None u n Get named configuration option from git repository n try return subprocess check_output GIT u config u get option rstrip decode u utf 8 except subprocess CalledProcessError as e return default
select top k features . vary k and plot data,def feature_selection_trials global pos neg totals features retrain True if not retrain and os path isfile FDATA_FILE pos neg totals cPickle load open FDATA_FILE return words list set pos keys neg keys print Total no of features len words words sort key lambda w MI w num_features accuracy bestk 0 limit 500 path aclImdb test step 500 start 20000 best_accuracy 0 0 for w in words start features add w for k in xrange start 40000 step for w in words k k step features add w correct 0 size 0 for file in os listdir path pos limit correct classify open path pos file read True size 1 for file in os listdir path neg limit correct classify open path neg file read False size 1 num_features append k step accuracy append correct size if correct size best_accuracy bestk k print k step correct size features set words bestk cPickle dump get_relevant_features open FDATA_FILE w pylab plot num_features accuracy pylab show
"ensure a beehive resource exists as attribute in the beehive context . if this is not the case , the attribute is created by using the default_value .",def ensure_context_attribute_exists context name default_value None if not hasattr context name setattr context name default_value
"returns the last error in tuple format ( code , message ) .",def last_error self return self _session last_error
extract data from pandas . dataframe for labels,def extract_pandas_labels labels if isinstance labels pd DataFrame if len labels columns 1 raise ValueError Only one column for labels is allowed if all dtype name in PANDAS_DTYPES for dtype in labels dtypes return labels values astype float else raise ValueError Data types for labels must be int float or bool else return labels
"merge the properties of "" dev "" into this device .",def merge_from self dev if dev job is not None self job dev job if dev replica is not None self replica dev replica if dev task is not None self task dev task if dev device_type is not None self device_type dev device_type if dev device_index is not None self device_index dev device_index
convenience method for structured logging .,emit info def struct self kwargs return self fields kwargs
iterate through terminal symbols in no particular order .,def iterterminals self return iter self _sigma
instantiate a dialect class by name .,def get_dialect name None u return available_dialects output u map name
find out the correspondence between layer names and parameter names .,def param_name_dict layer caffe_pb2 LayerParameter param_names f name for f in layer DESCRIPTOR fields if f name endswith _param param_type_names type getattr layer s __name__ for s in param_names param_names s len _param for s in param_names param_type_names s len Parameter for s in param_type_names return dict zip param_type_names param_names
all arguments except for server_hostname and ssl_context have the same meaning as they do when using : func:`ssl.wrap_socket ` .,def ssl_wrap_socket sock keyfile None certfile None cert_reqs None ca_certs None server_hostname None ssl_version None ciphers None ssl_context None context ssl_context if context is None context create_urllib3_context ssl_version cert_reqs ciphers ciphers if ca_certs try context load_verify_locations ca_certs except IOError as e raise SSLError e except OSError as e if e errno errno ENOENT raise SSLError e raise if certfile context load_cert_chain certfile keyfile if HAS_SNI return context wrap_socket sock server_hostname server_hostname return context wrap_socket sock
main entry point function for plugin,def Plugin_Start mac_info u airport_pref_plist_path u Library Preferences SystemConfiguration com apple airport preferences plist mac_info ExportFile airport_pref_plist_path __Plugin_Name u False success plist error mac_info ReadPlist airport_pref_plist_path if success networks ReadAirportPrefPlist plist networks if len networks 0 PrintAll networks mac_info output_params airport_pref_plist_path else log info u No wifi networks found else log error u Could not open plist airport_pref_plist_path log error u Error was error
function to read in the fits file from oculus . - find the 99.5 % value - make all values above 99.5 % value white - write image array to a png,def make_image fitsfile FILENAME_FITS pngfile FILENAME_PNG data fits getdata fitsfile max_val percentile data 99 5 scaled data 256 0 max_val new_scaled ma masked_greater scaled 255 0 new_scaled fill_value 255 0 img_data new_scaled filled result Image fromarray img_data astype uint8 font ImageFont truetype usr share fonts truetype dejavu DejaVuSansMono ttf 24 textstamp Brecon Beacons All Sky s datetime now strftime Y m d H M draw ImageDraw Draw result draw text 10 10 textstamp font font fill 255 result save pngfile return
there was a syntax error in c{filename}.,def syntaxError self filename msg lineno offset text line text splitlines 1 if offset is not None offset offset len text len line self _stderr write s d d s n filename lineno offset 1 msg else self _stderr write s d s n filename lineno msg self _stderr write line self _stderr write n if offset is not None self _stderr write re sub S line offset n
turn a datetime into a date string as specified in rfc 2822 .,def format_datetime dt usegmt False u Turn a datetime into a date string as specified in RFC 2822 n n If usegmt is True dt must be an aware datetime with an offset of zero In n this case GMT will be rendered instead of the normal 0000 required by n RFC2822 This is to support HTTP headers involving date stamps n now dt timetuple if usegmt if dt tzinfo is None or dt tzinfo datetime timezone utc raise ValueError u usegmt option requires a UTC datetime zone u GMT elif dt tzinfo is None zone u 0000 else zone dt strftime u z return _format_timetuple_and_zone now zone
tests methods common to all properties,def testBasicROProperty propRef cbRef global DESC print testBasicROProperty print Testing propRef attributes print name propRef _get_name print characteristic_component_name propRef _get_characteristic_component_name print description propRef _get_description print format propRef _get_format print units propRef _get_units print resolution propRef _get_resolution print default_timer_trigger propRef _get_default_timer_trigger print min_timer_trigger propRef _get_default_timer_trigger print default_value propRef _get_default_value print print Testing propRef methods print get_characteristic_by_name propRef get_characteristic_by_name no_name print find_characteristic propRef find_characteristic no regular expression print get_all_characteristics propRef get_all_characteristics print get_sync propRef get_sync print get_async propRef get_async cbRef DESC print create_monitor propRef create_monitor cbRef DESC print create_postponed_monitor propRef create_postponed_monitor 10000000L cbRef DESC
method invoked to alter the behavior of some simulated corba method / attribute,def submit self event None method_name self comp_method if self operation_type Attributes method_name _get_ method_name temp_dict Value None Timeout float self sleepCounter getvalue temp_dict Value self st getvalue strip split n temp_dict Value getCompLocalNSList self comp_name temp_dict Value temp_dict Value listToCodeObj temp_dict Value getSimProxy self comp_name gui_handler setMethod method_name temp_dict
returns an optimal policy assuming the next value function is v v is a list of values for each state returns a list of the indexes of optimal actions for each state,def policy self v return argmax enumerate self reward s a self discount product self trans s a v for a in range len self actions for s in range len self states
get the cooling states of one or more cpufreq cooling device(s ) ( all by default ),def _dfg_cpufreq_cooling_state self cpus None df self _dfg_trace_event thermal_power_cpu_limit df df cpus freq cdev_state if cpus is not None masks self _matchingMasks cpus df df df cpus isin masks return df
"build a shutdown handler , called from the signal methods in response to e.g. sigterm",def get_shutdown_handler message None def handler signum frame display show Service shutdown message motors disable exit 0 return handler
parse p_tags_file xml tags file and store it in memory .,def _parse_tags_file self p_tags_file l_tags_doc xml dom minidom parse p_tags_file l_xml_root_element l_tags_doc getElementsByTagName tags 0 for i_tag_node in l_xml_root_element getElementsByTagName tag l_raw_tag for i_key in length name position channelNumber l_raw_tag i_key i_tag_node getAttribute i_key for i_node in i_tag_node childNodes try l_raw_tag i_node tagName i_node firstChild nodeValue except AttributeError pass self _tags append tag_utils unpack_tag_from_dict l_raw_tag def cmp_tags t1 t2 ts1 t1 start_timestamp ts2 t2 start_timestamp if ts1 ts2 return 0 elif ts1 ts2 return 1 else return 1 self _tags sort cmp_tags
configure system for the unit test @param self : essential if you override this definition @return : boolean - if successful true ; if failure false @author : ekkehard j. koch,def setConditionsForRule self success True return success
check on whether fix was correct @param self : essential if you override this definition @param prulesuccess : did report run successfully @return : boolean - if successful true ; if failure false @author : ekkehard j. koch,def checkFixForRule self pRuleSuccess self logdispatch log LogPriority DEBUG pRuleSuccess str pRuleSuccess success True return success
this is the main worker of the dbhandler . it requires the metadata dictonary and the findings list of tuples .,def loaddata self metadata findings try if RuleCount in metadata cur self con cursor cur execute INSERT INTO RunMetaData RunTime HostName UploadAddress IPAddress OS PropertyNumber SystemSerialNo ChassisSerialNo SystemManufacturer ChassisManufacturer UUID MacAddress xmlFileName STONIXversion RuleCount VALUES s s s s s s s s s s s s s s s metadata RunTime metadata Hostname metadata UploadAddress metadata IPAddress metadata OS metadata PropertyNumber metadata SystemSerialNo metadata ChassisSerialNo metadata SystemManufacturer metadata ChassisManufacturer metadata UUID metadata MACAddress metadata xmlFileName metadata STONIXversion metadata RuleCount cur execute SELECT RowId from RunMetaData WHERE xmlFileName s metadata xmlFileName row cur fetchone runid row 0 for key in findings cur execute INSERT INTO RunData MetaDataId Rule Finding VALUES s s s runid key findings key else cur self con cursor cur execute INSERT INTO RunMetaData RunTime HostName UploadAddress IPAddress OS PropertyNumber SystemSerialNo ChassisSerialNo SystemManufacturer ChassisManufacturer UUID MacAddress xmlFileName STONIXversion RuleCount VALUES s s s s s s s s s s s s s s metadata RunTime metadata Hostname metadata UploadAddress metadata IPAddress metadata OS metadata PropertyNumber metadata SystemSerialNo metadata ChassisSerialNo metadata SystemManufacturer metadata ChassisManufacturer metadata UUID metadata MACAddress metadata xmlFileName metadata STONIXversion 999999 cur execute SELECT RowId from RunMetaData WHERE xmlFileName s metadata xmlFileName row cur fetchone runid row 0 for key in findings cur execute INSERT INTO RunData MetaDataId Rule Finding VALUES s s s runid key findings key except mdb Error as err if self con self con close sys exit 1
return information about the yum exit codes,def yumCodes self ecode msg No further information available codeDict 0 Success 1 An error occurred 100 There are packages available for update try msg str codeDict ecode except KeyError as err self logger log LogPriority DEBUG str err return msg
"pygame.cursors.compile(strings , black , white , xor ) - > data , mask compile cursor strings into cursor data",def compile strings black X white xor o size len strings 0 len strings if size 0 8 or size 1 8 raise ValueError cursor string sizes must be divisible by 8 s size for s in strings 1 if len s size 0 raise ValueError Cursor strings are inconsistent lengths maskdata filldata maskitem fillitem 0 step 8 for s in strings for c in s maskitem maskitem 1 fillitem fillitem 1 step step 1 if c black maskitem maskitem 1 fillitem fillitem 1 elif c white maskitem maskitem 1 elif c xor fillitem fillitem 1 if not step maskdata append maskitem filldata append fillitem maskitem fillitem 0 step 8 return tuple filldata tuple maskdata
this layer does not propagate gradients .,def backward self top propagate_down bottom pass
returns a list of all options that have a non - default value,def get_configured_options ret for sname in DEFAULTS for key in _configuration configured_keys sname ret append s s sname key return ret
returns true if the fpga is programmed,def is_programmed self raise AssertionError s not implemented sys _getframe f_code co_name
writes a 16-bit word to the specified command register,def write_word self cmd value self bus write_word_data self address cmd value self log debug write_word Wrote 0x 04X to command register 0x 02X value cmd
@see l{nulldatastorer < datafinder.persistence.data.datastorer . nulldatastorer > },def __init__ self identifier persistenceIdentifier serverNodeName connectionPool NullDataStorer __init__ self identifier self _persistenceIdentifier persistenceIdentifier self _serverNodeName serverNodeName self _connectionPool connectionPool
tests the comparison of two instances .,def testComparison self self assertEquals self _store self _store self assertEquals self _store datastore DefaultDataStore self _store name self assertNotEquals self _store datastore DefaultDataStore anotherName self assertNotEquals self _store None
@see : l{nullprivilegestorer < datafinder.persistence.privileges.privilegestorer . nullprivilegestorer > },def retrievePrivileges self connection self __connectionPool acquire try webdavStorer self __connectionHelper createResourceStorer self __persistenceId connection try options webdavStorer options except WebdavError as error raise PersistenceError error reason else privileges list if allow in options privileges self _mapHttpOptionsToPrivileges options allow return privileges finally self __connectionPool release connection
retrieves the file content of the associated item and returns its local path .,staticmethod def _getContent item dataUri item dataUri print item dataUri if not item isManaged and dataUri startswith file localContentPath dataUri 8 temporaryFileObject None else localContentPath temporaryFileObject item getTemporaryFileObject False temporaryFileObject close return localContentPath temporaryFileObject is None
getter for the data store configuration handler .,property def dataStoreHandler self return self _dataStoreHandler
this function is executed when we start to scan create a thread by each scan : param arguments : it is a command : return : none,def start self arguments if not self __IP MessageBox critical Error IP not found elif not arguments MessageBox critical Error Command is empty elif self __scanThread isRunning MessageBox critical Error A scanning is running else self __view setState scan self __IP str self __projectFile readValue Information IP self __scanThread host self __IP self __scanThread arguments arguments self __scanThread start
"pass in array of json objects , a dictionary with key / value pairs to match against , and another dictionary with expected key / value pairs .",def check_array_result object_array to_match expected num_matched 0 for item in object_array all_match True for key value in to_match items if item key value all_match False if not all_match continue for key value in expected items if item key value raise AssertionError s expected s s str item str key str value num_matched num_matched 1 if num_matched 0 raise AssertionError No objects matched s str to_match
return a copy of dictionary * d * with keys with value `` none `` removed .,def clear_nones d if not isinstance d dict return d else return dict k clear_nones v for k v in d iteritems if clear_nones_filter v
"adds a shortcut between input and residual block and merges them with "" sum """,def _shortcut input residual input_shape K int_shape input residual_shape K int_shape residual stride_width int round input_shape ROW_AXIS residual_shape ROW_AXIS stride_height int round input_shape COL_AXIS residual_shape COL_AXIS equal_channels input_shape CHANNEL_AXIS residual_shape CHANNEL_AXIS shortcut input if stride_width 1 or stride_height 1 or not equal_channels shortcut Conv2D filters residual_shape CHANNEL_AXIS kernel_size 1 1 strides stride_width stride_height padding valid kernel_initializer he_normal kernel_regularizer l2 regularizer_rate input return add shortcut residual
render a request . this is called on the leaf resource for a request .,def render request
return true if s1 < s2 .,def vtkVariantLessThan s1 s2 return vtk vtkVariant s1 vtk vtkVariant s2
convert a long to a bytestring,def _long_to_bytes n length byteorder u Convert a long to a bytestring n n For use in python version prior to 3 2 n Source n http bugs python org issue16580 msg177208 n if byteorder u little indexes list range length else indexes reversed list range length return bytearray n i 8 255 for i in indexes
mute microphone and increase number of requests to mute,def mute self self mute_calls 1 if self microphone self microphone mute
show the dialog as a child process,def call self import webbrowser webbrowser open_new_tab self url
: type head : listnode : type k : int : rtype : listnode,def rotateRight self head k if head is None return if head next is None return head pre ListNode None pre next head cur head l 0 while cur l 1 if cur is not head cur prev pre cur cur next pre pre next cur pre head prev cur for _ in range k l cur prev next None cur next head head cur cur cur prev return head
replace unprintable characters in a text with a default one .,def printable text default alphabet None if alphabet is None alphabet unicode_printable return join i if i in alphabet else default for i in text
plot phase tensor map in lat - long ( unprojected ) coordinate system : param edi_file_list : a list of edi files : param freq : the frequency value ( within a certain tolerance ftol ) : param save_path : path to file / dir to save the plot as jpg or png file : return :,def plot_pt edi_file_list freq save_path None ellipse_dict size 0 2 colorby phimin range 0 90 1 cmap mt_bl2gr2rd arrow_dict size 0 5 lw 0 2 head_width 0 04 head_length 0 04 threshold 0 8 direction 0 pt_obj PlotPhaseTensorMaps fn_list edi_file_list plot_freq freq ftol 0 1 mapscale deg xpad 0 4 ypad 0 4 ellipse_dict ellipse_dict plot_tipper yr arrow_dict arrow_dict save_fn save_path path2figure pt_obj plot save_path save_path pt_obj export_params_to_file save_path save_path print Please check your output figure s path2figure return
create title as main control .,def create_title self vbox Gtk VBox new False 0 self _title_label Gtk Label new self _title_label set_alignment 0 0 5 self _title_label set_use_markup True self _title_label set_ellipsize Pango EllipsizeMode MIDDLE font Pango FontDescription 8 self _subtitle_label Gtk Label new self _subtitle_label set_alignment 0 0 5 self _subtitle_label set_use_markup False self _subtitle_label modify_font font vbox pack_start self _title_label True True 0 vbox pack_start self _subtitle_label False False 0 self _container pack_start vbox True True 0
checks if logo has the correct dimensions and extension,def check_image form param logo form cleaned_data param if logo is not None image Image open logo mode r xsize ysize image size ext image format in VALID_FORMATS return xsize WIDTH and ysize HEIGHT and ext else return True
"get the input elements that will be transformed into tasks in a generic way . the elements themselves are free - form , and become the input to the first transform .",def loader kind path config params loaded_tasks u n Get the input elements that will be transformed into tasks in a generic n way The elements themselves are free form and become the input to the n first transform n n By default this reads jobs from the jobs key or from yaml files n named by jobs from The entities are read from mappings and the n keys to those mappings are added in the name key of each entity n n If there is a job defaults config then every job is merged with it n This provides a simple way to set default values for all jobs of a n kind More complex defaults should be implemented with custom n transforms n n Other kind implementations can use a different loader function to n produce inputs and hand them to transform_inputs n def jobs defaults config get u job defaults jobs config get u jobs iteritems jobs_from itertools chain from_iterable load_yaml path filename iteritems for filename in config get u jobs from for name job in itertools chain jobs jobs_from if defaults job merge defaults job yield name job for name job in jobs job u name name logger debug u Generating tasks for format kind name yield job
stop the process via a custom signal and test properties,def test_stop_process_custom_signal self self runner start returncode self runner stop signal SIGTERM self assertFalse self runner is_running self assertNotIn returncode None 0 self assertEqual self runner returncode returncode self assertIsNotNone self runner process_handler self assertEqual self runner wait 1 returncode
look up the checksum for the given installer .,def rustup_hash host return RUSTUP_HASHES get host None
the : class:`downloadingpanel ` instance for the downloading panel .,property def downloading self return self _create_panel_for_id downloading
issue get request to a given url and return the response .,def get url import requests logger debug GET s url resp requests get url stream True resp raise_for_status return resp
"return a jarreader for the given basefile instance , keeping a log of the preloaded entries it has .",def _open_jar self path file jar JarReader fileobj file open if jar is_optimized self optimizedjars True if not any f compressed for f in jar self compressed False if jar last_preloaded jarlog jar entries keys self jarlogs path jarlog jarlog index jar last_preloaded 1 return jar
-u mochitest - webgl sets unittests=[mochitest - webgl ],def test_u_single self u tos TryOptionSyntax u try u mochitest webgl graph_with_jobs self assertEqual sorted tos unittests sorted u test u mochitest webgl
holds a reference to a : class:`marchannels ` object .,property def mar_channels self return self _mar_channels
"when showing possible requests to add , only show projects the user is a contributor to . if the user is unauthenticated , return no projects however , if the user is staff , then show them all the available projects .",def choices_for_request self self choices Project objects get_manager self request user return super ProjectManagerAutocomplete self choices_for_request
contributors should be able to edit projects .,def test_contributor self response http_get_response self url self view self contributor self kwargs eq_ response status_code 200
posting data for a crowdfund should create it .,def test_post self user UserFactory is_staff True name Project Crowdfund description A crowdfund payment_required 100 payment_capped True date_due date today timedelta 20 data name name description description payment_required payment_required payment_capped payment_capped date_due date_due request self request_factory post self url data request user user request mock_middleware request response self view request slug self project slug pk self project pk self project refresh_from_db eq_ self project crowdfunds count 1 A crowdfund should be created and added to the project crowdfund self project crowdfunds first eq_ crowdfund name name eq_ crowdfund description description expected_payment_required Decimal payment_required payment_required 0 15 100 eq_ crowdfund payment_required expected_payment_required Expected payment of expected 2f actually actual 2f expected expected_payment_required actual crowdfund payment_required eq_ crowdfund payment_capped payment_capped eq_ crowdfund date_due date_due eq_ response status_code 302
measure bed temperature . : return : temperature in celsius .,def get_bed_temperature return thermistor get_temperature BED_TEMPERATURE_SENSOR_CHANNEL
decorator for registering methods that provide bgps public api .,def register_method name def decorator func setattr func __api_method_name__ name return func return decorator
simple shortcut for indicating a 302 redirect in a django routing file .,def temporaryRedirect targetUrl return RedirectView as_view url targetUrl permanent False
collapse / expand particular module in the table of results,def collapseModule self headerRow doCollapse name headerRow id table document getElementById tableId clsName getRowClsName name allRows table tHead children rows filter lambda x x classList contains clsName allRows for row in rows self setCollapsed row doCollapse if doCollapse headerRow classList add self modCollapseClass else headerRow classList remove self modCollapseClass
finds all non indexed foreign keys from all tables of given metadata .,def non_indexed_foreign_keys metadata engine None reflected_metadata MetaData if metadata bind is None and engine is None raise Exception Either pass a metadata object with bind or pass engine as a second parameter constraints defaultdict list for table_name in metadata tables keys table Table table_name reflected_metadata autoload True autoload_with metadata bind or engine for constraint in table constraints if not isinstance constraint ForeignKeyConstraint continue if not has_index constraint constraints table name append constraint return dict constraints
equivalent radius @param radius : core radius @param thickness : shell thickness,def ER radius thickness return radius thickness
"call func(*args , * * kw ) with a timeout of second seconds .",def limitedTime second func args kw return func args kw
"set a prefered ffi backend ( cffi , ctypes ) .",def set_backend name None possible list _BACKENDS if name is None names else names name split for name in reversed names for backend in list possible if backend NAME name possible remove backend possible insert 0 backend break else raise LookupError Unkown backend r name if null not in names possible b for b in possible if b NAME null _ACTIVE_BACKENDS possible
convert an http response 's status code to a readable string .,def status response return HTTP_STATUS response status_code lower
schedules an action to be executed .,def schedule self action state None return self schedule_relative 0 action state
param dork string dork to add it to url engin,def prepareEngin self dork page engin self options get engin lower if engin in bing return self engins get engin format dork page else domain choice self googleDot return self engins get engin format domain self connector queryEncode dork page
returns a humanized string representing time difference,def humanize_duration duration days duration days hours duration seconds 3600 minutes duration seconds 3600 60 seconds duration seconds 3600 60 parts if days 0 parts append u s s days _ day if days 1 else _ days if hours 0 parts append u s s hours _ hour if hours 1 else _ hours if minutes 0 parts append u s s minutes _ minute if minutes 1 else _ minutes if seconds 0 parts append u s s seconds _ second if seconds 1 else _ seconds return join parts if len parts 0 else _ 1 second
parse profile_file ( output from vim 's : profile ) and write it into data_file ( coverage.py compatible ) .,main command click argument profile_file type click File r required False nargs 1 click option data file required False show_default True default DEFAULT_COVERAGE_DATA_FILE type click File mode w click option source type click types Path exists True help Source files dirs to include This is necessary to include completely uncovered files show_default True multiple True def write_coverage profile_file data_file source m MergedProfiles source source m add_profile_files profile_file if not m write_coveragepy_data data_file data_file raise CustomClickException No data to report
verifies the task is authorized to perform rpcs .,def do_POST self if self client_address 0 self server authorized_address logging error Received unauthorized RPC request from s self task_address 0 self send_response 403 response Forbidden self send_header Content type text plain self send_header Content length str len response self end_headers self wfile write response else return SimpleJSONRPCServer SimpleJSONRPCRequestHandler do_POST self
logs |msg| to stderr regardless of --flags .,def _log_error self msg print sys stderr ERROR s msg
calculates tests_location when mode is --remaining .,def process_builder_remaining data filename builder tests_location for test in data gtest_tests name test test if test get swarming get can_use_on_swarming_builders tests_location name count_run_on_swarming 1 else tests_location name count_run_local 1 tests_location name local_configs setdefault filename append builder
loads file_path into the in - memory resource map .,def AddFileToResourceMap self file_path file_path os path realpath file_path if file_path in self resource_map return with open file_path rb as fd response fd read fs os fstat fd fileno content_type mimetypes guess_type file_path 0 zipped False if content_type in text html text css application javascript zipped True sio StringIO StringIO gzf gzip GzipFile fileobj sio compresslevel 9 mode wb gzf write response gzf close response sio getvalue sio close self resource_map file_path content type content_type content length len response last modified fs st_mtime response response zipped zipped index index html if os path basename file_path index dir_path os path dirname file_path self resource_map dir_path self resource_map file_path
shuts down the process started by launch .,def Shutdown self self _DeleteAVD if self popen self popen poll if self popen returncode None self popen kill self popen None
second derivative of radial coordinate with respect to compactified,def get_d2rdX2 self X d2Xdr2 self get_d2Xdr2 X with np errstate invalid ignore d2rdX2 1 0 d2Xdr2 return d2rdX2
returns the root mean squared logarithmic error of predictions,def rmsle y df df2 p False prediction np asarray df y actual np asarray df2 y rsmle np sqrt np mean np power np log actual 1 np log prediction 1 2 if p print rsmle 0 format rsmle return rsmle
add child to the node .,def add_child self a_node if not isinstance a_node Node raise TypeError argument should be Node class self children append a_node a_node set_parent self
ask the user to answer by yes or no,def ask_yes_no question default False while True if default ui info ui green ui reset question Y n else ui info ui green ui reset question y N answer read_input if answer lower in y yes return True if answer lower in n no return False if not answer return default ui warning Please answer by yes or no
": param order : list of indexes in which to print objects , ordered by printing order . : param todo : list of indexes which are not yet inserted into the order list .",def __init__ self order todo self order order self todo todo
can only handle specification * data * in dictionary format .,def revcmap data data_r for key val in data items if isinstance val collections Callable valnew _reverser val else valnew 1 0 x y1 y0 for x y0 y1 in reversed val data_r key valnew return data_r
selects and return n random ports that are available .,def select_random_ports n ports for i in xrange n sock socket socket sock bind 0 while sock getsockname 1 in _random_ports sock close sock socket socket sock bind 0 ports append sock for i sock in enumerate ports port sock getsockname 1 sock close ports i port _random_ports add port return ports
"safely check for pyqt4 or pyside , without importing submodules",def has_binding api module_name QT_API_PYSIDE PySide QT_API_PYQT PyQt4 QT_API_PYQTv1 PyQt4 QT_API_PYQT_DEFAULT PyQt4 module_name module_name api import imp try mod __import__ module_name imp find_module QtCore mod __path__ imp find_module QtGui mod __path__ imp find_module QtSvg mod __path__ if api QT_API_PYSIDE return check_version mod __version__ 1 0 3 else return True except ImportError return False
add multiple engines to our cluster,def add_engines self n 1 block True self engines extend add_engines n if block self wait_on_engines
"find optimization opportunities in adds , muls , pows and negative coefficient muls",def opt_cse exprs order canonical from sympy matrices import Matrix opt_subs dict adds set muls set seen_subexp set def _find_opts expr if expr is_Atom return if iterable expr list map _find_opts expr return if expr in seen_subexp return expr seen_subexp add expr list map _find_opts expr args if _coeff_isneg expr neg_expr expr if not neg_expr is_Atom opt_subs expr Mul S NegativeOne neg_expr evaluate False seen_subexp add neg_expr expr neg_expr if expr is_Mul muls add expr elif expr is_Add adds add expr elif expr is_Pow if _coeff_isneg expr exp opt_subs expr Pow Pow expr base expr exp S NegativeOne evaluate False for e in exprs if isinstance e Basic _find_opts e def _match_common_args Func funcs if order none funcs list ordered funcs else funcs sorted funcs key lambda x len x args func_args set e args for e in funcs for i in xrange len func_args for j in xrange i 1 len func_args com_args func_args i intersection func_args j if len com_args 1 com_func Func com_args diff_i func_args i difference com_args func_args i diff_i set com_func if diff_i opt_subs funcs i Func Func diff_i com_func evaluate False diff_j func_args j difference com_args func_args j diff_j set com_func opt_subs funcs j Func Func diff_j com_func evaluate False for k in xrange j 1 len func_args if not com_args difference func_args k diff_k func_args k difference com_args func_args k diff_k set com_func opt_subs funcs k Func Func diff_k com_func evaluate False comutative_muls set for m in muls c nc m args_cnc cset True if c c_mul Mul c if nc opt_subs m Mul c_mul Mul nc evaluate False if len c 1 comutative_muls add c_mul _match_common_args Add adds _match_common_args Mul comutative_muls return opt_subs
"write data to the log file , if active",def log_write self data kind input if self log_active and data write self logfile write if kind input if self timestamp write str_to_unicode time strftime a d b Y H M S n time localtime write data elif kind output and self log_output odata u n join u Out s s for s in data splitlines write u s n odata self logfile flush
the callables ' func ' and ' deriv_func ' have no ' _ _ name _ _ ' attribute .,def test_wrong_shape_Dfun_callable self func ReturnShape 1 deriv_func ReturnShape 2 2 assert_raises TypeError optimize leastsq func x0 0 1 Dfun deriv_func
"scale the coordinates of the point by multiplying by `` x `` and `` y `` after subtracting `` pt `` -- default is ( 0 , 0 ) -- and then adding `` pt `` back again ( i.e. `` pt `` is the point of reference for the scaling ) .",def scale self x 1 y 1 pt None if pt pt Point pt return self translate pt args scale x y translate pt args return Point self x x self y y
"delete by group , type and i d e.g. delete https://backdrop / data / gcloud / sales / mjaxni0woc0xnsawmdowmd",app route data data_group data_type data_set_id methods DELETE cache_control nocache statsd timer write route data delete data_set def delete_by_group_type_and_id data_group data_type data_set_id data_set_config admin_api get_data_set data_group data_type _validate_config data_set_config _validate_auth data_set_config try errors _delete_data_set data_set_config data_set_id if errors return jsonify messages errors 400 return jsonify status ok except ParseError ValidationError as e abort 400 repr e
return list of features and their importance in classification,def feature_importances self feature_names feature for feature in self features train return list zip feature_names self feature_importances_
"writes help text for a sub - section of commands , specifically to be reused for resource commands and system / configuration commands .",def format_command_subsection self ctx formatter commands header rows for subcommand in commands cmd self get_command ctx subcommand if cmd is None continue help cmd short_help or rows append subcommand help if rows with formatter section header formatter write_dl rows
changed values are saved to all tickets .,def test_save_values self first_ticket_id self _insert_ticket Test 1 reporter joe component foo second_ticket_id self _insert_ticket Test 2 reporter joe selected_tickets first_ticket_id second_ticket_id new_values component bar batch BatchModifyModule self env batch _save_ticket_changes self req selected_tickets new_values leave self assertFieldChanged first_ticket_id component bar self assertFieldChanged second_ticket_id component bar
executes a simple tensorflow function .,def testFunction self def APlus2B a b return a b 2 aval np array 4 3 2 1 reshape 2 2 astype np float32 bval np array 5 6 7 8 reshape 2 2 astype np float32 expected APlus2B aval bval with self test_session as sess function Defun dtypes float32 dtypes float32 def Foo a b return APlus2B a b a constant_op constant aval name a b constant_op constant bval name b with self test_scope call_f Foo a b result sess run call_f self assertAllClose result expected rtol 0 001
read text file in path and return a list of integer token ids .,def tokenize self path tokens 0 with tf gfile Open path r as f for line in f words line split eos tokens len words for word in words self add word with tf gfile Open path r as f ids np zeros tokens astype np int64 token 0 for line in f words line split eos for word in words ids token self word2idx word token 1 return ids
"fit upper harmonic function to a set of ( angle , intensity ) pairs .",def fit_upper_harmonic phi intensities order u n Fit upper harmonic function to a set of angle intensity pairs n n With order set to 3 or 4 the resulting amplitudes divided by n the semimajor axis length and local gradient measure the deviations n from perfect ellipticity n n The harmonic function that is fit is n n math n y phi order y0 An sin order phi Bn cos order phi n n Parameters n n phi float or numpy ndarray n The angle s along the elliptical path going towards the positive n y axis starting coincident with the position angle That is the n angles are defined from the semimajor axis that lies in n the positive x quadrant n intensities numpy ndarray n The intensities measured along the elliptical path at the n angles defined by the phi parameter n order int n The order of the harmonic to be fitted n n Returns n n y0 An Bn float n The fitted harmonic values n an bn 1 0 def optimize_func x return x 0 x 1 np sin order phi x 2 np cos order phi intensities return _least_squares_fit optimize_func np mean intensities an bn
set the custom policy rules to override .,def set_rules self rules overwrite True if isinstance rules dict rules oslo_policy Rules from_dict rules self expected_policy_actions extend rules policy armada common policy _ENFORCER policy set_rules rules overwrite overwrite
crawls all tweets which mention the bot from the twitter rest api .,def crawl self reports try if not self waiting if self last_mention 0 mentions self api mentions_timeline else mentions self api mentions_timeline since_id self last_mention for status in mentions text re sub a zA Z0 9 _ A Za z A Za z0 9 _ status text reports append report Report status author screen_name twitter text status id status created_at self save_last return reports except tweepy RateLimitError logger error Twitter API Error Rate Limit Exceeded exc_info True self waitcounter 60 15 1 except requests exceptions ConnectionError logger error Twitter API Error Bad Connection exc_info True self waitcounter 10 except tweepy TweepError logger error Twitter API Error General Error exc_info True return
check if this object has the same properties as another content object .,def __eq__ self other return hasattr other properties and self properties other properties
parse the annotation and add it to interval metadata .,def parse self self result sid imd for sid imd in read self files gff format gff3
extract all of the names from a fasta file,def extract_names fasta names for record in FastaReader fasta name record name split 0 names append name return names
register custom lint checkers with pylint . any new checkers should also be registered here .,def register linter linter register_checker ClusterRunnerTokenChecker linter
returns all the animation related properties as a dictionary,def animation_properties self properties animation name animation duration 0 animation delay 0 animation iteration count 1 animation timing function ease for key in properties if self properties get key value self properties get key properties key value get value return properties
invoke map_func on each file in sim_files and reduce results using reduce_func .,def map_reduce_files files map_func reduce_func if len files x map map_func files return reduce reduce_func x else raise TypeError No files
"we need to convert a dictionary where keys and values are bytes , to unicode strings . this happens when a python 2 master sends a dictionary back to a python 3 worker .",def decode data encoding utf 8 errors strict data_type type data if data_type bytes return bytes2unicode data encoding errors if data_type in dict list tuple if data_type dict data iteritems data return data_type map decode data return data
this will be called when shutting down,def on_shutdown self pass
extract the tonic pitch class of the key .,def _extract_tonic self meta_element key_element meta_element find key Key if not key_element or not key_element string logger error s has no key element self filename return None if key_element string not in self NOTE_TO_PITCH_CLASS logger error s has unrecognized key s self filename key_element string return None return self NOTE_TO_PITCH_CLASS key_element string
"take the column , and normalize it with the computed means and std devs .",def _transform self row mean self means self current_column stddev self stddevs self current_column x row self current_column x_normalized x mean stddev output_column self current_column self column_suffix new_row new_dataframe_row row output_column x_normalized return new_row
create a new relationship between two existing documents .,def document_rels request record document_id_0 rel document_id_1 try document_0 Document objects get id document_id_0 relationship DocumentSchema objects get type DocumentSchema expand_rel rel document_1 Document objects get id document_id_1 DocumentRels objects create document_0 document_0 document_1 document_1 relationship relationship except Document DoesNotExist raise Http404 except DocumentSchema DoesNotExist raise Http404 return DONE
get the serialized python object .,def get_object self envname modname varname iteration None nc_path envname modname varname format envname envname modname modname varname varname if iteration is not None pickled self _ncfile nc_path iteration else pickled self _ncfile nc_path 0 obj pickle loads codecs decode pickled encode base64 return obj
get all dates from the time series as ` datetime ` instances .,property def dates self return to_datetime timestamp for timestamp _ in self points
return dic.items ( ) using list instead of tuple .,def itemsList dic return map list dic items
converts a call log into a pandas data frame . this function errors if you do n't have pandas available .,def call_log2dataframe log if not _pandas_available raise NotImplementedError This function requires pandas args log args values log values hpar_names args keys zipped zip zip args values values dictlist dict k v for k v in zip hpar_names args value value for args value in zipped df pandas DataFrame dictlist return df
"send an http request , and catch any exception that might occur due to connection problems .",def _send_request_safe_mode self method url kwargs try return requests Session request self method url kwargs except MissingSchema InvalidSchema InvalidURL raise except RequestException as e r LocustResponse r error e r status_code 0 r request Request method url prepare return r
make a matlab - compatible vector from a list .,staticmethod def vector_from_list a dtype float n len a vector System Array CreateInstance dtype n for i in range n vector i a i return vector
returns the length ( number of letters ) in the current hand .,def calculateHandlen hand numLetters 0 for key in hand numLetters hand key return numLetters
"create gaussobsmodel and its prior distr . returns object that does not yet have global parameters until init_global_params ( ) is called . until then , it has no components and ca n't be used in learn algs .",classmethod def CreateWithPrior cls inferType priorArgDict Data D Data dim if inferType EM obsPrior None return cls inferType D obsPrior min_covar priorArgDict min_covar else obsPrior GaussGammaDistr CreateAsPrior priorArgDict Data return cls inferType D obsPrior
returns one - line human - readable terse description of this object,def get_info_string self pass
transactional helper to decrement the value for a given sharded counter .,ndb transactional def _decrement name num_shards index random randint 0 num_shards 1 shard_key_string SHARD_KEY_TEMPLATE format name index counter TailboneGeneralCounterShard get_by_id shard_key_string if counter is None counter TailboneGeneralCounterShard id shard_key_string counter count 1 counter put memcache decr name
extract contents of rom to a 2d image,def extract self self open_rom r num_tiles os path getsize self in1 self multiple tiles_per_line 20 if not self args width else self args width self edge lines num_tiles tiles_per_line 1 tiles_per_line dest_width tiles_per_line self edge if not self args width else self args width dest_height lines self edge if self args verbose print input has d tiles num_tiles print destination will hold d tiles dpx x dpx tiles_per_line lines dest_width dest_height d pygame Surface dest_width dest_height depth 8 d set_palette 0 0 0 randint 100 255 randint 100 255 randint 100 255 for i in xrange 1 16 dpa pygame PixelArray d edge self edge i self pos2D_iterator dest_width for n in range num_tiles x y i next t self read_tile_from_rom tpa pygame PixelArray t dpa x x edge y y edge tpa pygame image save d self out self close_rom
load muv datasets . does not do train / test split,def load_muv_ecfp u print u About to load MUV dataset current_dir os path dirname os path realpath __file__ dataset_file os path join current_dir u datasets muv csv gz print u About to featurize MUV dataset featurizer dc feat CircularFingerprint size 1024 MUV_tasks sorted u MUV 692 u MUV 689 u MUV 846 u MUV 859 u MUV 644 u MUV 548 u MUV 852 u MUV 600 u MUV 810 u MUV 712 u MUV 737 u MUV 858 u MUV 713 u MUV 733 u MUV 652 u MUV 466 u MUV 832 loader dc data CSVLoader tasks MUV_tasks smiles_field u smiles featurizer featurizer dataset loader featurize dataset_file transformers dc trans BalancingTransformer transform_w True dataset dataset print u About to transform data for transformer in transformers dataset transformer transform dataset return MUV_tasks dataset transformers
iterate on the raw ptb data .,def ptb_producer raw_data batch_size num_steps name None with tf name_scope name PTBProducer raw_data batch_size num_steps raw_data tf convert_to_tensor raw_data name raw_data dtype tf int32 data_len tf size raw_data batch_len data_len batch_size data tf reshape raw_data 0 batch_size batch_len batch_size batch_len epoch_size batch_len 1 num_steps assertion tf assert_positive epoch_size message epoch_size 0 decrease batch_size or num_steps with tf control_dependencies assertion epoch_size tf identity epoch_size name epoch_size i tf train range_input_producer epoch_size shuffle False dequeue x tf strided_slice data 0 i num_steps batch_size i 1 num_steps x set_shape batch_size num_steps y tf strided_slice data 0 i num_steps 1 batch_size i 1 num_steps 1 y set_shape batch_size num_steps return x y
builds phy output . if large files writes 50000 loci at a time to tmp files and rebuilds at the end,def makephy data samples longname names i name for i in samples names sort locifile os path join data dirs outfiles data name loci locus iter open locifile rb fdict name for name in names partitions initial_pos 1 done 0 nloci 0 nbases 0 while nloci 5000000 seqs anames while 1 try samp locus next except StopIteration done 1 break if in samp nloci 1 break else try name seq samp split except ValueError print samp anames append name 1 seqs append seq strip arrayed np array list i for i in seqs if done break mask i for i in arrayed T if any j not in list Nn for j in i masked np dstack mask 0 loc_name p str nloci loc_range str initial_pos str len masked 0 initial_pos 1 initial_pos len masked 0 partitions append loc_name loc_range for name in names if name in anames fdict name append masked anames index name tostring else fdict name append N masked shape 1 nbases len fdict name 1 if not nloci 10000 0 for name in fdict with open os path join assembly dirs outfiles tmp _ phy tmp format name nloci wb as wout wout write join fdict name del fdict fdict name for name in names superout open os path join assembly dirs outfiles assembly name phy wb print superout len names nbases if nloci 10000 0 for name in names print superout name longname 3 len name join fdict name else for name in names superout write format name longname 3 len name join fdict name tmpfiles glob glob os path join assembly dirs outfiles tmp name phy tmp tmpfiles sort for tmpf in tmpfiles with open tmpf rb as tmpin superout write tmpin read os remove tmpf superout write n superout close raxml_part_out open os path join assembly dirs outfiles assembly name phy partitions w for partition in partitions print raxml_part_out DNA s partition raxml_part_out close return partitions
initialization and setting of streams ' parameters .,def __init__ self self content_len 0 self requests 1 self transaction_per_conn 1 self tcp_reset False self p1_src_start_ip 16 0 0 1 self p1_src_end_ip 16 0 0 10 self p1_dst_start_ip 48 0 0 1 self p1_dst_end_ip 48 0 0 10 self http_req GET 0KB bin HTTP 1 1 r nHost host r nUser Agent trex astf r nAccept r nConnection keep alive r n r n format host self p1_dst_start_ip self http_res HTTP 1 1 200 OK r nServer nginx 1 13 7 r nDate Mon 01 Jan 2018 00 00 00 GMT r nContent Type application octet stream r nContent Length length r nLast Modified Mon 01 Jan 2018 00 00 00 GMT r nConnection keep alive r nETag 5a027c14 0 r nAccept Ranges bytes r n r n format length self content_len
connect to the server ( two channels ),def __connect self self logger pre_cmd Connecting to RPC server on 0 1 format self conn_info server self conn_info sync_port rc self rpc connect if not rc return rc rc self rpc transmit api_sync_v2 params self api_ver self logger post_cmd rc if not rc if rc errno JsonRpcErrNo MethodNotSupported return RC_ERR Mismatch between client and server versions return rc self rpc api_h rc data api_h self logger pre_cmd Connecting to publisher server on 0 1 format self conn_info server self conn_info async_port rc self async connect self logger post_cmd rc if not rc return rc self state self CONNECTED None return RC_OK
mine an auxpow block on the given rpc connection .,def mineScryptAux node chainid ok auxblock node getauxblock target auxpow reverseHex auxblock target apow computeAuxpowWithChainId auxblock hash target chainid ok res node getauxblock auxblock hash apow
"get the contact from the session , else look up using the logged - in user . create an unsaved new contact if ` create ` is true .",def from_request self request create False contact None if request user is_authenticated try contact Contact objects get user request user id request session CUSTOMER_ID contact id except Contact DoesNotExist pass else create False if request session get CUSTOMER_ID try contactBySession Contact objects get id request session CUSTOMER_ID if contact is None contact contactBySession elif contact contactBySession log debug CURIOUS The user authenticated as r contact id r and a session as r contact id r contact user get_full_name contact id Contact objects get id request session CUSTOMER_ID full_name request session CUSTOMER_ID log debug Deleting the session contact del request session CUSTOMER_ID except Contact DoesNotExist log debug This user has a session stored customer id r which doesn t exist anymore Removing it from the session request session CUSTOMER_ID del request session CUSTOMER_ID if contact is None if create contact Contact user request user else raise Contact DoesNotExist return contact
fname : filename of the sound file we want to load,def loadMatlabFile self fname if not self cached raise ValueError Can only read cached Matlab files if self verbose print Loading s fname try data loadmat fname dsift mat descrs T except return None return data
emit a tracer enter event .,def start self tag None args None self __detect_tag tag self __emit_trace args
gets git and init versions and commits since the init version,def get_git_status self self _get_git_branch self _get_init_release_tag try self _get_log_commits except Exception as inst raise Exception Error the version in __init__ py is so git log is looking for commits that have happened since that version but it appears there is not existing tag for that version You may need to roll back the version in __init__ py to what is actually commited Check with git tag format self init_version inst print __init__ __version__ format self init_version print is commits ahead of origin format self tag len self commits self init_version
return warning shown on declining data sharing consent,def get_data_sharing_consent_warning self return self q css alert warning strong text 0
no duplicates should exist when reverse relationships are made explicit,def test_relations_found_for_article2 self create_relationships self msid1 self msid2 self msid3 self msid2 self msid3 self msid1 self msid3 self msid1 self msid2 relation_logic _relate_using_msids create_relationships expected_relationships self msid1 self msid2 self msid3 self msid2 self msid3 self msid1 self msid3 self msid1 self msid2 for msid expected_relations in expected_relationships av models Article objects get manuscript_id msid latest_version actual_relationships relation_logic internal_relationships_for_article_version av self assertCountEqual expected_relations r manuscript_id for r in actual_relationships for r I expected relations to r msid expected_relations
iterate through tarfile result chunks .,def __iter__ self data self read while data yield data data self read
make sure the object has a unique i d,def _assertId self object if getattr object id False return object id get_next_id self context
require several deb packages to be installed .,def packages pkg_list update False options None pkg_list pkg for pkg in pkg_list if not is_installed pkg if pkg_list install pkg_list update update options options
create the test data file for regression tests . this function is not used when testing ! it is here to document how the data file was generated .,def generate_test_data model make_model inc dec 30 20 shape 100 91 area 4500 4500 5000 5000 x y z gridder regular area shape z 10 data dict x x y y z z inc inc dec dec shape shape for field in FIELDS if field tf data field getattr polyprism field x y z model inc dec else data field getattr polyprism field x y z model np savez_compressed TEST_DATA_FILE data
stores stats summary in a dataframe . stats ( ) must be called before calling this function,def summary strategies metrics u Stores stats summary in a DataFrame n stats must be called before calling this function index columns strategies index data for metric in metrics index append metric data append strategy stats metric for strategy in strategies df pd DataFrame data columns columns index index return df
"test if we return the exact p - value for a significant test when requested , even if we do n't need to calculate it in order to determine that the test is significant .",def test_significant2 my_N my_ind u Test if we return the exact p value for a significant test when n requested even if we don t need to calculate it in order to determine that n the test is significant res get_xlmhg_test_result my_N my_ind pval_thresh 0 045 exact_pval u if_significant assert res pval 0 0244453044375645
"create an erratum object . returns the object or none if it already exists . to force update the erratum , set force = true",def create_erratum name etype issue_date synopsis force False errata Erratum objects all with transaction atomic e c errata get_or_create name name etype etype issue_date issue_date synopsis synopsis if c or force return e
this function takes an app or library name and will return the corresponding repo for that app or library,def get_repo_of_app_or_library app_or_library_name specs get_specs repo_name specs get_app_or_lib app_or_library_name repo if not repo_name return None return Repo repo_name
detach a data disk from a vmss vm model,def detach_model vmssvm_model lun data_disks vmssvm_model properties storageProfile dataDisks data_disks disk for disk in data_disks if disk get lun lun vmssvm_model properties storageProfile dataDisks data_disks return vmssvm_model
"checks the pending task queue and , given there 's not an in - progress task for the given app + env , marks the latest as in progress and fires the execute_task job .",queue job def check_queue tasks list db session query Task id Task app_id filter Task status TaskStatus pending group_by Task id Task app_id if not tasks return logging info Found pending tasks for d queues len tasks deploys list db session query Deploy id Deploy app_id Deploy environment filter Deploy task_id in_ set t id for t in tasks group_by Deploy id Deploy app_id Deploy environment apps a id a for a in App query filter App id in_ set t app_id for t in tasks for deploy_id app_id environment in deploys app apps app_id with lock redis deploycheck format app id environment timeout 5 if has_active_deploy app id environment logging info Deploy already in progress for s s app name environment continue task_id get_pending_task_id app id environment if not task_id logging info Unable to find a pending deploy for s s app name environment continue Task query filter Task id task_id update status TaskStatus in_progress synchronize_session False queue push freight jobs execute_deploy deploy_id
test the ' remote_branches ' attribute .,def test_remote_branches self u self model update_status self assertEqual self model remote_branches self git u remote u add u origin u self git u fetch u origin self model update_status self assertEqual self model remote_branches u origin master
all_boxes is a list of length number - of - classes . each list element is a list of length number - of - images . each of those list elements is either an empty list [ ] or a numpy array of detection .,def evaluate_action_classification self all_boxes output_dir None raise NotImplementedError
"runs ls with config set to be empty , confirms no authentication cli error .",def test_transfer_call_no_auth self output self run_line globus ls str GO_EP1_ID config assert_exit_code 1 self assertIn No Authentication provided output
builds a band pass filter with complex taps by making an lpf and spinning it up to the right center frequency,def complex_band_pass gain Fs freq_sb1 freq_pb1 freq_pb2 freq_sb2 passband_ripple_db stopband_atten_db nextra_taps 2 center_freq freq_pb2 freq_pb1 2 0 lp_pb freq_pb2 center_freq 1 0 lp_sb freq_sb2 center_freq lptaps low_pass gain Fs lp_pb lp_sb passband_ripple_db stopband_atten_db nextra_taps spinner cmath exp 2j cmath pi center_freq Fs i for i in xrange len lptaps taps s t for s t in zip spinner lptaps return taps
convert passband ripple spec expressed in db to an absolute value,def passband_ripple_to_dev ripple_db return 10 ripple_db 20 1 10 ripple_db 20 1
determines whether a test is a performance test .,def _IsPerfTest self test return _PERF_TEST_ANNOTATION in self test_pkg GetTestAnnotations test
return user details from twitter account,def get_user_details self response fullname first_name last_name self get_user_names response name return username response screen_name email fullname fullname first_name first_name last_name last_name
"given a middleware class ( not an instance ) , returns a view decorator . this lets you use middleware functionality on a per - view basis . the middleware is created with no params passed .",def decorator_from_middleware middleware_class return make_middleware_decorator middleware_class
"fetch a bunch of keys from the cache . for certain backends ( memcached , pgsql ) this can be * much * faster when fetching multiple values .",def get_many self keys version None u n Fetch a bunch of keys from the cache For certain backends memcached n pgsql this can be much faster when fetching multiple values n n Returns a dict mapping each key in keys to its value If the given n key is missing it will be missing from the response dict n d for k in keys val self get k version version if val is not None d k val return d
add text as a line to the output .,def emit self text self value extend self dent text n
removes all file location info from a google test program 's output .,def RemoveLocations test_output Removes all file location info from a Google Test program s output Args test_output the output of a Google Test program Returns output with all file location info in the form of DIRECTORY FILE_NAME LINE_NUMBER or DIRECTORY FILE_NAME LINE_NUMBER replaced by FILE_NAME return re sub gtest_output_test_ gtest cc d d 1 test_output
run the unit test suite .,nox session nox parametrize python_version 2 7 3 4 3 5 3 6 def unit_tests session python_version session interpreter python format python_version session install mock pytest pytest cov pyfakefs session install e session run py test rxs cov cov append cov report
convert camel case string to underscores .,def camelcase_to_underscore name s1 re sub A Z a z 1_ 2 name return re sub a z0 9 A Z 1_ 2 s1 lower
parses the iedb mhcallelename xml file and returns a list of allele namedtuple objects containing information about that each allele 's hla class and source organism .,memoize def load_alleles result path local_path etree xml etree ElementTree parse path for allele in etree iterfind MhcAlleleName name_element allele find DisplayedRestriction mhc_class_element allele find Class if name_element is None or mhc_class_element is None continue name name_element text synonyms set for synonym_element in allele iterfind Synonyms for synonym in synonym_element text split synonyms add synonym strip mhc_class mhc_class_element text organism_element allele find Organsim if organism_element is None organism None else organism organism_element text locus_element allele find Locus if locus_element is None locus None else locus locus_element text allele_object Allele name name mhc_class mhc_class locus locus organism organism synonyms synonyms result append allele_object return result
"generates a beta carbon for a glycine using the coordinates for the amide n , alpha c , and carboxyl c.",def calcGlyCbeta Ncoord CAcoord COcoord CA_CO_vector CA_N_vector for i in range 3 CA_CO_vector append COcoord i CAcoord i CA_N_vector append Ncoord i CAcoord i rotation_amount 240 pi 180 0 rotated arbRot CA_CO_vector CA_N_vector rotation_amount CBeta for i in range 3 CBeta append rotated i CAcoord i return CBeta
read stdin and return if match regex,def u_user_check regex question while True temp getpass question if match regex temp return u_ut_crypto temp print Provide a correct alfanum password
get an intent to start the app : return : intent,def get_start_intent self package_name self get_package_name if self get_main_activity package_name s self get_main_activity return Intent suffix package_name
the apparent radius ratio for a contaminated transit .,def contaminated_k k0 cn return k0 sqrt 1 cn
generate the test files that are distributed with hyperspy .,def generate_files for dtype in ripple dtype2keys keys for shape dims in SHAPES_SDIM for dim in dims for metadata in True False s _create_signal shape shape dim dim dtype dtype metadata metadata filename _get_filename s metadata filepath os path join MYPATH ripple_files filename s save filepath overwrite True
u = h(pad(a ) | pad(b ) ),def get_common_secret self server_public client_public u u H PAD A PAD B n n param int server_public n param int client_public n rtype int n return self hash self pad client_public self pad server_public
"accumulates the preference maps over the course of the simulation . on the last iteration , computes the stabilities for all the accumulated maps and returns the stability values as metadata .",def stability_analysis figure times roi ROI disable True if figure Fig10_12 else False simulation_time topo sim time preference topo sim V1 views maps OrientationPreference last data preference preference topo sim V1 views maps OrientationPreference last cyclic_range if simulation_time times 0 topo stability_maps preference roi roi if simulation_time times 1 topo stability_maps append preference roi roi stabilities analysis stability_index topo stability_maps return metadata stabilities stabilities else topo stability_maps append preference roi roi
: param df : : param column : : return :,def median df column return df approxQuantile column 0 5 0 01 0
construct a zipfile or contextualzipfile as appropriate .,def __new__ cls args kwargs if hasattr zipfile ZipFile __exit__ return zipfile ZipFile args kwargs return super ContextualZipFile cls __new__ cls
check if a document has the collocation indicated by pattern . the words must appear consecutively to match .,def check_colloc self doc pattern search_set self get_search_set pattern 0 for idx word in enumerate doc if word in search_set if len pattern 1 len doc idx 1 return 0 for word pat in zip doc idx 1 pattern 1 if word not in self get_search_set pat return 0 return 1 return 0
set a breakpoint at a specified line .,def cmd_break self cmd args u Set a breakpoint at a specified line n n The required argument of the vim user command is fname lnum n n result u Invalid arguments n name lnum debugger name_lnum args if name is None return if name self bp_id 1 self add_bp self bp_id name lnum result u Breakpoint d at file s line d n self bp_id name lnum if not self step_bufname self step_bufname name self lnum 0 self console_print result self print_prompt
"return the symbol , or python text , associated with this symbol , or none",def symbol self return self sym
removes invalid handles in all groups and removes empty groups .,def cleanup self u Removes invalid handles in all groups and removes empty groups n empty_groups for name group in self group remove_invalid_handles if not len group empty_groups append name for name in empty_groups self delete name
"a common part between fit ( ) and predict ( ) are made be a function , gen_ax validation is departed from all information . this validation information are not used for training in mlp while it is used in the linear regression methods such as ordinary , ridge , laso .",def fit self xA_train_val_idx ya_all batch_size 10 nb_epoch 20 verbose 0 val_ratio 0 2 if type xA_train_val_idx list xA_train_val_idx np array xA_train_val_idx T ln_train_val xA_train_val_idx shape 0 ln_train int ln_train_val 1 0 val_ratio xA_train_idx xA_train_val_idx ln_train xA_val_idx xA_train_val_idx ln_train self xA_train_idx_T xA_train_idx T AX_train ya_train self gen_AX xA_train_idx ya_all xA_train_idx 0 AX_val ya_val self gen_AX xA_val_idx ya_all xA_val_idx 0 return super fit AX_train ya_train AX_val ya_val verbose verbose batch_size batch_size nb_epoch nb_epoch
given : a fuzzlogger with multiple ifuzzloggerbackends . when : calling test_log_pass ( ) with some text . then : test_log_pass ( ) is called with that same text on each ifuzzloggerbackend .,def test_log_pass self self logger log_pass description self some_text self mock_logger_1 log_pass assert_called_once_with description self some_text self mock_logger_2 log_pass assert_called_once_with description self some_text
"get http query string from lookup params like { ' param1':'value1 ' , ' param2__lt':'value2 '",def get_query_string request lookup_params None remove None if lookup_params is None lookup_params if remove is None remove params dict request GET iterlists copy for r in remove for k in params keys if k startswith r del params k for k v in lookup_params items if k in params and v is None del params k elif v is not None params k v query_string for k values in params items print k for v in values if query_string query_string query_string u s s k v return mark_safe query_string replace 20
: type k : int : rtype : int,def preimageSizeFZF self K def count_of_factorial_primes n p cnt 0 while n 0 cnt n p n p return cnt p 5 left right 0 p K while left right mid left right left 2 if count_of_factorial_primes mid p K right mid 1 else left mid 1 return p if count_of_factorial_primes left p K else 0
build a dictionary through a list of words : type dictionary : list[str ] : rtype : void,def buildDict self dictionary for word in dictionary reduce dict __getitem__ word self trie setdefault _end
: type start : int : type end : int : rtype : bool,def book self start end for i j in self __calendar if start j and end i return False self __calendar append start end return True
paint the mask of the current surface .,def paint_mask surface node name opacity mask_node surface masks name mask_node tag g mask_node opacity opacity if mask_node get maskUnits userSpaceOnUse width_ref height_ref x y else x size surface node get x x y size surface node get y y width size surface node get width x height size surface node get height y width_ref width or surface width height_ref height or surface height mask_node x size surface mask_node get x 10 width_ref mask_node y size surface mask_node get y 10 height_ref mask_node height size surface mask_node get height 120 width_ref mask_node width size surface mask_node get width 120 height_ref if mask_node get maskUnits userSpaceOnUse x mask_node x y mask_node y mask_node viewBox format mask_node x mask_node y mask_node width mask_node height from surface import SVGSurface mask_surface SVGSurface mask_node None surface dpi surface surface context save surface context translate x y surface context scale mask_node width mask_surface width mask_node height mask_surface height surface context mask_surface mask_surface cairo surface context restore
get the main dojo javascript file look in conf / settings.py for available profiles .,def dojo_src_file self uncompressed_str gfx_str xd_str if self config get uncompressed False uncompressed_str uncompressed js if self config get use_gfx False gfx_str gfx if self config get use_xd False xd_str xd return path s dojo gfx sdojo xd s js uncompressed s path self dojo_base_url xd xd_str gfx gfx_str uncompressed uncompressed_str
returns an iterator that points to the first token .,def __iter__ self return Token Iterator self
the un - normalized log probabilities .,property def logits self return self _distribution logits
"given a world , a simulation duration , and a list of initial conditions , runs simulations for all initial conditions .",def batchSim world duration initialConditions returnItems simDt 0 01 simInit None simStep None simTerm None res if isinstance initialConditions dict v0 dict itervalues next for k v in initialConditions iteritems assert len v len v0 initialConditions entries must all be of same length print klampt batch batchSim Running len v0 simulations for i in xrange len v0 initCond dict k v i for k v in initialConditions iteritems try simRes doSim world duration initCond returnItems trace False simDt simDt simInit simInit simStep simStep simTerm simTerm except Exception print Exception thrown on trial i simRes error res append simRes else print klampt batch batchSim Running len initialConditions simulations for i initCond in enumerate initialConditions try simRes doSim world duration initCond returnItems trace False simDt simDt simInit simInit simStep simStep simTerm simTerm except Exception print Exception thrown on trial i simRes error res append simRes return res
test the default for all switches .,def test_default self self set_file_content default 42 self assertEqual 42 10 9 UserSpeed get_speed dpid self assertEqual 42 10 9 UserSpeed get_speed dpid 4
updates the image.type flag based on user dropdown input .,def _set_image_type self img_type self current_image type img_type self current_image set_complete self _enable_disable_save
update company monthly sales history based on sales invoices,def execute u frappe reload_doctype u Company companies d u name for d in frappe get_list u Company for company in companies update_company_current_month_sales company update_company_monthly_sales company
apply hard local winner - take - all on every rows of a theano matrix .,def lwta p block_size batch_size p shape 0 num_filters p shape 1 num_blocks num_filters block_size w p reshape batch_size num_blocks block_size block_max w max axis 2 dimshuffle 0 1 x T ones_like w max_mask T cast w block_max float32 indices numpy array range 1 block_size 1 max_mask2 max_mask indices block_max2 max_mask2 max axis 2 dimshuffle 0 1 x T ones_like w max_mask3 T cast max_mask2 block_max2 float32 w2 w max_mask3 w3 w2 reshape p shape 0 p shape 1 return w3
tests that untiedautoencoder calls the model superclass constructor,def test_untied_ae ae Autoencoder 5 7 act_enc tanh act_dec cos tied_weights True model UntiedAutoencoder ae model _ensure_extensions
"linear regression helper : param step_hash : string , step hash : param save : int , 1 or 0 . if save equals 1 , the record will be saved to database : return : coefficients",def regression step_hash save 1 coefficients dict try x out mem cpu vrt_mem load_train_frame step_hash coefficients ao coefficients bo coefficients ro reg_single_feature x out coefficients am coefficients bm coefficients rm reg_single_feature x mem coefficients av coefficients bv coefficients rv reg_single_feature x vrt_mem coefficients ac 0 if len cpu 0 coefficients bc sum cpu len cpu coefficients rc 1 for coefficient in coefficients coefficients coefficient 0 if numpy isnan coefficients coefficient else coefficients coefficient if save record_result step_hash coefficients ao coefficients bo coefficients ro 1 record_result step_hash coefficients am coefficients bm coefficients rm 2 record_result step_hash coefficients ac coefficients bc coefficients rc 3 record_result step_hash coefficients av coefficients bv coefficients rv 4 return coefficients ao coefficients bo coefficients am coefficients bm coefficients ac coefficients bc coefficients av coefficients bv except Exception as e print e
"i forward _ _ conform _ _ to self.original if it has it , otherwise i simply return none .",def __conform__ self interface if hasattr self original __conform__ return self original __conform__ interface return None
this function fetches game cover art and other data from giant bomb .,def game_data title url https www giantbomb com api search query 0 api_key 1 format json format title settings GIANTBOMB headers Content Type application json game try data query_service url headers entries data results entry list filter lambda x x resource_type game entries 0 game img entry image super_url game link entry site_detail_url game name entry name game year int entry original_release_date 0 3 except Exception game img https static thingsima de shared img no_cover png return game
"predict the system state at the next timestep , updating the estimate .",def predict self control None A B P Q x self _A self _B self _P self _Q self _x assert control is None B is None Control input must be given if and only if control matrix is set if B is None B 0 u 0 else u np asanyarray control reshape 1 1 self _x A x B u self _P A P A T Q
returns either an icon or thumbnail of the provided file,def get_icon self evidence resource True if resource curr_icon_dir resources icons else curr_icon_dir self icon_dir if volume_type in evidence or storage_type in evidence or compression_type in evidence or archive_type in evidence if not evidence mimetype_known evidence mimetype self pathspec_helper get_mimetype evidence pathspec if self is_expandable_evidence evidence return curr_icon_dir _evidence png if not meta_type in evidence return curr_icon_dir _blank png if evidence meta_type Directory or unicode evidence file_name strip or unicode evidence file_name strip return curr_icon_dir _folder png if evidence meta_type File and evidence meta_type Device return curr_icon_dir _blank png if evidence mimetype startswith image and resource return plugins thumbnail evidence url_query elif evidence mimetype startswith image self pathspec_helper create_thumbnail evidence if os path isfile evidence thumbnail_cache_path return evidence thumbnail_cache_path else return curr_icon_dir _missing png elif not os path isfile self icon_dir str evidence extension lower png return curr_icon_dir _blank png else return curr_icon_dir evidence extension lower png
ask the user to confirm a changeset .,def confirm_changes self changeset while True choice input Make these changes Y N D for details if choice upper Y return True elif choice upper N return False elif choice upper D print changeset summarize else print Please type Y or N or D
"calculate an lra term , eg . < eqmmm - eevb > qmmm or < eqmmm - eevb > evb .",def CalculateLRATerm self skip None trim None collect for parameter comment in skip first trim last if isinstance parameter int if self logging print s Skipping s d configurations _MODULE_LABEL comment parameter nsteps parameter elif isinstance parameter float if self logging percent int parameter 100 0 print s Skipping s d d of configurations _MODULE_LABEL comment percent nparameter nsteps int self nsteps parameter else nsteps 1 collect append nsteps nskip ntrim collect steps self steps if nskip 0 steps steps nskip if ntrim 0 steps steps ntrim collect 0 0 for n step in enumerate steps collect step target step reference return collect n
a common initialization routine for samples .,def init argv name version doc filename scope None parents if scope is None scope https www googleapis com auth name parent_parsers tools argparser parent_parsers extend parents parser argparse ArgumentParser description doc formatter_class argparse RawDescriptionHelpFormatter parents parent_parsers flags parser parse_args argv 1 client_secrets os path join os path dirname filename client_secrets json flow client flow_from_clientsecrets client_secrets scope scope message tools message_if_missing client_secrets storage file Storage name dat credentials storage get if credentials is None or credentials invalid credentials tools run_flow flow storage flags http credentials authorize http httplib2 Http service discovery build name version http http return service flags
wait for card insertion or removal .,def waitforcardevent self AbstractCardRequest waitforcardevent self presentcards evt threading Event if INFINITE self timeout timertimeout 1 else timertimeout self timeout timer threading Timer timertimeout signalEvent evt INFINITE self timeout readerstates timerstarted False while not evt isSet if not timerstarted timerstarted True timer start time sleep self pollinginterval readernames self getReaderNames for reader in readernames if not reader in readerstates readerstates reader reader SCARD_STATE_UNAWARE for oldreader in readerstates keys if oldreader not in readernames del readerstates oldreader if readerstates hresult newstates SCardGetStatusChange self hcontext 0 readerstates values else hresult 0 newstates if SCARD_E_TIMEOUT hresult if evt isSet raise CardRequestTimeoutException elif SCARD_E_UNKNOWN_READER hresult pass elif 0 hresult timer cancel raise CardRequestException Failed to get status change SCardGetErrorMessage hresult else timer cancel for state in newstates readername eventstate atr state r oldstate readerstates readername if oldstate SCARD_STATE_PRESENT and eventstate SCARD_STATE_CHANGED SCARD_STATE_PRESENT eventstate eventstate 4294967295 SCARD_STATE_CHANGED if eventstate SCARD_STATE_PRESENT and eventstate SCARD_STATE_CHANGED presentcards append Card Card readername atr return presentcards if evt isSet raise CardRequestTimeoutException
test cases can load fixture objects into models defined in packages,def testClassFixtures self u self assertEqual Article objects count 3 self assertQuerysetEqual Article objects all u Django conquers world u Copyright is fine the way it is u Poker has no place on ESPN lambda a a headline
a simple view that expects a trace request and echoes its status line .,def trace_view request if request method upper TRACE return HttpResponseNotAllowed TRACE elif request body return HttpResponseBadRequest TRACE requests MUST NOT include an entity else protocol request META SERVER_PROTOCOL t Template method uri version name TRACE Template c Context method request method uri request path version protocol return HttpResponse t render c
call receiver with arguments and an appropriate subset of named,def robustApply receiver arguments named receiver codeObject startIndex function receiver acceptable codeObject co_varnames startIndex len arguments codeObject co_argcount for name in codeObject co_varnames startIndex startIndex len arguments if name in named raise TypeError Argument r specified both positionally and as a keyword for calling r name receiver if not codeObject co_flags 8 for arg in named keys if arg not in acceptable del named arg return receiver arguments named
write some data to the serial device .,def writeSomeData self data return fdesc writeToFD self fileno data
"parse a primitive regexp followed by * , + , ? modifiers .",def parse_mod self re self parse_prim while not self end and self c in if self c re Rep re elif self c re Rep1 re else re Opt re self next return re
change the metadata associated with this group .,def setMetadata meta
extract rows specified in the argument list .,def extract_rows data rows try out for r in rows out append data r return out except IndexError raise IndexError data s rows s data rows return out
make sure unassigned code points from unicode 3.2 are rejected .,def test_nodeprepUnassignedInUnicode32 self self assertRaises UnicodeError nodeprep prepare u u1d39
assert that we get the correct op code for an rsa remove identity request,def test_agentc_REMOVE_RSA_IDENTITY self d self client sendRequest agent AGENTC_REMOVE_RSA_IDENTITY self pump flush return d addCallback self assertEqual
: param addr : an ipv6 address in string form .,def str_to_int addr flags 0 try packed_int _inet_pton AF_INET6 addr return packed_to_int packed_int except Exception raise AddrFormatError r is not a valid IPv6 address string addr
"with browser_xss_filter set to false , the middleware does not add an "" x - xss - protection "" header to the response .",override_settings BROWSER_XSS_FILTER False def test_xss_filter_off self self assertNotIn x xss protection self process_response
apply < func > on each element in < data > and return the list consisting of the return values from < func>.,def transform func data out for r in data out append func r return out
the strings passed in remote_user should be cleaned and the known users should not have been configured with an email address .,def test_known_user self super RemoteUserCustomTest self test_known_user self assertEqual User objects get username knownuser email self assertEqual User objects get username knownuser2 email
"test array2 _ _ getitem _ _ method , negative index",def testGetBad1 self self assertRaises IndexError self array2 __getitem__ 1
> > > d = dict ( ) > > > obj = test_return(d ) > > > next(obj ) 1 > > > next(obj ) traceback ( most recent call last ) : stopiteration > > > d['i_was_here ' ] true,def test_return a yield 1 a i_was_here True return
test the echo flag 's independence to a specific engine .,def test_echo_flag_independence self e1 self _testing_engine e2 self _testing_engine e1 echo True e1 execute select 1 close e2 execute select 2 close e1 echo False e1 execute select 3 close e2 execute select 4 close e2 echo True e1 execute select 5 close e2 execute select 6 close assert self buf buffer 0 getMessage startswith SELECT 1 assert self buf buffer 2 getMessage startswith SELECT 6 assert len self buf buffer 4
parsing production that handles trailing arguments after a -- is given .,def trailing_production data tokens data TRAILING x 1 for x in tokens del tokens
add the overridexml parts for disabling ccda,def _addOverrides self aam_info overridexml ElementTree SubElement aam_info overrideXML override_app ElementTree SubElement overridexml application package_sets ElementTree SubElement override_app packageSets for sap packages in ACC_PACKAGE_SETS items self _addPackageSet package_sets sap packages
always returns `` none `` .,def get self key return None
return the property dictionary for a matplotlib . axis instance,def get_axis_properties axis props label1On axis _major_tick_kw get label1On True if isinstance axis matplotlib axis XAxis if label1On props position bottom else props position top elif isinstance axis matplotlib axis YAxis if label1On props position left else props position right else raise ValueError 0 should be an Axis instance format axis locator axis get_major_locator props nticks len locator if isinstance locator ticker FixedLocator props tickvalues list locator else props tickvalues None formatter axis get_major_formatter if isinstance formatter ticker NullFormatter props tickformat elif isinstance formatter ticker FixedFormatter props tickformat list formatter seq elif not any label get_visible for label in axis get_ticklabels props tickformat else props tickformat None props scale axis get_scale labels axis get_ticklabels if labels props fontsize labels 0 get_fontsize else props fontsize None props grid get_grid_style axis props visible axis get_visible return props
"returns session if not logged in ; puppet if one exists , otherwise return the player .",def get_puppet_or_player self if self logged_in return self puppet if self puppet else self player return None
query a new chunk of data,def load_chunk self data self site get query self generator self list_name text_type k v for k v in six iteritems self args if not data raise StopIteration self set_iter data if data get continue self args update data continue elif self list_name in data get query continue self args update data query continue self list_name else self last True
underlying ` paramiko . transport < http://www.lag.net/paramiko/docs/paramiko.transport-class.html > ` _ object . this makes it possible to call methods like : meth:`~paramiko . transport.set_keepalive ` on it .,property def transport self return self _transport
clean ` cleandir ` by removing it and all its children completely .,def clean cleandir tries 1000 while tries if os path exists cleandir try shutil rmtree cleandir except OSError if tries 1 raise else tries 1 continue break
return length of extenion header in bytes .,def __len__ self return self hdr_len_to_bytes self _hdr_len
test the xy slice cutout with incorrect cutout arguments,def test_xy_incorrect self p args 11000 11100 4000 4100 200 201 url https sd xy format SITE_HOST p token p channels 0 p resolution p args 0 p args 1 p args 2 p args 3 p args 4 assert 404 getURL url status_code
execute the plugin matching given argv list,def run self argv plugin self argv 0 plugin argv argv self current_plugin plugin try return plugin run argv finally self current_plugin DEFAULT_PLUGIN
retrieve list of nodes of the specified layer,def get self request args kwargs self get_layer nodes self get_nodes request args kwargs return Response nodes
parses a url of the form :,def parse_url self self scheme None self resource None self host None self port None if self url is None return scheme url self url split 1 parsed urlsplit url scheme http if parsed hostname self host parsed hostname elif unix in scheme self host localhost else raise ValueError Invalid hostname from s self url if parsed port self port parsed port if scheme ws if not self port self port 8080 elif scheme wss if not self port self port 443 elif scheme in ws unix wss unix pass else raise ValueError Invalid scheme s scheme if parsed path resource parsed path else resource if unix in scheme self unix_socket_path resource resource if parsed query resource parsed query self scheme scheme self resource resource
restores the associated tree from ' restored_tensors ' .,def restore self restored_tensors unused_restored_shapes with ops control_dependencies self _create_op return gen_model_ops tree_deserialize self _tree_handle restored_tensors 0 params self params serialized_params_proto
apply non - maxima suppression .,def apply_nonmaxima_suppression self max_bbox_overlap for frame_idx detections in self detections items if len detections 0 continue boxes np asarray d roi for d in detections scores np asarray d confidence for d in detections indices pymotutils preprocessing non_max_suppression boxes max_bbox_overlap scores self detections frame_idx detections i for i in indices
returns the list of edges in the selection set,def edges selex except1st False if len selex 0 selex FreeCADGui Selection getSelectionEx try if except1st eds e for sx in selex if sx selex 0 for so in sx SubObjects for e in so Edges else eds e for sx in selex for so in sx SubObjects for e in so Edges except FreeCAD Console PrintError nNo valid selection n return eds
returns the last error status for a windows socket operation .,def WSAGetLastError _ library dist load return library WSAGetLastError
a class method that returns true if the current platform supports coloring terminal output using this method . returns false otherwise .,def supported cls stream sys stdout if not stream isatty return False try import curses except ImportError return False else try try return curses tigetnum colors 2 except curses error curses setupterm return curses tigetnum colors 2 except Exception return False
logs out the user if he is logged in . then redirects to the log - in page .,def logout request login_url None kwargs msg Logging out user username s username request user username LOG info msg Securely logs a user out return django_auth_views logout_then_login request login_url login_url kwargs
unregister a callback for corresponding resource type .,def unprovide callback resource_type _get_manager unregister callback resource_type
returns extended resource for service type management .,classmethod def get_resources cls resource_attributes RESOURCE_ATTRIBUTE_MAP SEGMENTS controller base create_resource SEGMENTS SEGMENT directory get_plugin SEGMENTS resource_attributes allow_pagination True allow_sorting True return extensions ResourceExtension SEGMENTS controller attr_map resource_attributes
create a flow to create an l7 rule,def get_create_l7rule_flow self create_l7rule_flow linear_flow Flow constants CREATE_L7RULE_FLOW create_l7rule_flow add lifecycle_tasks L7RuleToErrorOnRevertTask requires constants L7RULE constants LISTENERS constants LOADBALANCER create_l7rule_flow add database_tasks MarkL7RulePendingCreateInDB requires constants L7RULE create_l7rule_flow add amphora_driver_tasks ListenersUpdate requires constants LOADBALANCER constants LISTENERS create_l7rule_flow add database_tasks MarkL7RuleActiveInDB requires constants L7RULE create_l7rule_flow add database_tasks MarkL7PolicyActiveInDB requires constants L7POLICY create_l7rule_flow add database_tasks MarkLBAndListenersActiveInDB requires constants LOADBALANCER constants LISTENERS return create_l7rule_flow
retrieves the current plugged networking configuration .,abc abstractmethod def get_plugged_networks self compute_id
escape a unicode string in an oauth - compatible fashion .,def _escape self s safe s s encode utf 8 if isinstance s six text_type else s s urlparse quote s safe if isinstance s six binary_type s s decode utf 8 return s
check that a service tag is n't in the module path,def service_tags_not_in_module_path physical_line filename if tempest scenario not in filename matches SCENARIO_DECORATOR match physical_line if matches services matches group 1 split for service in services service_name service strip strip modulepath os path split filename 0 if service_name in modulepath return physical_line find service_name T107 service tag should not be in path
generate connected components as subgraphs .,staticmethod def connected_component_subgraphs subgraph pass
create a vector with hanning window weights .,def hanning dtype N Create a vector with Hanning window weights arguments dtype data type of the vector e g float N length of the vector math y_i frac 1 2 1 cos frac 2 pi i 1 N 1 import_module vsip block dtype m import_module vsip signal window dtype return vector block m hanning N
returns the id code for this database . using codes for different database instances will allow you to define multiple schema types for more complex systems .,def code self return self __code
it returns list with dns found with ' filter ',def searchDN self search_base filter scope return _adclient searchDN_adclient self obj search_base filter scope
initializes the attributes for the class neuralnetdetector .,def __init__ self path_to_model waveform_length n_features input_tensor None self path_to_model path_to_model self waveform_length waveform_length self n_features n_features W_ae tf Variable tf random_uniform waveform_length n_features 1 0 np sqrt waveform_length 1 0 np sqrt waveform_length self vars_dict W_ae W_ae self saver tf train Saver self vars_dict self score_tf self _make_graph input_tensor
"get the current videoplayer positon . @returns int current position , int total length",def get_player_position self response self get_player_state if not response error and Duration in response total_str response Duration time_str response Time if total_str and time_str total utils duration_to_seconds total_str time utils duration_to_seconds time_str return time total return None None
convert a string containin a list of white - space - separated ( and/or newline - separated ) values into a numpy array,def parray string if string None return None try return np asarray string split np double except return string split
reserves a port for insecure rpc service once this server becomes active .,abc abstractmethod def add_insecure_port self address raise NotImplementedError
"check manageddatastructure would return singleton instance for unique identifier of ( list_domain , list_key ) .",def test_singleton_metaclass self test_md ManagedList list_domain test_singleton_domain list_key test_key1 list_name list_description zk_hosts TEST_ZK_HOSTS aws_keyfile TEST_AWS_KEYFILE s3_bucket TEST_S3_BUCKET test_md2 ManagedList list_domain test_singleton_domain list_key test_key1 list_name list_description zk_hosts TEST_ZK_HOSTS aws_keyfile TEST_AWS_KEYFILE s3_bucket TEST_S3_BUCKET test_md3 ManagedList list_domain test_singleton_domain list_key test_key2 list_name list_description zk_hosts TEST_ZK_HOSTS aws_keyfile TEST_AWS_KEYFILE s3_bucket TEST_S3_BUCKET test_md4 ManagedList list_domain test_singleton_domain2 list_key test_key1 list_name list_description zk_hosts TEST_ZK_HOSTS aws_keyfile TEST_AWS_KEYFILE s3_bucket TEST_S3_BUCKET self assertEqual test_md test_md2 self assertFalse test_md test_md3 self assertFalse test_md test_md4 with self assertRaises Exception ManagedHashMap list_domain test_singleton_domain list_key test_key1 list_name list_description zk_hosts TEST_ZK_HOSTS aws_keyfile TEST_AWS_KEYFILE s3_bucket TEST_S3_BUCKET
test that response validation is able to match api paths even when there is a base path .,def test_response_validation_with_valid_path_and_base_path schema SchemaFactory basePath api v1 paths get get responses 200 description Success response ResponseFactory url http www example com api v1 get validate_response response response request_method get schema schema
return a boolean to indicate if we need to reschedule another bracket iteration .,def should_reduce_configs self iteration bracket_iteration n_configs_to_keep self get_n_config_to_keep_for_iteration iteration iteration bracket_iteration bracket_iteration return n_configs_to_keep 0
return user unique i d provided by service,def get_user_id self details response return self _user_id response
"when receiving a read request from the parent socket , open our own socket and check the read request ; if we do n't have any options , send the first block .",def new_request self self sock ParentSocket socket AF_INET socket SOCK_DGRAM self sock setsockopt socket SOL_SOCKET socket SO_REUSEADDR 1 self sock bind self ip 0 self sock parent self if not self valid_mode or not self check_file self complete return self fh open self filename rb self filesize os path getsize self filename if not self parse_options if self block 1 self send_block return self reply_options
returns the matrix with unit - norm columns that is closests to a w.r.t . the frobenius norm .,def closest_unit_norm_column_approximation A m n A shape manifold Oblique m n solver ConjugateGradient X T matrix cost 0 5 T sum X A 2 problem Problem manifold manifold cost cost arg X return solver solve problem
clear the list of recorded warnings .,def clear self self _list
nothing should happen if we have no nodes to check .,twisted_wrapper def test_no_nodes self self strategies 0 sample_size 0 peer self overlays 1 my_peer peer last_response 1 self overlays 0 network add_verified_peer peer self strategies 0 take_step yield self deliver_messages self assertEqual len self overlays 0 network verified_peers 1
turn a formatted time back into a datetime .,def parse_strtime timestr fmt PERFECT_TIME_FORMAT return datetime datetime strptime timestr fmt
"returns initial route as read from input file , none if parsing errors occur filename - name of the input file with ' .tsp ' extension",def parse_input_route filename f open filename r route dimension 1 dimension_found False node_section_found False for line in f if DIMENSION in line tokens line split dimension int tokens 1 dimension_found True if NODE_COORD_SECTION in line node_section_found True break if not dimension_found print 99 TSP Parsing error DIMENSION not found f close return None elif not node_section_found print 99 TSP Parsing error NODE_COORD_SECTION header not found f close return None for line in f if EOF in line break coords get_coords line if not coords print 99 TSP Parsing error Invalid node data found f close return None route append Node coords f close if len route dimension print 99 TSP Parsing error number of nodes found does not match dimension return None return route
write a recipe to the workspace,def workspace_write repo branch recipe ws_dir workspace_dir repo branch if not os path isdir ws_dir os makedirs ws_dir filename joinpaths ws_dir recipe filename open filename wb write recipe toml encode UTF 8
override this instead of isenabled when using this mixin,def isActionAvailable self return True
returns a list of extra properties to set @param lang_id : used to select a specific set of properties,def Properties lang_id 0 if lang_id synglob ID_LANG_68K return list else return list
syntax specifications @param lang_id : used for selecting a specific subset of syntax specs,def SyntaxSpec lang_id 0 if lang_id synglob ID_LANG_NSIS return SYNTAX_ITEMS else return list
"override the standard findparagraph to properly handle fortran comment blocks . comment blocks start with c , c , or ! in column 1 .",def findParagraph self start end 1 try info F77CommentParagraph self start except BadParagraphError linenum self LineFromPosition start start self PositionFromLine linenum try info F77CommentParagraph self start except BadParagraphError info FundamentalMode findParagraph self start end return info
tests equality and hashing of database entries .,def test_eq_hash paper paper reset_iter a paper 0 assert a a assert hash a hash a auid assert http aflowlib duke edu AFLOWDATA in str a
this should be made compatible with the regular rtree call ...,def intersects self xxyy rect qc QgsRectangle xxyy 0 xxyy 2 xxyy 1 xxyy 3 results self qsi intersects rect return results
test saved search execution results are filtering .,def test_execute_filtered self with no_stdout response self authed_get savedsearch execute args 3 self assertEqual response status_code status HTTP_200_OK self assertEqual len response data 1
returns the minimum result from saved results .,def minimum self return self _search leq
tracked jobs get extra notifications when they complete,def test_track_completed self self lua put 0 worker queue jid klass 0 self lua track 0 track jid self lua pop 0 queue worker 10 with self lua self lua complete 0 jid worker queue self assertEqual self lua log channel ql completed data jid channel ql log data jid jid event completed queue queue
"trap 0xf72f , originally was [ 0x20 , 0x41 , 0xf8 ] .",def find_header CPU memory file_name get_file_name memory start_addr 0 stop_addr 0 type_ 3 file_name header tape_loader load_header file_name if header is None print umm no file on tape set_status memory 48 err 1 else setup_tape_header type_ header file_name header start_addr header end_addr memory set_status memory 0 err 0 set_VERCKK memory 0 set_IRQTMP memory 0 if err 0 CPU CLC else CPU SEC CPU clear_Z CPU set_PC 63282
"this method starts the server . there are two processes , one is an http server that shows and admin interface and the second is a thrift server that the client code calls .",def serve conf_path storage_factory None flawless lib config init_config conf_path if not os path exists config data_dir_path os makedirs config data_dir_path storage_factory storage_factory or lambda partition DiskStorage partition partition root_logger logging getLogger root_handler logging handlers TimedRotatingFileHandler filename config log_file when d interval 1 backupCount config log_days_to_keep root_logger setLevel getattr logging config log_level root_logger addHandler root_handler child_pid os fork if child_pid 0 handler FlawlessWebServiceHandler storage_factory storage_factory server SimpleThreadedHTTPServer config http_port SimpleRequestHTTPHandler server attach_service handler server request_queue_size 50 try server serve_forever except KeyboardInterrupt SystemExit server server_close else handler FlawlessThriftServiceHandler storage_factory storage_factory processor Flawless Processor handler transport TSocket TServerSocket port config port tfactory TTransport TFramedTransportFactory pfactory TBinaryProtocol TBinaryProtocolFactory server TServer TThreadedServer processor transport tfactory pfactory try server serve except KeyboardInterrupt SystemExit handler errors_seen sync transport close os kill child_pid signal SIGINT
"from the given shape , returns the subscripts of the given index",def ind2sub shape inds if type inds is not np ndarray inds np array inds assert len inds shape 1 Indexing must be done as a 1D row vector e g 3 6 6 return np unravel_index inds shape order F
: param timeout : : return :,def connect self timeout None pass
"send break condition . timed , returns to idle state after given duration .",def sendBreak self duration 0 25 if not self _isOpen raise portNotOpenError
carry out the fibonacci search method according * to the paper : ' autofocusing for tissue microscopy ' by t.t.e.yeo et al,def fibonacci_search interval f phi 0 5 1 5 0 5 def fibs n None A generator thanks to W J Earley that returns the fibonacci series a b 0 1 yield 0 yield 1 if n is not None for _ in range 1 n b b a a b a yield b else while True b b a a b a yield b def smallfib m Return N such that fib N m n 0 for fib in fibs m if fib m return n n n 1 def fib n Evaluate the n th fibonacci number return phi n phi n 5 0 5 a interval 0 b interval 1 N smallfib b a delta fib N 2 fib N b a x1 a delta x2 b delta y1 f x1 y2 f x2 for n in range N 1 1 1 if y1 y2 a x1 x1 x2 y1 y2 x2 b fib n 2 fib n b a y2 f x2 else b x2 x2 x1 y2 y1 x1 a fib n 2 fib n b a y1 f x1 if y1 y2 return x1 else return x2
waits on a file to be make,def wait_file path timeout 5 start time time while not os path isfile path and time time start timeout time sleep 0 1 if not os path isfile path raise Exception Timed out waiting for file s path while os path getsize path 0 and time time start timeout time sleep 0 1
"separate out the state variable into time , angles , velocities , and accelerations .",def update_state self self t self state 0 self q self state 1 3 self dq self state 3 5 self ddq self state 5
convert complex array back to i / q interleaved rtl - sdr samples .,def complex_to_raw array scaled array astype np complex64 view np float32 128 127 4 return scaled astype np uint8
unify two notebooks into a single notebook with diff metadata .,def notebook_diff nb1 nb2 check_modified True nb1_cells nb1 worksheets 0 cells nb2_cells nb2 worksheets 0 cells diffed_nb cells_diff nb1_cells nb2_cells check_modified check_modified line_diffs diff_modified_items diffed_nb cell_list list for i item in enumerate diffed_nb cell diff_result_to_cell item if i in line_diffs cell metadata extra diff data line_diffs i cell_list append cell nb1 worksheets 0 cells cell_list nb1 metadata nbdiff type diff return nb1
"itertools recipe > > > list(grouper(3 , iter('abcdefg ' ) ) ) [ [ ' a ' , ' b ' , ' c ' ] , [ ' d ' , ' e ' , ' f ' ] , [ ' g ' ] ]",def grouper n iterable return iter lambda list itertools islice iterable n
this function creates an image that can be used to test vis functions .,def create_colorful_test_image self ch255 np full 100 200 1 255 dtype np uint8 ch128 np full 100 200 1 128 dtype np uint8 ch0 np full 100 200 1 0 dtype np uint8 imr np concatenate ch255 ch128 ch128 axis 2 img np concatenate ch255 ch255 ch0 axis 2 imb np concatenate ch255 ch0 ch255 axis 2 imw np concatenate ch128 ch128 ch128 axis 2 imu np concatenate imr img axis 1 imd np concatenate imb imw axis 1 image np concatenate imu imd axis 0 return image
helper function for printing and logging evaluated sequences .,def print_and_log log id_to_word sequence_eval max_num_to_print 5 indices_arr np asarray sequence_eval samples helper convert_to_human_readable id_to_word indices_arr max_num_to_print for i sample in enumerate samples print Sample i sample log write nSample str i sample log write n print n log flush return samples
convert training data from ndjson files into tf . example in tf . record .,def convert_data trainingdata_dir observations_per_class output_file classnames output_shards 10 offset 0 def _pick_output_shard return random randint 0 output_shards 1 file_handles for filename in sorted tf gfile ListDirectory trainingdata_dir if not filename endswith ndjson print Skipping filename continue file_handles append tf gfile GFile os path join trainingdata_dir filename r if offset count 0 for _ in file_handles 1 count 1 if count offset break writers for i in range FLAGS output_shards writers append tf python_io TFRecordWriter s 05i of 05i output_file i output_shards reading_order list range len file_handles observations_per_class random shuffle reading_order for c in reading_order line file_handles c readline ink None while ink is None ink class_name parse_line line if ink is None print Couldn t parse ink from line if class_name not in classnames classnames append class_name features features class_index tf train Feature int64_list tf train Int64List value classnames index class_name features ink tf train Feature float_list tf train FloatList value ink flatten features shape tf train Feature int64_list tf train Int64List value ink shape f tf train Features feature features example tf train Example features f writers _pick_output_shard write example SerializeToString for w in writers w close for f in file_handles f close with tf gfile GFile output_file classes w as f for class_name in classnames f write class_name n return classnames
downloads cifar10 and uncompresses it locally .,def _download_and_uncompress_dataset dataset_dir filename _DATA_URL split 1 filepath os path join dataset_dir filename if not os path exists filepath def _progress count block_size total_size sys stdout write r Downloading s 1f filename float count block_size float total_size 100 0 sys stdout flush filepath _ urllib request urlretrieve _DATA_URL filepath _progress print statinfo os stat filepath print Successfully downloaded filename statinfo st_size bytes tarfile open filepath r gz extractall dataset_dir
train operation function for the given scope used file training .,def get_train_op_for_scope loss optimizer scopes params is_trainable lambda x x in tf trainable_variables var_list update_ops for scope in scopes var_list extend filter is_trainable tf contrib framework get_model_variables scope update_ops extend tf get_collection tf GraphKeys UPDATE_OPS scope return slim learning create_train_op loss optimizer update_ops update_ops variables_to_train var_list clip_gradient_norm params clip_gradient_norm
convert a length t list of bxn numpy tensors of length b list of txn numpy tensors .,def list_t_bxn_to_list_b_txn values_t_bxn T len values_t_bxn B N values_t_bxn 0 shape values_b_txn for b in range B values_pb_txn np zeros T N for t in range T values_pb_txn t values_t_bxn t b values_b_txn append values_pb_txn return values_b_txn
return the ` best ` most similar ` choices ` with ` query ` . useful for searching .,def most_similar query choices best None ignore_case False ratio_function ratio similarity_dict dict for choice in choices similarity_dict choice ratio_function query choice ignore_case return Counter similarity_dict most_common best
create an audio/ * type mime document .,def __init__ self _audiodata _subtype None _encoder encoders encode_base64 _params if _subtype is None _subtype _whatsnd _audiodata if _subtype is None raise TypeError Could not find audio MIME subtype MIMENonMultipart __init__ self audio _subtype _params self set_payload _audiodata _encoder self
encode a string with base64 .,def body_encode s maxlinelen 76 eol NL Encode a string with base64 Each line will be wrapped at at most maxlinelen characters defaults to 76 characters Each line of encoded text will end with eol which defaults to n Set this to r n if you will be using the result of this function directly in an email if not s return s encvec max_unencoded maxlinelen 3 4 for i in range 0 len s max_unencoded enc b2a_base64 s i i max_unencoded decode ascii if enc endswith NL and eol NL enc enc 1 eol encvec append enc return EMPTYSTRING join encvec
load the grammar ( maybe from a pickle ) .,def load_grammar gt Grammar txt gp None save True force False logger None if logger is None logger logging getLogger if gp is None head tail os path splitext gt if tail txt tail gp head tail join map str sys version_info pickle if force or not _newer gp gt logger info Generating grammar tables from s gt g pgen generate_grammar gt if save logger info Writing grammar tables to s gp try g dump gp except IOError as e logger info Writing failed str e else g grammar Grammar g load gp return g
test data splitting with posix parser,def testSplitPosix self self splitTest self posix_data comments True
find all files under ' dir ' and return the list of full filenames ( relative to ' dir ' ) .,def findall dir os curdir from stat import ST_MODE S_ISREG S_ISDIR S_ISLNK list stack dir pop stack pop push stack append while stack dir pop names os listdir dir for name in names if dir os curdir fullname os path join dir name else fullname name stat os stat fullname mode stat ST_MODE if S_ISREG mode list append fullname elif S_ISDIR mode and not S_ISLNK mode push fullname return list
absolute path including the query string .,property def request_uri self uri self path or if self query is not None uri self query return uri
return true if the octet should be escaped with body quopri .,def body_check octet u return chr octet _QUOPRI_BODY_MAP octet
remember an entity 's state to be saved during `` commit `` .,def put self entity if entity key is None raise ValueError Entity must have a key if not _dataset_ids_equal self dataset_id entity key dataset_id raise ValueError Key must be from same dataset as batch _assign_entity_to_mutation self mutation entity self _auto_id_entities
retrieve the contents of a file by its url .,def retrieve self url timeout None urlopen_kwargs if timeout is not None urlopen_kwargs timeout Timeout read timeout connect self _connect_timeout return self _request_wrapper GET url urlopen_kwargs
contains the data objects ( with tags and lengths ) returned by the icc in response to a command,def _get_app_interchange_profile self return 0000
"treat a totally blank line as a diff line to be flexible , since emacs can strip trailing spaces .",def _is_not_diff_line line return line strip and not line startswith DIFF_CHARS
"mobilenetv2 model from the ` "" inverted residuals and linear bottlenecks : mobile networks for classification , detection and segmentation "" < https://arxiv.org/abs/1801.04381 > ` _ paper .",def mobilenet_v2_0_5 kwargs return get_mobilenet_v2 0 5 kwargs
checks if value is string in both python2.7 and python3 +,def is_basestring value return isinstance value type u str
remove all triples from dst add all triples from src to dst,def evalCopy ctx u src dst u graph srcg _graphOrDefault ctx src dstg _graphOrDefault ctx dst if srcg identifier dstg identifier return dstg remove None None None dstg srcg
say only a single random hiragana character .,def challenge self character None if character is None character random choice japanese hiragana keys self _currentChallenge character actor self _actor action Say do actor None character
remove the specified external tool .,def delete self u n Remove the specified external tool n n calls DELETE api v1 courses course_id external_tools external_tool_id n https canvas instructure com doc api external_tools html method external_tools destroy _ n or DELETE api v1 accounts account_id external_tools external_tool_id n https canvas instructure com doc api external_tools html method external_tools destroy _ n n rtype class canvasapi external_tool ExternalTool n response self _requester request u DELETE u s external_tools format self parent_type self parent_id self id return ExternalTool self _requester response json
sets up a trial to try the specified ranges of parameter values in sequence ( holding all other parameters to their defaults and varying only one at a time ) .,def trial_sequence self params self _setup_trial params keys dm self _get_default_map keys dm keys vals dm k for k in keys trials for k v in params iteritems kidx keys index k for val in v trial vals trial kidx val trials tuple trial self param_keys keys self param_iterator iter trials
initialize a payload decoder with the result of reading a collection of coils from a modbus device .,staticmethod def fromCoils coils endian Endian Little if isinstance coils list payload pack_bitstring coils return BinaryPayloadDecoder payload endian raise ParameterException Invalid collection of coils supplied
draw an invisible text layer for ocr data .,def add_text_layer self pdf hocrfile page_num height dpi hocr ElementTree try hocr parse hocrfile except Exception logging info Error loading hocr not adding any text return logging debug xml etree ElementTree tostring hocr getroot for c in hocr getroot if c tag body continue for page in c if page attrib class ocr_page assert Why is this hocr not paging properly if page attrib id page_ d page_num break for line in page findall http www w3 org 1999 xhtml span if line attrib class ocr_line continue linebox self regex_bbox search line attrib title group 1 split textangle self regex_textangle search line attrib title if textangle textangle self _atoi textangle group 1 else textangle 0 try baseline self regex_baseline search line attrib title group 1 split except AttributeError baseline 0 0 linebox float i for i in linebox baseline float i for i in baseline for word in line if word attrib class ocrx_word continue word_text for child in word iter if child text word_text append child text word text join word_text if word text is None continue logging debug word s angle d word text strip textangle box self regex_bbox search word attrib title group 1 split box float i for i in box coords 0 box 0 box 1 90 box 0 box 3 180 box 2 box 3 270 box 2 box 1 x y coords get textangle box 0 box 1 style getSampleStyleSheet normal style BodyText normal alignment TA_LEFT normal leading 0 font_name font_size self _get_font_spec word attrib title normal fontName Helvetica normal fontSize font_size para RotatedPara escape word text strip normal textangle para wrapOn pdf para minWidth 100 para drawOn pdf x 72 dpi height y 72 dpi
"get the fields defined by this class as a tuple of ( fieldname , fieldtype , attribs ) where attribs is a dict .",def getClassFields self ret for fname fieldinfo in self fields fieldname self const_pool fieldinfo name_index 1 data tagval strbytes descname self const_pool fieldinfo descriptor_index 1 data tagval strbytes attrs for afield attrinfo in fieldinfo attributes attrname self const_pool attrinfo attribute_name_index 1 data tagval strbytes attrs attrname attrinfo attribute ret append fieldname descname attrs return ret
visualizes a lomap system model .,def visualize self edgelabel control current_node None draw pygraphviz assert edgelabel is None or nx is_weighted self g weight edgelabel if draw pygraphviz nx view_pygraphviz self g edgelabel elif draw matplotlib pos nx get_node_attributes self g location if len pos self g number_of_nodes pos nx spring_layout self g if current_node is None colors r else if current_node init current_node next self init iterkeys colors dict v r for v in self g colors current_node b colors colors values nx draw self g pos pos node_color colors nx draw_networkx_labels self g pos pos edge_labels nx get_edge_attributes self g edgelabel nx draw_networkx_edge_labels self g pos pos edge_labels edge_labels else raise ValueError Expected parameter draw to be either pygraphviz or matplotlib
test the csv export by a logged out user,def test_export_csv_logged_out self self user_logout self export_csv fail True
"helper function for creating new choice types . this can be called either as : choice(name , [ type1 , type2 , ... ] ) or : choice([type1 , type2 , ... ] ) in the latter case , the name of the new type will be autogenerated , and will look like "" choice_type1_type2 "" .",def Choice args if len args 2 name alternatives args else name Choice_ _ join a __name__ for a in args 0 alternatives args 0 assert isinstance name Compatibility stringy assert all issubclass t Type for t in alternatives return TypeFactory new ChoiceFactory PROVIDES name tuple t serialize_type for t in alternatives
execute this aggregation on a given column and return the result .,def run self table raise NotImplementedError
"general operation handler for posted operations . for operation ' foo ' looks for a method op_foo and calls it with op_foo(op , req ) . replies with code 500 if op_foo is not found .",def perform self req op req args get op if op is None or len op 1 req setResponseCode http NOT_ACCEPTABLE Invalid request return op op 0 op_method self get_op_method op if op_method is None req setResponseCode http NOT_IMPLEMENTED Operation not implemented op req setHeader Content Type text plain req write Operation not implemented op return else try return op_method op req except Exception as exn req setResponseCode http INTERNAL_SERVER_ERROR Request failed op log exception Request s failed op if req useSxp return xend err str exn else return p s p str exn
templates : mako lookup by name,def test_name self t MakoTemplate name mako_simple lookup views render var var self assertEqual start var end n t
archive : the archive to be created,def __init__ self archive inputs self inputs PathSet inputs BaseTarget __init__ self archive self inputs
checks if a node still holds the lock .,def holds_lock self lock_path path id format path self _lock_path id self entry_id try self _client retry self _client sync lock_path value stat self _client retry self _client get lock_path except NoNodeError return False return value self lock_id
remotely execute a zerovm application .,command with_logging arg container help Swift container name containing the zapp arg summary s action store_true help Show execution summary table arg zapp help Name of the zapp to execute login_args def execute args resp zpm execute args if args summary total_time exec_table zpm _get_exec_table resp print Execution summary print exec_table print Total time s total_time
"dumps(object , encoding = none ) - > string",def dumps value encoding None q deque _rdumpq q 0 value encoding return join q
"used when a badalice / badcarol class decides to interrupt processing , simulating a crash ; reload state and run backout .",def failure_injection self self load self backout Fake injection
write the results to a json file,staticmethod def export df filename df to_json filename
compute a cryptographic hash of a list of strings,def hash_strings string_list sha1_hash hashlib sha1 for item in string_list sha1_hash update item encode return sha1_hash digest
get first value matching the key .,def get self key default None return self getone key default
"methods for adding quarterly feed . : param quarterly_feed : data to feed , which in form of dataframe : type quarterly_feed : pd . dataframe",def addQuarterlyFeed self quarterly_feed instrument for index data in quarterly_feed iterrows index str index index index split 0 year int index split 0 month int index split 1 day int index split 2 cur_date datetime datetime year month day finance_data for column in quarterly_feed columns finance_data column int data column quarterly_instrument_data QuarterlyInstrumentData instrument finance_data self __quarterly_feeds append quarterly_instrument_data
test sapdiag headers dissection without compression,def test_sapdiag_header_dissection_plain self diag_item SAPDiagItem item_value TEST_PLAIN diag_header_plain SAPDiag compress 0 diag_header_plain message append diag_item new_diag_header_plain SAPDiag str diag_header_plain self assertEqual str diag_header_plain str new_diag_header_plain
download and extract the tarball from alex 's website .,def maybe_download_and_extract obj_dir None if obj_dir is not None dest_directory obj_dir else dest_directory FLAGS data_dir if not os path exists dest_directory os makedirs dest_directory filename DATA_URL split 1 filepath os path join dest_directory filename if not os path exists filepath def _progress count block_size total_size sys stdout write r Downloading s 1f filename float count block_size float total_size 100 0 sys stdout flush filepath _ urllib request urlretrieve DATA_URL filepath _progress print statinfo os stat filepath print Successfully downloaded filename statinfo st_size bytes extracted_dir_path os path join dest_directory cifar 10 batches bin if not os path exists extracted_dir_path tarfile open filepath r gz extractall dest_directory
"sends a "" controlled_motorcmd "" to motorcontrol . port is nxt.motor.port_[a-c ] , power is -100 - 100 , tacholimit is 0 - 999999 , speedreg is whether to try to maintain speeds under load , and brake is whether to enable active braking after the motor is in the specified place ( different from the nxt.motor.turn ( ) function 's brake arg ) .",def cmd self port power tacholimit speedreg 1 smoothstart 0 brake 0 interval 0 01 self last_is_ready if port in self last_cmd interval 0 015 self last_cmd port mode str 1 int brake 2 int speedreg 4 int smoothstart command 1 str port _power power _tacho tacholimit mode self brick message_write 1 command self last_cmd port time time
"print a message to the console , depending on log level .",def _print message log_level prefix kwargs if log_level get_log_level if prefix click secho format LOG_PREFIXES log_level nl False return click secho message kwargs
"like numpy 's ` random.shuffle ` , but always has the same effect on a given argument .",def reproducible_shuffle x _rs shuffle x
"tautulli application entry point . parses arguments , setups encoding and initializes the application .",def main if hasattr sys frozen plexpy FULL_PATH os path abspath sys executable else plexpy FULL_PATH os path abspath __file__ plexpy PROG_DIR os path dirname plexpy FULL_PATH plexpy ARGS sys argv 1 plexpy SYS_PLATFORM sys platform plexpy SYS_ENCODING None try locale setlocale locale LC_ALL plexpy SYS_LANGUAGE plexpy SYS_ENCODING locale getdefaultlocale except locale Error IOError pass if not plexpy SYS_ENCODING or plexpy SYS_ENCODING in ANSI_X3 4 1968 US ASCII ASCII plexpy SYS_ENCODING UTF 8 parser argparse ArgumentParser description A Python based monitoring and tracking tool for Plex Media Server parser add_argument v verbose action store_true help Increase console logging verbosity parser add_argument q quiet action store_true help Turn off console logging parser add_argument d daemon action store_true help Run as a daemon parser add_argument p port type int help Force Tautulli to run on a specified port parser add_argument dev action store_true help Start Tautulli in the development environment parser add_argument datadir help Specify a directory where to store your data files parser add_argument config help Specify a config file to use parser add_argument nolaunch action store_true help Prevent browser from launching on startup parser add_argument pidfile help Create a pid file only relevant when running as a daemon parser add_argument nofork action store_true help Start Tautulli as a service do not fork when restarting args parser parse_args if args verbose plexpy VERBOSE True if args quiet plexpy QUIET True logger initLogger console not plexpy QUIET log_dir False verbose plexpy VERBOSE if args dev plexpy DEV True logger debug u Tautulli is running in the dev environment if args daemon if sys platform win32 sys stderr write Daemonizing not supported under Windows starting normally n else plexpy DAEMON True plexpy QUIET True if args nofork plexpy NOFORK True logger info Tautulli is running as a service it will not fork when restarted if args pidfile plexpy PIDFILE str args pidfile if os path exists plexpy PIDFILE try with open plexpy PIDFILE r as fp pid int fp read os kill pid 0 except IOError as e raise SystemExit Unable to read PID file s e except OSError logger warn PID file s already exists but PID d is not running Ignoring PID file plexpy PIDFILE pid else raise SystemExit PID file s already exists Exiting plexpy PIDFILE if plexpy DAEMON plexpy CREATEPID True try with open plexpy PIDFILE w as fp fp write pid n except IOError as e raise SystemExit Unable to write PID file s e else logger warn Not running in daemon mode PID file creation disabled if args datadir plexpy DATA_DIR args datadir else plexpy DATA_DIR plexpy PROG_DIR if args config config_file args config else config_file os path join plexpy DATA_DIR config FILENAME if not os path exists plexpy DATA_DIR try os makedirs plexpy DATA_DIR except OSError raise SystemExit Could not create data directory plexpy DATA_DIR Exiting if not os access plexpy DATA_DIR os W_OK raise SystemExit Cannot write to the data directory plexpy DATA_DIR Exiting plexpy DB_FILE os path join plexpy DATA_DIR database FILENAME if os path isfile os path join plexpy DATA_DIR plexpy db and not os path isfile os path join plexpy DATA_DIR plexpy DB_FILE try os rename os path join plexpy DATA_DIR plexpy db plexpy DB_FILE except OSError as e raise SystemExit Unable to rename plexpy db to tautulli db s e if plexpy DAEMON plexpy daemonize plexpy initialize config_file plexpy start if args port http_port args port logger info Using forced web server port i http_port else http_port int plexpy CONFIG HTTP_PORT if plexpy CONFIG ENABLE_HTTPS try import OpenSSL except ImportError logger warn The pyOpenSSL module is missing Install this module to enable HTTPS HTTPS will be disabled plexpy CONFIG ENABLE_HTTPS False web_config http_port http_port http_host plexpy CONFIG HTTP_HOST http_root plexpy CONFIG HTTP_ROOT http_environment plexpy CONFIG HTTP_ENVIRONMENT http_proxy plexpy CONFIG HTTP_PROXY enable_https plexpy CONFIG ENABLE_HTTPS https_cert plexpy CONFIG HTTPS_CERT https_cert_chain plexpy CONFIG HTTPS_CERT_CHAIN https_key plexpy CONFIG HTTPS_KEY http_username plexpy CONFIG HTTP_USERNAME http_password plexpy CONFIG HTTP_PASSWORD http_basic_auth plexpy CONFIG HTTP_BASIC_AUTH webstart initialize web_config if plexpy CONFIG LAUNCH_BROWSER and not args nolaunch and not plexpy DEV plexpy launch_browser plexpy CONFIG HTTP_HOST http_port plexpy CONFIG HTTP_ROOT while True if not plexpy SIGNAL try time sleep 1 except KeyboardInterrupt plexpy SIGNAL shutdown else logger info Received signal s plexpy SIGNAL if plexpy SIGNAL shutdown plexpy shutdown elif plexpy SIGNAL restart plexpy shutdown restart True elif plexpy SIGNAL checkout plexpy shutdown restart True checkout True else plexpy shutdown restart True update True plexpy SIGNAL None
helper that reads bundles from the webapp .,def read_bundle text_length_bytes sys stdin read 4 text_length struct unpack i text_length_bytes 0 raw_text sys stdin read text_length decode utf 8 return json loads raw_text
"parse elf file into a { path : [ ( symbol , linenumber , size ) ] } dictionary",def parse_elf filename minimum_size None symbol_type_list None function_path_regex_in None function_name_regex_in None object_path_regex_in None object_name_regex_in None function_path_regex_ex None function_name_regex_ex None object_path_regex_ex None object_name_regex_ex None output subprocess check_output nm radix d S l size sort filename addr size type name path line addressses x split for x in output splitlines paths dict for foo in addressses size foo 1 stype foo 2 symbolname foo 3 if len foo 4 pathname lineno foo 4 split else pathname lineno size int size if minimum_size and size minimum_size continue pathname path normpath pathname if pathname 0 pathname pathname 1 if stype in tT ppati function_path_regex_in npati function_name_regex_in ppate function_path_regex_ex npate function_name_regex_ex elif stype in bB ppati object_path_regex_in npati object_name_regex_in ppate object_path_regex_ex npate object_name_regex_ex else ppat None npat None ppati None ppate None npati None npate None if ppati and not re search ppati pathname continue if npati and not re search npati symbolname continue if ppate and re search ppate pathname continue if npate and re search npate symbolname continue if symbol_type_list and stype not in symbol_type_list continue if not pathname in paths paths pathname list paths pathname append symbolname lineno size stype return paths
loop ( ) function repeats over and over ... forever !,def loop print Blink sequence board digital_write 13 1 board sleep 0 5 board digital_write 13 0 board sleep 0 5
result array assignment for the stats_uniform_pdf ferret pyef,def ferret_compute id result resbdf inputs inpbdfs pyferret stats assignresultsarray DISTRIB_NAME FUNC_NAME result resbdf inputs inpbdfs
creates a new apirequest object for the specified api call .,def __init__ self api_call authentication_token self _api_call api_call self _authentication_token authentication_token self _connection http client HTTPSConnection SLACK_DOMAIN
"return a dictionary of running processes , with their id as the value . the id is used to determine which process was most recently loaded .",def get_running_processes task_list os popen tasklist NH FO CSV read splitlines running_processes for i task_raw in enumerate task_list image task_raw split 1 0 1 1 if in image running_processes image i return running_processes
pass user organization to the form .,def get_form_kwargs self u kw super TaskCreateView self get_form_kwargs kw update u organization self request user organization return kw
: type root : treenode : type sum : int : rtype : bool,def hasPathSum root sum if root is None and sum is 0 return False if not root return False if not root left and not root right and root val sum return True return hasPathSum root left sum root val or hasPathSum root right sum root val
translates objective input to model input with respect to current variable,def objective_to_model self x_objective return x_objective
uses ' errors ' dictionary to generate defines in doserr.c file,def _gen_doserr_defs self errors fp self _open_out_file self FNAME_DOSERR_DEFS for err_code in sorted errors keys err_name errors err_code err_name fp write t s s err_name err_name fp write n fp close
retrieves the field making up the feature if the feature is based on a single field .,property def field self if len self _fields 1 return self _fields 0 return None
"it 's possible that training repositories have different programming languages than the repos in the validation set . thus , both data frames have different feature columns . this method completes the columns for both data frames .",def complete_columns training_df valid_df for c in valid_df columns if c not in training_df columns training_df c 0 for c in training_df columns if c not in valid_df columns valid_df c 0 return training_df valid_df
load user data from service .,def user_data self access_token args kwargs return self get_json self USER_DATA_URL params access_token access_token
do whatever is needed to reset the state - typically a scene clear will be enough .,def setUp self slicer mrmlScene Clear 0
make fits image into png image,def fits_to_png fn_in fn_out None vmin None vmax None scaling arcsinh extension png if fn_out is None base_in ext_in os path splitext fn_in if ext_in fits fn_out base_in extension else fn_out fn_in extension if not os path isfile fn_in print skipping fn_in as in file does not exist else img fits getdata fn_in img_scaled scale_img img vmin vmin vmax vmax scaling scaling si imsave fn_out img_scaled
author : airbnb_csirt description : identifies creation of an ami with a non encrypted volume reference : https://amzn.to/2rqilun playbook : ( a ) reach out to the user who created the volume ( b ) re - create the ami with encryption enabled ( c ) delete the old ami,rule logs cloudwatch events req_subkeys detail requestParameters eventName def unencrypted_ami_volume rec if rec detail eventName CreateImage return False elif rec detail requestParameters is None return False req_params rec detail requestParameters block_device_items req_params get blockDeviceMapping get items if not block_device_items return False volume_encryption_enabled set for block_device in block_device_items volume_encryption_enabled add block_device get ebs get encrypted return not any volume_encryption_enabled
helper function to put mock parameters in parameter store for an app integration,def put_mock_params self app_type config cluster unit_test_cluster app_name unit_app prefix unit_test_prefix type app_type schedule_expression rate 1 hour self put_parameter Name _config format FUNCTION_NAME Value json dumps config Overwrite True state last_timestamp 1505591798 current_state running self put_parameter Name _state format FUNCTION_NAME Value json dumps state Overwrite True self put_parameter Name _auth format FUNCTION_NAME Value json dumps self get_auth_info app_type Overwrite True
slackoutput - json list to text,def test_json_list_to_text self simple_list test_value_01 test_value_02 nested value_03 result SlackOutput _json_list_to_text simple_list t 0 assert_equal len result 4 assert_equal result 0 1 test_value_01 assert_equal result 1 2 test_value_02 assert_equal result 2 3 assert_equal result 3 t nested value_03
initiate todaychart.py module to graph sump pit activity .,def main csv_file home pi raspi sump csv waterlevel csv format time strftime Y m d filename home pi raspi sump charts today png bytes2str todaychart bytesdate2str H M S todaychart graph csv_file filename bytes2str
"test retrieval user list expected : [ [ user , attendance ] , [ user , attendance ] ]",def test_attendance_to_user_list self pass
verify that a meta network is properly created,patch disco_aws_automation disco_subnet DiscoSubnet __init__ return_value None def test_create_meta_network self mock_subnet_init self meta_network create self mock_vpc_conn get_all_route_tables assert_called_once_with filters MOCK_ROUTE_FILTER self mock_vpc_conn get_all_security_groups assert_called_once_with filters MOCK_ROUTE_FILTER self assertEquals self meta_network centralized_route_table MOCK_ROUTE_TABLE self assertEquals self meta_network security_group self mock_vpc_conn get_all_security_groups return_value 0 calls call MOCK_ZONE1 name self meta_network 10 101 0 0 18 MOCK_ROUTE_TABLE id call MOCK_ZONE2 name self meta_network 10 101 64 0 18 MOCK_ROUTE_TABLE id call MOCK_ZONE3 name self meta_network 10 101 128 0 18 MOCK_ROUTE_TABLE id mock_subnet_init assert_has_calls calls self assertEquals len self meta_network disco_subnets values len MOCK_ZONES
"create a backup - restore pipeline if needed , and activate it to restore a particular table from either a particular backup or the latest one .",def restore_backup self table_name backup_dir None force_update False metanetwork None env self config environment pipeline_name s restore s table_name env pipeline_description DynamoDB backup restore pipeline for s env tags environment env template self RESTORE_PIPELINE_TEMPLATE table_name table_name if not backup_dir self logger debug Looking in S3 for most recent backup of s s env table_name backup_dir self _find_latest_backup env table_name self logger info Restoring from backup s backup_dir pipeline self _mgr fetch_or_create self RESTORE_PIPELINE_TEMPLATE pipeline_name pipeline_name tags tags pipeline_description pipeline_description log_location self _s3_url logs metanetwork metanetwork force_update force_update param_values self _get_table_params table_name param_values myInputS3Loc self _s3_url env table_name backup_dir self logger debug Starting restore pipeline with these parameter values s param_values start_resp self _mgr start pipeline param_values self logger debug Started pipeline got response s start_resp
this is called [ ( c+n)/m ] in martig 2016,def calc_sum mh cm nm C_H cm mh N_H nm mh Nc_Nh 10 C_H 8 39 12 Nn_Nh 10 N_H 7 78 12 Nc_Nh_sun 10 8 39 12 Nn_Nh_sun 10 7 78 12 CplusN np log10 Nc_Nh Nn_Nh np log10 Nc_Nh_sun Nn_Nh_sun mh return CplusN
"clean a dictionary of data of potentially sensitive info before sending to the database . function based on the "" _ clean_credentials "" function of django ( https://github.com/django/django/blob/stable/1.11.x/django/contrib/auth/__init__.py#l50 )",def _clean_data self data if isinstance data list return self _clean_data d for d in data if isinstance data dict SENSITIVE_FIELDS api token key secret password signature data dict data if self sensitive_fields SENSITIVE_FIELDS SENSITIVE_FIELDS field lower for field in self sensitive_fields for key value in data items try value ast literal_eval value except ValueError SyntaxError pass if isinstance value list or isinstance value dict data key self _clean_data value if key lower in SENSITIVE_FIELDS data key self CLEANED_SUBSTITUTE return data
evaluate the post - test conditions,def evaluate_post_checks self if not self _postchecks return None LOGGER debug Evaluating post checks finished_deferred defer Deferred self __evaluate_check self _postchecks 0 finished_deferred return finished_deferred
get list of available deployable images .,def get_available_images self image_options list for k v in self resources items if v get_image_name not in image_options image_options append v get_image_name return image_options
create vg on top of ram memory to speed up lv performance .,error context_aware def vg_ramdisk vg_name ramdisk_vg_size ramdisk_basedir ramdisk_sparse_filename error context Creating virtual group on top of ram memory logging info vg_size ramdisk_vg_size vg_ramdisk_dir os path join ramdisk_basedir vg_name ramdisk_filename os path join vg_ramdisk_dir ramdisk_sparse_filename vg_ramdisk_cleanup ramdisk_filename vg_ramdisk_dir vg_name result if not os path exists vg_ramdisk_dir os mkdir vg_ramdisk_dir try logging info Mounting tmpfs result utils run mount t tmpfs tmpfs vg_ramdisk_dir logging info Converting and copying dev zero cmd dd if dev zero of ramdisk_filename bs 1M count 1 seek vg_size result utils run cmd verbose True logging info Finding free loop device result utils run losetup find verbose True except error CmdError as ex logging error ex vg_ramdisk_cleanup ramdisk_filename vg_ramdisk_dir vg_name raise ex loop_device result stdout rstrip try logging info Creating loop device result utils run losetup loop_device ramdisk_filename logging info Creating physical volume s loop_device result utils run pvcreate loop_device logging info Creating volume group s vg_name result utils run vgcreate vg_name loop_device except error CmdError as ex logging error ex vg_ramdisk_cleanup ramdisk_filename vg_ramdisk_dir vg_name loop_device raise ex logging info result stdout rstrip
od.__eq__(y ) < = = > od==y . comparison to another od is order - sensitive while comparison to a regular mapping is order - insensitive .,def __eq__ self other if isinstance other OrderedDict return len self len other and self items other items return dict __eq__ self other
tests the duration with endpoints and finite time .,def test_duration_finite self t TimePeriod start datetime datetime 2000 1 1 end datetime datetime 2000 1 2 self assertEqual datetime timedelta days 1 t duration
create a new control panel .,def __init__ self parent self parent parent wx Panel __init__ self parent style wx SUNKEN_BORDER parent SHOW_CONTROL_PANEL_KEY True parent subscribe SHOW_CONTROL_PANEL_KEY self Show control_box wx BoxSizer wx VERTICAL control_box AddStretchSpacer options_box forms static_box_sizer parent self sizer control_box label Trace Options bold True orient wx VERTICAL forms check_box sizer options_box parent self label Peak Hold ps parent key PEAK_HOLD_KEY forms check_box sizer options_box parent self label Average ps parent key AVERAGE_KEY avg_alpha_text forms static_text sizer options_box parent self label Avg Alpha converter forms float_converter lambda x 4f x ps parent key AVG_ALPHA_KEY width 50 avg_alpha_slider forms log_slider sizer options_box parent self min_exp AVG_ALPHA_MIN_EXP max_exp AVG_ALPHA_MAX_EXP num_steps SLIDER_STEPS ps parent key AVG_ALPHA_KEY for widget in avg_alpha_text avg_alpha_slider parent subscribe AVERAGE_KEY widget Enable widget Enable parent AVERAGE_KEY parent subscribe AVERAGE_KEY widget ShowItems widget ShowItems True parent subscribe AVERAGE_KEY self _update_layout forms check_box sizer options_box parent self label Persistence ps parent key USE_PERSISTENCE_KEY persist_alpha_text forms static_text sizer options_box parent self label Persist Alpha converter forms float_converter lambda x 4f x ps parent key PERSIST_ALPHA_KEY width 50 persist_alpha_slider forms log_slider sizer options_box parent self min_exp PERSIST_ALPHA_MIN_EXP max_exp PERSIST_ALPHA_MAX_EXP num_steps SLIDER_STEPS ps parent key PERSIST_ALPHA_KEY for widget in persist_alpha_text persist_alpha_slider parent subscribe USE_PERSISTENCE_KEY widget Enable widget Enable parent USE_PERSISTENCE_KEY parent subscribe USE_PERSISTENCE_KEY widget ShowItems widget ShowItems True parent subscribe USE_PERSISTENCE_KEY self _update_layout for trace in TRACES trace_box wx BoxSizer wx HORIZONTAL options_box Add trace_box 0 wx EXPAND forms check_box sizer trace_box parent self ps parent key TRACE_SHOW_KEY trace label Trace s trace trace_box AddSpacer 10 forms single_button sizer trace_box parent self ps parent key TRACE_STORE_KEY trace label Store style wx BU_EXACTFIT trace_box AddSpacer 10 control_box AddStretchSpacer y_ctrl_box forms static_box_sizer parent self sizer control_box label Axis Options bold True orient wx VERTICAL forms incr_decr_buttons parent self sizer y_ctrl_box label dB Div on_incr self _on_incr_db_div on_decr self _on_decr_db_div forms incr_decr_buttons parent self sizer y_ctrl_box label Ref Level on_incr self _on_incr_ref_level on_decr self _on_decr_ref_level y_ctrl_box AddSpacer 2 forms single_button sizer y_ctrl_box parent self label Autoscale callback self parent autoscale control_box AddStretchSpacer forms toggle_button sizer control_box parent self true_label Stop false_label Run ps parent key RUNNING_KEY self SetSizerAndFit control_box def on_mouse_wheel event if event GetWheelRotation 0 self _on_incr_ref_level event else self _on_decr_ref_level event parent plotter Bind wx EVT_MOUSEWHEEL on_mouse_wheel
"find out which name the main swig file has . in particular , is it a modname.i or a modname_swig.i ? returns none if none is found .",def _get_mainswigfile self modname self _info modname swig_files modname i modname _swig i for fname in swig_files if os path isfile os path join self _dir swig fname return fname return None
make sure we say ' red ' when interpreter thinks ' read ',def test_read_correction self command_text set the office to read command Command command_text assert command room office assert command action hue assert command value settings COLORS red
"http_basic_credentials are not checked , only parsed from request",app route authenticate method GET def authenticate http_basic_credentials service BiiService app store None return service authenticate http_basic_credentials user http_basic_credentials password
"execute join process , do nothing .",def execute self self executed True
sets the headlight of the camera of the viewport,abstractmethod def setHeadlightIsActive self active return False
assign new actions to controls via xclips,def assign_new_actions self string if self _xt_scripts for x in self _xt_scripts x assign_new_actions string ident string string index 2 string index strip actions string string index 2 strip for c v in self _control_list items if ident v ident new_actions actions split on_action ident new_actions 0 off_action None if on_action and len new_actions 1 if new_actions 1 strip off_action on_action else off_action ident new_actions 1 if on_action v on_action on_action v off_action off_action break
adds a given bug to the db .,def add_bug number summary status assigned_to system bug Bug number int number summary summary status status assigned_to assigned_to system system db session add bug db session commit
"translates ( range , nbins ) -- > { starts , ends , medians }",def get_bins freqRange 05 95 numbins 9 fullrange float x for x in freqRange split binlen fullrange 1 fullrange 0 float numbins bin_starts fullrange 0 binlen i for i in range numbins bin_ends fullrange 0 binlen i for i in range 1 numbins 1 bin_medians float bin_starts i float bin_ends i 2 0 for i in range len bin_starts bin_medians_str get_bin_strings bin_medians return fullrange bin_starts bin_ends bin_medians bin_medians_str
write a fp into the cache . @param i d : the object id . @type i d : str @param fp : file pointer . @type fp : file - like object .,def putf self id fp raise Exception not implemented
for anyone wishing to directly access the receiver,def get_receiver_surf self return self _rec
start ( or reload ) a bird daemon using the given parameters .,def _start_bird_daemon self bird bird_conf bird_config bird_log bird_ctl bird_pid self logger debug creating BIRD configuration file s bird_conf bird_config conf bird_conf bird_config log bird_log bird_config log_level self log_level bird_config overlay self name bird_config asn self asn if not self dry_run with open bird_conf w as fil fil write self bird_conf_template render bird_config if util pid_exists pid_file bird_pid self logger debug connecting to the BIRD control socket s bird_ctl sock None data None if self dry_run data 0001 BIRD 1 4 0 ready n else sock socket socket socket AF_UNIX socket SOCK_STREAM sock connect bird_ctl data sock recv RECV_MAX decode UTF 8 if not re match 0001 BIRD 0 9 ready n data raise UnexpectedResponseError connecting data self logger debug reloading BIRD configuration if self dry_run data 0002 Reading configuration from s n0003 Reconfigured bird_conf else sock send bytes configure s n bird_conf UTF 8 data sock recv RECV_MAX decode UTF 8 if 0002 Reading configuration from s bird_conf not in data or 0003 Reconfigured not in data and 0004 Reconfiguration in progress not in data raise UnexpectedResponseError reloading config data if not self dry_run sock close else bird_command bird c bird_conf s bird_ctl P bird_pid self logger debug starting BIRD using command s join bird_command bird_process self netns Popen bird_command stdout subprocess PIPE stderr subprocess PIPE try stdout stderr bird_process communicate if bird_process returncode 0 raise ProcessError s encountered an error on execution bird bird_process stdout stderr if stdout self logger debug stdout n s stdout decode UTF 8 if stderr self logger debug stderr n s stderr decode UTF 8 finally bird_process release
"parse a fen string into components and store in the ` board ` and ` state ` properties , and append the fen string to the game history * without * clearing it first .",def set_fen self fen self fen_history append fen fields fen split fields 4 int fields 4 fields 5 int fields 5 self state State fields 1 self board set_position fields 0
take a list of z matrices ( given by their decomposition ) and reconstruct them for the given indices .,def predict self ZList inds predXList for Z in ZList U s V Z Xhat ExpSU SparseUtils reconstructLowRank U s V inds predXList append Xhat return predXList
remove naughty words that might come from wordnet synsets and lemmata .,def remove_bad_words words bad_words nigger wop kike faggot fuck pussy cunt return word for word in words if word lower not in bad_words
return an iterator over the lines of an input file .,def iter_lines self f for line_no line in enumerate iter f start 1 self line line self line_no line_no yield line log info parsed d lines line_no
atmospheres ( atm ) to pascals ( pa ),def atm_to_pa atm return atm 101325
read graph in leda format from string or iterable .,def parse_leda lines if is_string_like lines lines iter lines split n lines iter line rstrip n for line in lines if not line startswith or line startswith n or line for i in range 3 next lines du int next lines if du 1 G nx DiGraph else G nx Graph n int next lines node for i in range 1 n 1 symbol next lines rstrip strip if symbol symbol str i node i symbol G add_nodes_from s for i s in node items m int next lines for i in range m try s t reversal label next lines split except raise NetworkXError Too few fields in LEDA GRAPH edge d i 1 G add_edge node int s node int t label label 2 2 return G
return the pagerank of the nodes in the graph .,def pagerank_numpy G alpha 0 85 personalization None weight weight try import numpy as np except ImportError raise ImportError pagerank_numpy requires NumPy http scipy org if len G 0 return if personalization is None nodelist G nodes else nodelist personalization keys M google_matrix G alpha personalization personalization nodelist nodelist weight weight eigenvalues eigenvectors np linalg eig M T ind eigenvalues argsort largest np array eigenvectors ind 1 flatten real norm float largest sum centrality dict zip nodelist map float largest norm return centrality
parse one packet and return the associate http request if any .,def handle_packet timestamp packet u eth dpkt ethernet Ethernet packet try eth dpkt ethernet Ethernet packet except dpkt dpkt NeedData dpkt dpkt UnpackError return None if not isinstance eth data dpkt ip IP logging info u Non IP Packet type not supported s n eth data __class__ __name__ return None ip eth data if not isinstance ip data dpkt tcp TCP return tcp ip data try request dpkt http Request tcp data except dpkt dpkt NeedData dpkt dpkt UnpackError return None return datetime datetime utcfromtimestamp timestamp request
"setup the exposure type : exptime - exposure time in milliseconds frametype - ' normal ' - open shutter exposure ' dark ' - exposure with shutter closed ' rbi_flush ' - flood ccd with internal light , with shutter closed",def set_exposure self exptime frametype normal exptime c_long exptime if frametype normal frametype fliframe_t FLI_FRAME_TYPE_NORMAL elif frametype dark frametype fliframe_t FLI_FRAME_TYPE_DARK elif frametype rbi_flush frametype fliframe_t FLI_FRAME_TYPE_RBI_FLUSH else raise ValueError frametype must be either normal dark or rbi_flush self _libfli FLISetExposureTime self _dev exptime self _libfli FLISetFrameType self _dev frametype
creates a new experiment instance .,def create_experiment output_dir u n Creates a new Experiment instance n n Args n output_dir Output directory for model checkpoints and summaries n import pdb pdb set_trace config run_config RunConfig tf_random_seed FLAGS tf_random_seed save_checkpoints_secs FLAGS save_checkpoints_secs save_checkpoints_steps FLAGS save_checkpoints_steps keep_checkpoint_max FLAGS keep_checkpoint_max keep_checkpoint_every_n_hours FLAGS keep_checkpoint_every_n_hours gpu_memory_fraction FLAGS gpu_memory_fraction config tf_config gpu_options allow_growth FLAGS gpu_allow_growth config tf_config log_device_placement FLAGS log_device_placement train_options training_utils TrainOptions model_class FLAGS model model_params FLAGS model_params if config is_chief gfile MakeDirs output_dir train_options dump output_dir bucket_boundaries None if FLAGS buckets bucket_boundaries list map int FLAGS buckets split u train_input_pipeline input_pipeline make_input_pipeline_from_def def_dict FLAGS input_pipeline_train mode tf contrib learn ModeKeys TRAIN train_input_fn training_utils create_input_fn pipeline train_input_pipeline batch_size FLAGS batch_size bucket_boundaries bucket_boundaries scope u train_input_fn dev_input_pipeline input_pipeline make_input_pipeline_from_def def_dict FLAGS input_pipeline_dev mode tf contrib learn ModeKeys EVAL shuffle False num_epochs 1 eval_input_fn training_utils create_input_fn pipeline dev_input_pipeline batch_size FLAGS batch_size allow_smaller_final_batch True scope u dev_input_fn def model_fn features labels params mode u Builds the model graph model _create_from_dict u class train_options model_class u params train_options model_params models mode mode return model features labels params estimator tf contrib learn Estimator model_fn model_fn model_dir output_dir config config params FLAGS model_params print u Creating hooks train_hooks for dict_ in FLAGS hooks hook _create_from_dict dict_ hooks model_dir estimator model_dir run_config config train_hooks append hook print u Creating metrics eval_metrics for dict_ in FLAGS metrics metric _create_from_dict dict_ metric_specs eval_metrics metric name metric print u Launching experiment experiment PatchedExperiment estimator estimator train_input_fn train_input_fn eval_input_fn eval_input_fn min_eval_frequency FLAGS eval_every_n_steps train_steps FLAGS train_steps eval_steps None eval_metrics eval_metrics train_monitors train_hooks return experiment
"grant a user permission to select , insert , and update their own rows in the row level security policy table .",staticmethod def add_user_to_policy_table username username username lower policy grantor s username grantee username grantor settings DATABASES default USER repo_base settings POLICY_DB repo settings POLICY_SCHEMA table settings POLICY_TABLE security_policies RowLevelSecurityManager find_security_policies repo_base repo repo table table policy policy policy_type None grantee grantee grantor grantor safe False if len security_policies 0 return with _superuser_connection repo_base settings POLICY_DB as conn conn create_security_policy policy policy policy_type select grantee grantee grantor grantor repo_base repo_base repo repo table table conn create_security_policy policy policy policy_type insert grantee grantee grantor grantor repo_base repo_base repo repo table table conn create_security_policy policy policy policy_type update grantee grantee grantor grantor repo_base repo_base repo repo table table
return a dictionary representation of the variable .,def to_dict self return type self type parents list self supertypes properties self properties
return an encoded wire format version of the header for this message as it stands . totallength - 4 bytes headerlength - 2 bytes encoded header pieces,classmethod def encode cls msg options list for key name in MAGIMessage OPTIONS iteritems val getattr msg name if val is not None if key 20 options append struct pack BBI key 4 val elif key 50 options append struct pack BB ds len val key len val val else for item in val if item is None log warning Got a None value in key s skipping key else options append struct pack BB ds len item key len item item optionstr join options headerlen 6 len optionstr totallen 2 headerlen if msg data is not None totallen len msg data return struct pack IHIBB totallen headerlen msg msgid msg flags msg contenttype optionstr
is this a null section ?,def is_null self return False
convert a list of words into a dictionary of word / count pairs . does not include words not deemed interesting .,def getcounts words None counts collections Counter words wordsused len counts shortwords word for word in counts if len word 3 ignore shortwords after all and are because been but for from has have her more not now our than that the these they their this was were when who will with year hpv19slimfeature div for word in ignore counts pop word None tempcopy _ for _ in words for word in tempcopy if noalpha word counts pop word None return counts wordsused
"sethandshakemode can not take a value other than none , 0 , 1 , 2 or 3 .",def test_dci_sethandshakemode_03 assert raises ValueError t SetHandshakeMode 32
helper function for calculating albedo given the semi - major axis . the prototype provides only a dummy function that always returns the same value of 0.367 .,def calc_albedo_from_sma self a p np array 0 367 a size return p
sets the zoom amount to this view by taking the view iconsize()*value,def setZoomAmount self value self zoomAmount value currentSize self iconSize newSize currentSize width value if newSize self defaultMinIconSize or newSize self defaultMaxIconSize return currentSize setWidth newSize currentSize setHeight newSize self requestZoom emit newSize self zoomAmount self setIconSize currentSize
modifies the relationship between the current user and the target user .,base apimethod def update self action request http Request POST self get_url action action return request parsers parse_json
return the resource corresponding to a single case .,base resource cases Case def case self case_id is_external False return cases Case self case_id is_external
returns the average length of a user session per day .,base apimethod def avg_session_length self args kwargs return self _get AvgSessionLength args kwargs
converts django model to sqlalchemy table,def convert_model model field_types options model _meta fields rels for f in options get_fields i f name if i in field_types fields append sa column i field_types i elif f is_relation if f many_to_many rels i convert_m2m f elif f many_to_one fields append FIELD_CONVERTER convert f elif f one_to_many pass elif f one_to_one if not f auto_created fields append FIELD_CONVERTER convert f else raise ConversionError Unknown relation format i else fields append FIELD_CONVERTER convert f return sa table options db_table fields rels
convert a dict struct into a objdict structure,def dict_to_objdict dictionnary None o objdict if dictionnary for k v in dictionnary iteritems if type v dict o k dict_to_objdict v else o k v return o
use given credentials to login to studio .,def login_to_studio self email password if self studio_url is None raise ValueError You must supply studio_url to init self login email password self studio_url signin login_post
get a feed of all updates to an issue .,def get_comments self project_name issue_id desired_class gdata projecthosting data CommentsFeed kwargs return self get_feed gdata projecthosting data COMMENTS_FULL_FEED project_name issue_id desired_class desired_class kwargs
tests overriding on the class that has the @final methods in it .,def test_override_on_super self old_a self class_ a old_f self class_ f try with self assertRaises TypeError self class_ f lambda args None except Exception self class_ f old_f raise try with self assertRaises TypeError self class_ a SubClass a except Exception self class_ a old_a raise
generates a unique key for a node .,def get_key self node return self _get_hash_value node obj
check the user has this permission .,def _get_granted self return get_permissions_manager check_permissions self
"adds all of the matching values in the specified * input_context * to the specified * output_context * , and then applies itself recursively to all contexts contained in the specified * input_context*.",def _add_context self input_context values path self _add_values input_context values path gdc input_context get_data_context for name in input_context data_contexts self _add_context gdc name values path_for path input_context data_context_name
return full source of start tag : ' < ... > ' .,def get_starttag_text self u return self __starttag_text
"this is a shortcut for arranging to serialize third - party clases . ' copier ' must be a callable which accepts an instance of the class you want to serialize , and returns a tuple of ( typename , state_dictionary ) . if it returns a typename of none , the original class 's fully - qualified classname is used .",def registerCopier klass copier klassname reflect qual klass class _CopierAdapter implements ICopyable def __init__ self original self nameToCopy self state copier original if self nameToCopy is None self nameToCopy klassname def getTypeToCopy self return self nameToCopy def getStateToCopy self return self state registerAdapter _CopierAdapter klass ICopyable
return object of specified type and i d .,def loadObject self objType objId raise NotImplementedError
upgrades the idevice class members from version 1 to version 2 . should be called in derived classes .,def _upgradeIdeviceToVersion2 self log debug upgrading to version 2 for 0 12 self userResources if self icon self systemResources icon_ self icon gif else self systemResources
test that the tree properties lets us extract the right information .,def testProperties self t parse_tree A B C self assertEqual t leaves_identifiers A B C self assertNotEqual t leaves A B C self assertEqual len t edges 2 n1 _ _ n2 _ _ t edges self assertEqual type n1 Tree self assertEqual type n2 Leaf self assertEqual n2 identifier C
return the amqp binary encoded value of the frame,def marshal self pieces self properties encode pieces insert 0 struct pack HxxQ self properties INDEX self body_size return self _marshal pieces
extract _ _ * meta * _ _ from meta_file .,def find_meta meta meta_match re search P name __ meta __ s s P value s format meta meta META_FILE re M if meta_match return meta_match group value raise RuntimeError Unable to find __ meta __ string format meta meta
convert pwm array to pssm array,def pwm_array2pssm_array arr background_probs DEFAULT_BASE_BACKGROUND b background_probs2array background_probs b b reshape 1 4 1 return np log arr b astype arr dtype
test that will open and close sessions repeatedly,def open_and_close_sessions self slot get_token_by_label_ex self token_label ret h_session c_open_session slot assert ret_vals_dictionary ret ret_vals_dictionary CKR_OK ret c_close_session h_session assert ret_vals_dictionary ret ret_vals_dictionary CKR_OK
set members based using inventory .,def _configure self PetscComponent _configure self self verbose self inventory verbose return
calculate matrix of derivatives of basis functions .,def _calculateBasisDerivMatNonlinear self basisDeriv iQuad B numpy zeros self spaceDim self spaceDim self spaceDim self numBasis dtype numpy float64 for iBasis in xrange self numBasis for iDim in xrange self spaceDim for jDim in xrange self spaceDim B jDim iDim self spaceDim iBasis self spaceDim iDim basisDeriv iQuad iBasis jDim return B
"generates a networkx . digraph from shapefiles . point geometries are translated into nodes , lines into edges . coordinate tuples are used as keys . attributes are preserved , line geometries are simplified into start and end coordinates . accepts a single shapefile or directory of many shapefiles .",def read_shp path try from osgeo import ogr except ImportError raise ImportError read_shp requires OGR http www gdal org net nx DiGraph def getfieldinfo lyr feature flds f feature return f GetField f GetFieldIndex x for x in flds def addlyr lyr fields for findex in xrange lyr GetFeatureCount f lyr GetFeature findex flddata getfieldinfo lyr f fields g f geometry attributes dict zip fields flddata attributes ShpName lyr GetName if g GetGeometryType 1 net add_node g GetPoint_2D 0 attributes if g GetGeometryType 2 attributes Wkb g ExportToWkb attributes Wkt g ExportToWkt attributes Json g ExportToJson last g GetPointCount 1 net add_edge g GetPoint_2D 0 g GetPoint_2D last attributes if isinstance path str shp ogr Open path lyrcount shp GetLayerCount for lyrindex in xrange lyrcount lyr shp GetLayerByIndex lyrindex flds x GetName for x in lyr schema addlyr lyr flds return net
are benchmarks added to apps on the list ?,def test_benchmarks_in_apps self app_manager self _get_loaded_app_manger for app in app_manager apps values assert issubclass app benchmark CoreBenchmark
creates a wrapper function that saves / restores flag values .,def _FlagSaver func overrides functools wraps func def _FlagSaverWrapper args kwargs Wrapper function that saves and restores flags with FlagContext overrides return func args kwargs return _FlagSaverWrapper
setup token return data for these tests .,def setUp self super TokensApiPrintTokensForUserWithTokensTest self setUp self returned_token_doc LoadTestJsonFile primarydomain com_valid_tokendata json
return iterable containing trips that visit this stop .,def GetTrips self schedule None return trip for trip ss in self _GetTripSequence schedule
"check an existing trajectory and return the trajectory time in ns , the delta t , and the number of frames",def checkTrajectory filename cmdnames cmds GromacsCommands proc subprocess Popen cmdnames gmxcheck split f filename stdin None stderr subprocess STDOUT stdout subprocess PIPE ret proc communicate step re compile Step s 0 9 s 0 9 re MULTILINE if proc returncode 0 sys stderr write pwd s n os getcwd sys stderr write Got s n unicode ret 0 errors ignore match step search ret 0 frames int match group 1 dt float match group 2 ns frames 1 dt 1000 0 sys stderr write Using trajectory s with g ns of trajectories n filename ns return ns dt frames
read the xml from the string str . ' description ' describes the source of this xml in exceptions .,def readString self str description parser xml sax make_parser parser setContentHandler self inputSrc xml sax InputSource inputSrc setByteStream StringIO str inputSrc setPublicId description inputSrc setSystemId description parser parse inputSrc
runs standard installation function with given parameters and commands,def linstall parameters arg install args make prefix prefix s defaultprefix s datadir prefix s data s infodir prefix s info s localstatedir prefix s localstate s mandir prefix s man s sysconfdir prefix s conf s parameters s argument s prefix install_dir defaultprefix cst prefix man cst man info cst info localstate cst localstate conf cst conf data cst data parameters parameters argument arg args join member for member in args split if member out notify running s args if not system args raise BuildError linstall failed else dir_file s usr share info dir install_dir if os path isfile dir_file shelltools remove_file s usr share info dir install_dir
test a revoked commitment transaction being published .,unittest expectedFailure def test_revoked self self alice lit create self bob lurl 50000000 25000000 self propagate afee 50000000 self alice bit getbalance bfee 75000000 self bob bit getbalance self assertGreaterEqual afee 0 self assertGreaterEqual bfee 0 self assertEqual self alice lit getbalance self bob lurl 50000000 self assertEqual self bob lit getbalance self alice lurl 25000000 self bob lit send self alice lurl 5000000 self assertEqual self alice lit getbalance self bob lurl 55000000 self assertEqual self bob lit getbalance self alice lurl 20000000 commitment self alice lit getcommitmenttransactions self bob lurl self alice lit send self bob lurl 10000000 self assertEqual self alice lit getbalance self bob lurl 45000000 self assertEqual self bob lit getbalance self alice lurl 30000000 for transaction in commitment self alice bit sendrawtransaction transaction self propagate time sleep 1 self propagate self assertGreaterEqual self bob bit getbalance 150000000 bfee
"starts a new game / world - instance first , lets print the final world and q - state : this used to be called by the qlearning module but seems to make more sense - and be more flexible :-) - to call it from here , ourselves we can then call it ourselves from ' act ' etc too , if we wish",def reset self if self game 1 self _show self _showQ print scenarioimage reset if self appleMoves self appleX random randint 0 self size 1 self appleY random randint 0 self size 1 else self appleX self appleY self size 2 self finished False sampledOnce False while not sampledOnce or self posX self appleX and self posY self appleY self posX random randint 0 self size 1 self posY random randint 0 self size 1 sampledOnce True self game 1
deserializes the container configuration json file at fullpath as dict . : param fullpath : str : path to the container configuration json file : return : dict,def get_configuration fullpath CONTAINER_CONFIG_PATH return fileoperations get_json_dict fullpath
raise the specified alarm when the segmentation fault handler is executed .,def alarm_on_segfault self alarm self register_alarm alarm for alarm in listify alarm self _set alarm segfault alarm alias multi True return self _section
"body_bytes = ( json.dumps ( { "" command "" : [ "" loadfile "" , "" /users / stevejohnson / music / itunes / itunes media / music / kid condor / kid condor ep/01 imagining.mp3 "" ] } ) + ' ' ) .encode('utf-8 ' ) log.info ( "" > % r "" , body_bytes ) mpv_socket.sendall(body_bytes )",def _test
test the creation of a simple xlsxwriter file with conditional formatting .,def test_create_file self filename self got_filename workbook Workbook filename worksheet workbook add_worksheet format1 workbook add_format bg_color FFFF00 fg_color FF0000 pattern 12 worksheet write A1 Hello format1 worksheet write B3 10 worksheet write B4 20 worksheet write B5 30 worksheet write B6 40 worksheet conditional_format B3 B6 type cell format format1 criteria greater than value 20 workbook close got exp _compare_xlsx_files self got_filename self exp_filename self ignore_files self ignore_elements self assertEqual got exp
test example file converting unicode text .,def test_create_file self filename self got_filename textfile codecs open self txt_filename r utf 8 workbook Workbook filename worksheet workbook add_worksheet worksheet set_column A A 50 row 0 col 0 for line in textfile if line startswith continue worksheet write row col line rstrip n row 1 workbook close textfile close got exp _compare_xlsx_files self got_filename self exp_filename self ignore_files self ignore_elements self assertEqual got exp
return a tuple with the usb busses .,def busses return Bus g for k g in _interop _groupby _interop _sorted core find find_all True key lambda d d bus lambda d d bus
return an array of light patterns .,def get_bytes self name return self maps name
return the error message to be sent to the client if the current request passes fails any user - defined validation .,def is_valid_method model resource None validation_function_name is_valid_ format request method lower if hasattr model validation_function_name return getattr model validation_function_name request resource
test that combination assignment / expressions of the same identifier log the ident as ' undeclared ',def test_locate_identifiers_3 self code x x 5 for y in range 1 y hi z for z in range 1 z q for q in range 1 q parsed ast PythonCode code exception_kwargs eq_ parsed undeclared_identifiers set x y z q range
clean the database before / after the test .,def clean_db src SourceAccess objects name TSRC first if src src delete user CRITsUser objects username TUSER_NAME first if user user delete
parse a file by guessing topic type,def parse_file self filename for topic meta_msg in self __topic_dict items try message meta_msg parse_file filename if message print identified topic s topic return meta_msg message except text_format ParseError as e print Tried s failed topic continue return None None
stand - alone codeline without assignment etc .,def Statement node return 0 s
checks that the correct and distort functions are indeed inversely related to each other,def test self xin yin xtes ytes self correct xin yin xold yold self distort xtes ytes error math sqrt xin xold xin xold yin yold yin yold if error self tolerance logging error Blobcorrector Test Failed raise Exception Problem in correctorclass
"verify that the homepage , when accessed at edx.org , has the edx footer",def test_edx_footer self with patch dict django conf settings FEATURES IS_EDX_DOMAIN True resp self client get self assertEqual resp status_code 200 self assertContains resp edx footer
just make sure descriptor loads without error,def test_import self descriptor self get_dummy_course START
show the instructor grading interface .,cache_control no_cache True no_store True must_revalidate True def staff_grading request course_id course_key SlashSeparatedCourseKey from_deprecated_string course_id course get_course_with_access request user staff course_key ajax_url _reverse_with_slash staff_grading course_key return render_to_response instructor staff_grading html course course course_id course_id ajax_url ajax_url staff_access True
"start the required stub service running on a local port . since these services can be reconfigured on the fly , we start them on a scenario basis when needed and stop them at the end of the scenario .",def start_stub name service SERVICES get name None if service fake_server service class port_num service port setattr world name fake_server
"given an http response json with the key ' rubric ' , render out the html required to display the rubric and put it back into the response",def _render_rubric self response view_only False try if rubric in response rubric response rubric rubric_renderer CombinedOpenEndedRubric self system view_only rubric_dict rubric_renderer render_rubric rubric success rubric_dict success rubric_html rubric_dict html response rubric rubric_html return response except etree XMLSyntaxError RubricParsingError log exception Cannot parse rubric string Raw string 0 format response rubric return success False error Error displaying submission except ValueError log exception Error parsing response 0 format response return success False error Error displaying submission
test that we check for email addresses in a case insensitive way,def test_capitalized_duplicate_email self UserFactory create email self new_email self check_duplicate_email self new_email capitalize
email a single - use link for performing a password reset .,intercept_errors AccountInternalError ignore_errors AccountRequestError def request_password_change email orig_host is_secure form PasswordResetForm email email if form is_valid form save from_email settings DEFAULT_FROM_EMAIL domain_override orig_host use_https is_secure else raise AccountUserNotFound
test switch command with no branch,pytest mark cli def test_switch_no_branch self runner CliRunner result runner invoke cli switch fake assert result exit_code 2 assert Please specify a branch to switch in result output assert Faked not in result output
returns the indentation of first line of string,def get_indent_level string lines string splitlines lineno 0 line lines lineno indent 0 total_lines len lines while line total_lines and indent 0 indent len line len line lstrip line lines lineno line 1 return indent
test creating a new user .,pytest mark django_db def test_create image models User objects create image image is_active True is_staff True is_superuser True first_name John last_name Doe
create a new list entry for the given profile item .,def perform_create self serializer item models ProfileItem objects get pk self kwargs get pk return serializer save profile_item item
df[n ] = dflocal[n ] | [ dfup[c ] for c in tree.children[n ] ],def _compute_df self block tree result set for succ in block succs if tree get_parent_of succ is not block result add succ for c in tree get_children_of block self _compute_df c tree for v in self dominance_frontier c if not tree is_dominator block v or block is v result add v self dominance_frontier block result
perform a query for articles that contain two authors .,def query_for_author_pair self author1 author2 data self create_query_data AU author1 AU author2 return self _generic_query data
string representation of extracted results .,def __repr__ self details title self titles url self urls image self images videos self videos description self descriptions feed self feeds details_strs max_shown 50 for name values in details if values value values 0 count len values if count 1 0 details_strs append s s s more name value max_shown count 1 else details_strs append s s name value max_shown return s s self __class__ __name__ join details_strs
"inserts a header with image , title and subtitle",def insert_header self title subtitle bmp_file hbh 57 hbw 150 self header ui Panel self 0 0 self width hbh 2 if bmp_file self header image ui Bitmap self header 0 0 hbw hbh self header image set_image os path join unicode str self info image_dir mbcs unicode str bmp_file mbcs if title self header title ui Label self header hbw 20 10 self width 200 16 text title self header title set_font bold True if subtitle self header subtitle ui Label self header hbw 20 26 self width 200 26 text subtitle self header line ui EtchedRectangle self header 0 hbh self width 2 self header height hbh 2 self header set_background_color 255 255 255
"assumes valid name , valid name+flags combination , valid condcode . check the operands and return an error string if invalid , empty string otherwise .",def check_swapop operands operands x strip for x in operands split if len operands 3 return Expected 3 operands got i len operands if len operands 2 4 return Invalid syntax if operands 2 0 or operands 2 1 return Missing brackets around third operand of swap instruction operands 2 operands 2 1 1 strip for op in operands if not helpers is_reg op return Only registers are allowed here for op in operands if helpers get_reg_num op 15 return PC is not allowed here return
read the tag and build date straight from the appropriate file .,def version_info for line in open XIMPOL_VERSION_FILE_PATH readlines exec line strip n return TAG BUILD_DATE
returns a type checker for a message field of the specified types .,def GetTypeChecker field if field cpp_type _FieldDescriptor CPPTYPE_STRING and field type _FieldDescriptor TYPE_STRING return UnicodeValueChecker if field cpp_type _FieldDescriptor CPPTYPE_ENUM return EnumValueChecker field enum_type return _VALUE_CHECKERS field cpp_type
convert camelcase string to snake_case ( from https://gist.github.com/jaytaylor/3660565 ),def _to_snake_case camel_case_str return re sub A Z _ 1 camel_case_str lower lstrip _
generates a password with random chararcters,def genpass pattern w 32 try return rstr xeger pattern except re error as e raise ValueError str e
"if the env var can not be interpreted as int , fall back to one thread .",def test_threads_omp_env_arg_borked self expected 3 def fake_cpu_count args kw return expected with patch psutil cpu_count fake_cpu_count with temporary_env PYEMMA_NJOBS this is not right res coor assign_to_centers self X self centers_big n_jobs None return_dtrajs False self assertEqual res n_jobs expected
"posteriors , loglikes , logpots = weight(models , iter , priors = none )",def weight models iter priors None verbose 0 loglikes logpots i 0 for model in models if verbose 0 print Model i loglikes model logpots model sample_likelihood model iter verbose i 1 max_loglike Inf max_logpot Inf for model in models max_loglike max max_loglike loglikes model max max_logpot max max_logpot logpots model max posteriors sumpost 0 for model in models loglikes model max_loglike logpots model max_logpot posteriors model mean exp loglikes model mean exp logpots model if priors is not None posteriors model priors model sumpost posteriors model for model in models posteriors model sumpost return posteriors loglikes logpots
"given a fasta file . yield tuples of header , sequence author : brentp url : https://www.biostars.org/p/710/",def fasta_iter file_path with open file_path as fh faiter x 1 for x in groupby fh lambda line line 0 for header in faiter header next header 1 strip seq join s strip for s in next faiter yield header seq
execute the actions necessary to perform a ` molecule init scenario ` and returns none .,def execute self scenario_name self _command_args scenario_name role_name os getcwd split os sep 1 role_directory util abs_path os path join os getcwd os pardir msg Initializing new scenario format scenario_name LOG info msg molecule_directory config molecule_directory os path join role_directory role_name scenario_directory os path join molecule_directory scenario_name scenario_base_directory os path dirname scenario_directory if os path isdir scenario_directory msg The directory molecule exists Cannot create new scenario format scenario_name util sysexit_with_message msg scenario_base_directory os path join role_directory role_name templates scenario driver driver_name format self _command_args scenario verifier verifier_name format self _command_args for template in templates self _process_templates template self _command_args scenario_base_directory self _process_templates molecule self _command_args role_directory role_directory os path join role_directory role_name msg Initialized scenario in successfully format scenario_directory LOG success msg
check the efficiency of the tracker pattern recognition using recontructed data and mc truth,def efficiency_mc args eff_mc analysis scifi_efficiency PatternRecognitionEfficiencyMC eff_mc cut_on_tof True eff_mc cut_on_tof_time True eff_mc tof_upper_cut 50 0 eff_mc tof_lower_cut 27 0 eff_mc n_hits_cut 5 eff_mc run args can ROOT TCanvas can Divide 2 2 can cd 1 eff_mc hpt_m_tku Draw can cd 2 eff_mc hpz_m_tku Draw can cd 3 eff_mc hpt_m_tkd Draw can cd 4 eff_mc hpz_m_tkd Draw can Update raw_input Press any key to finish return eff_mc can
handles the finalisation of the module,def _death self raise NotImplementedError _death function not implemented in class s self __class__ __name__
reset maustransform and set logging . @param self object reference .,def setUp self MausConfiguration configuration DEFAULT_CONFIG worker_process_init_callback MausTransform transform None MausTransform is_dead True
"check that we set the seed , particle generator correctly",def test_birth_empty_part_counter self beam_def TEST_COUNTER beam self beam_maker _MapPyBeamMaker__birth_empty_particles beam_def self assertEqual self beam_maker seed beam_def random_seed self assertEqual self beam_maker particle_generator counter
test maus_cpp.covariance_matrix.__repr _ _ ( ),def test_repr self ref_data float j i for j in range 1 7 for i in range 1 7 ref_array numpy array ref_data cov covariance_matrix create_from_matrix ref_array test_array eval repr cov for i x_array in enumerate test_array for j x in enumerate x_array self assertAlmostEqual x ref_data i j
automatically called when this custom code class loads .,def on_load self pass
set resolution to current bug report .,def do_resolution self line if not line print Sorry RESOLUTION cannot be empty return Bug set_bug_attr resolution line self current_br bug resolution self current_br bug resolution if resolution print RESOLUTION was 0 format resolution else print There was no RESOLUTION set self current_br bug resolution line print RESOLUTION is now 0 format line
mail this invite to the specified user .,def send self sender None personal_message None sender_addr _ A fellow Mozillian from_addr settings FROM_NOREPLY if sender sender_addr s s sender full_name sender email from_addr settings FROM_NOREPLY_VIA sender full_name subject _ Please join me on mozillians org template get_template phonebook emails invite_email txt message template render personal_message personal_message sender sender_addr link self get_url filtered_message message replace 34 replace 39 send_mail subject filtered_message from_addr self recipient
"return a sample data structure , with default values .",def option_collection kwargs defaults u debug True defaults update kwargs return defaults
this is the exact same code as simplexmlrpcserver.__init _ _ except it calls securetcpserver.__init _ _ instead of plain old tcpserver.__init _ _,def __init__ self addr requestHandler SecureXMLRPCRequestHandler logRequests 1 self funcs self logRequests logRequests self instance None SecureTCPServer __init__ self addr requestHandler
generate the nginx rewrite rules for the given registered applications,def generate_nginx_rules app_names error for app_name static in create_rules app_names error yield location static s app_name yield alias s static yield yield
helper to curve through set of control points .,def curveThrough self path pointlist assert len pointlist 3 1 No of points must be 3n 1 for integer n x y pointlist 0 path moveTo x y idx 1 while idx len pointlist 2 p1 p2 p3 pointlist idx idx 3 path curveTo p1 0 p1 1 p2 0 p2 1 p3 0 p3 1 idx idx 3
"handle a new frame , override this for useful behavior",def processFrame self frame pass
print a human readable object description,def __str__ self return u Dummy NetEngine s self host
median normalized peak bias ( % ),def MdnNPB obs mod paxis axis None return np ma median old_div mod max axis paxis obs max axis paxis obs max axis paxis axis axis 100 0
normalize given array according to given bounds .,def manualy_normalize bounds x low up bounds widths up low widths widths 1 0 widths 0 y x low widths return y
test for updating the power module information .,def test_update self power_controller self __get_controller self assertEquals power_controller get_power_modules power_controller register_power_module 1 POWER_API_8_PORTS self assertEquals 1 id 1 address 1 name u version 8 input0 u input1 u input2 u input3 u input4 u input5 u input6 u input7 u sensor0 0 sensor1 0 sensor2 0 sensor3 0 sensor4 0 sensor5 0 sensor6 0 sensor7 0 times0 None times1 None times2 None times3 None times4 None times5 None times6 None times7 None inverted0 0 inverted1 0 inverted2 0 inverted3 0 inverted4 0 inverted5 0 inverted6 0 inverted7 0 power_controller get_power_modules times join 00 00 for _ in range 14 power_controller update_power_module id 1 name module1 input0 in0 input1 in1 input2 in2 input3 in3 input4 in4 input5 in5 input6 in6 input7 in7 sensor0 0 sensor1 1 sensor2 2 sensor3 3 sensor4 4 sensor5 5 sensor6 6 sensor7 7 times0 times times1 times times2 times times3 times times4 times times5 times times6 times times7 times inverted0 0 inverted1 0 inverted2 0 inverted3 0 inverted4 0 inverted5 0 inverted6 0 inverted7 0 self assertEquals 1 id 1 address 1 version 8 name module1 input0 in0 input1 in1 input2 in2 input3 in3 input4 in4 input5 in5 input6 in6 input7 in7 sensor0 0 sensor1 1 sensor2 2 sensor3 3 sensor4 4 sensor5 5 sensor6 6 sensor7 7 times0 times times1 times times2 times times3 times times4 times times5 times times6 times times7 times inverted0 0 inverted1 0 inverted2 0 inverted3 0 inverted4 0 inverted5 0 inverted6 0 inverted7 0 power_controller get_power_modules
"remove k , v pairs with empty values from a dictionary .",def _remove_empty_fields_from_dict self dictionary resulting_dict dictionary copy empty_keys k for k v in dictionary items if v is None for k in empty_keys del resulting_dict k return resulting_dict
set up the env for test .,def setUp self super RoleBasedPolicyFixture self setUp policy json load open CONF oslo_policy policy_file for action rule in policy items policy action role s self role self policy_dir self useFixture fixtures TempDir self policy_file_name os path join self policy_dir path policy json with open self policy_file_name w as policy_file json dump policy policy_file CONF set_override policy_file self policy_file_name oslo_policy congress common policy reset congress common policy init self addCleanup congress common policy reset
the entry point for all build subcommand tasks,def build args builder None fail False try manifest None with open args manifest r as fh manifest fh read buildspec BuildSpec manifest args version args type args parallel args projects builder BuilderFactory create_builder args type buildspec def _signal_handler args LOG info Process interrrupted Cleaning up builder cleanup sys exit signal signal signal SIGINT _signal_handler rc builder build except Exception as e LOG exception Oops something went wrong s e fail True builder cleanup if fail sys exit 1 sys exit rc
associate an authorization verifier with a request token .,def save_verifier self token verifier request pass
"get fibre channel wwpns from the system , if any .",def get_fc_wwpns self hbas self get_fc_hbas wwpns for hba in hbas if hba port_state Online wwpn hba port_name replace 0x wwpns append wwpn return wwpns
returns true if nrpe client is running,def is_agent_installed self return check_tcp host self ipaddress port 5666
determine if a column of numbers in an xls file are integral .,def determine_number_type values integral True for v in values if v and v 1 0 integral False break if integral return int else return float
"gradient of function , or jacobian if function fun returns 1d array",def approx_fprime x f epsilon None args kwargs None centered True kwargs if kwargs is None else kwargs n len x f0 f x args kwargs dim np atleast_1d f0 shape grad np zeros n dim float ei np zeros np shape x float if not centered epsilon _get_epsilon x 2 epsilon n for k in range n ei k epsilon k grad k f x ei args kwargs f0 epsilon k ei k 0 0 else epsilon _get_epsilon x 3 epsilon n 2 0 for k in range n ei k epsilon k grad k f x ei args kwargs f x ei args kwargs 2 epsilon k ei k 0 0 grad grad squeeze axes 0 1 2 grad ndim axes 2 axes 1 1 return np transpose grad axes axes squeeze
"return a human - friendly html summary of insights or status of this intelligence module to report in weekly and test mode emails : param botengine : botengine environment : param oldest_timestamp_ms : oldest timestamp in milliseconds to summarize : param newest_timestamp_ms : newest timestamp in milliseconds to summarize : param test_mode : true to add or modify details for test mode , instead of a general weekly summary",def get_html_summary self botengine oldest_timestamp_ms newest_timestamp_ms test_mode False return
check if the given file hash is in the store .,def is_in_store self store_id an_hash raise NotImplementedError is_in_store must be reimplemented by s self
field_modifier : required | optional | repeated,def p_field_modifier self p p 0 LU i p 1
updates the camera state with the state of this mode .,def update_camera self pass
checks if the upload user and host are the same as the local user and server .,def _is_same_host self upload_user upload_host if upload_user and upload_user self _current_user return False if upload_host in self LOCAL_HOSTS return True try this_server socket gethostbyaddr socket gethostname 0 if upload_host this_server return True except pass return False
calculate the coin supply based on ' eras ' defined in crypto_data . some currencies do n't have a simple algorithmically defined halfing schedule so coins supply has to be defined explicitly per era .,def _per_era_supply self block_height coins 0 for era in self supply_data eras end_block era end start_block era start reward era reward if not end_block or block_height end_block blocks_this_era block_height start_block coins blocks_this_era reward break blocks_per_era end_block start_block coins reward blocks_per_era return coins
returns the state of the selected unit . select a unit using ` selectunit ` .,def getState self states 2 POWERUP 4 READY 12 ERROR 14 STOP 8 RUN 10 WARN ret self _cmdReadMemoryWord 20620 return states get ret UNKNOWN
returns a brush for the color .,def _get_brush self color result self _brushes get color if result is None qcolor self _get_color color result QtGui QBrush qcolor self _brushes color result return result
"given serialized record data , return a tuple of tuples of type oids and attributes .",def record_unpack data long_unpack long_unpack oid_unpack oid_unpack null_sequence null_sequence len len columns long_unpack data offset 4 for x in range columns typid oid_unpack data offset offset 4 offset 4 if data offset offset 4 null_sequence att None offset 4 else size long_unpack data offset offset 4 offset 4 att data offset offset size if size 1 or len att size raise ValueError insufficient data left in message offset size yield typid att if len data offset 0 raise ValueError extra data d octets at end of record len data
returns the thread associated with this stack frame .,def GetThread self RaiseNotImpl GetThread
convert a click.option call into a click . option object .,def extract_option_object option option def opt pass return opt __click_params__ 0
short repr to use when rendering pipeline graphs .,def graph_repr self final re sub d d lambda x format float x group 0 2E self _expr return Expression l l format final
"builds a l - p norm function . this regularizer encourages the intensity of pixels to stay bounded . i.e. , prevents pixels from taking on very large values .",def __init__ self img_input p 6 0 super LPNorm self __init__ if p 1 raise ValueError p value should range between 1 inf self name L Norm Loss format p self p p self img img_input
test record import throws redcaperror for bad import,def test_import_exception self data self reg_proj export_records data 0 non_existent_key foo with self assertRaises RedcapError as cm self reg_proj import_records data exc cm exception self assertIn error exc args 0
deduce the encoding of a python source file ( binary mode ) from magic comment .,def parse_encoding fp pos fp tell fp seek 0 try line1 fp readline has_bom line1 startswith codecs BOM_UTF8 if has_bom line1 line1 len codecs BOM_UTF8 m _PYTHON_MAGIC_COMMENT_re match line1 decode ascii ignore if not m try import parser parser suite line1 decode ascii ignore except ImportError SyntaxError pass else line2 fp readline m _PYTHON_MAGIC_COMMENT_re match line2 decode ascii ignore if has_bom if m raise SyntaxError python refuses to compile code with both a UTF8 byte order mark and a magic encoding comment return utf_8 elif m return m group 1 else return None finally fp seek pos
create the filesystem when passing none ( indicates filesystem default ),def test_creating_none self an_fs self _fs_class device self loop_devices 0 label None self assertIsNone an_fs create
"return the sec representation of this key as hex text . if use_uncompressed is not set , the preferred representation is returned .",def sec_as_hex self use_uncompressed None sec self sec use_uncompressed use_uncompressed if sec is None return None return self _ui_context sec_text_for_blob sec
softmax over a batch of masked items .,def softmax_masked x mask e_x T exp x x max axis 1 keepdims True astype theano config floatX mask astype theano config floatX return e_x e_x sum axis 1 keepdims True
function makes a prediction of one sample with a tree model . if y label is defined it returns node identifier and margin .,def predict tree x y dist False node_id 1 while 1 nodes tree node_id if nodes 0 5 c if x nodes 0 1 nodes 0 2 index node_id 0 nodes 0 0 else index node_id 1 nodes 1 0 elif x nodes 0 1 in nodes 0 2 index node_id 0 nodes 0 0 elif x nodes 1 1 in nodes 1 2 index node_id 1 nodes 1 0 else node_id str nodes 0 0 str nodes 1 0 index nodes 0 0 0 0 k nodes 0 3 get k 0 nodes 1 3 get k 0 for k in set nodes 0 3 set nodes 1 3 if node_id in tree keys continue if dist suma sum nodes index 3 values return Counter k v float suma for k v in nodes index 3 iteritems prediction max nodes index 3 key nodes index 3 get if y return prediction probs sorted zip nodes index 3 keys np true_divide nodes index 3 values np sum nodes index 3 values key itemgetter 1 reverse True if prediction y margin probs 0 1 probs 1 1 if len probs 1 else 1 else margin dict probs get y 0 probs 0 1 return node_id margin
update the hash value that uniquely characterizes this object .,def __update_hash self md5 hashlib md5 md5 update d self exc_type md5 update x self exc_pc md5 update x self faultyaddr md5 update d self access self hashz md5 hexdigest
override this method in subclasses .,def run self pass
reduces shortlist of q tables matches down to a best match and its thumbnail : param matches : list of keyword matches : return : best match,def find_best_match matches matches_tpremoved x for x in matches if thumbnail not in x or preview not in x bestMatch min matches_tpremoved key len thumbs x for x in matches if thumbnail in x if thumbs bestThumb bestMatch else bestThumb min thumbs key len return bestMatch bestThumb
"return stateinfo c , c = ( stateinfo a ) * ( stateinfo b )",def TensorProduct a b constraint 0 c StateInfo a _env c refresh_by _dmrg PyTensorProduct a _raw b _raw constraint True return c
"% feature(""docstring "" ) gr_make_align_on_samplenumbers_ss::align_state "" wraps the c++ : gr_align_on_samplenumbers_ss::align_state "" ;",def generate_swig_doc_i self pass
parse the http - equiv refrsh parameter from the given response,def get_meta_refresh response if response not in _metaref_cache text response body_as_unicode 0 4096 text _noscript_re sub u text text _script_re sub u text _metaref_cache response html get_meta_refresh text response url response encoding return _metaref_cache response
test that navigating to the registration page while logged in redirects you to the dashboard,def test_get_register_while_logged_in self self client login username self user1 username password password response self client get register self assertEqual response status_code 302 self assertTemplateNotUsed response registration register html
read a value from the reader .,def read self reader font tableStack raise NotImplementedError self
read defaults for options from environment,def _read_environment for key in options env PYGLET_ s key upper try value os environ env if _option_types key is tuple options key value split elif _option_types key is bool options key value in true TRUE True 1 elif _option_types key is int options key int value except KeyError pass
get generator attribute from generatorconfig object .,def get_attributes self return self config get_attributes
"register a specific notification handler function for the specified type of notification , that will be executed each time a log with this notification type is processed .",classmethod def register_notification cls notification_type notification_function if notification_type in cls notification_functions logger warning Notification s was registered twice notification_type cls notification_functions notification_type notification_function
verify that lp : # 1597919 does n't come back .,def test_build_rewrites_shebangs self self run_snapcraft stage python entry point python2_entry_point os path join self stage_dir bin python2_test python3_entry_point os path join self stage_dir bin python3_test python_entry_point os path join self stage_dir bin python_test with open python2_entry_point as f python2_shebang f readline strip with open python3_entry_point as f python3_shebang f readline strip with open python_entry_point as f python_shebang f readline strip self assertThat python2_shebang Equals usr bin env python2 self assertThat python3_shebang Equals usr bin env python3 self assertThat python_shebang Equals usr bin env python3
"get version of a tool by executing it with argument "" --version "" and returning stdout . @param executable : the path to the executable of the tool ( typically the result of executable ( ) ) @param arg : an argument to pass to the tool to let it print its version @param use_stderr : true if the tool prints version on stderr , false for stdout @return a ( possibly empty ) string of output of the tool",def _version_from_tool self executable arg version use_stderr False try process subprocess Popen executable arg stdout subprocess PIPE stderr subprocess PIPE stdout stderr process communicate except OSError as e logging warning Cannot run 0 to determine version 1 format executable e strerror return if stderr and not use_stderr logging warning Cannot determine 0 version error output 1 format executable util decode_to_string stderr return if process returncode logging warning Cannot determine 0 version exit code 1 format executable process returncode return return util decode_to_string stderr if use_stderr else stdout strip
handles response from query of room i d from room alias,def _handle_default_room_id self response print in handle_default_room_id s response room_id self default_room_id response room_id self props authenticated True
returns the index of the end character .,abstractproperty def character_span self pass
get and configure the cache db wrapper,def includeme config settings config get_settings cache_impl get_cache_impl settings kwargs cache_impl configure settings cache cache_impl kwargs cache reload_if_needed config add_request_method partial cache_impl kwargs name db reify True config add_postfork_hook partial cache_impl postfork kwargs return cache_impl
specialized assert that ignores the indent level .,def assertEqualIgnoreLeadingWhitespace self expected_lines lines self assertEqual expected_lines self StripLeadingWhitespace lines
invalidate the cached content of a particular `` < % def > `` within this template .,def invalidate_def self name self invalidate render_ s name __M_defname render_ s name
@param timelines : the timelines object @type timelines : timelinecollection @param custom : a customplotinfo - object . values in this object usually override the other options . if the object has an attribute named gnuplotcommands ( which is assumed to be a string list ) then these strings are executed during initialization of the plot ( the purpose of this is to set non - standard stuff ),def __init__ self timelines custom showWindow True registry None GeneralPlotTimelines __init__ self timelines custom showWindow showWindow registry registry Gnuplot __init__ self persist self spec persist self itemlist if self spec start or self spec end rng if self spec start rng str self spec start rng if self spec end rng str self spec end rng self set_string xrange rng if len self alternate 0 self set_string y2tics try if self spec logscale self set_string logscale y except AttributeError pass try if self spec ylabel self set_string ylabel self spec ylabel except AttributeError pass try if self spec xlabel self set_string xlabel self spec xlabel except AttributeError pass try if self spec y2label self set_string y2label self spec y2label except AttributeError pass raiseit False if raiseit in dir self spec raiseit self spec raiseit if raiseit x11addition raise else x11addition noraise if showWindow if uname 0 Darwin self set_string terminal x11 x11addition GnuplotTimelines terminalNr 1 else self set_string terminal x11 x11addition else self set_string terminal dumb self with_ self spec with_ try for l in custom gnuplotCommands self l except AttributeError pass self redo
add to the ignore - facility of the current vcs @param expr : a regular expression,def addRegexpToIgnore self expr notImplemented self addRegexpToIgnore
"format a number as a string . use scientific notation for large and small numbers , remove ' .0 ' from integers .",def number_to_string number if abs number 10000000 0 return e number elif int number number return d int number elif abs number 1e 05 return e number else return f number
inserts childtree in the right position ( regions will be rearanged to fit the organisation of self ),def insertTree self childTree aux_insertTree childTree self
returns a reference to the root singleton metric store .,def root_metric_store global _STORE if not _STORE _STORE MetricStore return _STORE
returns the list of available subsets .,def available_subsets self return train validation
make sure that other installed plugins do n't affect the same keyword argument .,def setup self app for other in app plugins if not isinstance other MySQLPlugin continue if other keyword self keyword raise PluginError Found another mysql plugin with conflicting settings non unique keyword elif other name self name self name _ s self keyword
ensure it 's possible to dynamically insert a new hug api on demand,def test_api_fixture hug_api assert isinstance hug_api hug API assert hug_api api
"od.pop(k[,d ] ) - > v , remove specified key and return its value .",def pop self key default __marker if key in self result self key del self key return result if default is self __marker raise KeyError key return default
"return wind direction in degrees . zero degrees is the arrow poiting at the front of the unit , away from the solar panel",def wind_direction b return b 360 255
published : yes soft deadline : not passed hard deadline : not passed - > visible grading : yes file attachment : no validation : no group work : < depends on authors parameter > upload for description : no,def create_open_assignment course grading_scheme authors 3 assign Assignment title uccrap Open assignment course course download http example org assignments 1 download uccrap gradingScheme grading_scheme publish_at last_week soft_deadline tomorrow hard_deadline next_week has_attachment False max_authors authors assign save return assign
get the value of the slider .,def get self return self _nsObject floatValue
this methods can verify be used to verify that user has permission to access filename .,def verify self filename return True
"list the absolute paths of all files with the specified extension in the directory recursively : param str extension : extension that will be filtered for : param str directory : path to the directory to list : return list[str , .. ] files : list of absolute file paths",def list_all_files_with_extension_in_directory directory extension file_names list_all_files_in_directory directory return filter lambda f f endswith format extension file_names
create a new domain associated with the current account .,def add self attributes domain None response self request post domains domain attributes if response was_successful domain dnsimple models Domain self request response to_dict domain return domain
return an ( by default ) inline - styled html document for the cursor 's selection .,def html_inline cursor scheme editor inline True number_lines False full_html True wrap_tag pre wrap_attrib id wrap_attrib_name document c lydocument cursor cursor return html c scheme inline number_lines full_html wrap_tag wrap_attrib wrap_attrib_name
return the html body for the named help page .,def html name from import page return page Page name body
returns a context manager to call for each event to send .,contextlib contextmanager def sender self l yield l append if l self send_events l
add actions to zoom the viewer,def addZoomActions self m self _menu m addSeparator sm QMenu m sm setTitle _ Zoom m addMenu sm ac self _actionCollection sm addAction ac viewer_fit_width sm addAction ac viewer_fit_height sm addAction ac viewer_fit_both sm addSeparator sm addAction ac viewer_zoom_in sm addAction ac viewer_zoom_out sm addAction ac viewer_zoom_original
returns the qlabel displaying the message text .,def messageLabel self return self _messageLabel
generate coordinate transform matrix for a tablet controlling screen out of n_screens in a row,def CTMGenerator dw dh mw mh mx my return f 0 f 0 f f 0 0 1 float mw dw float mx dw float mh dh float my dh
combine a list of regexes into one that matches any of them .,def join_regex regexes if len regexes 1 return join regexes elif regexes return regexes 0 else return
filter test cases based on command - line arguments .,def FilterTestCasesByArgs self args filtered globs exact_matches for a in args argpath a split if argpath 0 self name continue if len argpath 1 or len argpath 2 and argpath 1 return path join argpath 1 if path 1 path path 1 globs append path else exact_matches append path for t in self tests for a in globs if t path startswith a filtered append t break for a in exact_matches if t path a filtered append t break self tests filtered
basic test that minim test file can be read,def testMinimRead self self setupConfig rodir self createTestRo testbase test data 2 RO test minim ro testMinim rouri ro_manifest getRoUri rodir minimbase ro_manifest getComponentUri rodir Minim UserRequirements2 rdf target ro_manifest getComponentUri rodir data UserRequirements astro ods constraint ro_minim getElementUri minimbase create data UserRequirements astro ods model ro_minim getElementUri minimbase runnableRO g ro_minim readMinimGraph minimbase expected_minim target MINIM hasChecklist constraint constraint MINIM forPurpose rdflib Literal create UserRequirements astro ods constraint MINIM toModel model model RDF type MINIM Model self checkTargetGraph g expected_minim msg Not found in Minim self deleteTestRo rodir return
configure all rules recursively - bind them to current ruleset and convert string references to ` field ` rules .,def configure_rules self rules parent None result for r in rules if isinstance r BaseRule result append r configure self parent elif isinstance r string_types result append self convert_string r configure self parent else raise ValueError Dont know how to convert s repr r return result
"set all the default preference claims a user gets : thm : the user 's chosen theme top : the default forum topic for this user , if none else chosen gro : thread expansion strategy for the zoo forum 0=expand all threads n>0 : expand last n*10 threads rev : user 's configured time for editing a thread . initialize the available signing and encryption keys to "" none "" . based on the username , set the expected cookie name and i d . todo : refactor auth settings to use similar default strategy .",def __default_preferences self self valid False self cookie_name None self theme GlobalTheme theme self thm GlobalTheme index self top general self gro 0 self rev self zoo get zoo edit_window self instance_id GlobalConfig get server instance_id
"pop the oldest task . it 's required that the caller first acquire the semaphore . : return onedrived.od_tasks.base.taskbase | none : the first qualified task , or none .",def pop_task self with self _lock ret None if len self queued_tasks ret self queued_tasks pop 0 del self tasks_by_path ret local_abspath return ret
": param n : number of charge : return : when to shoot nth charge , milliseconds",def ts self n try root1 root2 solve_quadratic self slope 2 0 self minrps n except ZeroDivisionError root2 float n self minrps return int root2 1000
resize the image to fit in the given area while keeping aspect ratio .,def resize_contain img size fill 0 return_param False C H W img shape out_H out_W size scale_h out_H H scale_w out_W W scale min min scale_h scale_w 1 scaled_size int H scale int W scale if scale 1 img resize img scaled_size y_slice x_slice _get_pad_slice img size size out_img np empty C out_H out_W dtype img dtype out_img np array fill reshape 1 1 1 out_img y_slice x_slice img if return_param param y_offset y_slice start x_offset x_slice start scaled_size scaled_size return out_img param else return out_img
turn competition mode on or off .,def competition_mode self on pass
get available keys in message .,def keys self namespace None iterator eccodes codes_keys_iterator_new self codes_id namespace namespace keys while eccodes codes_keys_iterator_next iterator key eccodes codes_keys_iterator_get_name iterator keys append key eccodes codes_keys_iterator_delete iterator return keys
get_results ( ) optional name argument overrides the one in the results file,def test_get_results_name self res get_results name malkovich self assertIsNotNone res antutu malkovich
purpose : the purpose of this function is to determine whether or not the device the image was taken on is an accepted mobile device . inputs : string device outputs : none returns : boolean assumptions : n / a,def is_device self device if device in self criteria acceptedMobileDevices return True else return False
read terminal status line : ring indicator,def getRI self if not self _isOpen raise portNotOpenError if self logger self logger info returning dummy for getRI return False
imports a set of up journal - level metadata into janeway .,def handle self args options importer import_journal_metadata options
get /testing - login/ should show a test login page .,def test_testing_login self response self client get testing login self assert_200 response self assert_template_used testing login html
"clean up everything . at least you need to place this clean ( ) call to the callback manager , that will unregister all the registered callbacks .",def clean global cm pyrebox_print Cleaning module n cm clean pyrebox_print Cleaned module n
convert the integer value to its igmpv3 encoded time value if needed .,def float_encode self value if value 128 code value elif value 31743 code 255 else exp 0 value 3 while value 31 exp 1 value 1 exp 4 code 128 exp value 15 return code
create a project on the osf .,def _create_osf_project dlgr_id description None if not description description Experiment registered by Dallinger format dlgr_id r requests post nodes format root data type nodes category project title Experiment dlgr format dlgr_id 0 8 description description headers Authorization Bearer format config get osf_access_token r raise_for_status osf_id r json data id logger info Project registered on OSF at http osf io format osf_id return osf_id
construct a jwt for use with the named client .,def get_id_token user client_name try client Client objects get name client_name except Client DoesNotExist raise ImproperlyConfigured OAuth2 Client with name s does not exist client_name user_profile UserProfile objects get user user now datetime datetime utcnow expires_in getattr settings OAUTH_ID_TOKEN_EXPIRATION 30 payload preferred_username user username name user_profile name email user email administrator user is_staff iss settings OAUTH_OIDC_ISSUER exp now datetime timedelta seconds expires_in iat now aud client client_id sub anonymous_id_for_user user None return jwt encode payload client client_secret
accepts the same arguments as xmodule.x_module : xmodule.__init _ _,def __init__ self args kwargs super CapaModule self __init__ args kwargs
log events related to server requests .,def server_track request event_type event page None if event_type startswith event_logs and request user is_staff return try username request user username except username anonymous event username username ip _get_request_ip request referer _get_request_header request HTTP_REFERER accept_language _get_request_header request HTTP_ACCEPT_LANGUAGE event_source server event_type event_type event event agent _get_request_header request HTTP_USER_AGENT page page time datetime datetime utcnow host _get_request_header request SERVER_NAME context eventtracker get_tracker resolve_context shim remove_shim_context event log_event event
filter the queryset . no - op since it 's done by keyedconfigurationmodeladmin,def queryset self request queryset return queryset
internal workflow operation to remove an entrance exam,def _delete_entrance_exam request course_key store modulestore course store get_course course_key if course is None return HttpResponse status 400 remove_entrance_exam_milestone_reference request course_key course store get_course course_key if course entrance_exam_id metadata entrance_exam_enabled False entrance_exam_minimum_score_pct None entrance_exam_id None CourseMetadata update_from_dict metadata course request user remove_entrance_exam_graders course_key request user return HttpResponse status 204
calculate / update the kermit crc16 checksum for some data,def crc16_kermit data crc 0 tab CRC16_KERMIT_TAB for c in data tbl_idx crc ord c 255 crc tab tbl_idx crc 8 65535 return crc 65535
"od.update(e , * * f ) - > none . update od from dict / iterable e and f.",def update args kwds if len args 2 raise TypeError update takes at most 2 positional arguments d given len args elif not args raise TypeError update takes at least 1 argument 0 given self args 0 other if len args 2 other args 1 if isinstance other dict for key in other self key other key elif hasattr other keys for key in other keys self key other key else for key value in other self key value for key value in kwds items self key value
mclogin -- checks the status of minecraft 's login servers .,hook command autohelp False def mclogin inp bot None username bot config get api_keys get mc_user None password bot config get api_keys get mc_pass None if password is None return error no login set login http get https login minecraft net user username password password version 13 if username lower in login lower return Minecraft login servers appear to be online else return Minecraft login servers appear to be offline
base64 encode the der cert and wrap with proper begin / end lines .,def der_to_pem self der_cert_bytes f base64 standard_b64encode der_cert_bytes return ssl PEM_HEADER n textwrap fill f 64 n ssl PEM_FOOTER n
returns a list of all guild rewards,def guild_rewards self resourceUrl data guild rewards return self get_resource resourceUrl
set the queryset here so it filters on tenant and works with pagination .,def get_queryset self return super DealContactedByViewSet self get_queryset all
searches the database for a team with the given password reset token,def find_user_by_reset_token token db api common get_conn user db users find_one password_reset_token token if user is None raise WebException That is not a valid password reset token return user
"print the text , flush immediately .",def write_flush text sys stdout write text sys stdout flush
check for errors in the response .,def _check_response self response if response is None return known_responses self config get known_responses if known_responses response self _strip_response response if response in known_responses print known_responses response return else raise CommandFailedError Received an unknown response response failed_message self config get command_failed_message if failed_message is not None and failed_message in response raise CommandFailedError Command failed This is likely due to an invalid state change exception_message self config get exception_message if exception_message is not None and exception_message in response raise CommandExceptionError Command caused an exception on the device Your command is likely invalid check your json projector config
it returns the table and column name pointed by the foreign key .,def _get_foreign_key self table column cache_key table column if cache_key in self _foreign_cache return self _foreign_cache cache_key referer_table self _table_classes table referer_col referer_table columns column result get_foreign_key referer_table referer_col self _foreign_cache cache_key result return result
authenticated part of the workflow simply login & upload every activity,def run self if not self user authenticate raise Exception Invalid credentials for activity in self activities self rate_limit activity upload self user logger info All done
the constructor : param app : the application : type app : edmunds.application.application,def __init__ self app self app app
test get errors : return : void,def test_translate_errors self rule self rand_str 20 self write_config self config app self create_application translator app localization translator self assert_is_instance translator ConfigTranslator fallback_locale app config app localization locale fallback None directory app fs path self logs_directory self clear_paths append directory data en unknownkey1 nl unknownkey2 nl_BE unknownkey3 bo unknownkey1 ar unknownkey2 for locale_str key params in data with app test_request_context rule localizator app localization localizator None translator given_locale_strings locale_str with self assert_raises_regexp TranslationError Could not find the sentence for locale s and key s fallback_locale key localizator translate key params data nl A smashing sentence smashing nl_BE A smashing sentence smashing for locale_str expected key params in data with app test_request_context rule localizator app localization localizator None translator given_locale_strings locale_str self assert_equal expected localizator translate key params self assert_true self _is_in_log_files app directory Could not find the sentence for locale s and key s locale_str 2 key msg s s locale_str expected
runs the v8 presubmit checks .,def _V8PresubmitChecks input_api output_api import sys sys path append input_api os_path join input_api PresubmitLocalPath tools from presubmit import CppLintProcessor from presubmit import SourceProcessor from presubmit import StatusFilesProcessor results if not CppLintProcessor RunOnFiles input_api AffectedFiles include_deletes False results append output_api PresubmitError C lint check failed if not SourceProcessor RunOnFiles input_api AffectedFiles include_deletes False results append output_api PresubmitError Copyright header trailing whitespaces and two empty lines between declarations check failed if not StatusFilesProcessor RunOnFiles input_api AffectedFiles include_deletes True results append output_api PresubmitError Status file check failed results extend input_api canned_checks CheckAuthorizedAuthor input_api output_api return results
testing _ _ len _ _ method .,def test_length self adapted Adapter a 10 b c 20 assert_that len adapted equal_to 2
return list of files with the given extension in the data_dir,def get_file_list data_dir file_ext file_ext file_ext if isinstance file_ext list else file_ext file_names os path join data_dir fn for fn in os listdir data_dir if any fn endswith ext for ext in file_ext return file_names
validate the given id number the method raises an openerp.exceptions.validationerror if the eval of python validation code fails,api multi def validate_id_number self id_number self ensure_one if self env context get id_no_validate return eval_context self _validation_eval_context id_number try safe_eval self validation_code eval_context mode exec nocopy True except Exception as e raise UserError _ Error when evaluating the id_category validation code n s n s self name e if eval_context get failed False raise ValidationError _ s is not a valid s identifier id_number name self name
"make request to jolokia , make sure we have valid data , print out the metrics for each mbean .",def process_data self data try data self j4p getRequests except JolokiaError utils err error issue connecting to Jolokia self url if len data 1 for mbean in data if error in mbean utils err error mbean error for monitor in self monitors if monitor mbean mbean request mbean if mbean status 200 self print_metrics mbean value monitor metric mbean timestamp monitor taglist monitor not_tags break else utils err error mbean not found monitor mbean
create a train dataset reader containing 2913 images in hwc order .,def train return reader_creator download VOC_URL CACHE_DIR VOC_MD5 trainval
closes the connection to the mongodb server,def close self self connection close self status STATUS_CLOSED
"keeps a reference to the object x in the memo . because we remember objects by their i d , we have to assure that possibly temporary objects are kept alive by referencing them . we store a reference at the i d of the memo , which should normally not be used unless someone tries to deepcopy the memo itself ...",def _keep_alive x memo try memo id memo append x except KeyError memo id memo x
draw a rect with rounded corners to surface . argument rad can be specified to adjust curvature of edges ( given in pixels ) . an optional border width can also be supplied ; if not provided the rect will be filled . both the color and optional interior color ( the inside argument ) support alpha .,def round_rect surface rect color rad 20 border 0 inside 0 0 0 0 rect pg Rect rect zeroed_rect rect copy zeroed_rect topleft 0 0 image pg Surface rect size convert_alpha image fill 0 0 0 0 _render_region image zeroed_rect color rad if border zeroed_rect inflate_ip 2 border 2 border _render_region image zeroed_rect inside rad surface blit image rect
compile this basic block to java assembly,def compile self for bb in self basicBlocks bb compile
get targets for loadable modules .,def _windowsLdmodTargets target source env for_signature return _dllTargets target source env for_signature LDMODULE
override to change query index for this request .,def _get_es_index self options return self web_settings ES_INDEX
check if the resource has been deleted . for observing purpose .,property def deleted self return self _deleted
get the unique process i d,staticmethod def get_client_id pass
child class should override this function to implement their body,def on_device_remove self pairedDeviceId deviceDTO groupName groupId pass
delete a collection and the associated row in the tree entry table,def delete self username None from drastic models import Notification if self is_root return cfg get_config None session connection get_session keyspace cfg get KEYSPACE drastic session set_keyspace keyspace query SimpleStatement DELETE FROM tree_entry WHERE container s session execute query self path child TreeEntry objects filter container self container name u format self name first if child child delete state self mqtt_get_state payload self mqtt_payload state Notification delete_collection username self path self uuid payload self reset
last item with a key less - than k.,def slow_find_lt seq k for item in reversed seq if item k return item return 1
"trace_method_options is a method decorator that traces entry - exit of functions . it also prints args , kwargs and return values if optional parameters with_args , with_kwargs and with_return are set to true .",def trace_method_options method with_args False with_kwargs False with_return False def decorated self args kwargs __current_method_name push method __name__ 0 try _indent _output_file write method __name__ enter if with_args _output_file write args _output_file write str str arg for arg in args _output_file write if with_kwargs _output_file write kwargs kwarglist k str v for k v in kwargs iteritems kwarglist sort _output_file write str kwarglist _output_file write _output_file write n result method self args kwargs _indent _output_file write method __name__ exit if with_return _output_file write return s str result _output_file write n finally __current_method_name pop return result return decorated
open_file(filename : str ) - > none parses an xml file .,def open_file self filename self filename filename try self dom minidom parse filename except xml parsers expat ExpatError as e raise self XMLParseError e lineno e offset e code
oktriggered(checked : bool ) - > none update vistrail controller ( if neccesssary ) then close the widget,def okTriggered self checked False self updateController self controller self emit QtCore SIGNAL doneConfigure self close
use this method if you need to access the request context .,def init_with_context self context pass
update / create current working directory in config.py if the directory exists .,def __updateCWD self cwdPath cwdPath cwdPath replace if not os path exists cwdPath print Directory could not be located if not os path isabs cwdPath print Please enter the absolute path to the working directory not the relative path print return import fileinput for i line in enumerate fileinput input src config_menu py inplace True if i 0 print CWD s str cwdPath if not CWD line strip 3 line line replace n print line return
returns the list of necessary attributes,def xml_get_attrs xml_element attrs result for attr in attrs result attr xml_element getAttribute attr return result
"return the embeddings of the given indexes . input : tensor of shape ( dim * ) output : tensor of shape ( dim * , output_dim )",def link self input self input input self output self embeddings self input return self output
create a parser for the command - line options . may be overwritten for adding more configuration options . @return : an argparse . argumentparser instance,def create_argument_parser self u n Create a parser for the command line options n May be overwritten for adding more configuration options n return an argparse ArgumentParser instance n parser argparse ArgumentParser fromfile_prefix_chars u description u Execute benchmarks for a given tool with a set of input files n Benchmarks are defined in an XML file given as input n Command line parameters can additionally be read from a file if file name prefixed with is given as argument n The tool table generator can be used to create tables for the results n Part of BenchExec https github com sosy lab benchexec parser add_argument u files nargs u metavar u FILE help u XML file with benchmark definition parser add_argument u d u debug action u store_true help u Enable debug output parser add_argument u r u rundefinition dest u selected_run_definitions action u append help u Run only the specified RUN_DEFINITION from the benchmark definition file u This option can be specified several times metavar u RUN_DEFINITION parser add_argument u t u tasks dest u selected_sourcefile_sets action u append help u Run only the tasks from the tasks tag with TASKS as name u This option can be specified several times metavar u TASKS parser add_argument u n u name dest u name default None help u Set name of benchmark execution to NAME metavar u NAME parser add_argument u o u outputpath dest u output_path type str default self DEFAULT_OUTPUT_PATH help u Output prefix for the generated results u If the path is a folder files are put into it u otherwise it is used as a prefix for the resulting files parser add_argument u T u timelimit dest u timelimit default None help u Time limit for each run e g 90s overwrites time limit and hard time limit from XML file use 1 to disable time limits completely metavar u SECONDS parser add_argument u M u memorylimit dest u memorylimit default None help u Memory limit if no unit is given MB are assumed 1 to disable metavar u BYTES parser add_argument u N u numOfThreads dest u num_of_threads default None type int help u Run n benchmarks in parallel metavar u n parser add_argument u c u limitCores dest u corelimit default None metavar u N help u Limit each run of the tool to N CPU cores 1 to disable parser add_argument u user dest u users action u append metavar u USER help u Execute benchmarks under given user account s needs password less sudo setup parser add_argument u no compress results dest u compress_results action u store_false help u Do not compress result files def parse_filesize_value value try value int value if value 1 return None logging warning u Value s for logfile size interpreted as MB for backwards compatibility specify a unit to make this unambiguous value value value _BYTE_FACTOR _BYTE_FACTOR except ValueError value util parse_memory_value value return value parser add_argument u maxLogfileSize dest u maxLogfileSize type parse_filesize_value default 20 _BYTE_FACTOR _BYTE_FACTOR metavar u SIZE help u Shrink logfiles to given size if they are too big 1 to disable default value 20 MB parser add_argument u commit dest u commit action u store_true help u If the output path is a git repository without local changes u add and commit the result files parser add_argument u message dest u commit_message type str default u Results for benchmark run help u Commit message if commit is used parser add_argument u startTime dest u start_time type parse_time_arg default None metavar u YYYY MM DD hh mm help u Set the given date and time as the start time of the benchmark parser add_argument u version action u version version u prog s __version__ return parser
add the initial splodge line .,def getInitialSplodgeLine self line location if not self isJustBeforeExtrusion return line self hasInitialSplodgeBeenAdded True if self splodgeRepository initialSplodgeQuantityLength value self minimumQuantityLength return line return self getSplodgeLineGivenDistance self initialSplodgeFeedRateMinute line self splodgeRepository initialLiftOverExtraThickness value location self initialStartupDistance
"setreuid(uid , uid ) to get euid 's privilige",def generate uid 0 try xuid s int uid except xuid s uid sc mov x0 s mov x1 s mov x8 145 svc 1 xuid xuid return sc
returns whether a given value is an exception type ( not an instance ) .,def is_exception val return isinstance val type and issubclass val Exception
callback method for the remove button . triggers the removal of the recent server entry by calling the gui controller which then removes the recent server ( from list in memory and also from file ) also removes the recent server directly from the liststore .,def onRemoveRecentClicked self widget selection self serverlist serverlistview get_selection result selection get_selected if result model iter result server self serverlist liststore get_value iter 8 gui GuiController gui removeRecent server model remove iter
verify that bug 1673 is not present ( global variable handling ),def test_bug1673 self output self run_pyobfuscate testfiles bug1673 py assert 49 self run_src output Incorrect value returned after obfuscation
return a prototype scanner instance for scanning idl source files,def IDLScan cs SCons Scanner ClassicCPP IDLScan IDLSUFFIXES CPPPATH t t include t import t return cs
return the square root of the population variance .,def pstdev data mu None var pvariance data mu try return var sqrt except AttributeError return math sqrt var
returns the top hit entry directly following the specified index,def __top_hit_entry self self __find_line_starting_with 1 comps self __current_line split return comps 1 float comps 2
make sure dashes have space after them,def check_dashes key data errors context title data key dashes re findall s w title if len dashes 0 errors key append Non hyphenated dashes in Title must be followed by a space Please change the title multiple_dashes re findall s 2 title if len multiple_dashes 0 errors key append Multiple consecutive dashes are not allowed in Titles Please change the title
return a collection of factories in play or specified for a hierarchy .,def _collect_management_factories_for self cls hierarchy util class_hierarchy cls factories set for member in hierarchy manager self manager_of_class member if manager is not None factories add manager factory else for finder in instrumentation_finders factory finder member if factory is not None break else factory None factories add factory factories discard None return factories
sum of squared total displacements for these atoms .,def sum_dr_squared self return sum atom dr_squared for atom in self atoms
generate an html coverage report using lcov .,def generate_coverage_report obj_dirs src_dirs repo_root bld_dir tmp_dir out_dir lcov_exe genhtml_exe assert len obj_dirs len src_dirs num_packages len obj_dirs args_list_list lcov_exe quiet no checksum no external b bld_dir p 0 while p num_packages obj_dir obj_dirs p src_dir src_dirs p p 1 package_name os path basename src_dir base_tracefile os path join tmp_dir package_name _base info run_tracefile os path join tmp_dir package_name _run info comb_tracefile os path join tmp_dir package_name _comb info filt_tracefile os path join tmp_dir package_name _filt info loc_d d obj_dir d src_dir lcov_base_cmd lcov_exe loc_d c i o base_tracefile lcov_run_cmd lcov_exe loc_d c o run_tracefile loc_d lcov_comb_cmd lcov_exe a base_tracefile a run_tracefile o comb_tracefile lcov_filt_cmd lcov_exe remove comb_tracefile t cpp o filt_tracefile cmd_descs lcov_base_cmd s Building baseline trace file package_name lcov_run_cmd s Building test run trace file package_name lcov_comb_cmd s Combining trace files package_name lcov_filt_cmd s Filtering trace file package_name args_list_list append package_name cmd_descs filt_tracefile Logs pprint CYAN Generating Coverage Report p 0 total num_packages 4 1 tracefiles failed_packages empty_packages while p num_packages args args_list_list p package_name args 0 cmd args 1 desc args 2 file_ _do_package cmd desc p 4 1 total if not file_ Logs pprint RED lcov failed for package s Ignoring package package_name failed_packages append package_name elif os stat file_ st_size 0 Logs pprint RED Trace file is empty for package s Ignoring package package_name empty_packages append package_name else tracefiles append file_ p 1 if not tracefiles Logs pprint RED No valid trace files return False genhtml_cmd genhtml_exe function coverage t Coverage Test Results p repo_root o out_dir t for t in tracefiles ret _run_cmd genhtml_cmd Generating html pages total total if ret 0 return False if empty_packages or failed_packages Logs pprint CYAN Ignored Packages for package in sorted empty_packages Logs pprint YELLOW package empty for package in sorted failed_packages Logs pprint RED package failed Logs pprint CYAN Generated Report Logs pprint YELLOW os path join out_dir index html return True
device writes ! crosscheck also http://www.monkeyboard.org/tutorials/81-display/70-usb-serial-to-hd44780-lcd here a sequence is listed,def __init__ self boardrevision 1 addr 39 port 1 withBacklight True withOneTimeInit True self displayshift self LCD_CURSORMOVE self LCD_MOVERIGHT self displaymode self LCD_ENTRYLEFT self LCD_ENTRYSHIFTDECREMENT self displaycontrol self LCD_DISPLAYON self LCD_CURSOROFF self LCD_BLINKOFF if withBacklight self blFlag self LCD_BACKLIGHT else self blFlag self LCD_NOBACKLIGHT self lcd_device i2c_device addr port if not self _isInitialised self init_lcd self lcd_write self LCD_DISPLAYCONTROL self displaycontrol self lcd_write self LCD_ENTRYMODESET self displaymode self lcd_write self LCD_CLEARDISPLAY self lcd_write self LCD_CURSORSHIFT self displayshift self lcd_write self LCD_RETURNHOME self setCustomChar return
input - model_list : list of preconfigured models - x_train_b : 2d array of features - y_train_b : 1d array of labels output - model_list : models that are re_fit to the training data,def retrain_models model_tuple_list X_train_b y_train_b trained_model_list for model_tuple in model_tuple_list name model model_tuple model fit X_train_b y_train_b trained_model_list append name model return trained_model_list
accessor function for read - only ' num ' attribute of rat .,def _get_num self return self __num
handler for when a websocket is closed .,def closed self code reason None
set the text and color of this item .,def setText self text color 200 200 200 color fn mkColor color self textItem setDefaultTextColor color self textItem setPlainText text self updateText
returns the json representation of `` value `` in a safe manner .,register filter json def json_filter value return mark_safe json dumps value sort_keys True indent 4 cls SafeJSONEncoder
"' 10.6 ' = > [ 10 , 6 ]",def parse_version version_str return map int re findall d version_str
update the given setting with the specified value .,def updateSetting self name value u if name not in self _settings raise ValueError u Specified setting 0 does not exist format name if hasattr self _settings name u __len__ and not isinstance self _settings name string_types if not hasattr value u __len__ or isinstance value string_types raise TypeError u Trying to update an array setting with a scalar 0 format name self _settings name value
tests calling views with the non - owner logged in .,def test_views__logged_in_non_owner self OTHER_USERNAME justtest OTHER_PASSWORD other_password OTHER_EMAIL justtest me com User objects create_user OTHER_USERNAME password OTHER_PASSWORD email OTHER_EMAIL self client login username OTHER_USERNAME password OTHER_PASSWORD error_urls self specific_entity_urls for url in error_urls self assert_url_response url STATUS_CODE__NOT_FOUND success_urls self non_specific_login_required_urls self no_login_required_urls for url in success_urls self assert_url_response url STATUS_CODE__SUCCESS
test the version and name override from the command line,def test_version_configuration_override self tarball name_and_version something else FileManager self assertEqual tarball version else self assertEqual tarball name something
constructor of the object @type node : xml element or none ( to create and empty one ) @param node : this is the node of the element . if it is none it will create a new object @type type : string @param type : the type of the object ( kaf or naf ),def __init__ self node None type NAF self type type if node is None self node etree Element property else self node node
returns the node of the element @rtype : xml element @return : the node of the element,def get_node self return self node
"utility function to create a plane unless the origin is none , in which case it returns none .",def plane_or_null origin x y if origin is None return None else return Rhino Geometry Plane origin x y
wrapper for getsystemservice . you must wrap the class with the appropriate object .,def get_system_service self service return self widget getSystemService service
"write will write a message to a stream , first checking the encoding",def write self stream message if isinstance message bytes message message decode utf 8 stream write message
verify that an invalid instance service raises an exception,def test_validate_context_invalid_service self self service_registry service_record return_value None with self assertRaises SystemExit ef_version validate_context self
make www and www.backup directory as admin or root user,task def setup_webspace sudo mkdir p live_project_full_path s env sudo mkdir p backup_project_full_path s archive env sudo chown R s s var www backup get_config deploy_user get_config deploy_user_group sudo chmod R 755 var www backup sudo chown R s s var www get_config deploy_user get_config deploy_user_group sudo chmod R 755 var www
return the suffix that must sound the same in a rhyme .,def rime phones return phones find_rime phones
applies adaptive thresholding to the given image .,def threshold image block_size DEFAULT_BLOCKSIZE mask None if mask is None mask np zeros image shape 2 dtype np uint8 mask 255 if len image shape 2 and image shape 2 4 image cv2 cvtColor image cv2 COLOR_BGRA2GRAY res _calc_block_mean_variance image mask block_size res image astype np float32 res astype np float32 255 _ res cv2 threshold res 215 255 cv2 THRESH_BINARY return res
optional method to update the task after the physics engine has stepped .,def after_step self physics
a convenience method for rendering graphs for a particular provider .,detail_route def graphs self request pk None u n A convenience method for rendering graphs for a particular provider n provider get_object_or_404 Provider pk pk queryset Graph objects filter type GRAPH_TYPE_PROVIDER serializer RenderedGraphSerializer queryset many True context u graphed_object provider return Response serializer data
immediately play instrument at channel with given note and velocity . the timestamp is ignored . this is a noop if no instrument is mapped to the given channel .,def noteon self channel note velocity timestamp self instrs get channel _DummyInstrument playnote note velocity
setup basic style for matplotlib figures,def setup_plotting options None override_setup True u Setup basic style for matplotlib figures n if options is None options def option_or_conf key default u Get a value from a dictionary the configuration or a default value n prefix u pyexperiment plot if key in options return options key elif prefix conf SECTION_SEPARATOR key in conf return conf prefix conf SECTION_SEPARATOR key else return default sns None if option_or_conf u seaborn enable True try import seaborn as sns except ImportError log warning u Cannot import seaborn Proceeding without global _SETUP_DONE if not override_setup and _SETUP_DONE return False font_size int option_or_conf u font_size 14 font u family u normal u weight u normal u size font_size matplotlib rc u font font matplotlib rc u text usetex bool option_or_conf u use_tex True matplotlib rc u lines linewidth int option_or_conf u line_width 4 matplotlib rc u figure facecolor u white label_size int option_or_conf u label_size 14 matplotlib rc u xtick labelsize label_size matplotlib rc u ytick labelsize label_size if sns is not None sns set_style option_or_conf u seaborn style u darkgrid sns set_palette option_or_conf u seaborn palette_name u colorblind desat option_or_conf u seaborn desat 0 6 _SETUP_DONE True return True
"returns true if name is a valid string for a library , other false",def check_libname name name str name if not name return 0 return name 0 in _FIRST_LETTERS and all ch in _OTHER_LETTERS for ch in name 1
return a collection of points used to interpolate the arc .,def line_interpolation_points self step 1 points length self length last_point length step traversed 0 while traversed last_point points append self point_at_offset traversed traversed step if length traversed step 2 points append self point_at_offset traversed points append self end_point clone return points
returns a rendered version of the given jinja2 template .,def render self template context template admin_template_environment get_template template values app_id self configuration app_id request self request sdk_version self _SDK_VERSION xsrf_token self xsrf_token values update context return template render values
network performance scripts block stylesheets test,def ScriptsBlockStylesheets request params page_title Performance Scripts Block Stylesheets Test resource_cgi_base RESOURCE_CGI_BASE resource_cgi RESOURCE_CGI resource_cgi2 RESOURCE_CGI2 return util Render request templates tests scripts block stylesheets html params CATEGORY
does safe_repr limit the amount of characters in a repr ?,def test_safe_repr self short abcdefghij long short 10 longer long 10 self assertEqual repr short safe_repr short limit 100 self assertEqual repr long safe_repr long limit 1000 self assertNotEqual repr longer safe_repr longer limit 100 self assertTrue len safe_repr longer limit 100 110
copy all the given named `` attrs `` of `` namespace `` into the global namespace .,def _copy_to_globals namespace attrs g globals for attr in attrs g attr getattr namespace attr
"traverse your thunderbird tree , converting each message file found into a claws - mail message directory .",def convert_tree in_treepath out_treepath for path subs files in os walk in_treepath outpath clean_path path if files for f in x for x in files if not x endswith msf process_file os path join path f os path join out_treepath outpath f
test utf-8 input file names .,def test_filenames_utf8 self input_path tests reference_data filenames_utf8 output_files test_ xc3 xa4 xc3 xb6 xc3 xbc xc3 x9f mp3 sync_music db self _execute_sync_music input_path output_files
return list of data corresponding to * field *,def getfield self field if field in self _fields i self _fields index field return d i for d in self _data else raise KeyError 0 not a field format field
saves npz file containing roi masks .,def to_npz self filename roidata dict name vd data for name vd in self rois items np savez filename roidata
properly setup an empty watchdog directory .,def initialize self for _watchdog filename _stat in self _list_gen self watchdog_path os unlink filename os chmod self watchdog_path 1023
sync app monitor count with instance count .,def _run_sync instance_api instance init authz NullAuthorizer zkclient context GLOBAL zk conn state scheduled monitors zkclient ChildrenWatch z path scheduled exc exit_on_unhandled def _scheduled_watch children Watch scheduled instances scheduled sorted children grouped collections defaultdict list k list v for k v in itertools groupby scheduled lambda n n rpartition 0 state scheduled grouped return True def _watch_monitor name Watch monitor zkclient DataWatch z path appmonitor name exc exit_on_unhandled def _monitor_data_watch data _stat event Monitor individual monitor if event and event type DELETED or data is None _LOGGER info Removing watch on deleted monitor r name return False try count yaml load data count except Exception _LOGGER exception Invalid monitor r name return False _LOGGER info Reconfigure monitor s count s name count state monitors name count count available 2 0 count last_update time time rate 2 0 count _INTERVAL return True zkclient ChildrenWatch z path appmonitor exc exit_on_unhandled def _appmonitors_watch children Watch app monitors monitors set children extra state monitors keys monitors for name in extra _LOGGER info Removing extra monitor r name if state monitors pop name None is None _LOGGER warn Failed to remove non existent monitor r name missing monitors state monitors keys for name in missing _LOGGER info Adding missing monitor s name _watch_monitor name _LOGGER info Ready while True time sleep 1 if not reevaluate instance_api state _LOGGER error Unhandled exception while evaluating state break
tests conversion of values into human readable format .,def test_humanreadable self self assertEqual 1 0M utils bytes_to_readable 1024 K self assertEqual 1 0G utils bytes_to_readable 1024 M self assertEqual 2 5T utils bytes_to_readable 1024 1024 2 5 M self assertEqual 1 0K utils bytes_to_readable 1024 B self assertEqual 2 310 utils cpu_to_readable 2310 self assertEqual 23 10 utils cpu_to_cores_readable 2310
update work variables at end of timestep .,def update t dt w_ w_1 q_rhs bcs enable_EC enable_NS namespace for qi in q_rhs values qi t t dt for boundary_name bcs_fields in bcs iteritems for field bc in bcs_fields iteritems if isinstance bc value df Expression bc value t t dt for subproblem enable in zip EC NSu NSp enable_EC enable_NS enable_NS if enable w_1 subproblem assign w_ subproblem
error output only gets sent to the stream after the test has stopped .,def test_startErrorStop self self distReporter startTest self test self assertEqual self stream getvalue self distReporter addError self test error self assertEqual self stream getvalue self distReporter stopTest self test self assertNotEqual self stream getvalue
classes representing constants containers are not intended to be instantiated .,def __new__ cls raise TypeError s may not be instantiated cls __name__
complete the initialization of this l{flagconstant}.,def _realize self container names value if isinstance names str name names names set names elif len names 1 name names else name join sorted names _Constant _realize self container name value self value value self names names
check for existence and validity of the parameters,def validate_parameters self params if E_0 not in params params E_0 0 0 if P_0 not in params params P_0 0 0 if G_0 not in params params G_0 float nan if Gprime_0 not in params params Gprime_0 float nan expected_keys V_0 K_0 Kprime_0 G_0 Gprime_0 for k in expected_keys if k not in params raise KeyError params object missing parameter k if params P_0 0 0 warnings warn Unusual value for P_0 stacklevel 2 if params V_0 1e 07 or params V_0 0 001 warnings warn Unusual value for V_0 stacklevel 2 if params K_0 1000000000 0 or params K_0 10000000000000 0 warnings warn Unusual value for K_0 stacklevel 2 if params Kprime_0 0 0 or params Kprime_0 10 0 warnings warn Unusual value for Kprime_0 stacklevel 2 if params G_0 0 0 or params G_0 10000000000000 0 warnings warn Unusual value for G_0 stacklevel 2 if params Gprime_0 5 0 or params Gprime_0 10 0 warnings warn Unusual value for Gprime_0 stacklevel 2
"pcr on genome , using two primer sequences . returns tuple of pcr product sequence , primer a blast results , and primer b blast results . produuct sequence may be none if primers do not bind unique or in a way that can result in a pcr product .",def pcr_from_genome genome primer_a_sequence primer_b_sequence primer_a_results primer_a_binding_check_len primer_b_results primer_b_binding_check_len res blast_genome genome blastn primer_a_sequence for r in res primer_a_results append r primer_a_binding_check_len append len primer_a_sequence res blast_genome genome blastn primer_b_sequence for r in res primer_b_results append r primer_b_binding_check_len append len primer_b_sequence for i in range MIN_BINDING_LENGTH BINDING_LENGTH_HI p primer_a_sequence i res blast_genome genome blastn p for r in res primer_a_results append r primer_a_binding_check_len append len p for i in range MIN_BINDING_LENGTH BINDING_LENGTH_HI p primer_b_sequence i res blast_genome genome blastn p for r in res primer_b_results append r primer_b_binding_check_len append len p pcr_products uniq_products for a_len a_res in zip primer_a_binding_check_len primer_a_results for b_len b_res in zip primer_b_binding_check_len primer_b_results product compute_pcr_product primer_a_sequence a_len a_res primer_b_sequence b_len b_res if product is not None k product 0 a_res fragment_id if k not in uniq_products pcr_products append product uniq_products k product if len pcr_products 1 product pcr_products 0 0 region pcr_products 0 1 return product primer_a_results primer_b_results dict region region region fragment_name region fragment name fragment_id region fragment id else return None primer_a_results primer_b_results None
replaces space character ( ' ' ) with a random blank character from a valid set of alternate characters,def tamper payload kwargs blanks 09 0A 0C 0D retVal payload if payload retVal quote doublequote firstspace False False False for i in xrange len payload if not firstspace if payload i isspace firstspace True retVal random choice blanks continue elif payload i quote not quote elif payload i doublequote not doublequote elif payload i and not doublequote and not quote retVal random choice blanks continue retVal payload i return retVal
: return : the list of category labels used by this classifier . : rtype : list of ( immutable ),def labels self raise NotImplementedError
returns true iff this order is buying the market 's base currency ( and selling the counter currency ),property def is_bid self return self from_amount currency self market counter_currency
enters a replay scope that unsets it at the end .,contextlib contextmanager def replay_scope self sess current_replay self replay sess try self set_replay sess True yield finally self set_replay sess current_replay
make a monte carlo sampler object .,def make_monty self args kwargs return self monty_cls args kwargs
return the absolute path to a file in the test / data directory . the name specified should be relative to test / data .,def data_path name return os path join os path dirname __file__ data name
import 1 minute magnetic field from cassini .,def mag_1min starttime endtime coords valid_coords KRTP KSM KSO RTN if coords not in valid_coords raise ValueError coords must be one of format valid_coords base_url http pds ppi igpp ucla edu ditdos download id pds PPI CO E_SW_J_S MAG 4 SUMM 1MINAVG V1 0 DATA Rs u def_unit saturnRad 60268 u km if coords KRTP units OrderedDict Bx u nT By u nT Bz u nT X Rs B u nT Y u deg Z u deg Local hour u dimensionless_unscaled n points u dimensionless_unscaled if coords RTN units OrderedDict Bx u nT By u nT Bz u nT X u AU Y u AU Z u AU B u nT Local hour u dimensionless_unscaled n points u dimensionless_unscaled if coords KSM or coords KSO units OrderedDict Bx u nT By u nT Bz u nT X Rs Y Rs Z Rs B u nT Local hour u dimensionless_unscaled n points u dimensionless_unscaled local_base_dir cassini_dir mag 1min dirs fnames extension TAB for year in starttime year endtime year dirs append format year fnames append _FGM_ _1M format year coords def download_func remote_base_url local_base_dir directory fname extension url format base_url year util _download_remote url fname extension local_base_dir directory def processing_func f if error_message in f readline location f name f close os remove f name raise util _NoDataError data pd read_table f names Time Bx By Bz B X Y Z Local hour n points delim_whitespace True parse_dates 0 index_col 0 f close return data return util process dirs fnames extension local_base_dir base_url download_func processing_func starttime endtime units units
test ` call ` function .,def test_call self y _ self model self x training False self assertEqual y shape self config batch_size self config n_classes
show form to update a fragment .,blueprint route fragments uuid snippet_id update permission_required SnippetPermission update templated def update_fragment_form snippet_id snippet _find_snippet_by_id snippet_id current_version snippet current_version form FragmentUpdateForm obj current_version name snippet name return form form snippet snippet
"set the y range [ low , high ] that the ticks are drawn on . 0 is the bottom of the view , 1 is the top .",def setYRange self vals self yrange vals self rebuildTicks
marks the given point with a small circle on the canvas . used primarily for debugging purposes .,def _mark_point self x y color 0 size 4 if isinstance color int colors 1 0 0 0 1 0 0 0 1 1 1 0 0 1 1 1 0 1 color colors color len colors if len color 3 color 0 5 ctx self context ctx save ctx set_source_rgba color ctx arc x y size 2 0 0 2 pi ctx fill ctx restore
od.itervalues - > an iterator over the values in od,def itervalues self for k in self yield self k
deletes a cohort . user must have owner permissions on the cohort .,endpoints method DELETE_RESOURCE ReturnJSON http_method DELETE path cohorts cohort_id def delete self request user_email None if endpoints get_current_user is not None user_email endpoints get_current_user email cohort_id request get_assigned_value cohort_id if user_email is None raise endpoints UnauthorizedException Authentication failed Try signing in to to register with the web application format BASE_URL django setup try django_user Django_User objects get email user_email user_id django_user id except ObjectDoesNotExist MultipleObjectsReturned as e logger warn e request_finished send self raise endpoints NotFoundException s does not have an entry in the user database user_email try try cohort_to_deactivate Django_Cohort objects get id cohort_id if cohort_to_deactivate active is True cohort_perm Cohort_Perms objects get cohort_id cohort_id user_id user_id if cohort_perm perm OWNER cohort_to_deactivate active False cohort_to_deactivate save return_message Cohort d successfully deleted cohort_id else return_message You do not have owner permission on cohort d cohort_id else return_message Cohort d was already deleted cohort_id return ReturnJSON message return_message except ObjectDoesNotExist MultipleObjectsReturned as e logger warn e raise endpoints NotFoundException Either cohort d does not have an entry in the database or you do not have owner or reader permissions on this cohort cohort_id finally request_finished send self
shortcut function to call predict_phenotype(trait ) for every individual in the population .,def predict_phenotype self trait for x in self individuals x predict_phenotype trait
return all subsurfaces in the idf .,def getshadingsurfaces self surface_type surfaces itertools chain from_iterable self idfobjects key upper for key in self idd_index ref2names AllShadingSurfNames if surface_type surfaces filter lambda x x Surface_Type lower surface_type lower surfaces return list surfaces
converts stringifed scope value to a list .,def string_to_scopes scopes if not scopes return if isinstance scopes six string_types return scopes split else return scopes
get a random int by state[n+1 ] = ( a state[n ] + c ) mod m since we have m = = 2**32 the overflow does the modulus operation for us .,def rand self self state self a self state self c return self state
"returns a filename , based on the provided filename , that 's suitable for use in the target storage system .",def get_valid_name self name return get_valid_filename name
returns the model matching the given app_label and case - insensitive model_name .,def get_model self app_label model_name seed_cache True if seed_cache self _populate return self app_models get app_label SortedDict get model_name lower
mark the amplitude and scattering matrices as up to date .,def _set_scatter_signature self self _scatter_signature self thet0 self thet self phi0 self phi self alpha self beta self orient
the world the entity resides in .,property def world self return self _world
try to create a triple_octupole class .,def test_triple_octupole to TripleOctupole
saves message and timestamp to logfile .,def Log self Message Message datetime utcnow strftime Y m d H M S f 3 Message if Logger display print Message if not os path isfile self filePath raise Exception self filePath Log File Broken Logger my_logger debug Message
"usage : - > put the script in python site packages and then use as below import loaddaysimtrips conn , trip_data = loaddaysimtrips . getdaysimtripsdb(daysimtripfilepath )",def GetDaySimTripsDB1 daysimtripfilepath start time time print Start reading daysim trips tripsfile open daysimtripfilepath rb reader csv DictReader tripsfile delimiter t conn sqlite3 connect memory trip_data conn cursor trip_data execute CREATE TABLE trips otaz INT dtaz INT deptm INT arrtm INT mode INT half INT etrps DOUBLE conn commit for row in reader try otaz int row otaz dtaz int row dtaz deptm int row deptm arrtm int row arrtm mode int row mode half int row half etrps 1 0 float row trexpfac except print Could not batch row try trip_data execute insert into trips values otaz dtaz deptm arrtm mode half etrps conn commit except print Could not commit row tripsfile close print Finished pushing trips to sqlite db in time time start secs return conn trip_data
no override uses static versions .,override_settings STATIC_ROOT static MEDIA_ROOT media STATIC_URL http example com static MEDIA_URL http example com media def test_no_override eq_ get_media_root static eq_ get_media_url http example com static
returns an array of member information,def members self return member as_dict for member in self member_set all
command and option completion for the main option parser ( and options ) and its subcommands ( and options ) .,def autocomplete if PIP_AUTO_COMPLETE not in os environ return cwords os environ COMP_WORDS split 1 cword int os environ COMP_CWORD try current cwords cword 1 except IndexError current subcommands cmd for cmd summary in get_summaries options try subcommand_name w for w in cwords if w in subcommands 0 except IndexError subcommand_name None parser create_main_parser if subcommand_name if subcommand_name help sys exit 1 should_list_installed subcommand_name in show uninstall and not current startswith if should_list_installed installed lc current lower for dist in get_installed_distributions local_only True if dist key startswith lc and dist key not in cwords 1 installed append dist key if installed for dist in installed print dist sys exit 1 subcommand commands_dict subcommand_name for opt in subcommand parser option_list_all if opt help optparse SUPPRESS_HELP for opt_str in opt _long_opts opt _short_opts options append opt_str opt nargs prev_opts x split 0 for x in cwords 1 cword 1 options x v for x v in options if x not in prev_opts options k v for k v in options if k startswith current for option in options opt_label option 0 if option 1 and option 0 2 opt_label print opt_label else if current startswith or current startswith opts i option_list for i in parser option_groups opts append parser option_list opts o for it in opts for o in it for opt in opts if opt help optparse SUPPRESS_HELP subcommands opt _long_opts opt _short_opts print join x for x in subcommands if x startswith current sys exit 1
append `` record `` to the database .,def append self record record index self header recordCount record _write self header recordCount 1 self _changed True self _new False
parses a single host entry .,def parse_host_entry line default_user default_port default_password fields line split if len fields 3 sys stderr write Bad line s Format should be user password host port user password line return None None None None host_field fields 0 host port user password parse_host host_field default_port default_port if len fields 3 if user is None user fields 1 else sys stderr write User specified twice in line s n line return None None None None if password is None password fields 2 else sys stderr write Password specified twice in line s n line return None None None None if user is None user default_user if password is None password default_password return host port user password
"spawn the pickup at a random location , or no location at all , and return the tile location .",def spawn_pickup self pickup tile self level get_random_flat_tile if tile pickup is None tile pickup pickup x y tile get_center tile pickup container tile return tile return None
"recursive method which create a partial ast from real objects ( only function , class , and method are handled )",def object_build self node obj if obj in self _done return self _done obj self _done obj node for name in dir obj try member getattr obj name except AttributeError attach_dummy_node node name continue if ismethod member member member im_func if isfunction member filename getattr member func_code co_filename None if filename is None assert isinstance member object object_build_methoddescriptor node member name elif filename getattr self _module __file__ None attach_dummy_node node name member else object_build_function node member name elif isbuiltin member if self imported_member node member name continue object_build_methoddescriptor node member name elif isclass member if self imported_member node member name continue if member in self _done class_node self _done member if not class_node in node locals get name node add_local_node class_node name else class_node object_build_class node member name self object_build class_node member if name __class__ and class_node parent is None class_node parent self _done self _module elif ismethoddescriptor member assert isinstance member object object_build_methoddescriptor node member name elif isdatadescriptor member assert isinstance member object object_build_datadescriptor node member name elif type member in _CONSTANTS attach_const_node node name member else attach_dummy_node node name member
returns a copy of the ' i'th row .,def getrow self i new lil_matrix 1 self shape 1 dtype self dtype new rows 0 self rows i new data 0 self data i return new
"user has received the invite email , and has followed the link to accept or or refuse it .",def invite_email request code if request user handled common_views handle_view_action request invite_accept request user url overview invite_reject request user url overview if handled return handled invite api invite_get api ROOT code from_actor invite from_actor from_actor_ref api actor_get api ROOT from_actor view from_actor_ref if not from_actor_ref return util RedirectError That invite is no longer valid inbox api inbox_get_actor_contacts api ROOT view nick limit 5 entries api entry_get_entries api ROOT inbox stream_keys e stream for e in entries streams api stream_get_streams api ROOT stream_keys actor_nicks view nick s owner for s in streams values if s e owner for e in entries e actor for e in entries actors api actor_get_actors api ROOT actor_nicks streams display prep_stream_dict streams actors entries display prep_entry_list entries streams actors sidebar_green_top True c template RequestContext request locals t loader get_template invite templates email html return http HttpResponse t render c
test that sessionlist can append items to request.session .,def test_session_list_can_append_items_to_list self session self client session session_list1 SessionList session session_list1 append foo session_list2 SessionList session self assertEqual session_list2 foo
this method does nothing for dynamodbadapter .,def commit self print dynamo commit
wrapper for nvme reset command . - args : - none : - returns : - none,tools nottest def nvme_reset_ctrl self nvme_reset_cmd nvme reset self ctrl err subprocess call nvme_reset_cmd shell True stdout subprocess PIPE assert_equal err 0 ERROR nvme reset failed time sleep 5 rescan_cmd echo 1 sys bus pci rescan proc subprocess Popen rescan_cmd shell True stdout subprocess PIPE stderr subprocess PIPE time sleep 5 assert_equal proc wait 0 ERROR pci rescan failed
read all seq.fa files and create a matrix and unique fasta files . the information is,def prepare args try f open args config r seq_out open op join args out seqs fastq w ma_out open op join args out seqs ma w except IOError as e traceback print_exc raise IOError Can not create output files s s or read s op join args out seqs ma op join args out seqs fastq args config logger info Reading sequeces seq_l sample_l _read_fastq_files f args logger info Creating matrix with unique sequences logger info Filtering min counts s min size s max size s min shared s args minc args minl args maxl args min_shared _create_matrix_uniq_seq sample_l seq_l ma_out seq_out args min_shared logger info Finish preprocessing Get a sorted BAM file of seqs fa and run seqcluster cluster
returns the source code covered by this range .,def source self u n Returns the source code covered by this range n return self source_buffer source self begin_pos self end_pos
method to extract variables into system wise class instance,def unpack_variables self variables mvars self mvars self log debug in unpack_variables mvars runname variables runname 0 mvars pdbfile variables pdbfile 0 mvars dcdfile variables dcdfile 0 if mvars dcdfile 3 dcd mvars xstfile variables xstfile 0 mvars aliasfile variables aliasfile 0 mvars create_alias_flag variables create_alias_flag 0 mvars number_q_values variables number_q_values 0 mvars q_max variables q_max 0 self log debug vars mvars return
"read in the file or data , populating a lxml._elementtree object stripping out namespaces",def read_xml_no_ns filename parsed_xml read_xml filename if parsed_xml is None return None return delete_namespace parsed_xml
""" returns keyframe i d in order 0 ... len(items )",def item_id_at self index return list self posdict values index
return the subgraph of this graph whose vertices are the given ones and whose edges are all the edges of the original graph between those vertices .,abc abstractproperty def full_subgraph self vertices
"returns the last ` num_lines ` of a file , or less if the file is smaller . seeks to eof .",def _read_last_lines num_lines mesos_file file_size mesos_file size fetch_size LINE_SIZE num_lines end file_size start max end fetch_size 0 data while True mesos_file seek start data mesos_file read end start data data_tmp _strip_trailing_newline data lines data_tmp split n if len lines num_lines ret lines num_lines break elif start 0 ret lines break end start start max end fetch_size 0 mesos_file seek file_size return ret
"return the "" git clone "" argument for cloning the repository",def repository self repo_index return self repos repo_index repository
check whether a name is valid as a netbios name .,def valid_netbios_name name if len name 15 return False for x in name if not x isalnum and not x in _ return False return True
checking the course already exists in db .,def clean self cleaned_data super CourseAccessRoleForm self clean if not self errors if CourseAccessRole objects filter user cleaned_data get email org cleaned_data get org course_id cleaned_data get course_id role cleaned_data get role exists raise forms ValidationError Duplicate Record return cleaned_data
saves object and logs change to object,def save_model self request obj form change obj save_and_log request user
"removes keys from a dict that pass some filter function , and returns a dict of all the removed key - value pairs . ex . usage : pop_matching_keys_from_dict({'a ' : 1 , ' b ' : 2 , ' c ' : 3 } , lambda k : k in [ ' a','b ' ] ) # > { ' a ' : 1 , ' b ' : 2 }",def pop_matching_keys_from_dict dict_to_pop filter_func return pop_keys_from_dict dict_to_pop filter filter_func dict_to_pop copy
nothing should break when navigating to the profile and back to learners search page,def test_profile_navigation self browser base_test_data create_enrolled_user_batch 2 program base_test_data program is_staff False browser get learners browser click_when_loaded By CLASS_NAME menu icon browser wait until lambda driver open in driver find_element_by_class_name nav drawer get_attribute class browser click_when_loaded By CSS_SELECTOR a profile image browser wait_until_loaded By CLASS_NAME user page browser click_when_loaded By CLASS_NAME menu icon browser wait until lambda driver open in driver find_element_by_class_name nav drawer get_attribute class browser click_when_loaded By CSS_SELECTOR a href learners browser wait_until_loaded By CLASS_NAME learner results
checks to make sure the cwd is the application root directory,def check_cwd app_root os path dirname os path abspath __file__ if app_root os getcwd print INFO Switching CWD to s app_root os chdir app_root
"this will connect to the server , and if the features tag is found then set the namespace to be jabber : client as that is required for jabberd2 . "" server "" and "" proxy "" arguments have the same meaning as in xmpp . client.connect ( ) .",def connect self server None proxy None if self sasl self Namespace auth NS_COMPONENT_1 self Server server 0 CommonClient connect self server server proxy proxy if self connected and self typ jabberd2 or not self typ and self Dispatcher Stream features None and not self xcp self defaultNamespace auth NS_CLIENT self Dispatcher RegisterNamespace self defaultNamespace self Dispatcher RegisterProtocol iq dispatcher Iq self Dispatcher RegisterProtocol message dispatcher Message self Dispatcher RegisterProtocol presence dispatcher Presence return self connected
return boolean indicating whether this extension is available,def glInitDrmImageMESA from OpenGL import extensions return extensions hasGLExtension _EXTENSION_NAME
return boolean indicating whether this extension is available,def glInitBlendEquationSeparateOES from OpenGL import extensions return extensions hasGLExtension _EXTENSION_NAME
return numpy array of zeros in given size,def zeros self dims typeCode raise NotImplementedError Sized output doesn t yet work
return boolean indicating whether this extension is available,def glInitParameterBufferObject2NV from OpenGL import extensions return extensions hasGLExtension _EXTENSION_NAME
wrap the given pointer - setting function,def wrapPointerFunction name baseFunction glType arrayType startArgs defaultSize function wrapper wrapper baseFunction if ptr in baseFunction argNames pointer_name ptr else pointer_name pointer assert not getattr function pyConverters None Reusing wrappers if arrayType arrayModuleType arraydatatype GL_CONSTANT_TO_ARRAY_TYPE glType function setPyConverter pointer_name arrayhelpers asArrayType arrayModuleType else function setPyConverter pointer_name arrayhelpers AsArrayOfType pointer_name type function setCConverter pointer_name converters getPyArgsName pointer_name if size in function argNames function setPyConverter size function setCConverter size arrayhelpers arraySizeOfFirstType arrayModuleType defaultSize if type in function argNames function setPyConverter type function setCConverter type glType if stride in function argNames function setPyConverter stride function setCConverter stride 0 function setStoreValues arrayhelpers storePointerType pointer_name arrayType function setReturnValues wrapper returnPyArgument pointer_name return name function
generate a gaussian random partition graph .,def gaussian_random_partition_graph n s v p_in p_out directed False seed None if s n raise nx NetworkXError s must be n assigned 0 sizes while True size int random normalvariate s float s v 0 5 if size 1 continue if assigned size n sizes append n assigned break assigned size sizes append size return random_partition_graph sizes p_in p_out directed seed
"extract "" data "" labels from the library.yml file . each item labelled as "" data "" is a path that can be accessed through internet : param it - iterable ( list / dict ) of the yaml file",classmethod def get_data cls it if type it list outp for i in it outp outp cls get_data i return outp elif type it dict outp if content in it keys outp outp cls get_data it content if data in it keys outp outp it data return outp
return a friendly http greeting .,app route def hello print there u go return Hello my Beaturiful World n
generate a parameter set with a given layer model . todo : right a decoding equivalent to pass to lmfit.minimize,def params_from_model self u n Generate a parameter set with a given layer model n TODO Right a decoding equivalent to pass to lmfit minimize n params Parameters def _process_parameter layer_name p if p vary params add u s__ s layer_name p name value p value min p minimum max p maximum for l in self _model_layers _process_parameter l name l _thickness _process_parameter l name l _nsld_real _process_parameter l name l _roughness return params
create a new user entity and save look up account with account_id and use in reference when creating new user,def create_new_user account_id user_id account_entity memcache_db get_entity account_id Accounts user_key get_user_key account_id user_id new_user Users key_name user_key userid user_id isEnabled yes accountRef account_entity try memcache_db save_entity new_user user_key except logging error Error saving new user entity return
"parses .annot files and returns an overlap matrix . see docs / file_formats_ld.txt . if num is not none , parses .annot files split across [ num ] chromosomes ( e.g. , the output of parallelizing ldsc.py --l2 across chromosomes ) .",def annot fh_list num None frqfile None annot_suffix annot for fh in fh_list annot_compression if num is not None for i fh in enumerate fh_list first_fh sub_chr fh 1 annot_suffix i annot_s annot_comp_single which_compression first_fh annot_suffix i annot_s annot_compression append annot_comp_single if frqfile is not None frq_suffix frq first_frqfile sub_chr frqfile 1 frq_suffix frq_s frq_compression which_compression first_frqfile frq_suffix frq_s y M_tot 0 for chr in xrange 1 num 1 if frqfile is not None df_annot_chr_list annot_parser sub_chr fh chr annot_suffix i annot_compression i sub_chr frqfile chr frq_suffix frq_compression for i fh in enumerate fh_list else df_annot_chr_list annot_parser sub_chr fh chr annot_suffix i annot_compression i for i fh in enumerate fh_list annot_matrix_chr_list np matrix df_annot_chr for df_annot_chr in df_annot_chr_list annot_matrix_chr np hstack annot_matrix_chr_list y append np dot annot_matrix_chr T annot_matrix_chr M_tot len df_annot_chr_list 0 x sum y else for i fh in enumerate fh_list annot_s annot_comp_single which_compression fh annot_suffix i annot_suffix i annot_s annot_compression append annot_comp_single if frqfile is not None frq_suffix frq frq_s frq_compression which_compression frqfile frq_suffix frq_suffix frq_s df_annot_list annot_parser fh annot_suffix i annot_compression i frqfile frq_suffix frq_compression for i fh in enumerate fh_list else df_annot_list annot_parser fh annot_suffix i annot_compression i for i fh in enumerate fh_list annot_matrix_list np matrix y for y in df_annot_list annot_matrix np hstack annot_matrix_list x np dot annot_matrix T annot_matrix M_tot len df_annot_list 0 return x M_tot
an alias used for queries .,property def alias self if not hasattr self _alias self _alias self table alias entry return self _alias
create instance flavor target component : nova,def test_create_flavor self fail_msg Flavor was not created properly flavor self verify 30 self _create_flavors 1 fail_msg flavor creation self compute_client 255 1 msg_s2 Flavor name is not the same as requested self verify_response_true flavor name startswith ost1_test flavor Step 2 failed msg format msg msg_s2 msg_s3 Disk size is not the same as requested self verify_response_body_value body_structure flavor disk value 1 msg msg_s3 failed_step 3 msg_s4 Flavor failed to be deleted self verify 30 self _delete_flavors 4 msg_s4 flavor deletion self compute_client flavor
return conditions and their associated values in a dict .,def get_conditions self if not hasattr self conditions raise NotImplementedError conditions attribute must be overridden for c in self conditions value getattr self c if callable value self _condits c value elif value self _condits c value return self _condits
get - spider - stats < spider > - get stats of a running spider,def cmd_get_spider_stats args opts stats jsonrpc_call opts stats get_stats args 0 for name value in stats items print 40s s name value
test moleculedatabase.save with gzipped output .,def test_save_gz self _ filename tempfile mkstemp dir self temp_dir suffix gz for mol in self mols self database add_mol mol self database save filename self check_database filename filename with gzip open filename as f assert len f readlines len self mols
returns a dictionary of { field_name : field_index } for the given table . indexes are 0-based .,def _name_to_index cursor table_name return dict d 0 i for i d in enumerate get_table_description cursor table_name
checks a function that returns an ogr envelope by reference .,def check_envelope result func cargs offset 1 env ptr_byref cargs offset return env
returns the object that this comment is a comment on . returns none if the object no longer exists .,def get_content_object self from django core exceptions import ObjectDoesNotExist try return self content_type get_object_for_this_type pk self object_id except ObjectDoesNotExist return None
"sends a message to the managers , as defined by the managers setting .",def mail_managers subject message fail_silently False EmailMessage settings EMAIL_SUBJECT_PREFIX subject message settings SERVER_EMAIL a 1 for a in settings MANAGERS send fail_silently fail_silently
return rorp 's key for _ inode _ dictionaries,def get_inode_key rorp return rorp getinode rorp getdevloc
returns devices trusted for two - step authentication .,property def trusted_devices self request self session get s listDevices self _setup_endpoint params self params return request json get devices
"iterates over the stream , one line at a time . this avoids reading the entire file into memory at once .",def readlines self pending None for chunk in self iter_content if pending is not None chunk pending chunk lines chunk splitlines True if lines and lines 1 and chunk and lines 1 1 chunk 1 pending lines pop else pending None for line in lines yield line if pending is not None yield pending
: params float frequency : called frequency of the : meth:`~pypot.stoppablethread . stoppableloopthread.update ` method,def __init__ self frequency update None StoppableThread __init__ self self period 1 0 frequency self _update self update if update is None else update self _updated threading Event
position and add foreground image .,def add_foreground self image_name if not image_name return img self load_image image_name self fgr self add_image img self origin_x self origin_y self meter_bounding_box
transmit a ` process ` request to host,def process self plugin context instance None action None plugin plugin to_json instance instance to_json if instance is not None else None return self _dispatch process args plugin instance action
load the extension in ipython .,def load_ipython_extension ip global __pylada_is_loaded__ if not __pylada_is_loaded__ from types import ModuleType import pylada __pylada_is_loaded__ True pylada interactive ModuleType interactive pylada interactive jobfolder None pylada interactive jobfolder_path None pylada is_interactive True
this is run once for each class after all tests,classmethod def teardown_class cls pass
"when the test is actually a contextsuite , get the name from context .",def test_get_name_from_context_suite self plugin self _make_one context mock Mock __name__ FakeContext test ContextSuite context context name plugin _cls_name test self assertEqual name FakeContext
make sure dumpwindow ( ) function works,def test_dumpwindow self dlgdump dumpwindow self dlghandle for key item in dlgdump items self assertEquals item globals key self dlghandle editdump dumpwindow self edit_handle for key item in editdump items self assertEquals item globals key self edit_handle
"the name ofthis object , unique in the freecad document",property def Name self return self __object__ Name
"return true if grid is active , false otherwise .",def isGrid self return bool self grid
"return a fake status , as a list .",def status self path recurse False return FakeInfo
construct the request url : param uri : the required uri : return : the full url : rtype : str,def _get_url self uri return format Pocket api_url uri
return repository information for the current working tree .,def get_repository_info self u Return repository information for the current working tree n n Returns n rbtools clients RepositoryInfo n The repository info structure n if not check_install u cvs logging debug u Unable to execute cvs skipping CVS return None cvsroot_path os path join u CVS u Root if not os path exists cvsroot_path return None with open cvsroot_path u r as fp repository_path fp read strip i repository_path find u if i 1 repository_path repository_path i 1 i repository_path rfind u if i 1 host repository_path i try canon socket getfqdn host repository_path repository_path replace u s host u s canon except socket error as msg logging error u failed to get fqdn for s msg s host msg return RepositoryInfo path repository_path local_path repository_path
create a default style error handler .,def __init__ self file_path configuration increment_error_count line_numbers None if line_numbers is not None line_numbers set line_numbers self _file_path file_path self _configuration configuration self _increment_error_count increment_error_count self _line_numbers line_numbers self _category_totals
returns if a particular line should be checked,def should_line_be_checked self line_number return self _line_numbers is None or line_number in self _line_numbers
find the coveragetarget for given name,def GetCoverageTarget self name target self _targets_manifest GetTarget name if target is None msg Error test references undefined target s name msg append Ensure target is defined in s self _TARGET_DEF_FILE raise errors AbortError msg return target
train a cascade accoring to the algorithm in wang et al . ( 2011 ),baker command name train def WLM11 train_file validation_file test_file costs_file None importance_file None model_prefix None n_stages 0 gamma 0 1 beta_values 0 5 0 33 0 25 0 2 0 1 use_query_features False build_wlm11_cascade train_file validation_file test_file costs_file importance_file model_prefix model_prefix n_stages n_stages gamma ast literal_eval gamma beta_values ast literal_eval beta_values use_query_features use_query_features
returns the external ip of the given node .,def external_ip self node_id raise NotImplementedError
"`` ' pass ' `` if all critical tests succeeded , `` ' fail ' `` otherwise .",property def status self return PASS if self passed else FAIL
create gpg subpacket with 8-bit unsigned integers .,def subpacket_bytes subpacket_type values return subpacket subpacket_type B len values values
@brief constructs run decoder command .,def get_test_command mdir moses_ini in_file out_file background False amp get_background_command background return s s s s s n test mdir moses_ini in_file out_file amp
"setuptools needs to give back the same result as distutils , even if the fullname is not in ext_map .",def test_get_ext_filename self dist Distribution cmd build_ext dist cmd ext_map foo bar res cmd get_ext_filename foo wanted orig build_ext get_ext_filename cmd foo assert res wanted
"implement a forward binary method with a ufunc , e.g. , _ _ add__.",def _binary_method ufunc name def func self other if _disables_array_ufunc other return NotImplemented return ufunc self other func __name__ __ __ format name return func
"used to compute when we need to change the graphics state . for example , if we have two adjacent red shapes we do n't need to set the pen color to red in between . returns the effect the given shape would have on the graphics state",def getStateDelta shape delta for prop value in shape getProperties items if prop in STATE_DEFAULTS delta prop value return delta
schedule a func to be run,abstractmethod def apply_async self func callback None
"enable special function errors ( such as underflow , overflow , loss of precision , etc . )",def with_special_errors func def wrapper a kw old_filters list getattr warnings filters old_errprint sc errprint 1 warnings filterwarnings error category sc SpecialFunctionWarning try return func a kw finally sc errprint old_errprint setattr warnings filters old_filters wrapper __name__ func __name__ wrapper __doc__ func __doc__ return wrapper
od.__iter _ _ ( ) < = = > iter(od ),def __iter__ self root self __root curr root 1 while curr is not root yield curr 2 curr curr 1
process the element 's child elements in self.run .,def _process_nests self element block u nest_index i self parser blockprocessors tag_counter 1 while len self _tag_data i and self _tag_data i u left_index left_child_index self _tag_data i u left_index right_child_index self _tag_data i u right_index nest_index append left_child_index 1 right_child_index i 1 for i left_index right_index in enumerate nest_index 1 self run element block left_index right_index block right_index nest_index i 1 0 True self run element block nest_index 1 0 nest_index 1 1 block nest_index 1 1 True
computes the confusion matrix from predictions and labels .,tf_export confusion_matrix def confusion_matrix labels predictions num_classes None dtype dtypes int32 name None weights None with ops name_scope name confusion_matrix predictions labels num_classes weights as name labels predictions remove_squeezable_dimensions ops convert_to_tensor labels name labels ops convert_to_tensor predictions name predictions predictions math_ops cast predictions dtypes int64 labels math_ops cast labels dtypes int64 labels control_flow_ops with_dependencies check_ops assert_non_negative labels message labels contains negative values labels predictions control_flow_ops with_dependencies check_ops assert_non_negative predictions message predictions contains negative values predictions if num_classes is None num_classes math_ops maximum math_ops reduce_max predictions math_ops reduce_max labels 1 else num_classes_int64 math_ops cast num_classes dtypes int64 labels control_flow_ops with_dependencies check_ops assert_less labels num_classes_int64 message labels out of bound labels predictions control_flow_ops with_dependencies check_ops assert_less predictions num_classes_int64 message predictions out of bound predictions if weights is not None predictions get_shape assert_is_compatible_with weights get_shape weights math_ops cast weights dtype shape array_ops stack num_classes num_classes indices array_ops stack labels predictions axis 1 values array_ops ones_like predictions dtype if weights is None else weights cm_sparse sparse_tensor SparseTensor indices indices values values dense_shape math_ops to_int64 shape zero_matrix array_ops zeros math_ops to_int32 shape dtype return sparse_ops sparse_add zero_matrix cm_sparse
linearly interpolates values in new_x based on the values in x and y.,np deprecate message block_average_above is deprecated in SciPy 1 0 0 def block_average_above x y new_x bad_index None x atleast_1d_and_contiguous x np float64 y atleast_1d_and_contiguous y np float64 new_x atleast_1d_and_contiguous new_x np float64 if y ndim 2 raise ValueError linear only works with 1 D or 2 D arrays if len y shape 2 new_y np zeros y shape 0 len new_x np float64 for i in range len new_y bad_index _interpolate block_averave_above_dddd x y i new_x new_y i if bad_index is not None break else new_y np zeros len new_x np float64 bad_index _interpolate block_average_above_dddd x y new_x new_y if bad_index is not None msg block_average_above cannot extrapolate and new_x d f is out of the x range f f bad_index new_x bad_index x 0 x 1 raise ValueError msg return new_y
creates the real nvp or nice bijector .,def __init__ self num_masked shift_and_log_scale_fn is_constant_jacobian False validate_args False name None name name or real_nvp if num_masked 0 raise ValueError num_masked must be a positive integer self _num_masked num_masked self _input_depth None self _shift_and_log_scale_fn shift_and_log_scale_fn super RealNVP self __init__ event_ndims 1 is_constant_jacobian is_constant_jacobian validate_args validate_args name name
"initialize by reading the task files , if they exist .",def __init__ self taskdir name tasks self tasks self done self name name self taskdir taskdir filemap tasks self name done s done self name for kind filename in filemap path os path join os path expanduser self taskdir filename if os path isdir path raise InvalidTaskfile if os path exists path try with open path r as tfile tls tl strip for tl in tfile if tl tasks map _task_from_taskline tls for task in tasks if task is not None getattr self kind task id task except IOError as e raise BadFile path e strerror
test ii = -1^n * i for giant bit distributions,pytest mark parametrize i range 2 6 def test_ii2 i outcomes 0 i 1 i pmf 1 2 1 2 d D outcomes pmf ci coinformation d ii interaction_information d assert ii pytest approx 1 i ci
parameters ---------- optimizer : markovvaroptimizer the optimizer to track the optimization of .,def __init__ self constraints icb None self eq_constraints c fun for c in constraints if c type eq self ineq_constraints c fun for c in constraints if c type ineq self icb icb self eq_candidates self ineq_candidates
initialises internal variables . used internally .,def __init__ self PlugIn __init__ self DBG_LINE browser self _exported_methods self _handlers
precomputes the lu decomposition and other intermediate results needed to fit a tps to x_na with bend_coeff,def get_lu_decomp x_na bend_coef rot_coef n d x_na shape Q np c_ np ones n 1 x_na K_nn QWQ Q T dot WQ H Q T dot Q H d 1 d 1 bend_coef K_nn rot_coefs np ones d rot_coef if np isscalar rot_coef else rot_coef H 1 d 1 1 d 1 np diag rot_coefs A np r_ np zeros d 1 d 1 np c_ np ones n 1 x_na T _u _s _vh np linalg svd A T N _u n_cnts p l u scipy linalg lu N T dot H dot N res_dict p p l l u u N N rot_coeffs rot_coeffs return bend_coeff res_dict
ran whenever a reddit post is sent,dave module match https www reddit com r comments s dave module match https www redd it s dave module ratelimit 1 1 dave module dont_always_run_if_run def post bot args sender source if dave config redis exists reddit post mentioned format args 0 source return if not dave config redis exists reddit post format args 0 req get https reddit com json limit 1 format args 0 headers user agent irc bot https github com w4 if req status_code 200 return req req json dave config redis setex reddit post format args 0 200 pickle dumps req else req pickle loads dave config redis get reddit post format args 0 resp req 0 data children 0 data dave config redis setex reddit post mentioned format args 0 source 300 1 bot msg source assembleFormattedText A normal A bold A fg lightRed NSFW if resp over_18 else A bold resp title 75 resp title 75 and by A bold resp author r comments points posted format resp subreddit intcomma resp num_comments intcomma resp score naturaltime datetime utcnow timestamp resp created_utc
list of all backtraces assigned to this problem sorted by quality .,property def sorted_backtraces self return sorted self backtraces key lambda bt bt quality reverse True
"pull changes from a remote repository , merge new changes if needed .",command fetch r rev _ a specific revision you would like to pull _ REV e edit None _ invoke editor on commit messages force editor None _ edit commit message DEPRECATED switch parent None _ switch parents when merging commands commitopts commands commitopts2 commands remoteopts _ hg fetch SOURCE def fetch ui repo source default opts date opts get date if date opts date util parsedate date parent _p2 repo dirstate parents branch repo dirstate branch try branchnode repo branchtip branch except error RepoLookupError branchnode None if parent branchnode raise error Abort _ working directory not at branch tip hint _ use hg update to check out branch tip wlock lock None try wlock repo wlock lock repo lock cmdutil bailifchanged repo bheads repo branchheads branch bheads head for head in bheads if len repo head children 0 if len bheads 1 raise error Abort _ multiple heads in this branch use hg heads and hg merge to merge other hg peer repo opts ui expandpath source ui status _ pulling from s n util hidepassword ui expandpath source revs None if opts rev try revs other lookup rev for rev in opts rev except error CapabilityError err _ other repository doesn t support revision lookup so a rev cannot be specified raise error Abort err modheads exchange pull repo other heads revs cgresult if modheads 0 return 0 newheads repo branchheads branch newchildren repo changelog nodesbetween parent newheads 2 if len newheads 1 and len newchildren if newchildren 0 parent return hg update repo newchildren 0 else return 0 newchildren n for n in newchildren if n parent newparent parent if newchildren newparent newchildren 0 hg clean repo newparent newheads n for n in newheads if n newparent if len newheads 1 ui status _ not merging with d other new branch heads use hg heads and hg merge to merge them len newheads 1 return 1 if not newheads return 0 err False if newheads if opts switch_parent firstparent secondparent newparent newheads 0 else firstparent secondparent newheads 0 newparent ui status _ updating to d s n repo changelog rev firstparent short firstparent hg clean repo firstparent ui status _ merging with d s n repo changelog rev secondparent short secondparent err hg merge repo secondparent remind False if not err message cmdutil logmessage ui opts or Automated merge with s util removeauth other url editopt opts get edit or opts get force_editor editor cmdutil getcommiteditor edit editopt editform fetch n repo commit message opts user opts date editor editor ui status _ new changeset d s merges remote changes with local n repo changelog rev n short n return err finally release lock wlock
checks if daemon is started args - process start arguments pidfile - file with stored process pid,def CheckProcess self try with open self pidFile as pidReader pid int pidReader readline except ValueError IOError as e return None try cmdfile proc s cmdline pid if not os path isfile cmdfile return False with open cmdfile as psReader psLine psReader read if any psLine startswith checkname for checkname in self checkExecNames return pid return False except logging exception error while reading process status
converts human readable ipv4 or ipv6 string to int type representation . : param str ip : ipv4 or ipv6 address string : return : int type representation of ipv4 or ipv6 address,def text_to_int ip if not in ip return ipv4_to_int ip else return ipv6_to_int ip
returns a basic mock pwd.getpwuid call result . currently only the pw_name attribute has been set .,def get_mock_getpwuid self uid result Mock result pw_name self username return result
initialises a background task posting client .,def __init__ self data_manager logger self _logger logger self _data data_manager self _hk_thread None self _hk_running False
removes all ons mibs from mibs folder .,def clear_mibs_folder path if os path exists path shutil rmtree path
fixture of environment with lxc for unittests of methods get_ports and get_speed .,pytest fixture def env request monkeypatch env EnvTest SETUP ENV return env start request monkeypatch
parse the string value @return :,def parseValue self rawValue if self type_params ASCII_STR value idc GetString rawValue strtype idc ASCSTR_C description ASCII C String elif self type_params UNICODE_STR value idc GetString rawValue strtype idc ASCSTR_UNICODE description Unicode String else return value raw_value self normalize_raw_value value self addParsedvalue value 0 description raw_value
"return the exit status of the child process if it has finished , or -1 if it has n't finished yet .",def poll self if self sts 0 try pid sts os waitpid self pid os WNOHANG if pid self pid self sts sts _active remove self except os error pass return self sts
submit the specified backgroundjob to the background queue,classmethod def submit cls background_job background_job save journal_csv schedule args background_job id delay 10
"validate the kmer profile in the given filename , using ` counts ` as a reference .",def test_profile_file filename counts k name None u n Validate the kMer profile in the given filename using counts as a n reference n with open_profile filename as f name name or list f u profiles keys 0 assert name in f u profiles keys profile f u profiles s name assert profile attrs u length k assert profile attrs u total sum counts values assert profile attrs u non_zero len counts assert np array_equal profile as_array counts k
add to device time value .,def timeValue self name desc value rts2_type None print timevalue name 0 format desc value rts2_type if rts2_type else sys stdout flush
solve dependencies for the given job list . the list is allowed to contain element names of the following format :,def solve self job_names skip_missing False ignore_recommended True solver self pool Solver if ignore_recommended solver set_flag self solv Solver SOLVER_FLAG_IGNORE_RECOMMENDED 1 solver_problems solver solve self _setup_jobs job_names skip_missing solver_problem_info self _evaluate_solver_problems solver_problems if solver_problem_info raise KiwiSatSolverJobProblems solver_problem_info solver_transaction solver transaction return self _evaluate_solver_result solver_transaction
list all registered orca steps .,app route steps def list_steps return jsonify steps orca list_steps
test parsing of dptvalue1ucount with wrong value ( array containing string ) .,def test_from_knx_wrong_parameter2 self with self assertRaises ConversionError DPTValue1Ucount from_knx 0x23
run event with ` event_name ` on problem ` prob `,def run_event event_name prob state ret report run_event_on_problem_dir prob path event_name if ret 0 and state children_count 0 sys stderr write No actions were found for event format event_name return False return True
get the converted block at the given specific address with the given size .,def block self addr size try return self _blocks addr size except KeyError return None
check that trying to create a record from non - record xml fails .,def test_create_bad_xml self self assertRaises RecordFactoryException self _rf create_records nonrecordxml nonrecordxml
"rotates the arrow with self.arrow_rotation_speed according to how much time has elapsed ( given by dt ) . if dt is not specified , self.dt is used .",def rotate_arrow self dt None if dt None dt self dt self phi 360 0 self params arrow_rotation_time dt self phi self phi 360 0
return the total demand from the data frame .,def total_demand self return self demand values sum
create the target deploy directories if they do n't exist and clone a fresh copy of the project 's repository into each of the release directories .,def bootstrap_release_folders require path require deploy_group conditional_mkdir os path join env path env releases_root env deploy_group g w use_sudo True with cd os path join env path env releases_root first_exists exists env release_paths 0 if not first_exists run git clone s s env scm env release_paths 0 forward_agent True with cd os path join env path env releases_root if not exists env release_paths 1 run cp R s s env release_paths 0 env release_paths 1 chmod os path join env path env releases_root g w use_sudo True
copied from numpy 's _ greedy_path,def _greedy_path input_sets output_set idx_dict memory_limit if len input_sets 1 return 0 path for iteration in range len input_sets 1 iteration_results comb_iter for x in range len input_sets for y in range x 1 len input_sets comb_iter append x y for positions in comb_iter contract _find_contraction positions input_sets output_set idx_result new_input_sets idx_removed idx_contract contract if _compute_size_by_dict idx_result idx_dict memory_limit continue removed_size _compute_size_by_dict idx_removed idx_dict cost _compute_size_by_dict idx_contract idx_dict sort removed_size cost iteration_results append sort positions new_input_sets if len iteration_results 0 path append tuple range len input_sets break best min iteration_results key lambda x x 0 path append best 1 input_sets best 2 return path
set output message completion status to is_completed ( bool ) .,def set_completion self message is_completed if message in self _by_message self _by_message message _IS_COMPLETED is_completed
return a rawconfigparser for the platform .,def __initialize_config_info_inner config_fh global __config_info __config_info RawConfigParser configure_parser __config_info if config_fh is not None __config_info readfp config_fh
this function parses an xml file defining a tsp ( from tsplib http://www.iwr.uni-heidelberg.de/groups/comopt/software/tsplib95/ ) and returns the adjacency matrix that cna be then used to construct a pygmo.problem.tsp,def read_tsplib file_name import xml etree ElementTree as ET try tree ET parse file_name except ET ParseError as e print There was a problem parsing fileName n e return except IOError as e print There was a problem opening the file n e return root tree getroot adj_mat symmetric False try for idx_from vertice in enumerate root iter vertex tmp for idx_to edge in enumerate vertice if idx_from idx_to int edge text tmp append 0 symmetric True tmp append float edge get cost adj_mat append tmp if symmetric adj_mat idx_to 1 append 0 except TypeError print One of the values of the graph attributes is not valid print Hint idx_from idx_to edge get cost return return adj_mat
create a dialog box to capture and display errrors related to db while importing data : param : msg : type : string : return : qdialog,def feedback_message self msg msgbox QMessageBox msgbox setStandardButtons QMessageBox Ok QMessageBox No msgbox setWindowTitle Data Import msgbox setText msg msgbox exec_ msgbox show return msgbox
set opacity of the the outline . ranges from 0 - 1 .,def setStrokeOpacity self opacity if opacity 0 or opacity 1 return self style strokeOpacity opacity
: return : returns the currently selected document type in the combobox . : rtype : str,def current_document_type self return self _cbo_doc_type currentText
"transform instances are hashable , meaning you can use them as keys in dictionaries : > > > d = { scale(12 , 13 ) : none } > > > d { < transform [ 12 0 0 13 0 0 ] > : none } > > >",def __hash__ self return hash self __affine
update check fails when error restarting .,mock patch os execl mock patch subprocess call mock patch grow common utils is_packaged_app mock patch grow common rc_config RC_CONFIG mock patch grow sdk updater Updater current_version new_callable mock PropertyMock mock patch grow sdk updater Updater latest_version new_callable mock PropertyMock def test_check_for_updates_packaged_app_restart_fail self mock_latest_version mock_current_version mock_config mock_is_packaged_app mock_subprocess_call mock_os_execl mock_config needs_update_check True mock_is_packaged_app return_value True mock_latest_version return_value 0 1 1 mock_current_version return_value 0 1 0 mock_config get return_value True mock_subprocess_call return_value 0 mock_os_execl side_effect OSError with self assertRaises SystemExit self updater check_for_updates auto_update_prompt True mock_config write assert_called
"bigquery is not really great for handling deeply nested data and repeated fields . to maintain values of some fields while keeping the schema relatively simple , we artificially leave some of the fields as json strings .",def _flatten_result_inplace scenario_result scenario_result scenario clientConfig json dumps scenario_result scenario clientConfig scenario_result scenario serverConfig json dumps scenario_result scenario serverConfig scenario_result latencies json dumps scenario_result latencies scenario_result serverCpuStats for stats in scenario_result serverStats scenario_result serverCpuStats append dict scenario_result serverCpuStats 1 totalCpuTime stats pop totalCpuTime None scenario_result serverCpuStats 1 idleCpuTime stats pop idleCpuTime None for stats in scenario_result clientStats stats latencies json dumps stats latencies stats pop requestResults None scenario_result serverCores json dumps scenario_result serverCores scenario_result clientSuccess json dumps scenario_result clientSuccess scenario_result serverSuccess json dumps scenario_result serverSuccess scenario_result requestResults json dumps scenario_result get requestResults scenario_result serverCpuUsage scenario_result summary pop serverCpuUsage None scenario_result summary pop successfulRequestsPerSecond None scenario_result summary pop failedRequestsPerSecond None massage_qps_stats massage_qps_stats scenario_result
tokenize a lisp file or string buffer into internal hy objects .,def tokenize buf try return parser parse lexer lex buf except LexingError as e pos e getsourcepos raise LexException Could not identify the next token pos lineno pos colno buf except LexException as e if e source is None e source buf raise
return the clients to use for testing .,def get_clients initial other base_env debug agent_url if initial FAKE environment JujuData from_config base_env client fake_juju_client env environment return client client client else initial_client client_from_config base_env initial debug debug environment initial_client env if agent_url is None environment discard_option tools metadata url other_client initial_client clone_from_path other released_client initial_client clone_from_path None released_client env initial_client env return initial_client other_client released_client
build_ssh_cmd is a helper method taking pieces from client and remote,def build_ssh_cmd client unit command ssh_opts o User ubuntu o UserKnownHostsFile dev null o StrictHostKeyChecking no o PasswordAuthentication no status client get_status unit_status status get_unit unit cmd ssh ssh_opts unit_status public address command return cmd
"return string of the rst ( restructured text ) of the gallery page , showing information on all screenshots found .",def make_gallery_page infos def a s append formatted s to output which will be joined into lines output append s format info def t left right append left and right format strings into a table line l left format info r right format info if len l width1 or len r width2 Logger error items to wide for generated table s and s l r return output append 0 w1 1 w2 format l r w1 width1 w2 width2 gallery_top Gallery _Tutorials tutorials index html container title This gallery lets you explore the many examples included with Kivy Click on any screenshot to see the code This gallery contains Examples from the examples directory that show specific capabilities of different libraries and features of Kivy Demonstrations from the examples demos directory that explore many of Kivy s abilities There are more Kivy programs elsewhere Tutorials_ walks through the development of complete Kivy applications Unit tests found in the source code under the subdirectory kivy tests can also be useful We hope your journey into learning Kivy is exciting and fun output gallery_top for info in infos a n link num replace doc source gen__ dunder a pic num image images examples dunder png width 216pt align middle target gen__ dunder html a n title num replace title width1 width2 20 50 head width1 width2 a a head for info in infos t pic num title num t link num paragraphs info description split n n for p in paragraphs for line in textwrap wrap p width2 t line t t a head return n join output n
lookup name in a namespace spanning sys.modules and _ _ main.dict _ _,def get_entity self name namespace sys modules copy namespace update __main__ __dict__ return eval name namespace
return a normalized path relative to some root dir .,def normrelpath path root_dir return ospath normpath ospath relpath path start root_dir
a ` message ` attribute of an empty list is created .,requires_ws4py def test_handshake_ok self ws_client client _WebsocketClient ws an fake path ws_client handshake_ok self assertEqual ws_client messages
gets the default release to use when a release is not explicit .,def get_default_release self return DISTRO_SERIES_DEFAULT
return basic system information in a dictionary .,synchronous def get_sys_info os_release get_os_release if ID in os_release osystem os_release ID elif NAME in os_release osystem os_release NAME else osystem if UBUNTU_CODENAME in os_release distro_series os_release UBUNTU_CODENAME elif VERSION_ID in os_release distro_series os_release VERSION_ID else distro_series result hostname socket gethostname split 0 architecture get_architecture osystem osystem distro_series distro_series maas_version get_maas_version interfaces return result
return an iterator of this object and all previous versions .,def previous_versions self class VersionedTextFileIterator def __init__ self textfile self textfile textfile def __iter__ self return self def __next__ self textfile self textfile if textfile is None raise StopIteration else self textfile self textfile previous_version return textfile return VersionedTextFileIterator self
delete raid on a machine .,def delete self request system_id id raid RAID objects get_object_or_404 system_id id request user NODE_PERMISSION ADMIN node raid get_node if node status NODE_STATUS READY raise NodeStateViolation Cannot delete RAID because the machine is not Ready raid delete return rc DELETED
change the permission of a given bucket or given files .,bucket_group command chmod click argument mode nargs 1 click argument files nargs 1 click option force is_flag True pass_global_parameters def chmod_bucketcmd params mode files force allowed_perms private public read public read write aws exec read authenticated read bucket owner read bucket owner full control log delivery write if mode not in allowed_perms error_exit Mode must be one of the followings n t n t join allowed_perms See http docs aws amazon com AmazonS3 latest dev acl overview html canned acl for details if mode public read write and not force error_exit Setting public read write to a bucket or files might make you bankrupt If you are sure you understand what you do add force s3 get_s3_connection for full_path in files _ bucket path decompose_rpath full_path if bucket is None error_exit Use bucket name for specifying a bucket Use bucket name key name for specifying files if path s3 Bucket bucket Acl put ACL mode elif path find 1 or path find 1 if is_debugging print Glob expression s path for obj in s3 Bucket bucket objects all if not fnmatch fnmatch obj key path if is_debugging print skipped s s bucket obj key continue if is_debugging print chmod s s s mode bucket obj key obj Acl put ACL mode else s3 Bucket bucket Object path Acl put ACL mode
"use python to download the file , even though it can not authenticate the connection .",def download_file_insecure url target try from urllib request import urlopen except ImportError from urllib2 import urlopen src dst None try src urlopen url data src read dst open target wb dst write data finally if src src close if dst dst close
returns the output directory for the targets,def get_output_dir_target return os path join get_output_dir TARGETS_DIR
make path absolut and handle multiplatform issues,def make_path_absolute self path project_path if not os path isabs path path os path join os path dirname project_path path return os path normpath path
prepare color for stdout and stderr,def setup conf force_colors False u global COLORS_OUT COLORS_ERR COLORS_OUT generate_colors sys stdout force_colors force_colors color conf u formating u color bold conf u formating u bold italic conf u formating u italics COLORS_ERR generate_colors sys stderr force_colors force_colors color conf u formating u color bold conf u formating u bold italic conf u formating u italics for key value in conf u theme items COLORS_OUT key COLORS_OUT get value u COLORS_ERR key COLORS_ERR get value u
test whether two stat buffers reference the same file,def samestat s1 s2 return s1 st_ino s2 st_ino and s1 st_dev s2 st_dev
counts the number of warnings that occurs .,def warn self msg self _warnings 1 return Command warn self msg
remove and return an item from the queue .,def get self block True timeout None self not_empty acquire try if not block if self _empty raise Empty elif timeout is None while self _empty self not_empty wait else if timeout 0 raise ValueError timeout must be a positive number endtime _time timeout while self _empty remaining endtime _time if remaining 0 0 raise Empty self not_empty wait remaining item self _get self not_full notify return item finally self not_empty release
return the python representation of `` s `` ( a `` str `` or `` unicode `` instance containing a json document ),def decode self s _w WHITESPACE match obj end self raw_decode s idx _w s 0 end end _w s end end if end len s raise ValueError errmsg Extra data s end len s return obj
like dict.__delitem _ _ ( ) but does not raise keyerror for missing values .,def __delitem__ self elem if elem in self dict __delitem__ self elem
get the internal game state represented as a numpy array,def _get_state self u n get the internal game state represented as a numpy array n data self game_state data agent_states self game_state data agentStates num_ghosts len agent_states 1 s np zeros 2 num_ghosts 3 self num_total_food self num_total_capsules s 2 agent_states 0 configuration pos for i in range num_ghosts s 2 i 3 2 i 3 2 agent_states i 1 configuration pos s 2 i 3 2 agent_states i 1 scaredTimer i 2 num_ghosts 3 x 0 y 0 for char in str self layout_copy if char u s i data food x y i 1 elif char u n y 1 x 1 elif char u o coord x self layout_copy height y if coord in data capsules s i 1 0 i 1 x 1 return s
initialises a new ' genunitopschedule ' instance .,def __init__ self GeneratingUnit None args kw_args self _GeneratingUnit None self GeneratingUnit GeneratingUnit super GenUnitOpSchedule self __init__ args kw_args
initialises a new ' svvoltage ' instance .,def __init__ self angle 0 0 v 0 0 TopologicalNode None args kw_args self angle angle self v v self _TopologicalNode None self TopologicalNode TopologicalNode super SvVoltage self __init__ args kw_args
initialises a new ' irregulartimepoint ' instance .,def __init__ self time 0 0 value2 0 0 value1 0 0 IntervalSchedule None args kw_args self time time self value2 value2 self value1 value1 self _IntervalSchedule None self IntervalSchedule IntervalSchedule super IrregularTimePoint self __init__ args kw_args
initialises a new ' loadresponsecharacteristic ' instance .,def __init__ self pVoltageExponent 0 0 qConstantCurrent 0 0 pFrequencyExponent 0 0 exponentModel False qConstantImpedance 0 0 pConstantCurrent 0 0 qFrequencyExponent 0 0 pConstantPower 0 0 qVoltageExponent 0 0 qConstantPower 0 0 pConstantImpedance 0 0 EnergyConsumer None args kw_args self pVoltageExponent pVoltageExponent self qConstantCurrent qConstantCurrent self pFrequencyExponent pFrequencyExponent self exponentModel exponentModel self qConstantImpedance qConstantImpedance self pConstantCurrent pConstantCurrent self qFrequencyExponent qFrequencyExponent self pConstantPower pConstantPower self qVoltageExponent qVoltageExponent self qConstantPower qConstantPower self pConstantImpedance pConstantImpedance self _EnergyConsumer self EnergyConsumer if EnergyConsumer is None else EnergyConsumer super LoadResponseCharacteristic self __init__ args kw_args
initialises a new ' tender ' instance .,def __init__ self kind cash amount 0 0 change 0 0 Cheque None Receipt None Card None args kw_args self kind kind self amount amount self change change self _Cheque None self Cheque Cheque self _Receipt None self Receipt Receipt self _Card None self Card Card super Tender self __init__ args kw_args
outagereports per customer for which this outagehistory is created .,def getOutageReports self return self _OutageReports
an outageschedule may operate many switches .,def getOutageSchedule self return self _OutageSchedule
terminals interconnect with zero impedance at a node . measurements on a node apply to all of its terminals .,def getConnectivityNode self return self _ConnectivityNode
the powersystemresource that contains the measurement in the naming hierarchy,def getPowerSystemResource self return self _PowerSystemResource
"a synchronous machine may operate as a generator and as such becomes a member of a generating unitfor the 2010 entsoe iop , this is required for synchronous machine .",def getGeneratingUnit self return self _GeneratingUnit
removes the node corresponding to each item in ' features ' .,def _delete_edges self features graph self _graph if graph is not None for feature in features for graph_edge in self factory edges if feature __class__ in graph_edge edge_for tail_feature getattr feature graph_edge tail_name head_feature getattr feature graph_edge head_name graph delete_edge id tail_feature id head_feature graph arrange_all
return a list of elements that should be added to the vcf header so :,staticmethod def header_info return MAP 1 Float Mappability at variant location
enable or disable underlined text : param value : allowed values : - true : enable underline attribute - fase : disable underline attribute,def set_underline self value self _set_text_attribute underline single value
add_stroke([point_list = list ] ) adds a stroke to the gesture and returns the stroke instance optional point_list argument is a list of the mouse points for the stroke,def add_stroke self point_list None self strokes append GestureStroke if isinstance point_list list or isinstance point_list tuple for point in point_list if isinstance point GesturePoint self strokes 1 points append point elif isinstance point list or isinstance point tuple if len point 2 or len point 2 raise ValueError A stroke entry should only have 2 values self strokes 1 add_point point 0 point 1 else raise TypeError The point list should either be tuples of x and y or a list of GesturePoint elif point_list is not None raise ValueError point_list should be a tuple list return self strokes 1
"> > > test1 = unittest . functiontestcase(lambda : none ) > > > test2 = unittest . functiontestcase(lambda : none ) > > > suite = unittest . testsuite((test1 , test2 ) ) > > > tests = [ ] > > > for test in suite : ... tests.append(test ) > > > tests = = [ test1 , test2 ] true",def test_TestSuite_iter
"perform dns lookup on str . if first character of digit is numeric , assume that str contains an ip address . otherwise , assume that str contains a hostname .",def dnslookup self str if str str if str 0 in string digits try value socket gethostbyaddr str 0 except value Lookup failed else try value socket gethostbyname str except value Lookup failed return value
returns python source for the given map .,def codegen name map comments 1 l Python Character Mapping Codec generated from s with gencodec py import codecs Codec APIs class Codec codecs Codec def encode self input errors strict return codecs charmap_encode input errors encoding_map def decode self input errors strict return codecs charmap_decode input errors decoding_map class StreamWriter Codec codecs StreamWriter pass class StreamReader Codec codecs StreamReader pass encodings module API def getregentry return Codec encode Codec decode StreamReader StreamWriter Decoding Map name if map has_key IDENTITY l append decoding_map codecs make_identity_dict range d map IDENTITY l append decoding_map update splits 1 del map IDENTITY else l append decoding_map splits 0 mappings map items mappings sort append l append i 0 for e value in mappings try u c value except TypeError u value c key keyrepr e if c and comments append t s s t s key unicoderepr u c else append t s s key unicoderepr u i 1 if i 4096 if splits 0 append else append append decoding_map update i 0 splits splits 1 if splits 0 append else append append n Encoding Map n nencoding_map codecs make_encoding_map decoding_map n return n join l
"rjust(s , width ) - > string",def rjust s width n width len s if n 0 return s return n s
method to get the requirements of the specified file .,def get_requirements filename file open filename r readlines out for a in file out append a strip return out
return matching serverdescriptions from a list .,def __call__ self server_descriptions return secondary_with_tags_server_selector self tag_sets server_descriptions
"provide list of credentials for the invoking member relative to the given slice . if the invocation is in a speaks - for context , the credentials will be for the ' spoken - for ' member , not the invoking tool .",def get_credentials slice_urn credentials options raise GFedv1NotImplementedError Method not implemented
returns the ' chat ' class for this script .,def getChat self return chat Chat self self _buddyListAncestries
returns an array of sounds reflecting the percentage of obj .,def _generatePercentage self obj args if not _settingsManager getSetting playSoundForValue return percent self _script utilities getValueAsPercent obj if percent is None return return
tests appending to a value in the environment .,def test_append_flags env env append_flags APPEND_TO_ME flag1 env append_flags APPEND_TO_ME flag2 env apply_modifications assert flag1 flag2 os environ APPEND_TO_ME
calculate ( normalized ) probabilities for p(w|z ) .,def p_z self d w_id f1 self ndk d self alpha np sum self ndk d self nTopics self alpha f2 self nkw w_id self beta self nk self beta len self corpus dictionary p f1 f2 return p np sum p
main function called from shell or _ _ main__.py,def main as_module False name __package__ if as_module name python m name cli prog_name name obj
indicates that the learner is stopping a run .,def stop_run self self runs 1 end time time
customize the drawing of the background .,def drawBackground self painter rect sceneRect self sceneRect background str options background if background startswith and background endswith try r g b background strip split 2 painter fillRect rect QtGui QBrush QtGui QColor int r int g int b except pass else painter drawImage rect QtGui QImage options background painter eraseRect sceneRect rightShadow QtCore QRectF sceneRect right sceneRect top 5 5 sceneRect height bottomShadow QtCore QRectF sceneRect left 5 sceneRect bottom sceneRect width 5 if rightShadow intersects rect or rightShadow contains rect painter fillRect rightShadow QtCore Qt darkGray if bottomShadow intersects rect or bottomShadow contains rect painter fillRect bottomShadow QtCore Qt darkGray painter setBrush QtCore Qt NoBrush painter drawRect sceneRect if not options grid return try r g b str options gridColor strip split 2 painter setPen QtGui QColor int r int g int b except return for i in range int sceneRect height 50 painter drawLine sceneRect left sceneRect top i 1 50 sceneRect right sceneRect top i 1 50 for i in range int sceneRect width 50 painter drawLine sceneRect left i 1 50 sceneRect top sceneRect left i 1 50 sceneRect bottom painter setPen QtCore Qt black
# 05 randomly check 100 file content read ' randomreadsize ' from beginning of file and make sure same content is obtained from disk and from vfs . this test reads directly through the vfs object .,def test05_RandomReadFile self checkAmount 100 while checkAmount randomFilepath self _randomItem os getcwd randomReadSize int random random os stat randomFilepath st_size with open randomFilepath r as f expectedContent f read randomReadSize vfsNodePath randomFilepath len os getcwd len os path basename os getcwd nodeFile self vfs getnode vfsNodePath open buff nodeFile read randomReadSize nodeFile close self assertEqual expectedContent buff checkAmount 1
name : mainwindow.updatelabels ( ) desc : gets the latest reading from the readings queue and display it,def updateLabels self if self thread exception None showErrorWindow self thread exception 0 self thread exception 1 else latestReading None while not self targetQueue empty latestReading self targetQueue get if latestReading None self tempDisplay config text str latestReading getTemperature deg C self humidDisplay config text str latestReading getHumidity self statusDisplay config text str latestReading getStatus self window after 1000 self updateLabels
generate a simple white matter mask by thresholding the given fa map .,def generate_simple_wm_mask fa_fname brain_mask_fname out_fname fa_threshold 0 3 median_radius 1 numpass 2 logger logging getLogger __name__ logger info Starting calculating a white matter mask using FA nib_container load_nifti fa_fname fa_data nib_container get_data fa_data fa_data fa_threshold 0 fa_data fa_data 0 1 if len fa_data shape 3 fa_data fa_data 0 filter_footprint np zeros 1 2 median_radius 3 filter_footprint median_radius median_radius median_radius 1 filter_footprint median_radius median_radius 1 filter_footprint median_radius median_radius 1 filter_footprint median_radius median_radius 1 mask load_brain_mask brain_mask_fname fa_data_masked np ma masked_array fa_data mask mask for ind in range numpass fa_data_masked median_filter fa_data_masked footprint filter_footprint mode constant write_nifti fa_data_masked out_fname nib_container get_header logger info Finished calculating a white matter mask
create a dict of rellinks for this tiddler in this tank .,def get_rellinks environ tiddler store environ tiddlyweb store bag_name tiddler bag links index True if tiddler title INDEX_PAGE links index False tiddlers filtered_tiddler title for filtered_tiddler in filter_tiddlers store list_bag_tiddlers Bag bag_name sort modified environ if renderable store get filtered_tiddler environ try this_index tiddlers index tiddler title prev_index this_index 1 if prev_index 0 prev_tiddler tiddlers prev_index else prev_tiddler None try next_tiddler tiddlers this_index 1 except IndexError next_tiddler None links prev prev_tiddler links next next_tiddler except ValueError pass return links
"remove link asset together , unmark asset_in as asset out dependency .",def remove_asset_link asset_in_id asset_out_id asset_in get_asset_raw asset_in_id asset_out get_asset_raw asset_out_id if asset_out in asset_in entities_out asset_in entities_out x for x in asset_in entities_out if x id asset_out_id asset_in save events emit asset remove link asset_in asset_in id asset_out asset_out id return asset_in serialize obj_type Asset
"reattaches the pp 's that were attached to a chunk inside brackets , to the chunk in front of the bracket : "" the purified homodimer ( two p50s ) of the dna - binding subunit "" instead of "" p50s "" as anchor we take "" homodimer "" as anchor for "" the dna - binding subunit "" .",def reattach_interjections attachments sentence output L sentence indexof R sentence indexof if len L len R brackets zip L R else return attachments for A P info in attachments rng range A P if P A rng reversed rng l sorted set L intersection set rng r sorted set R intersection set rng if len r 1 and len l 0 for bracket in brackets if bracket 1 r 0 i bracket 0 break try A sentence get i 1 CHUNK head index except AttributeError pass except IndexError output append A P info else output append A P reattach_interjections else output append A P info return output
returns a numpy array with all the coordinates of all the atoms in the molecule,def getCoordinates self c numpy zeros self getNumAtoms 3 for iat _atom in enumerate self getAtoms c iat _atom getCoordinate return c
"| simulate a surface brightness profile from spectrum file for a uniform distribution of dust , using 2 - 4 free parameters | | * * inputs * * | specfile : string : name of spectrum file | a0 : float [ um ] : minimum ( or single ) grain size to use | a1 : float [ um ] : maximum grain size for distribution ( if none , single used ) | p : float : power law index for grain size distribution | nh : float [ cm^-2 ] : hyrdogen column ( 1.0e22 ) | d2 g : float : dust - to - gas mass ratio ( 0.009 ) | rho : float [ g cm^-3 ] : mass density of a dust grain ( 3 ) | dict : boolean ( false ) : if true , returns halodict instead of interp object | alpha : np.array [ arcsec ] : angles for halo intensity values | aeff : intper1d object : x = energy [ kev ] , y = effective area [ cm^2 ] | exposure : float [ sec ] : observation exposure time | scatm : ss . scatmodel ( ) | elim : tuple containing energy limits [ kev ] | na : number of bins to use for grain size distribution | | * * returns * * | if dict = = false : | scipy.interpolate.interp1d object : x = pixels , y = counts / pix^2 | if dict = = true : | halodict object with full benefits of information",def simulate_uniform specfile a0 0 1 a1 None p 3 5 NH 1e 22 d2g 0 009 rho 3 0 return_dict False alpha ALPHA scatm SCATM elim None na 50 v False energy flux HD get_spectrum specfile if a1 None dust_dist GH distlib Grain rad a0 rho rho else dth a1 a0 na dust_dist GH distlib Powerlaw a0 a1 na a1 a0 dth p p rho rho ii range len energy if elim None if v print Limiting energy to values between elim 0 and elim 1 keV ii np where np logical_and energy elim 0 energy elim 1 0 halo_dict HD HaloDict energy ii rad dust_dist scatm scatm alpha alpha AH uniform_eq halo_dict NH NH d2g d2g result simulate_intensity halo_dict flux ii if return_dict return halo_dict else return result
attaches a callable that will be called when the future finishes .,def add_done_callback self fn if self _state not in CANCELLED FINISHED self _done_callbacks append fn return fn self
set a gauge value in statsd for the specified key,def set_gauge self key value 0 self _send key value g
"assumes zyx are dims 1 , 2 , 3 .",def ravel_zyx_dims tensor name ravel_zyx_dims return tf reshape tensor tensor shape_as_list 0 1 1 tensor shape_as_list 4 name name
test we can parse a standard file .,def testBasicParsingOldFormat self history_file os path join self base_path parser_test History history chrome_history ChromeParser open history_file rb entries x for x in history Parse try dt1 datetime datetime 1970 1 1 dt1 datetime timedelta microseconds entries 0 0 except TypeError ValueError dt1 entries 0 0 try dt2 datetime datetime 1970 1 1 dt2 datetime timedelta microseconds entries 1 0 except TypeError ValueError dt2 entries 1 0 time_results x 0 for x in entries self assertEqual time_results sorted time_results self assertEqual str dt1 2011 04 07 12 03 11 self assertEqual entries 0 2 http start ubuntu com 10 04 Google self assertEqual str dt2 2011 05 23 08 37 27 061516 self assertTrue entries 1 2 startswith https chrome google com webstore detail mfjkgbjaikamkkojmakjclmkianficch self assertEqual len entries 71
returns the name of the component which matches best our base listing .,def MatchBestComponentName self component fd self OpenAsContainer file_listing set fd ListNames if component not in file_listing lower_component component lower for x in file_listing if lower_component x lower component x break if fd supported_pathtype self pathspec pathtype new_pathspec rdf_paths PathSpec path component pathtype fd supported_pathtype else new_pathspec self pathspec last Copy new_pathspec path component return new_pathspec
check that threads are reaped when too old .,def testThreadsReaped self self now 0 with utils MultiStubber time time lambda self now threading _time lambda self now Queue _time lambda self now self test_pool CPUUsage lambda 0 done_event threading Event res def Block done count done wait res append count for i in range 2 self MAXIMUM_THREADS self test_pool AddTask Block done_event i Blocking inline False self assertEqual len self test_pool self MAXIMUM_THREADS done_event set self now 1000 self WaitUntil lambda len self test_pool self NUMBER_OF_THREADS self assertEqual len self test_pool self NUMBER_OF_THREADS
"deserialize a myproxy server response returns : integer response , errortext ( if any )",def deserialize_response msg lines msg split n responselines filter lambda x x startswith RESPONSE lines responseline responselines 0 response int responseline split 1 errortext errorlines filter lambda x x startswith ERROR lines for e in errorlines etext e split 1 errortext etext return response errortext
param : input_var ( t.vector ( ) | t.matrix ( ) | t.tensor3 ( ) | t.tensor4 ( ) ) : the tensor variable input to the model that corresponds to the number of dimensions of the input x of dataset input_var ( t.vector ( ) | t.matrix ( ) | t.tensor3 ( ) | t.tensor4 ( ) ) : the tensor variable output from the model that corresponds to the number of dimensions of the output y of dataset verbose ( bool ) : print out the layer stats from each layer if true,def __init__ self input_var output_var verbose True self input_var input_var self output_var output_var self layers self verbose verbose
create a new nsis instance given an nsis installer loaded in |fd| .,def __init__ self fd self _block_cache self _pe None self fd fd Parsed installer file self firstheader None Firstheader structure found at the beginning of the NSIS blob self header None Header structure found at the beginning of the uncompressed NSIS blob self sections List of sections installable by the installer self entries Installer instructions self pages Installer pages if not self _parse raise HeaderNotFound self version_major self version_minor self _detect_version
"generic decorator to add hooks . generally , this is not called directly by plugins . decorators that plugins use are automatically generated below with the setattrs you 'll see",def hook_add hookname arg poll_timer 60 def wrap f if hookname poll utils spawn def _f self args kwargs while True f self args kwargs time sleep poll_timer setattr _f _is_ s_hook hookname True _f _hook_arg arg return _f else setattr f _is_ s_hook hookname True f _hook_arg arg return f return wrap
"given a string or unicode instance , produce a new url instance .",def make_url name_or_url if isinstance name_or_url util string_types return _parse_rfc1738_args name_or_url else return name_or_url
": param payload : the websocket message payload , which can be utf-8 encoded text or a binary string . : type payload : bytes : param is_binary : `` true `` iff payload is binary , else the payload contains utf-8 encoded text . : type is_binary : bool : param dont_compress : iff `` true `` , never compress this message . this only has an effect when websocket compression has been negotiated on the websocket connection . use when you know the payload is incompressible ( e.g. encrypted or already compressed ) . : type dont_compress : bool",def __init__ self payload is_binary False dont_compress False assert type payload bytes assert type is_binary bool assert type dont_compress bool self payload payload self is_binary is_binary self dont_compress dont_compress
provides additional validation of the arguments collected by argparse .,def getArguments parser return parser parse_args
provides additional validation of the arguments collected by argparse .,def getArguments parser return parser parse_args
extract and mask the reference sequence . replace masked regions with n,def get_ref_seq options ref_fa mask last_pos pos ref_seq ref_fa options chrom last_pos pos 1 seq if mask mask_seq mask options chrom last_pos pos 1 seq ref_seq join x if y N and int y options mask_value else N for x y in zip ref_seq mask_seq return ref_seq
add a component to the netlist . the general form is : ' name np nm args ' where np is the positive node and nm is the negative node .,def add self string self _add string self _invalidate
write tillage section in dssat control file .,def _writeTillage self fout fout write TILLAGE r n
compute the squared loss for regression .,def squared_loss y_true y_pred return y_true y_pred 2 mean 2
provide pointers to the paths of the metadata file,SeqProp metadata_path setter def metadata_path self m_path if not m_path self metadata_dir None self metadata_file None else if not op exists m_path raise OSError file does not exist format m_path if not op dirname m_path self metadata_dir else self metadata_dir op dirname m_path self metadata_file op basename m_path self update parse_kegg_gene_metadata self metadata_path overwrite True
"calculates skip map for large sources . skip map is a list of tuples where first element of tuple is line number and second is length of the skip region : [ ( 1 , 10 ) , ( 15 , 10 ) ] means skipping 10 lines after line 1 and 10 lines after line 15 .",def _calc_skips self heatmap num_lines if num_lines self MIN_SKIP_SIZE return skips prev_line 0 for line in sorted heatmap curr_skip line prev_line 1 if curr_skip self SKIP_LINES skips append prev_line curr_skip prev_line line if num_lines prev_line self SKIP_LINES skips append prev_line num_lines prev_line return skips
"run a command , collecting data from the underlying process stdout and stderr , and returning the collected otuput .",def run self self _start_process out err self _proc communicate self _finalize out err return out
"host networks are no longer persisted in libvirt db , therefore , they are removed as part of the upgrade . note : the role of managing libvirt networks has passed to virt .",def _cleanup_libvirt_networks libvirt_networks for net in libvirt_networks libvirtnetwork removeNetwork net
performs validation on the short_url field .,def validate_short_url form field if not field data isalnum raise ValidationError Custom alias must be alphanumeric
return if string is invalid for storage in mongodb .,def _is_invalid_for_mongo key return any key count value 0 for value in ILLEGAL_VALUES
": param path : file name : ' compromised.yml ' , ' plugin : compromised.yml ' , ' custom : compromised.yml ' : type path : str : param name : short rule name : type name : str : param description : long description of rule : type description : str : param params : default parameters to use for rule customization : type params : dict",def add_rule self path name description params valid_path rule_template abs_rule_path path if valid_path is None print Rule definition path cannot be verified Saving anyway if not isinstance name str unicode or len name 0 raise ValueError Name cannot be empty name name strip if not isinstance description str unicode raise ValueError Description must be a string description description strip r_id self db insert self table active False rule_path path name name description description params cPickle dumps params return r_id
should show version if args.version is true .,def test_shows_version args _create_mock_args version True _helper_run_eg_responds_to_args_correctly args call_show_version True
create the idex for all results .,def write_index self self index_fh write html n body n for name in self cases self index_fh write a href cases s html s a n name name self index_fh write body n html n
internal on_mouseup handler . do not override,def on_mouseup self event self _layout prefix self _template self _label margin top 0
record the tuning record to a redis db .,def log_to_redis host localhost port 6379 dbn 11 import redis red redis StrictRedis host host port port db dbn def _callback _ inputs results Callback implementation for inp result in zip inputs results red set inp result return _callback
replace any sequence of whitespace characters with a single space,def normalize_spaces s return join s split
magic that get a variable from sos dictionary and set to python dictionary,line_magic def sosput self line for var in x strip for x in line split if x strip if var not in self shell user_ns raise RuntimeError not exist in python dict format var env sos_dict var copy deepcopy self shell user_ns var
test equality for single operand expressions .,def test_single_operand_expressions self self assert_equal_expressions A A self assert_equal_expressions 0 0 self assert_equal_expressions 1 1 self assert_not_equal_expressions A B self assert_not_equal_expressions A 0 self assert_not_equal_expressions A 1 self assert_not_equal_expressions 1 A self assert_not_equal_expressions 0 A
test a case where we expect or to be distributed from the left .,def test_applicable_or_distribute_from_right self root self get_tree_root_from_expr_str A and B and C or D dor root distribute_ors self assertTrue dor is not root self assertTrue dor l_child l_child is not root l_child l_child self assertTrue dor r_child l_child l_child is not root l_child r_child self assertTrue dor r_child r_child l_child is not root l_child r_child r_child root_D_node root r_child self assertTrue dor l_child r_child is not root_D_node self assertTrue dor r_child l_child r_child is not root_D_node self assertTrue dor r_child r_child r_child is not root_D_node self assertEqual str dor n join and or A D and or B D or C D
makes the script file to be run by yap .,def __script self mode filestem scriptPath s s self tmpdir Aleph SCRIPT script open scriptPath w os chmod scriptPath S_IREAD S_IEXEC cat lambda x script write x n cat initialization run_aleph cat run_aleph cat consult aleph cat read_all s filestem for setting value in self settings items cat set s s setting str value cat s mode eof if self postScript else if mode induce_features cat consult features features_fn filestem Aleph FEATURES_SUFFIX dataset_fn filestem Aleph PROP_DATASET_SUFFIX cat save_features s features_fn cat save_dataset s s dataset_fn eof else rules_fn filestem Aleph RULES_SUFFIX cat write_rules s s rules_fn eof if self postScript cat self postGoal cat self postScript script close
get a list of bit.ly api error codes .,def errors self request self _getURL errors result self _fetchUrl request json simplejson loads result self _CheckForError json return json results
see if objects were added automatically ( by the factory ) to the current site .,def test_basics self self assertEqual list self gallery1 sites all self site1 self assertEqual list self photo1 sites all self site1
is true when `` argument `` is a positive integer - equivalent number .,def is_positive_integer_equivalent_number argument from abjad import mathtools try return 0 argument and mathtools is_integer_equivalent_number argument except TypeError return False
calls measure - maker on `` time_signatures `` .,def __call__ self time_signatures import abjad measures for time_signature in time_signatures time_signature abjad TimeSignature time_signature measure abjad Measure time_signature implicit_scaling self implicit_scaling measures append measure for i measure in enumerate measures skip abjad Skip 1 time_signature measure time_signature duration time_signature duration if measure implicit_scaling implied_prolation time_signature implied_prolation multiplier duration __div__ implied_prolation else multiplier abjad Multiplier duration abjad attach multiplier skip measure skip return abjad select measures
handles lilypond `` \relative `` command .,def relative self pitch music Handles LilyPond relative command if self _is_unrelativable music return music def recurse component pitch if self _is_unrelativable component return pitch elif isinstance component core Chord core Note pitch self _make_relative_leaf component pitch if component in self client _repeated_chords for repeated_chord in self client _repeated_chords component repeated_chord written_pitches component written_pitches elif isinstance component core Container for child in component pitch recurse child pitch return pitch pitch recurse music pitch self _make_unrelativable music return music
"extract the information concerning the methods inside of a .smali file ( [ class_name , method name , reg number , [ variables ] , class name ] ) .",def generate_file_metadata file_path with open file_path r as file file_metadata methods regs returned_reg payload monitor_function False inside False for line in file if line find class 0 words line split class_name words 1 elif line find method 0 and line find abstract 0 words line split method_name words 1 words1 method_name split returned_reg reg_type words1 1 inside True elif line find has been injected on 0 and inside words line split payload append words 1 elif line find monitor enter 0 or line find return wide 0 and inside monitor_function True elif line find return 0 20 0 and inside words line split if len words 1 returned_reg reg words 1 regs extend words 1 else returned_reg reg v 1 elif line find end method 0 and inside regs sorted set regs if len returned_reg 2 returned_reg reg v 1 methods append class_name method_name regs returned_reg monitor_function payload regs returned_reg payload monitor_function False inside False elif inside regs extend get_var_from_line line else continue file_metadata file_path methods return file_metadata file_path
creates an ` estimator ` object .,def create_estimator run_config hparams pipeline_config_path train_steps None eval_steps None train_batch_size None model_fn_creator model create_model_fn use_tpu False num_shards 1 params None kwargs configs config_util get_configs_from_pipeline_file pipeline_config_path configs config_util merge_external_params_with_configs configs hparams train_steps train_steps eval_steps eval_steps batch_size train_batch_size kwargs model_config configs model train_config configs train_config train_input_config configs train_input_config eval_config configs eval_config eval_input_config configs eval_input_config if FLAGS eval_training_data eval_input_config configs train_input_config if params is None params if train_steps is None and train_config num_steps train_steps train_config num_steps if eval_steps is None and eval_config num_examples eval_steps eval_config num_examples detection_model_fn functools partial model_builder build model_config model_config train_input_fn inputs create_train_input_fn train_config train_config train_input_config train_input_config model_config model_config eval_validation_input_fn inputs create_eval_input_fn eval_config eval_config eval_input_config eval_input_config model_config model_config eval_training_input_fn inputs create_eval_input_fn eval_config eval_config eval_input_config train_input_config model_config model_config estimator tpu_estimator TPUEstimator model_fn model_fn_creator detection_model_fn configs hparams use_tpu train_batch_size train_config batch_size eval_batch_size num_shards 1 if use_tpu else 1 use_tpu use_tpu config run_config params params return estimator train_input_fn eval_validation_input_fn eval_training_input_fn train_steps eval_steps
the function mutates the chromosome in three ways : 1 . insertion 2 . deletion 3 . insertion and deletion,def mutate_feat individual indpb input_fe X_tr for i in range 0 len individual chrom individual i X if random random indpb k random random if k 0 33 if chrom shape 1 1 ind random randint 0 chrom shape 1 1 final_feat list chrom columns values final_feat remove final_feat ind chrom chrom final_feat if k 0 66 present_feat list chrom columns values final_feat list set input_fe set present_feat if len final_feat 0 ind random randint 0 len final_feat 1 present_feat append final_feat ind ind_row list chrom index chrom X_tr loc ind_row chrom chrom present_feat else present_feat list chrom columns values ind random randint 0 len present_feat 1 final_feat list set input_fe set present_feat if len final_feat 0 ind1 random randint 0 len final_feat 1 present_feat ind final_feat ind1 ind_row list chrom index chrom X_tr loc ind_row chrom chrom present_feat individual i EstimatorGene chrom individual i y individual i base_estimator else do_nothing 2 return individual
average frequency spacing for a 2d isotropic plate .,property def average_frequency_spacing self Average frequency spacing for a 2D isotropic plate rtype class numpy ndarray math overline delta f _S 2D frac c_L 1 2 omega A with soundspeed of longitudinal waves math c_L angular frequency math omega plate area math A See Lyon equation 8 2 8 return self soundspeed_group 2 0 self frequency angular self component area
creates instance of class that describes member operator declaration,def create_member_operator self arguments keywords return member_operator_t arguments keywords
this method updates existing task sequence : return :,def update_sequence self sequence_data self _prepare_sequence_data init False self task_key_sequence_id sudo write sequence_data
create or update parallel runs for a case,app route case string case methods POST PUT def case_post_put case global master_ip master_port run_ids c_type restart False method request method filei None if fs_helpers case_exists case and method PUT ps_helpers kill_all_running_processes_for_case case restart True if fs_helpers case_exists case and method POST return jsonify type ResourceExists message Posted resource exists 400 if str c_type upper BEOPEST return jsonify runs ps_helpers start_beopest case master_ip master_port run_ids request restart debug DEBUG hostname hostname if str c_type upper MONTECARLO return jsonify runs ps_helpers start_monte_carlo case master_ip run_ids request debug DEBUG hostname hostname if str c_type upper GENERIC command python execute py return jsonify runs ps_helpers start_generic case master_ip run_ids request command hostname hostname return jsonify type TypeUnknown message Computing type unknown 400
write a warning to the error stream .,def warn self message u Write a warning to the error stream n n Parameters n n message str n The warning message n self log message self err
success : return list of node objects failure : raise resourcemanagerexception,def GetNodes self raise NotImplementedError
returns true is the given fileref has a corresponding file in the repository .,def is_local self fileref filepath fileref file sha1 fileref sha1 git_file self _make_local_path filepath return os path exists git_file and self _git_get_sha1 filepath sha1
get participants object list by ids or names,staticmethod def _get_participants names None ids None if ids return Flat_XML_Object_Base Elements PARTICIPANT_ID content id_ for id_ in ids elif names return Flat_XML_Object_Base Elements PARTICIPANT_USERNAME content name_ for name_ in names else msg Failed to get either participants names or ids raise AttributeError msg
"collects the routing table , filters out what we consider to be static routes worthy of storage in nav , and ensure storage as prefixes .",defer inlineCallbacks def collect_routes self mib IpForwardMib self agent ifmib IfMib self agent routes yield mib get_decoded_routes protocols WANTED_PROTOCOLS filtered r for r in routes if self is_wanted_route r self _logger debug d of d collected routes are static candidates len filtered len routes self _logger debug collected destinations r r destination for r in filtered for route in filtered ifindex yield mib get_cidr_route_column IfIndex route index alias None if ifindex alias yield ifmib retrieve_column_by_index ifAlias ifindex self route_to_containers route descr alias Prefix add_static_routes_sentinel self containers
return a list of bit numbers that have been set .,def get_set_bits self bits i for i in range len self if self i return bits
"given a user i d ( login name ) , return a fully qualified dn to identify this user , using the configured settings from webfront.conf .",def get_user_dn self u n Given a user id login name return a fully qualified DN to n identify this user using the configured settings from n webfront conf n if self user_dn return self user_dn method _config get u ldap u lookupmethod if method not in u direct u search raise LDAPConfigError u method must be direct or search not s method if method u direct self user_dn self construct_dn if method u search self user_dn self username self search_dn return self user_dn
convert the integer value to the light sensor resistance .,def _int2r val if 0 val 4095 r_sensor 4095 0 val 10 val else raise RuntimeError Value out of range or device not connected return float 0 2f format r_sensor
test for the patterngenerator class .,pytest mark skipif not flag reason need correct overlay to run def test_pattern_random ol download for num_samples in 1 MAX_NUM_PATTERN_SAMPLES loopback_sent build_random_pattern num_samples pattern_generator PatternGenerator mb_info pattern_generator trace use_analyzer True num_analyzer_samples num_samples pattern_generator setup loopback_sent stimulus_group_name stimulus analysis_group_name analysis frequency_mhz 100 pattern_generator run loopback_recv pattern_generator waveform waveform_dict list1 list2 list3 list for wavelane_group in loopback_sent signal if wavelane_group and wavelane_group 0 stimulus for i in wavelane_group 1 temp deepcopy i temp wave wave_to_bitstring i wave list1 append temp for wavelane_group in loopback_recv signal if wavelane_group and wavelane_group 0 stimulus for i in wavelane_group 1 temp deepcopy i temp wave wave_to_bitstring i wave list2 append temp elif wavelane_group and wavelane_group 0 analysis for i in wavelane_group 1 temp deepcopy i temp wave wave_to_bitstring i wave list3 append temp assert list1 list2 Stimulus not equal in generated and captured patterns assert list2 list3 Stimulus not equal to analysis in captured patterns pattern_generator stop pattern_generator reset del pattern_generator
sets a new value of this variable . : param value : the value to set,def set self value self value value
pass rule - defined variables back to the monitor for storage,def _store_variables self if self monitor is not None self monitor update_variables self variables
return a dict describing how to call this plotter,def get_description desc dict desc data True desc description This chart displays the frequency of having measurable precipitation reported by an ASOS site and the air temperature that was reported at the same time This chart makes an assumption about the two values being coincident whereas in actuality they may not have been desc arguments dict type zstation name zstation default AMW label Select Station network IA_ASOS return desc
process an hour 's worth of stage4 data into the hourly re,def merge valid nc ncopen mesonet data stage4 s_stage4_hourly nc valid year r tidx iemre hourly_offset valid val nc variables p01m tidx lats nc variables lat lons nc variables lon stride slice None None 3 lats np ravel lats stride stride lons np ravel lons stride stride vals np ravel val stride stride nn NearestNDInterpolator lons lats vals xi yi np meshgrid iemre XAXIS iemre YAXIS res nn xi yi res np where np logical_or res 0 res 250 0 0 res nc ncopen iemre get_hourly_ncname valid year a timeout 300 nc variables p01m tidx res nc close
default : instantiate the script and ask it to provide response,def get_response self result self task _get_raw_result if isinstance result dict and result get type download data base64 b64decode result data response HttpResponse data content_type result content_type status 200 response Content Disposition attachment filename filename format result return response else response HttpResponse result content_type application json status 200 return response
"we still allow adoption of orphaned * users by assigning them to organization member role , but only in the situation where the org admin already posesses indirect access to all of the user 's roles * orphaned means user is not a member of any organization",pytest mark django_db def test_orphaned_user_allowed org_admin rando organization role_access RoleAccess org_admin assert role_access can_attach organization member_role rando members None user_access UserAccess org_admin assert not user_access can_change rando last_name Witzel
a retry decorator for places where we do not want retries .,def no_retries fun return with_exponential_backoff retry_filter lambda _ False clock None fun
check the transform of zeros is all zeros,def test_zeros self win_s 512 timegrain fvec win_s f fft win_s fftgrain f timegrain assert_equal fftgrain norm 0 try assert_equal fftgrain phas 0 except AssertionError assert_equal fftgrain phas fftgrain phas 0 pi assert_equal fftgrain phas fftgrain phas 0 pi assert_equal np abs fftgrain phas np abs fftgrain phas pi 0 self skipTest fft fvec d phas 0 win_s This is expected when using fftw3 on powerpc
run the js test suite .,task def js with hide aborts warnings with lcd env huxley_root return not local npm test failed
required setup function for sphinx extensions .,def setup app app add_role bokeh palette bokeh_palette
creates a client to send requests to a wsgi application . parameters : - application : a wsgi application callable - * * kwargs : any changes / additions to the environ dictionary,def __init__ self application kwargs self application application self environ REQUEST_METHOD GET SCRIPT_NAME QUERY_STRING CONTENT_TYPE CONTENT_LENGTH SERVER_PORT 8000 SERVER_NAME platform uname 1 SERVER_PROTOCOL HTTP 1 1 wsgi version 1 0 wsgi url_scheme http wsgi input None wsgi errors sys stderr wsgi multithread False wsgi multiprocess False wsgi run_once False self environ update kwargs
evaluate a given expression over a list of data to produce an output data : param data_list : list of data used in the evaluation ( these will be identified by alias or var_name ) . should all be of the same data type and shape . : param expr : string python expression to evaluate . : param output_var : name to use for the output variable ( defaults to ' calculated_variable ' if not provided . : param units : string indicating the units of the output expression : param attributes : dictionary of attribute names : values to add to the output netcdf variable : return : data object matching the type of the input data ( i.e. griddeddata or ungriddeddata ) .,def evaluate self data_list expr output_var None units None attributes None import six if __ in expr raise EvaluationError Use of functions or variables with double underscores __ is not allowed safe_globals module globals module for module in self SAFE_MODULES safe_globals __builtins__ var globals __builtins__ var for var in self SAFE_BUILTINS safe_locals for var in data_list assert isinstance var alias six string_types assert isinstance var data numpy ndarray if not var is_gridded safe_locals var alias var data_flattened else safe_locals var alias var data try result eval expr safe_globals safe_locals except NameError as ex raise EvaluationError A variable or function referenced in your expression could not be found check your expression Error is s ex args 0 except ValueError as ex raise EvaluationError An error occurred evaluating your expression check that it s correct and that the variables are compatible shapes Error is s ex args 0 return self _post_process data_list result expr output_var units attributes
"use bwa to map reads to genome , bwa before 0.6.0 support ab solid color space",def bwa workflow conf target output outsai index if not conf pe bwa attach_back workflow ShellCommand tool aln q 5 l 32 k 2 t param NUM_THREADS param index input fastq output sai tool bwa input fastq target _100k fastq output sai outsai param NUM_THREADS conf threads index index name bwa aln bwa update param conf items bwa out attach_back workflow ShellCommand tool samse param index input sai input fastq output sam tool bwa input fastq target _100k fastq sai outsai output sam output param index index name bwa samse else bwa attach_back workflow ShellCommand tool aln q 5 l 32 k 2 t param NUM_THREADS param index input fastq1 output sai1 tool aln q 5 l 32 k 2 t param NUM_THREADS param index input fastq2 output sai2 tool bwa input fastq1 target 0 _100k fastq fastq2 target 1 _100k fastq output sai1 outsai 0 sai2 outsai 1 param NUM_THREADS conf threads index index name bwa aln bwa update param conf items bwa out attach_back workflow ShellCommand tool sampe param index input sai1 input sai2 input fastq1 input fastq2 output sam tool bwa input fastq1 target 0 _100k fastq fastq2 target 1 _100k fastq sai1 outsai 0 sai2 outsai 1 output sam output param index index name bwa sampe bwa allow_dangling True bwa allow_fail True out allow_dangling True out allow_fail True
map function arguments with aspect and override it if appropriate .,def map_setting_to_aspect aspectable_setting def _func_decorator func wraps func def _new_func self args kwargs if self section aspects aspects self section aspects for arg aspect_value in aspectable_setting items if arg in self section continue if isinstance aspect_value aspectclass kwargs arg aspects get aspect_value is not None if isinstance aspect_value Taste aspect_instance aspects get aspect_value aspect_name if aspect_instance kwargs arg aspect_instance tastes aspect_value name return func self args kwargs _new_func __metadata__ FunctionMetadata from_function func return _new_func return _func_decorator
"emit key and value , serializing avro data as needed .",def emit self key value key value self __serialize_as_needed key value super AvroContext self emit key value
"( : class:`numbers . real ` ) blue , from 0.0 to 1.0 .",property def blue self with self return library PixelGetBlue self resource
return the arc data collected .,def get_arc_data self if self branch return self data else return
a constructor for the reflection predictor .,def ScanStaticReflectionPredictor experiment dmin None margin 1 padding 0 kwargs if dmin is None dmin experiment detector get_max_resolution experiment beam get_s0 space_group experiment crystal get_space_group space_group space_group build_derived_patterson_group return _ScanStaticReflectionPredictor experiment beam experiment detector experiment goniometer experiment scan experiment crystal get_unit_cell space_group type dmin margin padding
calculate the variance of each bin .,def calculate_bin_variances self sum_deltasq self delta_hl 2 self summation_matrix sum_delta_sq self delta_hl self summation_matrix 2 return sum_deltasq self bin_counts sum_delta_sq self bin_counts 2
"for debugging , the factor is represented by its variables . : returns : string representation of the factor .",def __repr__ self return self __str__
attempt to get a functional config dictionary .,def get_configs config_file os environ get SWIFT_TEST_CONFIG_FILE etc swift func_test conf config sos_config try try config readconf config_file func_test except MissingSectionHeaderError config_fp StringIO func_test n open config_file read config readconf config_fp func_test except SystemExit print sys stderr UNABLE TO READ FUNCTIONAL TESTS CONFIG FILE sos_config_file config get sos_conf etc swift sos conf try conf readconf sos_config_file raw True sos_config conf except SystemExit print sys stderr UNABLE TO READ FUNCTIONAL TESTS SOS CONFIG FILE return config sos_config
sets up http connector and starts queue timer,def createClient self self client elasticsearch ElasticSearch self url self user self password self index self timer start self inter
test if xcodebuild is in the path,def check_exists fips_dir try subprocess check_output xcodebuild version return True except OSError subprocess CalledProcessError return False
returns a string representing the grayscale image in logodd format,def get_str self return self get_map as_string
create a temp file that is deleted when last reference gone,def test_create_temp_file self fout self prefix _temp tif geoimg gp GeoImage create fout xsz 1000 ysz 1000 nb 5 temp True self assertTrue os path exists fout band geoimg 1 geoimg None self assertTrue os path exists fout band None self assertFalse os path exists fout
use dnspython to update a zone in the dns server,def update_zone self zone_name zi db_soa_serial None candidate_soa_serial None force_soa_serial_update False wrap_serial_next_time False date_stamp None nsec3_seed False clear_dnskey False clear_nsec3 False try zone dnskey_flag nsec3param_flag self read_zone zone_name update_info dnskey_flag dnskey_flag nsec3param_flag nsec3param_flag except NoSuchZoneOnServerError as exc msg str exc return RCODE_RESET msg None None except dns query UnexpectedSource dns query BadResponse as exc msg Zone s server s not operating correctly zone_name server server_name return RCODE_FATAL msg None None except IOError OSError as exc if exc errno in errno EACCES errno EPERM errno ECONNREFUSED errno ENETUNREACH errno ETIMEDOUT msg Zone s server s s not available s zone_name self server self port exc strerror return RCODE_ERROR msg None None msg Zone s server s s fatal error s zone_name self server self port exc strerror return RCODE_FATAL msg None None current_soa_rr zone find_rdataset zone origin RRTYPE_SOA items 0 update_soa_serial_flag False curr_serial_no self get_serial_no zone try new_serial_no new_soa_serial_no curr_serial_no zone_name db_soa_serial db_soa_serial candidate candidate_soa_serial wrap_serial_next_time wrap_serial_next_time date_stamp date_stamp except SOASerialError as exc msg str exc if not sys stdin isatty log_critical msg return RCODE_FATAL msg None None if wrap_serial_next_time or force_soa_serial_update zi update_soa_serial new_serial_no else update_soa_serial_flag True del_rrs rr for rr in zone iterate_rdatas if rr not in zi iterate_dnspython_rrs add_rrs rr for rr in zi iterate_dnspython_rrs if rr not in zone iterate_rdatas do_clear_nsec3 clear_nsec3 and nsec3param_flag do_clear_dnskey clear_dnskey and dnskey_flag do_nsec3_seed nsec3_seed and not nsec3param_flag if not del_rrs and not add_rrs and not do_clear_nsec3 and not do_clear_dnskey and not do_nsec3_seed msg Domain s not updated as no change detected zone_name return RCODE_NOCHANGE msg curr_serial_no update_info soa_rdtype dns rdatatype from_text RRTYPE_SOA if update_soa_serial_flag zi update_soa_serial new_serial_no add_rrs rr for rr in zi iterate_dnspython_rrs if rr not in zone iterate_rdatas del_rrs rr for rr in del_rrs if rr 2 rdtype soa_rdtype tl_label dns name from_text origin dns name empty ns_rdtype dns rdatatype from_text RRTYPE_NS pre_add_rrs rr for rr in add_rrs if rr 0 tl_label and rr 2 rdtype ns_rdtype tl_ns_rdata rr 2 for rr in pre_add_rrs add_rrs rr for rr in add_rrs if rr not in pre_add_rrs del_rrs rr for rr in del_rrs if not rr 0 tl_label and rr 2 in tl_ns_rdata if do_nsec3_seed rn random getrandbits int settings nsec3_salt_bit_length hash_alg settings nsec3_hash_algorithm flags settings nsec3_flags iterations settings nsec3_iterations nsec3param_rdata s s s 016x hash_alg flags iterations rn rdata_list nsec3param_rdata split try stuff bytes fromhex rdata_list 1 except Exception msg Failed to seed NSEC3 salt SM reset required return RCODE_RESET msg None update_info keyring dns tsigkeyring from_text self key_name self tsig_key secret if self tsig_key algorithm hmac md5 key_algorithm dns tsig HMAC_MD5 else key_algorithm dns name from_text self tsig_key algorithm origin dns name from_text zone_name update dns update Update origin keyring keyring keyname self key_name keyalgorithm key_algorithm update present origin current_soa_rr for rr in pre_add_rrs update add rr 0 rr 1 rr 2 for rr in del_rrs update delete rr 0 rr 2 if do_clear_nsec3 update delete origin RRTYPE_NSEC3PARAM if do_clear_dnskey update delete origin RRTYPE_DNSKEY for rr in add_rrs update add rr 0 rr 1 rr 2 if do_nsec3_seed update add origin 0 RRTYPE_NSEC3PARAM nsec3param_rdata response dns query tcp update self server port self port rcode response rcode rcode_text dns rcode to_text response rcode success_rcodes dns rcode NOERROR if rcode in self success_rcodes msg Update s to domain s succeeded new_serial_no zone_name return RCODE_OK msg new_serial_no update_info elif rcode in self retry_rcodes msg Update s to domain s failed s will retry new_serial_no zone_name rcode_text return RCODE_ERROR msg None update_info elif rcode in self reset_rcodes msg Update s to domain s failed s SM reset required new_serial_no zone_name rcode_text return RCODE_RESET msg None update_info elif rcode in self fatal_rcodes msg Update s to domain s permanently failed s new_serial_no zone_name rcode_text return RCODE_FATAL msg None update_info else msg Update s to domain s permanently failed s unknown response new_serial_no zone_name response rcode return RCODE_FATAL msg None update_info
python api test : h2o.frame.h2oframe.get_frame ( ),def h2o_H2OFrame_get_frame frame1 h2o import_file pyunit_utils locate smalldata jira hexdev_29 csv frame2 h2o get_frame frame1 frame_id assert_is_type frame2 H2OFrame
"construct a kudu timedelta to set timeouts , etc . use this function instead of interacting with the timedelta class yourself .",def timedelta seconds 0 millis 0 micros 0 nanos 0 from kudu compat import long total_ns long 0 seconds long 1000000000 millis long 1000000 micros long 1000 nanos return TimeDelta from_nanos total_ns
@param receipt : the receipt message id . @type receipt : c{str },def __init__ self receipt extra_headers None super ReceiptFrame self __init__ RECEIPT headers extra_headers or self headers receipt id receipt
return list of up to limit pre - processed entries from traceback .,functools wraps traceback extract_tb def extract_tb tb limit None if limit is None if hasattr sys tracebacklimit limit sys tracebacklimit list n 0 while tb is not None and limit is None or n limit f tb tb_frame lineno tb tb_lineno co f f_code if co co_filename in fn_subst filename shrink fn_subst co co_filename else filename co co_filename shrink 0 lineno shrink if lineno 1 lineno 1 name co co_name linecache checkcache filename line linecache getline filename lineno f f_globals if line line line strip else line None list append filename lineno name line tb tb tb_next n n 1 return list
called to signal the echo server to shut down,def shutdown self if self _verbose print s shutting down time asctime self _must_shutdown True
project descriptors on the vocabulary to create a histogram of words .,def project self descriptors imhist zeros self nbr_words words distance vq descriptors self voc for w in words imhist w 1 return imhist
returns a jsonified 503 error message instead of a http 404 error .,app errorhandler 503 def not_found error return make_response jsonify error 503 something wrong 503
"load diaries from database . it will repeatedly call qapp.processevents while loading data , making ui still responsive if the amount of data is big . it also delay informing views to update , this avoid unnecessary layout operation .",def loadFromDb self start_time time clock sortBy settings Main listSortBy reverse settings Main getboolean listReverse self _yearFirstsArgs sortBy reverse iterator db sorted sortBy reverse firstChunk True rest len db yearFirsts yearBefore None while rest 0 if firstChunk firstChunk False count min 35 rest else count min 300 rest nextRow len self _lst self beginInsertRows QModelIndex nextRow nextRow count 1 for i in range count d list next iterator year d 1 4 if year yearBefore and nextRow i 0 yearFirsts int yearBefore nextRow i 1 if reverse else nextRow i yearBefore year self _lst append d if i 15 0 qApp processEvents self endInsertRows rest count pairs yearFirsts items if sortBy datetime else self _yearFirsts tuple sorted pairs reverse reverse logging debug loadFromDb took 2f sec time clock start_time
monkey - patch urllib3 with pyopenssl - backed ssl - support .,def inject_into_urllib3 connection ssl_wrap_socket ssl_wrap_socket util HAS_SNI HAS_SNI util IS_PYOPENSSL True
returns the value of the given flag .,def GetFlag flag _ParseAndStripGTestFlags sys argv return _flag_map flag
set the proxy source and use it to load proxy list,def set_source self source self _source source self load
emit a read_double or read_data call for pulling a gl function argument out of the buffer 's operand area .,def ReadData offset arg_type if arg_type GLdouble or arg_type GLclampd retval READ_DOUBLE d offset else retval READ_DATA d s offset arg_type return retval
"given a header class , make sure it 's complete . complain on stderr if not .",def checkHeader header_cls header_name getattr header_cls canonical_name or header_cls __name__ attrs dir header_cls checks canonical_name str True reference str True description str True valid_in_requests bool True valid_in_responses bool True syntax str list_rule True list_header bool True deprecated bool False for attr_name attr_types attr_required in checks attr_value getattr header_cls attr_name if getattr header_cls no_coverage and attr_name in syntax continue if attr_name in syntax and attr_value False continue if attr_required and attr_value None sys stderr write s lacks s n header_name attr_name elif True not in isinstance attr_value t for t in attr_types sys stderr write s s has wrong type n header_name attr_name canonical_name getattr header_cls canonical_name if canonical_name header_name sys stderr write s has mismatching canonical name s n header_name canonical_name loader unittest TestLoader header_mod HeaderProcessor find_header_module header_name tests loader loadTestsFromModule header_mod if tests countTestCases 0 and getattr header_cls no_coverage False sys stderr write s doesn t have any tests n header_name
"divides the receiver locally , creating child octants .",def divide self if debug print Dividing locally self self giveMyBBox mask self octree mask if not self isTerminal assert Could not divide non terminal octant self children for i in range self octree mask 0 1 self children append for j in range self octree mask 1 1 self children i append for k in range self octree mask 2 1 origin self origin 0 i self size 2 0 self origin 1 j self size 2 0 self origin 2 k self size 2 0 self children i j append Octant self octree self origin self size 2 0 if debug print Children self children i j k giveMyBBox
"description : returns a ranking of arms in the form of a list of dictionaries , which is conveneint for downstream applications",def most_current_ranking self app butler alg_label item app getModel json dumps exp_uid app exp_uid args alg_label alg_label return_dict return_dict headers label Rank field rank label Target field index label Score field score label Standard Deviation field standard_deviation label Precision field precision label Count field count return_dict data item targets return_dict plot_type columnar_table return return_dict
get narrative_sets all : get /api / v1/narrative_sets/ one : get /api / vi / narrative_sets / name,def get self narrative_set_name data_interface current_app config data_interface if narrative_set_name is None data data_interface read_narrative_sets response jsonify data else data data_interface read_narrative_set narrative_set_name response jsonify data return response
finds ` x ` for which the following equation holds : ` y = ( 1-exp(-alpha*x ) ) / ( 1-exp(-alpha ) ) ` .,def inverse self y alpha self exp_minus_alpha 1 if hasattr y __iter__ y i alpha 1 for i in y return log y return log y alpha 1
infer layout of the given memoryview * val*.,def infer_layout val if sys version_info 3 return C if val c_contiguous else F if val f_contiguous else A if val ndim 1 and val strides 0 val itemsize return C return A
simplified configuration for 1d kernel launch,def forall self nelem local_size 64 stream None return self configure nelem min nelem local_size stream stream
labels dictionary generated by corpuslabel.getlabels ( ) should match the label windows .,def testGetLabels self data pandas DataFrame timestamp generateTimestamps strp 2014 01 01 datetime timedelta minutes 5 10 windows 2014 01 01 00 00 2014 01 01 00 10 2014 01 01 00 10 2014 01 01 00 15 writeCorpus self tempCorpusPath test_data_file csv data writeCorpusLabel self tempCorpusLabelPath test_data_file csv windows corpus nab corpus Corpus self tempCorpusPath corpusLabel nab labeler CorpusLabel self tempCorpusLabelPath corpus for relativePath l in corpusLabel labels iteritems windows corpusLabel windows relativePath for t lab in corpusLabel labels test_data_file csv values for w in windows if w 0 t and t w 1 self assertEqual lab 1 Incorrect label value for timestamp r t
limit view to users with access to update this resource .,def dispatch self args kwargs result super ResourceUpdateView self dispatch args kwargs if not self object user_can_edit user_id self request user pk return HttpResponseForbidden return result
declares a rdfs class as part of the range of the property .,def add_range self p_range if p_range startswith u http www w3 org 2001 XMLSchema self type DATATYPE_PROPERTY if self type DATATYPE_PROPERTY and p_range not in self _ranges and len self _ranges 1 raise OMAlreadyDeclaredDatatypeError u Property datatype can only be specified once self _ranges add p_range
returns a dict representation of the suggestion object .,def to_dict self return author_name self get_author_name exploration_id self exploration_id exploration_version self exploration_version state_name self state_name description self description suggestion_html self suggestion_html
update an empty configuration with the default values,def test_update_set_config self from pecan import configuration conf configuration initconf conf update configuration conf_from_file os path join __here__ config_fixtures config py self assertEqual conf app root None self assertEqual conf app template_path myproject templates self assertEqual conf app static_root public self assertEqual conf server host 1 1 1 1 self assertEqual conf server port 8081
takes a modular crypt encoded argon2i or argon2id stored password hash and checks if the user provided password will hash to the same string when using the stored parameters,def verify password_hash password return nacl bindings crypto_pwhash_str_verify password_hash password
searches public and private articles using a keyword .,def search self keyword private False institution None group None published_since None modified_since None if private url account articles search else url articles search parameters search_for s keyword if institution parameters institution institution if group parameters group group if published_since parameters published_since published_since if modified_since parameters modified_since modified_since response self post url payload json dumps parameters headers self get_headers token self token results json loads response body_string return results
construct hilbert kernel with n grid points .,def hilbert_kernel_interpolate n mid n 1 2 aux np arange mid 1 dtype float np multiply aux 1 np log aux 1 aux 1 ker np zeros n float ker 1 mid aux 2 2 aux 1 1 aux 2 ker 1 mid 1 ker 1 mid return fft ker np pi
"returns a tuple ( found , value )",def _find_default self name defaults self _variable_defaults copy defaults update self global_defaults defaults update self _user_config if name in defaults return True defaults name else return False None
return a generator of records for the stack above the caller 's frame .,def lazy_stack frame sys _getframe 1 while frame yield frame frame frame f_back
converts from binary state to density,def binstate_to_density binstate return sum map int binstate
hostapd start with a multi - bss configuration file,def test_ap_multi_bss_config dev apdev for d in dev d request SET ignore_old_scan_res 1 ifname1 apdev 0 ifname ifname2 apdev 0 ifname 2 ifname3 apdev 0 ifname 3 logger info Set up three BSSes with one configuration file hostapd add_iface ifname1 multi bss conf hapd hostapd Hostapd ifname1 hapd enable multi_check dev True True True hostapd remove_bss ifname2 multi_check dev True False True hostapd remove_bss ifname3 multi_check dev True False False hostapd remove_bss ifname1 multi_check dev False False False hostapd add_iface ifname1 multi bss conf hapd hostapd Hostapd ifname1 hapd enable hostapd remove_bss ifname1 multi_check dev False False False
tests adding footers to the columns,def testAddingFooters self table Table Test table self createContainer self assertIsNone table getColumnFooter col1 self assertIsNone table getColumnFooter col2 self assertIsNone table getColumnFooter col3 table setColumnFooter col1 Footer1 self assertEquals Footer1 table getColumnFooter col1 table setColumnFooter col2 Footer2 self assertEquals Footer2 table getColumnFooter col2 table setColumnFooter fail FooterFail
gets a paramater for download stream . parameters are optional information about the downloadable stream and their meaning depends on the used adapter . for example in webadapter they are interpreted as http response headers .,def getParameter self name if self _params is not None return self _params get name return None
notifies the listeners that the selected color has changed,def fireColorChanged self self fireEvent ColorChangeEvent self self color
"list the bucket , possibly limiting the search with a prefix .",def list self bucket prefix None delimiter None retries 3 extra None bucket self get_bucket bucket opts if prefix opts Prefix prefix if delimiter opts Delimiter delimiter if extra opts ExtraArgs extra return key key for key in self _list_retry retries bucket opts
run a command using openssl in the current context .,def __call__ self cmd args kwargs self cmd self binary cmd if cmd x509 self cmd config self conf_path self cmd list args env for k v in os environ iteritems try env k encode utf8 v encode utf8 except UnicodeDecodeError pass if self base_conf_path is not None env OPENSSL_CONF self base_conf_path encode utf8 self proc subprocess Popen self cmd stdout subprocess PIPE stderr subprocess STDOUT env env stdout stderr self proc communicate self log stdout if self proc returncode 0 raise subprocess CalledProcessError self proc returncode self cmd output stdout self cmd self proc None return stdout
escapes to named entities where possible and numeric - escapes non - ascii,def escapeToNamedASCII text return escapeToNamed text encode ascii xmlcharrefreplace
plot a geometry element as a wireframe .,def plot_geometry ax gel ax plot_mesh ax gel coors gel conn gel edges ax plot_global_dofs ax gel coors gel conn return ax
"generate tables : basic , sensitivity , special .",def typeset_term_tables fd table scattab _st_ 2 _sd_ 0 _adj_ 0 _tl_ 1 _ul_ 1 _th 2 _eth 2 _of_ 2 new_tabs for term_name in six iterkeys table for term_tag tab_id in scattab if term_tag in term_name new_tabs tab_id append term_name break basic_keys list set table keys set new_tabs 0 set new_tabs 1 set new_tabs 2 typeset_term_table fd basic_keys table basic typeset_term_table fd new_tabs 0 table sensitivity typeset_term_table fd new_tabs 1 table large deformation typeset_term_table fd new_tabs 2 table special fd write newpage
authorise jid ' jid ' . works only if these jid requested auth previously .,def Authorize self jid self _owner send Presence jid subscribed
the simplex optimizer does not require gradients .,def opt self x_init f_fp None f None fp None statuses Converged Maximum number of function evaluations made Maximum number of iterations reached opt_dict if self xtol is not None opt_dict xtol self xtol if self ftol is not None opt_dict ftol self ftol if self gtol is not None print WARNING simplex doesn t have an gtol arg so I m going to ignore it opt_result optimize fmin f x_init disp self messages maxfun self max_f_eval full_output True opt_dict self x_opt opt_result 0 self f_opt opt_result 1 self funct_eval opt_result 3 self status statuses opt_result 4 self trace None
"od.__setitem__(i , y ) < = = > od[i]=y",def __setitem__ self key value dict_setitem dict __setitem__ if key not in self root self __root last root 0 last 1 root 0 self __map key last root key dict_setitem self key value
test computation of fock exchange between naos against this computed between gtos,def test_kmat_gto_vs_nao self vh_gto k_gto gto_hf get_jk k_gto conv conv_yzx2xyz_2d k_gto mf RHF system_vars_c init_pyscf_gto mol k_nao mf get_k dm rdm1 self assertTrue abs k_nao k_gto sum k_gto size 2 5e 05
gets the default path of hdlcc cache . intended for testing only .,def getDefaultCachePath project_file return p join p abspath p dirname project_file hdlcc
"indicate that a user is active , optionally in a room .",def touch r user ttl room None r expire path USERS user ttl if room if r sadd path ROOMS room 1 _create_room r room r expire path ROOMS room ttl if r sadd path ROOMS room USERS user 1 _join_room r room user r expire path ROOMS room USERS user ttl
calculate excepted score for a key : param key : the key to search for : return : excepted score,def _get_expected_score self key opponents self storage get key expected_score 0 0 for opponent_key opponent_stats in opponents items if opponent_key key continue wins opponent_stats wins loses opponent_stats loses prob_answer_wins math exp wins loses 1 math exp wins loses expected_score prob_answer_wins return expected_score
formats a constant for output .,def constant const format_spec None format_spec format_spec or default_format_spec effect lambda x x if format_spec color effect color constant elif format_spec html effect html constant if const kind string s const data translate string_escapes else s const name if const data is None else str const data return effect s
"add a new setting with the name , or a set of subsettings .",def add self setting posn 1 readonly False pixmap None name setting name if name in self setdict raise RuntimeError Name already in settings dictionary self setdict name setting if posn 0 self setnames append name else self setnames insert posn name setting parent self if pixmap setting pixmap pixmap if readonly setting readonly True
update locale to one given in preferences .,def updateUILocale global uilocale if settingdb ui_english uilocale qt4 QLocale c else uilocale qt4 QLocale system uilocale setNumberOptions qt4 QLocale OmitGroupSeparator qt4 QLocale setDefault uilocale
test finding a few ready files .,def test_multi_search pg_xlog for i in range 3 ready str i 8 3 pg_xlog touch ready ready complete_segment_name F 8 3 pg_xlog touch complete_segment_name done ready_history_file_name F 8 history pg_xlog touch ready_history_file_name ready segs worker WalSegment from_ready_archive_status str pg_xlog pg_xlog for i seg in enumerate segs assert seg name str i 8 3 assert i 2 pg_xlog assert_exists complete_segment_name done pg_xlog assert_exists ready_history_file_name ready
"redirects stdout or stderr to a stringio object . as of python 3.4 , there is a standard library contextmanager for this , but backwards compatibility !",contextlib contextmanager def stdchannel_redirected stdchannel try s io StringIO old getattr sys stdchannel setattr sys stdchannel s yield s finally setattr sys stdchannel old
configure oauth2 credentials for a google service account .,def ServiceAccountCredentials email key_file None key_data None if key_file key_data open key_file rb read return oauth2client client SignedJwtAssertionCredentials email key_data OAUTH2_SCOPE
return text with its offset in the document,def get_text obj if isinstance obj bioc BioCSentence return obj offset obj text elif isinstance obj bioc BioCPassage if obj text return obj offset obj text else text for sentence in obj sentences try text fill_char text sentence offset obj offset assert sentence text BioC sentence has no text format sentence offset text sentence text except raise ValueError Overlapping sentences d sentence offset return obj offset text elif isinstance obj bioc BioCDocument text for passage in obj passages try text fill_char text passage offset text get_text passage 1 except raise ValueError s overlapping passages d obj id passage offset return 0 text else raise ValueError obj must be BioCCollection BioCDocument BioCPassage or BioCSentence
simplest possible manipulator that can only handle no modification .,def do_first self self width 1 self height 1
test another part of sanity checking .,def testPartMediaSanityChecking self args media cd part size 650000000 foo bar baz failed False try picax config handle_args args except picax config ConfigError failed True assert failed
send an email about a dashboard being updated from grafana : param emails : list of emails to send to : param message : message listing the changes : param check_name : name of the status check : return none,task ignore_result True def send_grafana_sync_email emails message check_name send_mail subject Cabot check changed due to Grafana dashboard update format check_name message message from_email Cabot Updates format os environ get CABOT_FROM_EMAIL recipient_list emails
root group ( by itself ) is contained .,def test_root setup_teardown_file f setup_teardown_file 3 grp f create_group test with pytest raises NotImplementedError assert in grp
returns the currently selected data and time,def getSelectedTime self try hour self hourpicker currentItem text except AttributeError hour try minute self minutepicker currentItem text except AttributeError minute zone self ambutton isChecked and AM or PM return QTime fromString s s s hour zfill 2 minute zfill 2 zone hhmAP
implementation of a generic confidence - based function,staticmethod def confidence values alpha 1 weight None dtype double values weight values if weight is not None else values return alpha values astype dtype
"return filename in the xdg data home directory , where the directory is guaranteed to exist",def save_data_file filename direc base save_data_path PACKAGE_NAME if not direc return None filepath os path join direc filename return filepath
generates public key and master secret key .,def setup self if debug print Setup algorithm n A B for i in range self assump_size A append self group random ZR B append self group random ZR W for i in range self uni_size x for j1 in range self assump_size 1 y for j2 in range self assump_size 1 y append self group random ZR x append y W i 1 x V for j1 in range self assump_size 1 y for j2 in range self assump_size 1 y append self group random ZR V append y k for i in range self assump_size 1 k append self group random ZR g self group random G1 h self group random G2 e_gh pair g h g_A for i in range self assump_size g_A append g A i g_A append g g_WA for i in range self uni_size x for j1 in range self assump_size 1 y for j2 in range self assump_size prod A j2 W i 1 j2 j1 W i 1 self assump_size j1 y append g prod x append y g_WA i 1 x g_VA for j1 in range self assump_size 1 y for j2 in range self assump_size prod A j2 V j2 j1 V self assump_size j1 y append g prod g_VA append y h_k for i in range self assump_size 1 h_k append h k i e_gh_kA for i in range self assump_size e_gh_kA append e_gh k i A i k self assump_size pk g_A g_A g_WA g_WA g_VA g_VA e_gh_kA e_gh_kA msk h h k k B B W W V V return pk msk
whether the specified node is valid .,def is_valid self node lint_context node_type NodeType node type if node_type is NodeType OPTION option_name node value 1 is_valid option_name not in Abbreviations if not is_valid self _make_description_by_option_name option_name return is_valid excmd_node node is_set_cmd excmd_node ea cmd get name in SetCommandFamily if not is_set_cmd return True option_expr excmd_node str split 1 option_name re match a z option_expr group 0 is_valid option_name not in AbbreviationsIncludingInvertPrefix if not is_valid self _make_description_by_option_name option_name return is_valid
converts a workqueue to a json - able dictionary .,def _task_to_dict task payload task payload if payload and task content_type application json payload json loads payload return dict task_id task task_id queue_name task queue_name eta _datetime_to_epoch_seconds task eta source task source created _datetime_to_epoch_seconds task created lease_attempts task lease_attempts last_lease _datetime_to_epoch_seconds task last_lease payload payload content_type task content_type
merges the temporary multiproc error files created .,def merge_multiproc_files command filename barcode err_log stat_log exit_str Popen cat err_log _multiproc_ grep EXIT_CODE stdout PIPE shell True communicate 0 exit_code 0 for i in exit_str split n m re match EXIT_CODE n i if m exit_code exit_code int m group 1 if exit_code 0 yap_file_io write_data YAP_COMMAND command nINPUT FILE filename n stat_log os system cat err_log _multiproc_ stat_log yap_file_io write_data _ 30 n stat_log os system rm err_log _multiproc_ else yap_file_io write_data YAP_COMMAND command nINPUT FILE filename n err_log os system cat err_log _multiproc_ err_log yap_file_io write_data _ 30 n err_log os system rm err_log _multiproc_
pylint will complains about too many arguments .,def too_many_arguments_function arga argu argi arge argt args arga argu arga argi arga arge arga argt arga args return arga
log the reaction message at a specific loglevel .,def execute_reaction self self __log self _message
get a resource object to attach to note .,def get_resource self res resource_data open res rb read md5 hashlib md5 md5 update resource_data hash_val md5 digest hash_hex binascii hexlify hash_val data Types Data data size len resource_data data bodyHash hash_hex data body resource_data resource_attributes Types ResourceAttributes resource_attributes fileName res resource_attributes sourceURL file os path abspath res resource Types Resource resource attributes resource_attributes mime encoding self mimer guess_type res if not mime mime application octet stream resource mime mime resource data data return resource
split the given string s by whitespace and return a list of strings .,staticmethod def split s b def iter_words current_word current_word_start 0 for i c in enumerate s if c isspace if current_word yield current_word_start current_word current_word current_word_start i 1 else current_word c if current_word yield current_word_start current_word result_list result_idx len s 1 for start word in iter_words if b start result_idx min len result_list result_idx result_list append word if s and s 1 isspace or not s and b len s result_idx len result_list result_list append return result_list result_idx
admin view to appoint members to the position,permission_required involvement appoint_position fn get_position_by_pk def admin_appoint request pos_id None position get_object_or_404 Position pk pos_id if request method POST form AppointmentForm position request POST request FILES if form is_valid form save messages add_message request messages SUCCESS _ Your decisions have successfully been saved return HttpResponseRedirect reverse involvement_position_modeladmin_index else form AppointmentForm position view get_meta_title Appoint applicants get_page_title Appoint applicants for get_page_subtitle position __str__ header_icon pick context view view request request position position form form return render request involvement admin position_appointment html context
print random mentions fron tfrecord file .,def print_random_mentions_f1 data_directory filename context_features lcl tf FixedLenFeature dtype tf int64 rcl tf FixedLenFeature dtype tf int64 eml tf FixedLenFeature dtype tf int64 clean tf FixedLenFeature dtype tf int64 uid tf FixedLenFeature dtype tf string sequence_features labels tf FixedLenSequenceFeature dtype tf int64 lci tf FixedLenSequenceFeature dtype tf int64 rci tf FixedLenSequenceFeature dtype tf int64 emi tf FixedLenSequenceFeature dtype tf int64 tf reset_default_graph l_vars pickle load open data_directory local_variables pickle rb filename_queue tf train string_input_producer data_directory filename num_epochs 1 reader tf TFRecordReader _ ex reader read filename_queue context_parsed sequence_parsed tf parse_single_sequence_example serialized ex context_features context_features sequence_features sequence_features all_examples all_examples update context_parsed all_examples update sequence_parsed batch_size 100 batched_data tf train batch tensors all_examples batch_size batch_size dynamic_pad True allow_smaller_final_batch True name y_batch sess tf Session coord tf train Coordinator sess run tf initialize_all_variables sess run tf initialize_local_variables tf train start_queue_runners sess sess try try while not coord should_stop out sess run batched_data print_results_f1 out l_vars batch_size break except tf errors OutOfRangeError print Done training epoch limit reached finally coord request_stop sess close
"assert that : class:`~ulid.ulid . memoryview ` returns ` true ` on "" not equal "" comparisons against unsupported types .",def test_memoryview_ne_false_with_unsupported_type valid_bytes_128 unsupported_comparison_type assert ulid MemoryView valid_bytes_128 unsupported_comparison_type
document : the document this page belongs in .,property def parent self return self _document
perform common text parsing and return ready - to - go html .,def parse_general_text string context split_paragraphs True string parse_bulleted_lists string string parse_doctest_code string context if split_paragraphs paragraphs p for p in re split n n string if p string join surround_with_tag paragraph p for paragraph in paragraphs string parse_bold string string parse_italics string string parse_backtick_code string context return string
fisher 's exact test to test rule significance .,def apply_fisher ruleset for rule in ruleset rule pval fisher rule
the column number of the end of the text where the exception occurred .,def getColumnNumber self return self _colnum
normalize a pathname . will return the same result for equivalent paths .,def normpath s if not in s return s comps s split i 1 while i len comps 1 if comps i and comps i 1 if i 1 del comps i 1 i 1 i i 1 else raise norm_error Cannot use immediately after volume name else i i 1 s join comps if s 1 and len comps 2 and s len s s s 1 return s
returns all parameters with values as a string .,def get_all_params_as_string self all_params for param in self params items all_params append 0 1 format param 0 param 1 return join all_params
remove all elements from the orderedset .,def clear self while self self pop
tests whether the expression is an instance of type,def is_type self return False
reconstruct the array from the meta - information and the z - file .,def read self unpickler filename os path join unpickler _dirname self filename array unpickler np core multiarray _reconstruct self init_args with open filename rb as f data read_zfile f state self state data array __setstate__ state return array
returns the compressed graph according to the given experimental setup,def compress self setup designated set setup nodes zipped self copy marked n d for n d in self nodes data True if n not in designated and not d get compressed False while marked for node _ in sorted marked backward zipped predecessors node forward zipped successors node if not backward or len backward 1 and not backward 0 in forward self __merge_source_targets node zipped elif not forward or len forward 1 and not forward 0 in backward self __merge_target_sources node zipped else designated add node marked n d for n d in self nodes data True if n not in designated and not d get compressed False not_compressed n d for n d in zipped nodes data True if not d get compressed False return zipped subgraph n for n _ in not_compressed
displays the number of days remaining to the next congress .,def command_c3 self msg now datetime datetime utcnow congress datetime datetime year now year month self CONGRESS_MONTH day self CONGRESS_DAY if congress now congress congress replace year congress year 1 number congress year self FIRST_CONGRESS_YEAR 1 days congress now days text Time to number C3 days days format number number days days self respond msg text
"because we 're a python value node and do n't have a real timestamp , we get to ignore the calculator and just use the value contents .",def get_csig self calc None try return self ninfo csig except AttributeError pass contents self get_contents self get_ninfo csig contents return contents
load the extension in ipython .,def load_ipython_extension ip warnings simplefilter once SymPyDeprecationWarning SymPyDeprecationWarning feature using load_ext sympy interactive ipythonprinting useinstead from sympy import init_printing init_printing deprecated_since_version 0 7 3 issue 7013 warn init_printing ip ip
returns the frequency of the wave .,property def frequency self return self _frequency
register a handler in the ask system . key must be a string and handler a class inheriting from askhandler : :,def register_handler key handler if type key is Predicate key key name try getattr Q key add_handler handler except AttributeError setattr Q key Predicate key handlers handler
generates the prufer sequence that is delta beyond the current one .,def next self delta 1 return Prufer unrank self rank delta self nodes
solves an optimal control problem ( ocp ) : :,def ocp f gl regularize verbose False N 20 T 1 0 periodic False integration_intervals 1 exact_hessian None if not isinstance gl list raise Exception Constraints must be given as a list f f OptimizationParameter print f shape gl_pure gl_equality sort_constraints gl syms get_primitives f T gl_pure lims i start for i in syms x i end for i in syms x i start for i in syms u i end for i in syms u states struct_symMX entry str hash i shape i sparsity for i in syms x controls struct_symMX entry str hash i shape i sparsity for i in syms u variables struct_symMX entry str hash i shape i sparsity for i in syms v ext_symnames sorted set syms keys x u v p T ext_structures dict k struct_symMX entry str hash i shape i sparsity for i in syms k for k in ext_symnames ext_syms for k in ext_symnames ext_syms syms k ext_cl i __class__ for i in syms T 1 X struct_symMX entry V struct variables entry X struct states repeat N 1 entry U struct controls repeat N P struct_symMX entry str hash i shape i sparsity for i in syms p ode_out MXFunction ode_out syms x syms u syms p syms v ext_syms T 0 0 N vertcat i dot for i in syms x nonstates struct_symMX entry u struct controls entry p struct P entry v struct variables entry k struct ext_structures k for k in ext_symnames ode_out_ins states nonstates u nonstates p nonstates v for k in ext_symnames ode_out_ins nonstates k ode MXFunction ode states nonstates ode_out ode_out_ins 0 intg simpleRK ode integration_intervals 4 intg try_expand intg Pw0 P X V None if i nlp_var else DMatrix zeros i shape for i in ext_syms ext_constr for cl in ext_cl ext_constr_e gl gl_pure gl_equality cl process intg syms N T X P Pw0 states gl gl_pure gl_equality ext_constr ext_constr_e h_out MXFunction h_out syms x syms u syms p syms v ext_syms a for a in gl_pure if dependsOn a veccat syms x syms u g_out MXFunction g_out syms p syms v ext_syms lims a for a in gl_pure if not dependsOn a veccat syms x syms u f_out MXFunction f_out syms p syms v ext_syms lims f reg_out MXFunction reg_out syms x syms u syms p syms v ext_syms sumRows vertcat inner_prod i i for i in regularize T N h_out try_expand h_out g_out try_expand g_out f_out try_expand f_out reg_out try_expand reg_out if dependsOn f veccat syms x raise Exception Objective function cannot contain pure state variables Try adding start or end Lims X X 0 X X 1 X U 0 X U 1 G struct_MX entry str i expr g for i g in enumerate g_out Pw0 Lims entry path expr h_out X X k X U k Pw0 for k in range N ext_constr entry shooting expr X X k 1 intg X X k veccat X U k Pw0 1 0 for k in range N entry periodic expr X X 1 X X 0 if periodic else reg sumRows vertcat reg_out X X k X U k Pw0 0 for k in range N if reg isempty reg 0 nlp MXFunction nlp nlpIn x X p P nlpOut f f_out Pw0 Lims 0 reg g G for cl in ext_cl exact_hessian cl setOptions exact_hessian if exact_hessian is None exact_hessian True options options hessian_approximation exact if exact_hessian else limited memory if not verbose options print_time False options print_level 0 options verbose False solver NlpSolver solver ipopt nlp options x0 X 0 lbx X 0 ubx X 0 for i in syms v hs str hash i lbx V hs i lb ubx V hs i ub x0 V hs i init for j in xu for i in syms j hs str hash i lbx j capitalize hs i lb ubx j capitalize hs i ub for k in range N 1 if k N and j u continue x0 j capitalize k hs value_time i init t k 0 0 T init N par P 0 for i in syms p h str hash i par h i value lbg G 0 ubg G 0 for i eq in enumerate e for g e in zip gl gl_equality if not dependsOn g veccat syms x syms u if eq lbg str i ubg str i 0 else lbg str i Inf ubg str i 0 for i eq in enumerate e for g e in zip gl gl_equality if dependsOn g veccat syms x syms u if eq lbg path i ubg path i 0 else lbg path i Inf ubg path i 0 for cl in ext_cl cl setBounds lbx ubx x0 lbg ubg lbg shooting ubg shooting 0 if periodic lbg periodic ubg periodic 0 sol solver x0 x0 lbg lbg ubg ubg lbx lbx ubx ubx p par if solver getStat return_status Solve_Succeeded raise Exception Problem failed to solve Add verbose True to see what happened opt X sol x for i in syms v i sol opt V str hash i for i in syms x i sol opt X str hash i for i in syms u i sol opt U str hash i for cl in ext_cl cl extractSol solver return float solver getOutput f
raise if the request resulted in an http error code .,def raise_for_error self u Raise if the request resulted in an HTTP error code n n Raises n class kombu exceptions HttpError n if self error raise self error
execute tests in the passed module ( defaults to _ _ main _ _ ) with pytest .,def run_pytest module None filename None pytest_options pytest_plugins if module is None import __main__ as module if filename is None try filename module __file__ except AttributeError raise ValueError module has no __file__ attribute please pass filename instead return pytest main list pytest_options filename plugins list pytest_plugins ModuleCollectorPlugin module module filename filename
return ` true ` if lookup returns the same codec,def test_check_encoding_true self self assertEqual io check_encoding mock_stdout utf8 True self assertEqual io check_encoding mock_stdout utf 8 True self assertEqual io check_encoding mock_stdout UTF 8 True
convert a node to text format .,def to_text self name kw s StringIO for rds in self rdatasets if len rds 0 s write rds to_text name kw s write u n return s getvalue 1
ensuring exceptions are raised for operators & functions invalid on geography fields .,skipUnless postgis u This is a PostGIS specific test def test04_invalid_operators_functions self u z Zipcode objects get code u 77002 with self assertRaises ValueError City objects filter point__within z poly count with self assertRaises ValueError City objects filter point__contained z poly count htown City objects get name u Houston with self assertRaises ValueError City objects get point__exact htown point
invoke the post method on a resource . @param relpath : optional . a relative path to this resource 's path . @param params : key - value data . @param data : optional . body of the request . @param contenttype : optional .,def post self relpath None params None data None headers None return self invoke POST relpath params data headers
both timesince and timeuntil should work on date objects ( # 17937 ) .,def test_date_objects self u today datetime date today self assertEqual timesince today self oneday u 0 xa0minutes self assertEqual timeuntil today self oneday u 0 xa0minutes
return the * * printable * * digest of the message that has been hashed so far .,def hexdigest self return join 02x bord x for x in self digest
validate the specified tsig rdata against the other input parameters .,def validate wire keyname secret now request_mac tsig_start tsig_rdata tsig_rdlen ctx None multi False first True adcount struct unpack H wire 10 12 if adcount 0 raise dns exception FormError adcount 1 new_wire wire 0 10 struct pack H adcount wire 12 tsig_start current tsig_rdata aname used dns name from_wire wire current current current used upper_time lower_time fudge mac_size struct unpack HIHH wire current current 10 time upper_time long 0 32 lower_time long 0 current 10 mac wire current current mac_size current mac_size original_id error other_size struct unpack HHH wire current current 6 current 6 other_data wire current current other_size current other_size if current tsig_rdata tsig_rdlen raise dns exception FormError if error 0 if error BADSIG raise PeerBadSignature elif error BADKEY raise PeerBadKey elif error BADTIME raise PeerBadTime elif error BADTRUNC raise PeerBadTruncation else raise PeerError unknown TSIG error code d error time_low time fudge time_high time fudge if now time_low or now time_high raise BadTime junk our_mac ctx sign new_wire keyname secret time fudge original_id error other_data request_mac ctx multi first aname if our_mac mac raise BadSignature return ctx
indicate an attribute that populates from a query - time sql expression .,def query_expression prop ColumnProperty _sql null prop strategy_key query_expression True return prop
add a representer for the given type . multi - representer is a function accepting a dumper instance and an instance of the given data type or subtype and producing the corresponding representation node .,def add_multi_representer data_type multi_representer Dumper Dumper Dumper add_multi_representer data_type multi_representer
returns the comment associated with this cell,property def comment self return self _comment
returns sample rate for a dataset or given channel .,def _get_samplerate self channel None raise NotImplementedError
define the block for a direct interface .,def __str__ self s InterfaceBase __str__ self s n n return s
invoke hydrotrend through the shell .,def call self subprocess call hydrotrend in dir self input_dir out dir self output_dir
specifies what routes to expose for this test,def get_handlers self u raise NotImplementedError
assert a service can be resolved in the given environment .,def assertResolvable self service environment expected_address context None params service if context is not None params append context address run_python self python_binary resolve py params output True additional_env MDK_ENVIRONMENT environment self assertEqual address decode utf 8 expected_address
create a new repeat data source .,def __init__ self value None args kwargs super __init__ args kwargs self data numpy array value for _ in range self chunk_size
returns the name of the supplier .,classmethod def get_name cls return mind
' log_task ' is called when an individual task instance on a single host completes . it is responsible for logging a single ' taskresult ' record to the database .,def log_task self result status kwargs log debug Logging task result for task s s host s self task name self task id result _host get_name if include_role in result _result del result _result include_role result task_start self task time_start result task_end datetime now host self get_or_create_host result _host get_name if self loop_items results self _dump_results result _result for item in self loop_items results append self _dump_results item _result results jsonutils loads jsonutils dumps results else results jsonutils loads self _dump_results result _result ignore_errors kwargs get ignore_errors False if LooseVersion ansible_version LooseVersion 2 3 0 if not isinstance ignore_errors bool ignore_errors True if ignore_errors yes else False self taskresult models TaskResult task self task host host time_start result task_start time_end result task_end result jsonutils dumps results status status changed result _result get changed False failed result _result get failed False skipped result _result get skipped False unreachable result _result get unreachable False ignore_errors ignore_errors db session add self taskresult db session commit if self task action setup and ansible_facts in result _result values jsonutils dumps result _result ansible_facts facts models HostFacts values values host facts facts db session add facts db session commit
a context manager that creates a temporary database .,contextmanager def temp_db db name None if name is None name temp_name db create name if not db exists name raise DatabaseError failed to create database s try yield name finally db drop name if db exists name raise DatabaseError failed to drop database s
overrides the default rules to be run .,abstractmethod def set_rules self rules raise NotImplementedError The ability to specify rules has not been implemented
send a json event to the server,def send_event self client event params urllib urlencode msg json dumps event response client get httpevent params return response
compute the integral of : math:`x ` over the reference triangle,def ex4 N hk quad Quadrature GaussTetrahedron N comp_quad Quadrature CompositeTetrahedron quad hk quad_points np asarray quad points d quad_weights np asarray quad weights d ii_quad np sum quad_weights quad_points 0 ii_comp_quad np sum comp_quad weights comp_quad points 0 ee np abs ii_quad ii_comp_quad logEvent hk f t quad int f t comp quad int f error f comp_quad h ii_quad ii_comp_quad ee return comp_quad h ee
"return a ( user , account , password ) tuple for given host .",def authenticators self host if host in self hosts return self hosts host elif default in self hosts return self hosts default else return None
tests whether get_best_candidate works . - whether the best of the two candidates is the one it should be .,def test_get_best_candidate self cand_one self EAss get_next_candidate cand_one result 1 self EAss update cand_one cand_two self EAss get_next_candidate cand_two result 0 self EAss update cand_two assert_equal cand_two self EAss get_best_candidate
returns an iterator over all intervals in this set that intersect with the specified interval .,def get self start end u n Returns an iterator over all intervals in this set that intersect n with the specified interval n for interval in self intervals if intervalsIntersect start end interval 0 interval 1 yield interval
"the swift grb catalog . search for grbs by trigger number , location , t90 , and date range .",def __init__ self update False self _update update super SwiftGRBCatalog self __init__ swiftgrb threeML_config catalogs Swift Swift GRB catalog Swift GRB catalog self _build_other_obs_instruments
returns an image object populated with metadata for image with supplied identifier .,def image_get request image_id image glanceclient request images get image_id if not hasattr image name image name None return image
return the marshaled credentials for the amqp connection .,property def _credentials self return x00 s x00 s self _args username self _args password
manager an history of max 20 items,def __clean_actions self if self __closed_section get_n_items 21 uri self __closed_section get_item_attribute_value 0 uri get_string encoded sha256 uri encode utf 8 hexdigest action El lookup_action encoded if action is not None El remove_action encoded self __closed_section remove 0
returns the object pointed to by `` ref `` .,def ref_to_obj ref if not isinstance ref basestring raise TypeError References must be strings if not in ref raise ValueError Invalid reference if ref gosa backend command CommandRegistry dispatch return getattr PluginRegistry getInstance CommandRegistry dispatch modulename rest ref split 1 try obj __import__ modulename except ImportError raise LookupError Error resolving reference s could not import module ref try for name in modulename split 1 rest split obj getattr obj name return obj except Exception raise LookupError Error resolving reference s error looking up object ref
returns a deep copy of the current config .,def copy self return copy deepcopy self
@param parentprofiles : profiles of the polymer @type parentprofiles : profilecollection @param map : map positions in this profilecollection to positions in the parent profile @type map : n.array of int,def __init__ self parentProfiles map2model self map map2model assert isinstance parentProfiles B ProfileCollection self pc parentProfiles self default None self _viewSignal _ViewSignal self initVersion self version
write ca trace pdb with seqres records for t_coffee .,def write_tcoffee_pdb self model fname m_ca model compress model maskCA n_lines len m_ca 13 if not len m_ca 13 0 n_lines 1 chain_id m_ca chain_id 0 if not chain_id m_ca chain_id A m_ca lenAtoms chain_id A n_res m_ca lenResidues head res_from 0 res_to 13 for i in range n_lines s 4i s 4i i 1 chain_id n_res if res_to n_res res_to n_res for resname in m_ca atoms residue_name res_from res_to s 3s resname head SEQRES s res_from 13 res_to 13 m_ca writePdb fname headlines head
filter source mtgjson data and dump testdata .,def main print Fetching mtgjson data mtgjson fetch_mtgjson DATA_DIR print Reading mtgjson data mtg_data mtgjson read_mtgjson DATA_DIR print Generating testdata testdata collections OrderedDict for setcode setdata in mtg_data items if setcode not in TEST_SETS_TO_CARDS continue testsetdata collections OrderedDict k v for k v in setdata items if k cards testsetdata cards c for c in setdata cards if c name in TEST_SETS_TO_CARDS setcode testdata setcode testsetdata print Writing testdata with open TARGET_MTGJSON_FILE w as mtgjson_testfile json dump testdata mtgjson_testfile ensure_ascii False indent 2 sort_keys True print Done
"show user the daily leaderboard , no login is required",views route leaderboard period def leaderboard_period period entries store get_leaderboard period if not entries entries query_leaderboard_moves period store set_leaderboard period entries timeout 1800 urls utils page_urls period return render_template leaderboard html entries entries urls urls
can make_second_order_heatmap handle ` top ` < 0 ?,def test_top_is_negative self make_second_order_heatmap df2 top 10 self assert_ True
gets the rank score for a given test case,def get_score_LR G test_case snapshots_dict tfidf_matrix op_id_to_bow_id LogReg columns_to_use metric_normalization cited_cases get_cited_cases G test_case snapshot_year test_case year 1 snapshot_df snapshots_dict vertex_metrics_ str int snapshot_year ancentors v index for v in G vs select year_le snapshot_year edgelist zip test_case index len ancentors ancentors edge_data get_edge_data G edgelist snapshot_df columns_to_use tfidf_matrix op_id_to_bow_id metric_normalization edge_status None ancestor_ranking get_case_ranking_logreg edge_data LogReg columns_to_use score score_ranking cited_cases ancestor_ranking return score
try to resolve conflicts by applying the conflict resolution functions defined in _ resolution_functions list .,def _resolve_conflicts agi info_list nt_dict for func in _resolution_functions fo func agi info_list imm_dict is_eosz_conflict get_l2_fn_from_info _eosz_token if fo return fo return None
context manager that initialize figure that should contain figure that should be compared with expected one .,contextmanager def image_comparison original_image_path figsize 10 10 tol 0 001 currentdir os path abspath os path dirname __file__ original_image_path os path join currentdir original_image_path with tempfile NamedTemporaryFile suffix png as f figure plt figure figsize figsize yield figure figure savefig f name error compare_images f name original_image_path tol tol if error raise AssertionError Image comparison failed nInformation format error
return the usual commands that every run uses .,def _generate_preliminary_cmds self time_interval prelim_cmds if self is_HPCjob prelim_cmds module load cuda s n self cuda_version prelim_cmds module load gcc 5 4 0 n n prelim_cmds prmtop s n self topology_file prelim_cmds sim s n n time_interval return prelim_cmds
list all the installed docker images .,def installed_images self images image_string self cli images for image in image_string split image_name image strip if image_name REPOSITORY and image_name none images append image_name return images
return a rfc3339 date - time string corresponding to the given unix - epoch timestamp .,def timestamptostr ts return datetimetostr utcfromtimestamp ts
bind the function ( fn ) to its class when part of a method for to it 's module for unbound function .,def _bind self classes fn options for name cls in classes for _ function_ in inspection methods cls if function_ fn container self classes setdefault cls __name__ Class cls container Method fn options return mod inspection module fn container self functions setdefault mod __name__ Module mod container Function fn options
: type context : behave.runner.context : type service_name : str,when I get the query_results from a query of service_name def step_i_get_the_query_results_from_a_query_of_service_api context service_name service_client context services service_name client data context services service_name details query context services service_name resp service_client post data json dumps data url_suffix query
"fetches the given configuration , using the key and default value to hint the type it should be . recognized types are : - logging runlevel if key starts with "" log . "" - boolean if default is a boolean ( valid values are ' true ' and ' false ' , anything else provides the default ) - integer or float if default is a number ( provides default if fails to cast ) - list of all defined values default is a list - mapping of all defined values ( key / value split via "" = > "" ) if the default is a dict",def get self key default None callDefault log runlevelToStr default if key startswith log else default isMultivalue isinstance default list or isinstance default dict val self getValue key callDefault isMultivalue if val default return val if key startswith log if val lower in none debug info notice warn err val log strToRunlevel val else msg config entry s is expected to be a runlevel key if default None msg defaulting to s callDefault log log CONFIG log configEntryTypeError msg val default elif isinstance default bool if val lower true val True elif val lower false val False else msg config entry s is expected to be a boolean defaulting to s key str default log log CONFIG log configEntryTypeError msg val default elif isinstance default int try val int val except ValueError msg config entry s is expected to be an integer defaulting to i key default log log CONFIG log configEntryTypeError msg val default elif isinstance default float try val float val except ValueError msg config entry s is expected to be a float defaulting to f key default log log CONFIG log configEntryTypeError msg val default elif isinstance default list pass elif isinstance default dict valMap for entry in val if in entry entryKey entryVal entry split 1 valMap entryKey strip entryVal strip else msg ignoring invalid s config entry expected a mapping but s was missing key entry log log CONFIG log configEntryTypeError msg val valMap return val
decorator to throw an exception formatted with the line of the conanfile where the error ocurrs . : param reference : reference of the conanfile : return :,contextmanager def conanfile_exception_formatter conanfile_name func_name try yield except Exception as exc msg _format_conanfile_exception conanfile_name func_name exc raise ConanExceptionInUserConanfileMethod msg
"return the directory where tensorflow summaries are placed . if the directory does not exist , it is created .",def get_output_tb_dir imdb weights_filename outdir osp abspath osp join __C ROOT_DIR tensorboard __C EXP_DIR imdb name if weights_filename is None weights_filename default outdir osp join outdir weights_filename if not os path exists outdir os makedirs outdir return outdir
"start the metrics service , ensure its running , and its ip is known",def ensure_metrics_available self if not self event metrics_options enabled return self event metrics self ecs locate_metrics_service logger info Metrics info s metrics if not metrics self ecs create_metrics_service self event metrics_options raise ServicesStartingException Triggered metrics start deploy metrics deployments 0 ready deploy desiredCount deploy runningCount logger info Deploy info s deploy if not ready raise ServicesStartingException Waiting for metrics metric_ip container_arn self ecs locate_metrics_container_ip if not metric_ip raise Exception Unable to locate metrics IP even though its running self event influxdb_private_ip metric_ip self event metric_container_arn container_arn return self event
calculate coverage for genome intervals .,def bam2cov bam bed out sys stdout mapq 0 bufferSize 1000000 verbose 1 if verbose sys stderr write Loading intervals n c2i entries load_intervals bed verbose if verbose sys stderr write s intervals from s chromosomes loaded n entries len c2i if verbose sys stderr write Parsing alignments n counts parse_bam bam mapq c2i entries bufferSize verbose if verbose sys stderr write sense antisense alignments s s n sum counts 0 sum counts 1 for sense antisense line in zip counts 0 counts 1 open bed out write s t s t s n line 1 sense antisense
creates an appropriate subclass from a file path or magic string .,classmethod def from_string cls path if path APPENGINE_CREDENTIALS return AppengineCredentials if path GCE_CREDENTIALS return GCECredentials return FileCredentials path
"fetch : if we get a zero - length blob , everything works",def testFetchHappyZeroLengthBlob self def Read self request timeout None del timeout self request request response isolate_storage bytestream_pb2 ReadResponse response data yield response self mock ByteStreamStubMock Read Read s self get_server replies s fetch abc123 1 0 reply replies next self assertEqual 0 len reply
translates jobconfig.input_reader_params to json serializable format .,classmethod def params_to_json cls params return params
"prints dev_appserver log to stderr , works only if app is stopped .",def dump_log self print sys stderr 60 print sys stderr dev_appserver py log for s self app_id print sys stderr 60 for l in self _log or strip n splitlines sys stderr write s n l print sys stderr 60
fluch of file like objects .,def is_open self raise NotImplementedError
extract all images in the content : param text : : return :,def extract_images text extensions ExtractImagesExtension mkd markdown Markdown extensions extensions html mkd convert text return mkd images
retrieve all of the updates for the given service i d,def get_service_updates self service_id sql SELECT FROM db_service_status JOIN db_submitter_info ON db_service_status submission_id db_submitter_info submission_id WHERE service_id ORDER BY timestamp ASC results self _sql sql service_id fetchall rtn_list for r in results status Unknown if r service_status G SERVICE_STATUS SUBMITTED status Submitted elif r service_status G SERVICE_STATUS CANCELED status Canceled elif r service_status G SERVICE_STATUS SATISFIED status Satisfied elif r service_status G SERVICE_STATUS RESPONSE status Response tmp_dict service_status r service_status service_status_text status service_comments r service_comments timestamp r timestamp timestamp_text datetime datetime fromtimestamp int r timestamp strftime b d Y H M S z service_id r service_id rtn_list append tmp_dict return rtn_list
returns name that is unique within the model .,property def fullname self return FactTypes self name
make sure the value of progressbar is expected,def assertValue self expected_value procedurelogger expectedResult update progressBar s value to s expected_value assert self progressBar value expected_value actual value is s expected value is s self progressBar value expected_value
verify that the state - changed : sensitive event is being properly raised .,def test_sensitivity_event self sensitivity_button self app slControl findPushButton Toggle Sensitivity self assertTrue self textbox sensitive listener EventListener with listener listenTo self textbox sensitivity_button click sleep config SHORT_DELAY self assertFalse self textbox sensitive assert listener containsEvent self textbox object state changed sensitive qty 1 with listener listenTo self textbox sensitivity_button click sleep config SHORT_DELAY self assertTrue self textbox sensitive assert listener containsEvent self textbox object state changed sensitive qty 1
send deployments to new relic and speedcurve as specified .,def deploy_all app nr_api_key None nr_app_ids None sc_api_key None sc_site_id None from_tag None to_tag None verbose False u n Send deployments to New Relic and SpeedCurve as specified n n Return is True for success False for errors n n Keyword Arguments n app The name of the app kuma or kumascript n nr_api_key A New Relic Admin API key or None n nr_app_ids A list of New Relic application IDs can be empty n sc_api_key A SpeedCurve API key or None n sc_site_id A SpeedCurve site ID or None n from_tag Commit hash for what was deployed or None n to_tag Commit hash for what is now deployed or None n verbose Print status and responses n if to_tag revision to_tag else ts datetime now replace microsecond 0 revision ts isoformat if to_tag and from_tag from_sub_tag from_tag 7 to_sub_tag to_tag 7 compare_url app_compare app from_sub_tag to_sub_tag description compare_url else description None passed True count 0 nr_app_ids nr_app_ids or for app_num app_id in enumerate nr_app_ids response deploy_newrelic app_id nr_api_key revision description if response status_code 201 success u SUCCESS count 1 else success u FAILURE passed False if verbose safer_id u s_APP_ID_ d app upper app_num content response content replace app_id safer_id print u s s Deployment to New Relic application s d s success response status_code app app_num content if sc_api_key and sc_site_id response deploy_speedcurve sc_site_id sc_api_key revision description if response status_code 200 success u SUCCESS count 1 else success u FAILURE passed False if verbose safer_id u SITE_ID_0 content response content replace sc_site_id safer_id print u s s Deployment to SpeedCurve site ID s s success response status_code sc_site_id content return bool count and passed
decide whether a tag namespace is editable by a user,def allows_tag_namespace_for model_obj ns user if user is_staff or user is_superuser return True if not ns startswith system return True return False
check if a user belongs to admin group .,library global_function def user_is_admin user return user groups filter name Admin exists
object that understands versioning for a package,def __init__ self package self package package self release None self version None self _cached_version None
return the current state of the crawling robot,def getCurrentState self return self state
atom : : = ( testlist ) atom : : = ( ) atom : : = [ testlist ] atom : : = [ ] atom : : = { dictmaker } atom : : = { } atom : : = ` testlist ` atom : : = name atom : : = number atom : : = string_list,def p_atom self args
prints video information and usage output to stdout,def print_info self u video_data pafy new self url print u Now playing video_data title u video_data duration u if self verbose print u URL self url print u Description video_data description if self show_video print u Showing video in an external window
test to see that input is handled correctly .,def test_forward_backward_input_handling space1 odl uniform_discr 0 1 10 lin_ops odl ZeroOperator space1 odl ZeroOperator space1 g odl solvers ZeroFunctional space1 odl solvers ZeroFunctional space1 f odl solvers ZeroFunctional space1 h odl solvers ZeroFunctional space1 x0 noise_element space1 x x0 copy niter 3 forward_backward_pd x f g lin_ops h tau 1 0 sigma 1 0 1 0 niter niter assert x x0 with pytest raises ValueError forward_backward_pd x f g lin_ops h tau 1 0 sigma 1 0 niter niter g_too_many odl solvers ZeroFunctional space1 odl solvers ZeroFunctional space1 odl solvers ZeroFunctional space1 with pytest raises ValueError forward_backward_pd x f g_too_many lin_ops h tau 1 0 sigma 1 0 1 0 niter niter space2 odl uniform_discr 1 2 10 x noise_element space2 with pytest raises ValueError forward_backward_pd x f g lin_ops h tau 1 0 sigma 1 0 1 0 niter niter
not all of pyobjc and python understand unicode paths very well yet,def ensure_utf8 s if isinstance s unicode return s encode utf8 return s
"normal binary operator like 1 + 2 or 2 * 3 , etc .",def LeftBinaryOp p w left rbp return ast ArithBinary word ArithId w left p ParseUntil rbp
"returns a string representing the platform this build is targetted for . possible values : ' win ' , ' mac ' , ' linux ' , ' ios ' , ' android '",memoize def platform if OS in gyp_defines if android in gyp_defines OS return android else return gyp_defines OS elif IsWindows return win elif IsLinux return linux else return mac
"removes all occurences of an element from the tree . start at specified root_node if specified , otherwise start at tree 's root .",def remove_elements self name element None if not element element self root element remove_elements name
load plugins from various sources :,def plugins_load global pluginmgr if pluginmgr is not None plugins_close pluginmgr PluginManager
initiate the engine with source and envs @params : ` source ` : the souce text ` envs ` : the env data,def __init__ self source envs super TemplatePyPPL self __init__ source envs self engine TemplatePyPPLEngine source envs self source source
get more input if possible .,def grab_input self if not self file return if len self input self pos MIN_WINDOW return data self file read MIN_WINDOW if data is None or data self file None if self pos 2 MIN_WINDOW self del_pos MIN_WINDOW self del_line self input MIN_WINDOW count n self pos MIN_WINDOW self input self input MIN_WINDOW data else self input self input data
"take a boundary edge ( a , b ) , and in the list of points find a point ' c ' that lies on the left of ab and maximizes the angle acb",JavaScript def find_third_point a b pts_list edges found 0 minimum 10 8 c_index 1 pt_index 1 for c_point in pts_list c_index 1 if c_index a and c_index b and is_on_the_left c_index a b pts_list edge_intersects edge_intersects_edges a c_index pts_list edges or edge_intersects_edges b c_index pts_list edges if not edge_intersects crit criterion a b c_index pts_list if crit minimum minimum crit pt_index c_index found 1 if found 0 raise TriangulationError ERROR Optimal point not found in find_third_point return pt_index
"return a tuple of c_byte , converted from a list of python variables .",def c_bytes x return c_byte len x x
add one or more sprites to this display .,def add_sprites self sprites with self lock self sprites_to_load update sprites
create the wavelength lines for the input file,def _create_wavelength_lines self return self wavelength
get callbacks from handler for the visited node,def get_callbacks self node klass node __class__ methods self _cache get klass if methods is None handler self handler kid klass __name__ lower e_method getattr handler visit_ s kid getattr handler visit_default None l_method getattr handler leave_ s kid getattr handler leave_default None self _cache klass e_method l_method else e_method l_method methods return e_method l_method
get a unicode safe string representation of an object,def tostr object encoding None if isinstance object basestring if encoding is None return object else return object encode encoding if isinstance object tuple s for item in object if isinstance item basestring s append item else s append tostr item s append s append return join s if isinstance object list s for item in object if isinstance item basestring s append item else s append tostr item s append s append return join s if isinstance object dict s for item in object items if isinstance item 0 basestring s append item 0 else s append tostr item 0 s append if isinstance item 1 basestring s append item 1 else s append tostr item 1 s append s append return join s try return unicode object except return str object
how many rules will be needed by this superset construction ?,def rulesRequired supersets rulecounts if supersets is None return 0 total 0 for superset in supersets for part in superset total rulecounts part return total
get the hamming weight of a bitwise xor on two determinants . this will show how the number of orbitals in which they have different occupations,def n_excit idet jdet if idet jdet return 0 aexc n_excit_spin idet jdet 0 bexc n_excit_spin idet jdet 1 return aexc bexc
compute the inverse of a sparse or dense matrix,def spinv a if SP issparse a ai SPla inv a else ai la inv a return ai
returns the frequent itemsets of this model .,since 1 4 0 def freqItemsets self return self call getFreqItemsets map lambda x FPGrowth FreqItemset x 0 x 1
"perform rollouts , that is , given a set of samples , determine all the variables that are relevant to evaluating the cost function .",def performRollout self sample Perform rollouts that is given a set of samples determine all the variables that are relevant to evaluating the cost function n n param in sample The sample n return The variables relevant to computing the cost n raise NotImplementedError subclasses must override performRollout
"mask an octet string using the given masking key . the following masking algorithm is used , as defined in rfc 6455 :",def mask key original if len key 4 raise ValueError invalid masking key s key key map ord key masked bytearray original for i in xrange len masked masked i key i 4 return masked
"output function , passes first argument on , in case it is referenced",def out self gene val return val
plots an ` nstd ` sigma error ellipse based on the specified covariance matrix ( ` cov ` ) . additional keyword arguments are passed on to the ellipse patch artist .,def plot_cov_ellipse cov pos nstd 2 ax None kwargs u n Plots an nstd sigma error ellipse based on the specified covariance n matrix cov Additional keyword arguments are passed on to the n ellipse patch artist n n Parameters n n cov The 2x2 covariance matrix to base the ellipse on n pos The location of the center of the ellipse Expects a 2 element n sequence of x0 y0 n nstd The radius of the ellipse in numbers of standard deviations n Defaults to 2 standard deviations n ax The axis that the ellipse will be plotted on Defaults to the n current axis n Additional keyword arguments are pass on to the ellipse patch n n Returns n n A matplotlib ellipse artist n def eigsorted cov vals vecs np linalg eigh cov order vals argsort 1 return vals order vecs order if ax is None ax plt gca vals vecs eigsorted cov theta np degrees np arctan2 vecs 0 1 width height 2 nstd np sqrt vals ellip Ellipse xy pos width width height height angle theta kwargs ax add_artist ellip return ellip
provides a string representation of the double .,def __repr__ self address hex id self class_name self __class__ __name__ return of r object at format class_name self _doubles_target address
@param aty : array type information . @type aty : the value of wsdl : arraytype .,def __init__ self schema root aty SXAttribute __init__ self schema root if aty endswith self aty aty 2 else self aty aty
maps keys for attachment details view .,def _translate_attachment_detail_view _context vol d _translate_attachment_summary_view _context vol return d
called when a security group loses a member .,def trigger_instance_remove_security_group_refresh self context instance group_name raise NotImplementedError
get the response and close the connection .,def close self try self conn getresponse except Exception as excep LOG debug _ Exception during HTTP connection close in VMWareHTTpWrite Exception is s excep super VMWareHTTPWriteFile self close
picks a host that is up and has the fewest volumes .,def schedule_create_volume self context volume_id _args _kwargs elevated context elevated volume_ref db volume_get context volume_id availability_zone volume_ref get availability_zone zone host None None if availability_zone zone _x host availability_zone partition if host and context is_admin service db service_get_by_args elevated host nova volume if not utils service_is_up service raise exception WillNotSchedule host host driver cast_to_volume_host context host create_volume volume_id volume_id _kwargs return None results db service_get_all_volume_sorted elevated if zone results service gigs for service gigs in results if service availability_zone zone for result in results service volume_gigabytes result if volume_gigabytes volume_ref size FLAGS max_gigabytes msg _ All hosts have too many gigabytes raise exception NoValidHost reason msg if utils service_is_up service driver cast_to_volume_host context service host create_volume volume_id volume_id _kwargs return None msg _ Is the appropriate service running raise exception NoValidHost reason msg
"gets the cartesian product of a list of lists of values . for example , if the list is [ [ ' on ' , ' off ' ] , [ ' on ' , ' off ' ] ] , then the result will be a list of the following . * [ ' on ' , ' on ' ] * [ ' on ' , ' off ' ] * [ ' off ' , ' on ' ] * [ ' off ' , ' off ' ] : param lists : list of list of values . : return : cartesian product of values .",staticmethod def get_cartesian_product lists return i for i in itertools product lists
returns a single nic matching the given keyword arguments .,def get self kwargs result self filter kwargs if not result raise NICDoesNotExist NIC does not exist count len result if count 1 return result 0 else raise MultipleNICReturned Returned s instead of one NIC count
"draw a square with color ' color_out ' and given size at a given position ( x , y ) then draw four square of size ( size/5 ) with color ' color_in ' at : 1 ) coord : ( y + ( size / 5 ) , x + ( size / 5 ) ) 2 ) coord : ( y + ( size / 5 ) , x + ( 3 * size / 5 ) ) 3 ) coord : ( y + ( 3 * size / 5 ) , x + ( size / 5 ) ) 4 ) coord : ( y + ( 3 * size / 5 ) , x + ( 3 * size / 5 ) )",def draw_multisquare image position size color_out 255 color_in 255 x y position small_size size 5 image draw_poly image box x y x size y size color color_out square1 box x small_size y small_size x 2 small_size y 2 small_size square2 box x 3 small_size y small_size x 4 small_size y 2 small_size square3 box x small_size y 3 small_size x 2 small_size y 4 small_size square4 box x 3 small_size y 3 small_size x 4 small_size y 4 small_size squares square1 square2 square3 square4 for square in squares image draw_poly image square color color_in return image
get a list of avalable class names .,property def class_names self u return name for name in self _classes
"clears all of the fatal signal hooks without executing them . if any of the hooks passed a ' cancel ' function to add_hook ( ) , then those functions will be called , allowing them to free resources , etc .",def fork global _hooks for hook cancel run_at_exit in _hooks if cancel cancel _hooks
valuation of european call option in m76 model via lewis ( 2001 ) fourier - based approach : integration function .,def M76_int_func_sa u S0 K T r volatility lamb mu delta char_func_value M76_char_func_sa u 0 5 1j T r volatility lamb mu delta int_func_value 1 u 2 0 25 np exp 1j u np log S0 K char_func_value real return int_func_value
"executes cmd as a sub - process . returns the file objects ( child_stdout_and_stderr , child_stdin ) .",def popen4 cmd bufsize 0 mode t command _get_str cmd i oe os_popen popen4 None command mode bufsize return oe i
reads a ` supercell ` and creates the gulp cell,Sile_fh_open def read_supercell self key None kwargs self set_supercell_key key f _ self step_to self _keys sc if not f raise ValueError SileGULP tries to lookup the SuperCell vectors using key self _keys sc Use set_supercell_key to search for different name This could not be found found in file self file self readline cell np empty 3 3 np float64 for i in 0 1 2 l self readline split cell i float x for x in l 3 return SuperCell cell
example of a function that attempts to convert anything to a string .,basic_wrapper def plain_text argument return str argument
test starting and creating server when a server is currently running .,def test_flexx_in_thread3 res def main loop asyncio new_event_loop asyncio set_event_loop loop app create_server app start def try_start try app start except RuntimeError res append start fail def try_create try main except RuntimeError res append create fail t threading Thread target main t start while not app current_server _running time sleep 0 01 with raises RuntimeError app start with raises RuntimeError app create_server t1 threading Thread target try_start t1 start t1 join t2 threading Thread target try_create t2 start t2 join app stop t join assert res start fail create fail
generator to get contiguous address ranges with start and end address,def _enum_continguous_addr_start_end addr_list for _ b in itertools groupby enumerate addr_list lambda x_y x_y 1 x_y 0 b list b yield b 0 1 b 1 1
get first non none iterm from list : param iterable : : param func : : param kwargs : : return :,def first iterable func lambda L L is not None kwargs it el for el in iterable if func el if default in kwargs return next it kwargs default return next it
"handle the command args and display usage if needed . note that the usage is in english as we do n't necessarily have the language file to use . also , this will be run in the server , which should n't make mistakes .",def ProcessCommandArgs args levelChoices error io LEVEL ERROR top io LEVEL TOP warn io LEVEL WARN info io LEVEL INFO verbose io LEVEL VERBOSE debug io LEVEL DEBUG version 1 2 7 parser argparse ArgumentParser prog EdAsm py description Token assembler for Edison and Ed Py version s version parser add_argument v action version version prog s version parser add_argument r reghelp action store_true dest reghelp help Output all of the device types locations and registers parser add_argument d debug action store_true dest debug help Output parsing information parser add_argument s source action store_true dest source help Output source info with debug info parser add_argument w wav dest wavFilename default None help Output a wav file of the assembled code parser add_argument b bin type argparse FileType wb 0 dest binFile default None help Output a binary file of the assembled code parser add_argument p preamble action store_true dest preamble help Add preamble to the binary file written parser add_argument l type util LowerStr choices list zip levelChoices 0 default error help Output level default default s All output from previous levels and this one will be generated parser add_argument srcPath metavar SRC nargs default None help Path to the source to be assembled parsed parser parse_args args outputLevel x 1 for x in levelChoices if x 0 parsed l 0 if outputLevel 0 io Out SetSink io SINK CONSOLE io Out SetMaxLevel outputLevel if parsed source and not parsed debug print Warning source or s makes no sense without debug or d if parsed preamble and parsed binFile is None print Warning preamble or p makes no sense without bin or b if parsed reghelp print Device type locations and register help print hl_parser dump_reg_help sys exit 0 if parsed srcPath is None print Error missing source path sys exit 0 return parsed
tests when a disruption fail to publish to rabbitmq : return :,def test_disruption_with_rabbitmq_exception disruption models Disruption disruption contributor models Contributor disruption contributor_id disruption contributor id disruption cause models Cause disruption cause wording CauseTest disruption cause category models Category disruption cause category name CategoryTest disruption reference DisruptionTest localization models PTobject localization uri stop_area 123 localization type stop_area disruption localizations append localization wording models Wording wording key key_1 wording value value_1 disruption cause wordings append wording wording models Wording wording key key_2 wording value value_2 disruption cause wordings append wording tag models Tag tag name rer disruption tags append tag disruption status published chaos publisher publish MagicMock return_value False to_rabbitmq_not_sent send_disruption_to_navitia disruption eq_ to_rabbitmq_not_sent False
attempts to match a given header to a field of the imported model .,def _match_header self header fields options for field in fields if header lower field name lower or header lower field string lower return field if not in header return traversal subfields fields for section in header split match self _match_header section strip subfields options if not match return field match 0 subfields field fields traversal append field return traversal
check arguments and options for right types,def check_args self args arguments options self parse_arguments args named_args unnamed_args idx 0 arg_names_items self arg_names items for argument in arguments if len self arg_names idx key arg_type arg_names_items idx try named_args key arg_type argument except Exception as e self raise_tcl_error Cannot cast named argument s to type s with exception s key arg_type str e else unnamed_args append argument idx 1 for key in options if key not in self option_types and key timeout self raise_tcl_error Unknown parameter s key try if key timeout named_args key self option_types key options key else named_args key int options key except Exception as e self raise_tcl_error Cannot cast argument s to type s with exception s key self option_types key str e for key in self required if key not in named_args self raise_tcl_error Missing required argument s key return named_args unnamed_args
will load directly from keyword - without reorder ; ignoring zero .,def loadKeyword self fault_block_kw ok self _load_keyword fault_block_kw if not ok raise ValueError The fault block keyword had wrong type size type s size d grid_size d fault_block_kw typeName len fault_block_kw self grid_ref getGlobalSize
"print ' = = = = = = = = = = = = = add = = = = = = = = = = = = ' print ' # # # current row ' , self.__currentrow print ' numberlist : ' , self.__numberlist for i in range(1,len(self.__entries_func ) ) : tmp= self.__numberlist[i ] gridinfo= self.__entries_func[tmp].grid_info ( ) if len(gridinfo)!=0 : print ' row ' , str(i ) , ' entries list [ ' , str(tmp ) , ' ] : ' , self.__entries_func[tmp].grid_info()['row ' ] else : print ' row ' , str(i ) , ' empty ' #",def btn_add_click self if self __CurrentRow self __MaxRow self __CurrentRow self __CurrentRow 1 self __CurGridRow self __CurGridRow 1 add_index self __NumberList self __CurrentRow print Added Row self __CurrentRow print add_index NumberList 0 1 format self __CurrentRow add_index print Grid Row self __CurGridRow self __entries_Func add_index grid row self __CurGridRow column 0 self __entries_PinNumb add_index grid row self __CurGridRow column 1 self __btns_clear add_index grid row self __CurGridRow column 2 elif self __CurrentRow self __MaxRow print Max of Row is self __MaxRow
find the target in the partitions . files might be split to different framework - partition,def __findInFrwPartitions self target outClass innerClass TargetFinder __extractInnerClass target match self pathRegex search outClass if match None part1 match group part1 part2 match group part2 part3 match group part3 for partition in TargetFinder PARTITIONS if not partition endswith jar out partition jar out newTarget os path join partition part2 part3 if os path exists newTarget return TargetFinder __concatInnerClass outClass innerClass return target
"initializes tensorflow variables , which are returned by ` initializables ` property and uses feed dictionary returned by ` initializable_feeds ` property defined at icompilable interface and implemented by descendants .",def initialize self session None force False session self enquire_session session initializables self initializables if initializables misc initialize_variables variables initializables session session force force feed_dict self initializable_feeds
create an options parser for bin / ansible,def parse self self parser CLI base_parser usage prog U repository options connect_opts True vault_opts True runtask_opts True subset_opts True inventory_opts True module_opts True runas_prompt_opts True self parser add_option purge default False action store_true help purge checkout after playbook run self parser add_option o only if changed dest ifchanged default False action store_true help only run the playbook if the repository has been updated self parser add_option s sleep dest sleep default None help sleep for random interval between 0 and n number of seconds before starting This is a useful way to disperse git requests self parser add_option f force dest force default False action store_true help run the playbook even if the repository could not be updated self parser add_option d directory dest dest default None help directory to checkout repository to self parser add_option U url dest url default None help URL of the playbook repository self parser add_option full dest fullclone action store_true help Do a full clone instead of a shallow one self parser add_option C checkout dest checkout help branch tag commit to checkout Defaults to behavior of repository module self parser add_option accept host key default False dest accept_host_key action store_true help adds the hostkey for the repo url if not already added self parser add_option m module name dest module_name default self DEFAULT_REPO_TYPE help Repository module name which ansible will use to check out the repo Default is s self DEFAULT_REPO_TYPE self parser add_option verify commit dest verify default False action store_true help verify GPG signature of checked out commit if it fails abort running the playbook This needs the corresponding VCS module to support such an operation self parser add_option clean dest clean default False action store_true help modified files in the working repository will be discarded self parser add_option track subs dest tracksubs default False action store_true help submodules will track the latest changes This is equivalent to specifying the remote flag to git submodule update self parser set_defaults inventory None super PullCLI self parse if not self options dest hostname socket getfqdn self options dest os path join ansible pull hostname self options dest os path expandvars os path expanduser self options dest if self options sleep try secs random randint 0 int self options sleep self options sleep secs except ValueError raise AnsibleOptionsError s is not a number self options sleep if not self options url raise AnsibleOptionsError URL for repository not specified use h for help if self options module_name not in self SUPPORTED_REPO_MODULES raise AnsibleOptionsError Unsuported repo module s choices are s self options module_name join self SUPPORTED_REPO_MODULES display verbosity self options verbosity self validate_conflicts vault_opts True
import certificate from path into keystore located on keystore_path as alias,def import_cert_path module executable path keystore_path keystore_pass alias import_cmd s importcert noprompt keystore s storepass s file s alias s executable keystore_path keystore_pass path alias if module check_mode module exit_json changed True import_rc import_out import_err module run_command import_cmd check_rc False diff before n after s n alias if import_rc 0 return module exit_json changed True msg import_out rc import_rc cmd import_cmd stdout import_out error import_err diff diff else return module fail_json msg import_out rc import_rc cmd import_cmd
"adds , updates or deletes lambda stream ( dynamodb , kinesis ) event notifications . : param module : : param aws : : return :",def lambda_event_stream module aws client aws client lambda facts dict changed False current_state absent state module params state api_params dict FunctionName module params lambda_function_arn source_params module params source_params source_arn source_params get source_arn if source_arn api_params update EventSourceArn source_arn else module fail_json msg Source parameter source_arn is required for stream event notification batch_size source_params get batch_size if batch_size try source_params batch_size int batch_size except ValueError module fail_json msg Source parameter batch_size must be an integer found 0 format source_params batch_size source_param_enabled module boolean source_params get enabled True try facts client list_event_source_mappings api_params EventSourceMappings if facts current_state present except ClientError as e module fail_json msg Error retrieving stream event notification configuration 0 format e if state present if current_state absent starting_position source_params get starting_position if starting_position api_params update StartingPosition starting_position else module fail_json msg Source parameter starting_position is required for stream event notification if source_arn api_params update Enabled source_param_enabled if source_params get batch_size api_params update BatchSize source_params get batch_size try if not module check_mode facts client create_event_source_mapping api_params changed True except ClientError ParamValidationError MissingParametersError as e module fail_json msg Error creating stream source event mapping 0 format e else api_params dict FunctionName module params lambda_function_arn current_mapping facts 0 api_params update UUID current_mapping UUID mapping_changed False if source_params get batch_size and source_params batch_size current_mapping BatchSize api_params update BatchSize source_params batch_size mapping_changed True if source_param_enabled is not None if source_param_enabled if current_mapping State not in Enabled Enabling api_params update Enabled True mapping_changed True elif current_mapping State not in Disabled Disabling api_params update Enabled False mapping_changed True if mapping_changed try if not module check_mode facts client update_event_source_mapping api_params changed True except ClientError ParamValidationError MissingParametersError as e module fail_json msg Error updating stream source event mapping 0 format e elif current_state present api_params dict UUID facts 0 UUID try if not module check_mode facts client delete_event_source_mapping api_params changed True except ClientError ParamValidationError MissingParametersError as e module fail_json msg Error removing stream source event mapping 0 format e return camel_dict_to_snake_dict dict changed changed events facts
do the resource binding requested by a client connected .,def do_bind self stanza fr stanza get_from if fr and fr self peer r stanza make_error_response forbidden self send r r free return resource_n stanza xpath_eval bind bind bind resource bind BIND_NS if resource_n resource resource_n 0 getContent else resource auto if not resource r stanza make_error_response bad request else self unset_iq_set_handler bind BIND_NS r stanza make_result_response self peer set_resource resource q r new_query BIND_NS bind q newTextChild None jid to_utf8 self peer as_unicode self state_change authorized self peer r set_to None self send r r free
"return a string with the grounded representation of "" atom "" with respect to "" assignment "" .",def _ground_atom atom assignment names for name types in atom signature if name in assignment names append assignment name else names append name return _get_grounded_string atom name names
"truncate a string to maxlen characters , including ellipsis .",def trim_str text maxlen 60 assert isinstance text basestring s should be a string not a s text type text if len text maxlen return text maxlen 3 return text
index to corresponding three letter amino acid name .,def index_to_three i return dindex_to_3 i
select the object with given i d as the currently active object .,def disordered_select self id self selected_child self child_dict id
runs the user - supplied progress calculation rule,def _eval_progress self match _locals k safe_float v for k v in match groupdict items if x not in _locals _locals x safe_float x for x in match groups try return int eval self progress_expr _locals except return None
ca n't create a shake without a name .,def test_shake_create_error_on_name self self user stripe_plan_id mltshp double self user save arguments name title title description My little corner of the world response self post_url shake create arguments arguments self assertEqual response effective_url self get_url shake create self assertTrue response body find That URL is not valid 1
return the shape of the underlying matrix .,property def shape self return self X shape
ensure only one logger window open at a time,on_trait_change window opening def _handle_window_open self evt app self window application for win in app windows if win active_task if win active_task id pychron logger task evt veto True break
"returns x matrix x=[[1,xi , xi^2 , ... ] . . . [ 1,xj , xj^2 , ... ] ]",def _get_X self xs None if xs is None xs self clean_xs cols pow xs i for i in range self degree 1 return column_stack cols
helper to execute a post manageable_volumes api call .,def _get_resp_post self body version 3 8 req webob Request blank v3 s manageable_volumes fake PROJECT_ID req method POST req headers Content Type application json req headers OpenStack API Version volume version req environ cinder context self _admin_ctxt req body jsonutils dump_as_bytes body res req get_response app return res
returns a list of groups through view builder .,def _get_groups self req is_detail context req environ cinder context filters req params copy marker limit offset common get_pagination_params filters sort_keys sort_dirs common get_sort_params filters groups self group_api get_all context filters filters marker marker limit limit offset offset sort_keys sort_keys sort_dirs sort_dirs if is_detail groups self _view_builder detail_list req groups else groups self _view_builder summary_list req groups return groups
"initialize class , wrap wsgi app , and set up given limits .",def __init__ self application limits None limiter None kwargs base_wsgi Middleware __init__ self application if limiter is None limiter Limiter else limiter importutils import_class limiter if limits is not None limits limiter parse_limits limits self _limiter limiter limits or DEFAULT_LIMITS kwargs
returns an expiring report . : return :,def expiring_certificates kwargs ttl kwargs get ttl 30 now arrow utcnow validity_end now timedelta days ttl query database session_query Certificate query filter_by_deployment query deployment kwargs get deployed query filter_by_validity query validity valid query filter_by_validity_end query validity_end validity_end return query
writing all files fns_ins into fn_out,def merge_files fns_in fn_out with open fn_out w as fout for fn_in in fns_in with open fn_in as fin for line in fin fout write line
turn a command into its reasonably grammatical equivalent .,def _englishify_command command verb target command determiner the preposition None obj2 None if LOCATION in target preposition to if verb SEARCH_PROP else None obj1 target LOCATION elif PATIENT in target obj1 target PATIENT elif THEME in target obj1 target THEME if SOURCE in target obj2 from target SOURCE else print Warning Couldn t understand this target when building a response target try obj1 target values 0 except IndexError obj1 unknown try verb ACTION_ALIASES verb except KeyError if verb in SIMPLE_ACTUATORS or verb in COMPLEX_ACTUATORS determiner all obj1 s else determiner a response join verb preposition determiner obj1 if preposition else join verb determiner obj1 if obj2 response obj2 return response
place any commands to setup projectname here,def setup_app command conf vars config load_environment conf global_conf conf local_conf Base metadata create_all bind Session bind
gets supported files ' names from the path given as parameter,def get_presentation_elements_from_path self self presentation_elements Logger debug Presentation Creating the presentation elements from folder self media_path for filename in self presentation_filenames extension filename split 1 relative_filename self media_path filename Logger debug Relative filename s relative_filename if extension in self VIDEO_FORMATS self presentation_elements append PresentationElement ContentType Video relative_filename elif extension in self IMAGE_FORMATS self presentation_elements append PresentationElement ContentType Image relative_filename elif extension in self TEXT_FORMATS self presentation_elements append PresentationElement ContentType Text relative_filename else Logger error Presentation Unsupported filetype s extension
calculate an optimal array replication structure for a set of vectors .,def optimal_array_structure ordering_elements actual_values_elements None element_ordering_arrays dict ordering_elements if actual_values_elements is None actual_values_elements element_ordering_arrays actual_value_arrays dict actual_values_elements if set actual_value_arrays keys set element_ordering_arrays keys msg Names in values arrays do not match those in ordering arrays raise ValueError msg n_elements len ordering_elements element_priorities name n_elements index for index name array in enumerate ordering_elements base_structure GroupStructure from_component_arrays element_ordering_arrays target_structure _optimal_dimensioning_structure base_structure element_priorities if not target_structure elements_length len ordering_elements 0 1 vector_dims_shape elements_length else vector_dims_shape tuple struct size for _ struct in target_structure elements_and_dimensions base_structure build_arrays vector_dims_shape actual_value_arrays elements_and_dimensions name array dims for name array dims in six iteritems elements_and_dimensions if len dims primary_dimension_elements set name for name _ in target_structure if vector_dims_shape 1 shape else shape vector_dims_shape return shape primary_dimension_elements elements_and_dimensions
use exif class to parse latitude and longitude from exif .,def _read_lat_lon self filename exif EXIF filename lon lat exif extract_lon_lat return lat lon
turrets manager should correctly handle message if no uuid is provided,def test_update self res self manager update not present self assertFalse res
set the frequency sweep parameters on the specified or active channel,def set_frequency_sweep self start_freq stop_freq num_points kwargs raise NotImplementedError must implement with subclass
test bulk shear with observed sounding .,def test_bulk_shear data get_upper_air_data datetime 2016 5 22 0 DDC u v bulk_shear data pressure data u_wind data v_wind heights data height depth 6000 units meter truth 29 899581266946115 14 389225800205509 units knots assert_almost_equal u to knots truth 0 8 assert_almost_equal v to knots truth 1 8
"upload kits to the voltdb download site . args : version - version number such as 7.1.2 upload_type - upload types are "" ent "" ( only ent kit ) and "" all "" for all kits remote_dir - directory to upload to kits_dir - directory to pull kits from dry_run - if true , the upload will not be done",def upload_kits version upload_type ent remote_dir var www downloads voltdb com technologies server kit_dir home test releases released dry_run False if not version exit FATAL You must specify a version number that exists in tests releases released upload_type upload_type 3 if upload_type not in ent all exit FATAL Upload upload_type must be enterprise or all dry_run str_option_to_bool dry_run ent_kits voltdb ent s tar gz voltdb ent s SHA256SUM LINUX voltdb ent s tar gz MAC voltdb ent s tar gz all_kits ent_kits voltdb pro s tar gz voltdb pro s SHA256SUM voltdb s tar gz voltdb community s tar gz kits_home kit_dir voltdb version count 0 with quiet dircheck local ls d kits_home capture True if dircheck failed exit FATAL dircheck stderr for k in eval upload_type _kits f os path join kits_home k version with quiet filecheck local ls f if filecheck succeeded count 1 if dry_run print DRYRUN f remote_dir else with cd remote_dir put f k version if not count print Maybe the kits in kits_home do not match version version print This can happen if your tag does not match your version txt print print Maybe these files need to be renamed local ls kits_home exit FATAL No files uploaded
move libraries up through the zmi,def zmi_move_up self indices REQUEST self moveUp indices REQUEST RESPONSE redirect self absolute_url zmi_libraries
"reduce the number of kpoints by selecting a subset of indices . read the file fname_in and write the reduced data in fname_out . use the name of fname_in to determine the type of file , with possible extentions : eig.nc , eigr2d.nc , eigi2d.nc , gkk.nc , fan.nc",def reduce_kpoints subset fname_in fname_out if fname_in endswith EIG nc return reduce_kpoints_eig subset fname_in fname_out elif fname_in endswith EIGR2D nc or fname_in endswith EIGI2D nc return reduce_kpoints_eigr2d subset fname_in fname_out elif fname_in endswith GKK nc return reduce_kpoints_gkk subset fname_in fname_out elif fname_in endswith FAN nc return reduce_kpoints_fan subset fname_in fname_out else raise Exception Unrecognized file type for file format fname_in
"automated function to generate transformation matrix from b0 volume to volume ras coordinates . first of two automated transform generator functions and considerably simpler than the next one . if out_fname is not supplied , returns a numpy matrix containing the affine transform .",def fetch_b0_to_tkr b0vol_fname trk_fname fsenvsrc None out_fname None if fsenvsrc import cvu_utils cvu_utils tcsh_env_interpreter fsenvsrc v 1 0 read_header trk_fname vox_size import subprocess cmd mri_info s vox2ras tkr b0vol_fname proc subprocess Popen cmd shell True stdout subprocess PIPE crs_to_tkr_arr np loadtxt proc stdout b0_to_crs_arr np diag v v v 1 ret np dot b0_to_crs_arr crs_to_tkr_arr if out_fname np savetxt out_fname ret else return ret
"this is called for each test , beware",def setUp self self dbconn get_dbconn postgis self txn self dbconn cursor cursor_factory psycopg2 extras DictCursor
return an appropriate end string for this vtec,def get_end_string self prod if self action in CAN EXP return if self endts is None return until further notice fmt b d I M p if self endts prod valid datetime timedelta hours 1 fmt I M p localts self endts astimezone prod tz if prod z endswith ST and localts dst localts datetime timedelta hours 1 return till s s localts strftime fmt prod z
add hook to be triggered when the threshold of this source is surpassed,def add_edge_hook self hook if hook is None return self edge_hooks append hook
build a new markov chain generator model . returns a markovify text instance .,def build_text_model cache_path state_size corpus_filepath model_filepath markov_json load_model_json model_filepath logging debug Loading corpus from s corpus_filepath corpus load_corpus_text corpus_filepath logging debug Creating text model with state size s state_size if markov_json and state_size markov_json state_size logging debug Using existing chain file from s model_filepath text_model markovify Text from_dict markov_json elif markov_json and state_size markov_json state_size logging debug Existing chain file is of state size s where as requested is s state_size markov_json state_size logging debug Creating new chain file text_model markovify Text corpus state_size state_size chain None with open os path join cache_path markov_chain json w as json_file json_file write text_model to_json else logging debug Creating new chain file text_model markovify Text corpus state_size state_size chain None with open os path join cache_path markov_chain json w as json_file json_file write text_model to_json return text_model
apps should provide their entries to be added to the main nav : return : a list of : class:`sitemapentries < allura.app.sitemapentry > `,def main_menu self return SitemapEntry self config options mount_label
"gets an api object for a specified cluster keeps the api handle cached , so that only one handle for each cluster will be created in a session .",def get_api self cluster enable_hooks True clusters CLUSTERS if cluster not in clusters raise self CommandError EXIT_INVALID_CONFIGURATION Unknown cluster s cluster apis self apis if enable_hooks else self unhooked_apis base_class HookedAuroraClientAPI if enable_hooks else AuroraClientAPI if cluster not in apis api base_class clusters cluster AURORA_V2_USER_AGENT_NAME verbose False apis cluster api return add_auth_error_handler apis cluster
"returns a string reporting the node count . append a message informing the user if the node count is too low for good quorum , or is even ( meaning that one of the nodes is redundant for quorum ) .",def quorum_check self node_count len self read_peers if node_count 1 count_str unit format node_count else count_str units format node_count if node_count 3 return less than 3 is suboptimal format count_str if node_count 2 0 return an even number is suboptimal format count_str return format count_str
@param cnscon : eventual console connection .,def __init__ self cnscon None super sequence_controller self __init__ self sequence self active None self cnscon cnscon
test the platform ( ) function,def test_Platform self p SCons Platform Platform cygwin assert str p cygwin p env Environment p env assert env PROGSUFFIX exe env assert env LIBSUFFIX a env assert env SHELL sh env p SCons Platform Platform os2 assert str p os2 p env Environment p env assert env PROGSUFFIX exe env assert env LIBSUFFIX lib env p SCons Platform Platform posix assert str p posix p env Environment p env assert env PROGSUFFIX env assert env LIBSUFFIX a env assert env SHELL sh env p SCons Platform Platform irix assert str p irix p env Environment p env assert env PROGSUFFIX env assert env LIBSUFFIX a env assert env SHELL sh env p SCons Platform Platform aix assert str p aix p env Environment p env assert env PROGSUFFIX env assert env LIBSUFFIX a env assert env SHELL sh env p SCons Platform Platform sunos assert str p sunos p env Environment p env assert env PROGSUFFIX env assert env LIBSUFFIX a env assert env SHELL sh env p SCons Platform Platform hpux assert str p hpux p env Environment p env assert env PROGSUFFIX env assert env LIBSUFFIX a env assert env SHELL sh env p SCons Platform Platform win32 assert str p win32 p env Environment p env assert env PROGSUFFIX exe env assert env LIBSUFFIX lib env assert str try p SCons Platform Platform _does_not_exist_ except SCons Errors UserError pass else raise env Environment SCons Platform Platform env assert env env
"delete a snippet . this is allowed by anybody as long as he knows the snippet i d . i got too many manual requests to do this , mostly for legal reasons and the chance to abuse this is not given anyway , since snippets always expire .",def post self request args kwargs if delete in self request POST snippet get_object_or_404 Snippet secret_id self kwargs snippet_id snippet delete url 0 format reverse snippet_new return HttpResponseRedirect url return super SnippetDetailView self post request args kwargs
"return halo radius from halo mass , based on the specified mass definition . this is independent of halo profile , and simply returns",def HaloRadius mass cosmo redshift mdef vir Return halo radius from halo mass based on the specified mass definition This is independent of halo profile and simply returns math R left 3 M 4 pi Delta right 1 3 where math Delta is the density threshold which depends on cosmology redshift and mass definition note The units of the input mass are assumed to be math M_ odot h Parameters mass array_like either a numpy or dask array specifying the halo mass units assumed to be math M_ odot h cosmo class nbodykit cosmology cosmology Cosmology the cosmology instance redshift float compute the density threshold which determines the R M relation at this redshift mdef str optional string specifying the halo mass definition to use should be vir or XXXc or XXXm where XXX is an int specifying the overdensity Returns radius class dask array Array a dask array holding the halo radius from halotools empirical_models import halo_mass_to_halo_radius if not isinstance mass da Array mass da from_array mass chunks 100000 kws cosmology cosmo to_astropy mdef mdef redshift redshift return mass map_blocks lambda mass halo_mass_to_halo_radius mass mass kws dtype mass dtype
should sum otu counts by consensus,def test_sum_counts_by_consensus self obs_result obs_mapping sum_counts_by_consensus self otu_table 3 exp_result Root Bacteria Actinobacteria array 1 0 2 4 Root Bacteria Firmicutes array 1 3 1 1 Root Bacteria Other array 1 2 1 0 exp_mapping s1 0 s2 1 s3 2 s4 3 self assertItemsEqual obs_result exp_result self assertEqual obs_mapping exp_mapping obs_result obs_mapping sum_counts_by_consensus self otu_table 2 exp_result Root Bacteria array 3 5 4 5 exp_mapping s1 0 s2 1 s3 2 s4 3 self assertItemsEqual obs_result exp_result self assertEqual obs_mapping exp_mapping obs_result obs_mapping sum_counts_by_consensus self otu_table 4 exp_result Root Bacteria Actinobacteria Actinobacteria array 1 0 2 4 Root Bacteria Firmicutes Clostridia array 1 3 1 1 Root Bacteria Other Other array 1 2 1 0 exp_mapping s1 0 s2 1 s3 2 s4 3 self assertItemsEqual obs_result exp_result self assertEqual obs_mapping exp_mapping
clean a sff file and returns name of clean file and number of clean flowgrams .,def cleanup_sff flowgrams header outhandle None outdir tmp min_length 150 max_length 400 clean_filename if not outhandle fd clean_filename mkstemp dir outdir prefix cleanup_sff suffix sff txt close fd outhandle open clean_filename w l filter_sff_file flowgrams header lambda f within_length f min_length max_length lambda f f hasProperKey outhandle return clean_filename l
returns the time that this logentry was created,property def time self with qdb sql_connection TRN sql SELECT time FROM qiita WHERE logging_id s format self _table qdb sql_connection TRN add sql self id return qdb sql_connection TRN execute_fetchlast
return the input channel matching ` name ` . raise a ` valueerror ` if not found .,def input_channel self name for channel in self input_channels if channel name name return channel raise ValueError r is not a valid input channel name for r name self description name
function takes two lists and compares first elements .,def compare_first_smaller x y return cmp x 0 y 0
parse a sectioned setup file .,def _read self fp fpname if self main_section in self _sections cursect self _sections self main_section else cursect self _dict cursect __name__ self main_section self _sections self main_section cursect optname None lineno 0 e None while True line fp readline if not line break lineno lineno 1 if line strip or line 0 in continue if line split None 1 0 lower rem and line 0 in rR continue if line 0 isspace and optname value line strip if value cursect optname append value else mo self _optcre match line if mo optname vi optval mo group option vi value optname self optionxform optname rstrip if optval is not None if vi in and in optval pos optval find if pos 1 and optval pos 1 isspace optval optval pos optval optval strip if optval optval self _handle_set_option cursect optname optval else cursect optname optval else if not e e ParsingError fpname e append lineno repr line if e raise e all_sections self _defaults all_sections extend list self _sections values for options in all_sections for name val in list options items if isinstance val list options name n join val
remove non - existing edge .,def test_remove_edge4 self self graph remove_edge 4 5
validate that the given string is a valid x509 certificate .,def validate_cert cert_data if cryptography_library_available log debug Using the cryptography library to validate cert try x509 load_pem_x509_certificate cert_data default_backend return except Exception as e raise ValidationError Error validating CA cert s e code _ _run_cmd which openssl if code 0 log info Cryptography library is not installed and openssl is not available Unable to verify cert return log debug Using openssl to validate cert code output _run_cmd openssl x509 cert_data if code 0 raise ValidationError Error validating CA cert output
"input file exists , output does n't exist",def test_printout_abbreviated_path1 self for syntax in decorator_syntax oop_syntax s StringIO if syntax oop_syntax test_pipeline printout s second_task verbose 5 verbose_abbreviated_path 1 else pipeline_printout s second_task verbose 5 verbose_abbreviated_path 1 wrap_width 500 pipeline main ret s getvalue self assertTrue job1 a start test_verbosity job1 b start in ret
"return basic statistics about data as tuple : ( center , lcl , ucl ) .",def get_stats self return self center self lcl self ucl
returns a set of blobs a given net depends on and a set of output blobs that are written by the net inputs : net - net to return input / output blobs for ; lexical_scope - all external blob names visible to the net,def get_external_blob_names net lexical_scope u n Returns a set of blobs a given net depends on and a set of n output blobs that are written by the net n Inputs n net net to return input output blobs for n lexical_scope all external blob names visible to the net n net_proto net Proto net_ssa _ core get_ssa net_proto input_names core get_undefined_blobs net_ssa for input_name in input_names assert str input_name in lexical_scope u Input blob input_name u is undefined output_names set for op in net_proto op for output in op output if output in lexical_scope output_names add output return input_names output_names
"should return a short , lowercase string that identifies the type",classmethod def identifier cls raise NotImplementedError identifier
configuration has_quota ( new style ),def test_has_quota_new_style self self _conf self make_config fs_name hasquota nid_map nodes foo 1 10 nids foo 1 10 tcp mgt mode external quota False client node foo 2 3 self assertFalse self _conf has_quota self _conf self make_config fs_name hasquota nid_map nodes foo 1 10 nids foo 1 10 tcp mgt mode external quota True client node foo 2 3 self assertTrue self _conf has_quota
[ dev ] : evaluate an exprop using the current state,def eval_exprop self expr kwargs args for oarg in expr args arg self eval_expr_visitor oarg kwargs if arg is_id TOPSTR return exprid_top expr args append arg ret ExprOp expr op args return ret
get a byte array representing the value,def to_bytes value if isinstance value unicode return value encode utf8 elif not isinstance value str return str value return value
step 1b handles -ed and -ing suffixes ( or -edly and -ingly ) . removes double consonants at the end of the stem and adds -e to some words .,def step_1b w if w endswith y and w endswith edly ingly w w 2 if w endswith ed ing if w endswith ied return len w 4 and w 1 or w 2 if w endswith eed return R1 w endswith eed and w 1 or w for suffix in ed ing if w endswith suffix and has_vowel w len suffix w w len suffix if w endswith at bl iz return w e if is_double_consonant w 2 return w 1 if is_short w return w e return w
return the fully qualified domain names for this device,property def fqdns self return self attr_values fqdn
returns the * location * object corresponding to the first city found that matches the provided city name . the lookup is case insensitive .,deprecated will_be removed on_version 3 0 0 def location_for self city_name line self _lookup_line_by_city_name city_name if line is None return None tokens line split return Location tokens 0 float tokens 3 float tokens 2 int tokens 1 tokens 4
check that column colname exists .,def _check_column self filename colname gfits gammalib GFits filename gtable gfits 1 check int gtable contains colname self test_value check 1 Check column colname return
returns true if a is a parent of this node .,def has_parent self p return p in self parents
"connect to a tripp lite pdu ( power distribution unit ) and power cycle one of the loads . host one of the pdus , one of ' pdunetwork.solar.pvt ' , ' pduanalog.solar.pvt ' , or ' pdudigital.solar.pvt ' user username , currently set to ' admin ' for all three pdus passwd password loadn integer load number to power cycle wait duration [ s ] to wait before turning load back on if omitted , "" cycle "" is used instead of "" off "" followed by "" on returns true if successful , false otherwise",def pwr_cycle host loadn user admin passwd pwr4me wait None if wait is None term_str login Password response user n passwd n 1 n 1 n 2 n 2 n str loadn n 3 n X n X n X n X n dur False else term_str login Password response user n passwd n 1 n 1 n 2 n 2 n str loadn n 2 n 2 n X n X n X n X n if type wait int print Warning Could not interpret wait duration wait Must be an integer type Will use 30 s dur 30 else dur wait tn telnetlib Telnet host time sleep 1 for i in range len term_str out tn read_until term_str i 1 if out len term_str i term_str i print Telnet connection to host timed out tn close return False break if dur and i 8 time sleep dur tn write response i tn close return True
when the text is not specified the view should not patch the message and respond with a 400(bad request ) code .,def test_patch_message_without_text self timestamp 10 11 message create_message message_content Message username vitsalis channel self channel timestamp timestamp message_type text qstring urllib urlencode datetime_sent timestamp 10 typing False response self privileged_operation reverse chat message args message id qstring patch dbmessage Message objects get pk message id self assertEqual response status_code 400 self assertEqual dbmessage message_content message message_content self assertIsNone dbmessage datetime_sent
returns a list of all valid backends in the backend directory .,def get_available_backends self be_list for f in os listdir self backend_dir if self _valid_backend_file os path join self backend_dir f be_list append f 3 3 return be_list or
periodically print stats relating to the initial copy .,def _copy_stats_worker stats while True stats log gevent sleep 1
load the .ief file into the contents list .,def _loadFile self filepath logger info loading File filepath contents None try contents filetools getFile filepath return contents except IOError logger error IOError Unable to load file return False if contents None or contents logger error ief file is empty at filepath return False return contents
"placeholder . called when the connection receives a telnet option negotiation sequence , such as iac will echo .",def on_option self command option pass
returns a dict containing data for a current course run with the given seat type .,def get_course_run self seat_type results self _client search course_runs facets get selected_query_facets availability_current selected_facets seat_types_exact format seat_type results results objects results return self _client course_runs results 0 key get
returns path joined with the appropriate lms url root for the current site,def get_lms_url path site_configuration _get_site_configuration return site_configuration build_lms_url path
"initializer for dzfile , gets dzstruct to fill remaining values",def __init__ self super DZFile self __init__ DZFile
finds elements within the elements by xpath .,def find_elements_by_xpath self xpath return self find_elements by By XPATH value xpath
find rseqc read_duplication reports and parse their data,def parse_reports self self read_dups dict for f in self find_log_files rseqc read_duplication_pos if f f startswith Occurrence tUniqReadNumber if f s_name in self read_dups log debug Duplicate sample name found Overwriting format f s_name self add_data_source f section read_duplication self read_dups f s_name OrderedDict for l in f f splitlines s l split try if int s 0 500 self read_dups f s_name int s 0 int s 1 except pass self read_dups self ignore_samples self read_dups if len self read_dups 0 pconfig smooth_points 200 id rseqc_read_dups_plot title RSeQC Read Duplication ylab Number of Reads log10 xlab Occurrence of read yLog True tt_label strong point x occurrences strong point y reads self add_section name Read Duplication anchor rseqc read_dups description a href http rseqc sourceforge net read duplication py target _blank read_duplication py a calculates how many alignment positions have a certain number of exact duplicates Note plot truncated at 500 occurrences and binned p plot linegraph plot self read_dups pconfig return len self read_dups
"key pressed event handler , finish editing on return",def _key_pressed self view event if not event or event type Gdk EventType KEY_PRESS and Gdk keyval_name event keyval Return self _done return True
custom ' _ _ import _ _ ' function .,def _custom_import self name globals None locals None fromlist level 1 if not fromlist name name split 0 frame util get_caller_frame skip __name__ filename inspect getframeinfo frame filename if name in self _import_whitelist or not self _path_predicate filename with self allow_unsafe_import return ORIGINAL_IMPORT name globals locals fromlist level if name in self _safe_modules_config return self _get_safe_module name raise ImportError Importing module 0 is forbidden If you really need to import this module read about the allow_unsafe_import function documented at https buckbuild com function allow_unsafe_import html format name
return the encrypted text of a paste along with the javascript that decrypts it .,app route paste def render paste paste paste_whitelist sub paste try with open s s os environ get PASTE_PATH paste paste as p ciphertext p read return render_template render html ciphertext ciphertext except FileNotFoundError abort 404 except abort 500
update the password for the user,def update_password user pwd doctype u User fieldname u password logout_all_sessions False u n t tUpdate the password for the User n n t t param user username n t t param pwd new password n t t param doctype doctype name for encryption n t t param fieldname fieldname in given doctype for encryption n t t param logout_all_session delete all other session n t hashPwd passlibctx hash pwd frappe db sql u insert into __Auth doctype name fieldname password encrypted n t tvalues doctype s name s fieldname s pwd s 0 n t ton duplicate key update n t t t password pwd s encrypted 0 u doctype doctype u name user u fieldname fieldname u pwd hashPwd if logout_all_sessions from frappe sessions import clear_sessions clear_sessions user user keep_current True force True
return the debuggerstate representing the current state of the debugger .,def state self return self _state
responds to ' ping ' with a ' pong ' response .,handler command ping def ping_h args kwargs return text pong
"open , lock , read and parse the file .",def __init__ self statefile self statefile statefile try state_data self statefile read if not state_data self _data else self _data serializer Load state_data except Exception as msg self _data logging warning Invalid state file Using defaults Error message s msg if instance not in self _data self _data instance if node not in self _data self _data node self _orig_data serializer Dump self _data
reads a file with lines like key = value and returns a dict .,def _GetDictOfSsconfMap self ss_file_key data self _ReadFile ss_file_key lines data splitlines False mapping for line in lines key value line split mapping key value return mapping
gets the mmax for the fault - reading directly from the config file or using the msr otherwise,abc abstractmethod def get_mmax self mfd_conf msr rake area
get a trust by the trust i d .,abc abstractmethod def get_trust self trust_id deleted False raise exception NotImplemented
"simulates a flow in a lid - driven 2d cavity , and returns the average energy and density . this function was written as a regression test for the palabos library .",def cylinderFlow2D nx ny numIter floatT uMax 0 02 Re 100 0 nu uMax ny Re tau 3 nu 0 5 lattice Block2D nx ny D2Q9 BGK omega floatT 1 0 tau boundary regularized defineVelocityBC lattice lattice setBoundaryVelocity 0 0 0 0 lattice 1 nx 2 ny 1 setBoundaryVelocity uMax 0 0 lattice initializeAtEquilibrium 1 0 0 0 0 0 for i in range 0 numIter lattice collideAndStream averageEnergy1 significant lattice averageEnergy averageEnergy2 significant lattice kineticEnergy average averageDensity1 significant lattice averageDensity averageDensity2 significant lattice density average return Energy OK averageEnergy1 averageEnergy2 Density OK averageDensity1 averageDensity2 Av energy 6e averageEnergy1 Av density 6e averageDensity1
assert that got_result is expect_value returned by pred as valid .,def assertGoodResult self expect_value pred got_result source None target_path self assertEqual good_result expect_value pred source source target_path target_path got_result
"returns factory for transforming edges to label , value pairs .",def get_edge_label_value_transformer entity entity_manager name entity get class None return LABEL_VALUE_TRANSFORMER_TYPE get name EdgeLabelValueTransformer entity entity_manager
enumerates search document fields from entity properties .,def _get_document_fields self document_fields for property_name in self _properties value getattr self property_name None document_fields extend self _to_search_fields property_name value try document_fields extend self _to_search_fields identifier self identifier except AttributeError pass return document_fields
renders one json decoded data command at a time .,def RenderStatement self statement renderer command statement 0 options if command l self json_renderer decoder SetLexicon statement 1 elif command m renderer section Plugin s statement 1 plugin_name elif command s renderer section self json_renderer decoder Decode statement 1 options elif command e renderer report_error statement 1 elif command f args self json_renderer decoder Decode x options for x in statement 1 renderer format args elif command t renderer table_header columns statement 1 elif command r row self json_renderer decoder Decode x options for x in statement 1 renderer table_row row options
performs a batch datastore operation on a sequence of keys or entities .,def BatchDatastoreOp op entities_or_keys batch_size 25 for i in xrange 0 len entities_or_keys batch_size op entities_or_keys i i batch_size
generates the apple sus metadata catalog .,def GenerateAppleSUSMetadataCatalog logging info Generating catalog apple_update_metadata products unattended models AppleSUSProduct AllActive filter unattended True force_install_after_date models AppleSUSProduct AllActive filter force_install_after_date None for p in unattended products p product_id p for p in force_install_after_date products p product_id p catalog_plist_xml_fragments p plist GetXmlContent for p in products values catalog_plist_xml constants CATALOG_PLIST_XML n join catalog_plist_xml_fragments c models Catalog key_name apple_update_metadata c plist catalog_plist_xml c put models Catalog DeleteMemcacheWrap apple_update_metadata prop_name plist_xml return c
find the set exclusive - or of two arrays .,def setxor1d ar1 ar2 assume_unique False if not assume_unique ar1 unique ar1 ar2 unique ar2 aux np concatenate ar1 ar2 if aux size 0 return aux aux sort flag np concatenate True aux 1 aux 1 True flag2 flag 1 flag 1 return aux flag2
allow to switch to vimpdb instance,def trace_dispatch self frame event arg if hasattr self vimpdb return self vimpdb trace_dispatch frame event arg else return self _orig_trace_dispatch frame event arg
"index : index of record template : dict or list with a dict containing information about nodes concepts : model concepts exported from arches concepts_mapping : custom mapping between nodes and concept collections date : yyyy - mm - dd used for date fields n : number of node group instances to create when cardinality is "" n """,def create_record index template concepts concepts_mapping date n 2 if type template is list cardinality n num_instances n template template 0 instances elif type template is dict cardinality 1 num_instances 1 else raise Exception Incorrect template type s type template for no in range 1 num_instances 1 nodes deepcopy template for node_name node_value in list nodes items if node_value number nodes node_name 3 14 elif node_value string nodes node_name join string str index str no elif node_value string nodes node_name join string str index str no str val_no for val_no in range 1 n 1 elif node_value date nodes node_name date elif node_value date nodes node_name date for _ in range 1 n 1 elif node_value concept if node_name in concepts_mapping node_concepts list concepts concepts_mapping node_name items node_concepts node_concepts if len node_concepts 1 else node_concepts 1 concept node_concepts no 1 len node_concepts nodes node_name concept 0 else nodes pop node_name elif node_value concept if node_name in concepts_mapping node_concepts list concepts concepts_mapping node_name items node_concepts node_concepts if len node_concepts 1 else node_concepts 1 nodes node_name node_concepts val_no len node_concepts 0 for val_no in range n else nodes pop node_name elif resource instance in node_value nodes pop node_name elif semantic in node_value nodes pop node_name elif type node_value is dict or type node_value is list and type node_value 0 is dict nodes node_name create_record index node_value concepts concepts_mapping date n else raise Exception Unknown node value s str node_value if cardinality n instances append nodes elif cardinality 1 return nodes return instances
return requested project quota type .,def get_project_usage inst resource_list quota_dict get_project_quota inst if not quota_dict return policies get_policies inst quota_dict for p in policies r p resource value units show quota_dict r name project_usage r unit resource_list append r report_desc value return resource_list
args : file : the fasta file . can either be a name or a handle .,def __init__ self file if not hasattr file read self file open file r else self file file
populate the names of the arguments for this number of sites and guesses for each parameter in the model .,def _initialize_param self param_names beta format i for i in range 1 self _num_sites 1 param_guesses 1000000 0 for i in range self _num_sites param_names extend dH format i for i in range 1 self _num_sites 1 param_guesses extend 4000 0 for i in range self _num_sites super _initialize_param param_names param_guesses self _fit_beta_array np zeros self _num_sites dtype float self _fit_dH_array np zeros self _num_sites dtype float self _fit_beta_list beta format i 1 for i in range self _num_sites self _fit_dH_list dH format i 1 for i in range self _num_sites self _T_conc_free np zeros len self _S_conc dtype float
"will set connect callback function . if succeeded , self.recv will be called . otherwise the sock will be closed",def connect self sock addr_port server_addr self _search_server_addr addr_port 0 print addr_port addr_port print server_addr server_addr print serval local self server_addr_set 0 GetLocal assert str server_addr str self server_addr_set 0 GetLocal inetAddr ns3 InetSocketAddress server_addr addr_port 1 def connect_succeeded sock print Node s connect succeeded self name self logger debug Node s connect succeeded self name self after 0 self recv sock 512 self dispatcher def connect_failed sock self logger debug Node s connect failed self name self close_sock sock sock SetConnectCallback connect_succeeded connect_failed ret sock Connect inetAddr if ret 1 print node s cannot connect to server self name print node s connected to server self name
get a list of models matching the provided arguments . also adds pagination capabilities . returns empty array when no models match . todo-3 filter by entity kind as well,def list_follows_by_user db_conn params query SELECT FROM follows WHERE user_id user_id s ORDER BY created DESC TODO OFFSET LIMIT params user_id convert_slug_to_uuid params user_id return list_rows db_conn query params
"take an encrypted password , and verifies it . returns bool .",def is_password_valid real_encrypted_password given_password try return bcrypt verify given_password real_encrypted_password except return False
"returns the tuple color , style associated with msg_id as defined in self.color_mapping",def _get_decoration self msg_id try return self color_mapping msg_id 0 except KeyError return None None
stop vnfs running inside ees .,def do_stop self _line self mn stopVNFs
"wraps apersands in html with `` < span class=""amp "" > `` so they can be styled with css . apersands are also normalized to `` & amp ; `` . requires ampersands to have whitespace or an `` & nbsp ; `` on both sides .",def amp text text force_unicode text tag_pattern w s w s s s s s amp_finder re compile s nbsp amp 38 s nbsp intra_tag_finder re compile P prefix s P text P suffix s tag_pattern tag_pattern def _amp_process groups prefix groups group prefix or text amp_finder sub 1 span class amp amp span 3 groups group text suffix groups group suffix or return prefix text suffix output intra_tag_finder sub _amp_process text return mark_safe output
get the object that carries provenance for the series that the image passed is in .,def getSeries self image
enables immedaite enforcing of deferred constraints .,def enforce_constraints self self session flush try self session execute SET CONSTRAINTS ALL IMMEDIATE except DatabaseError handle_sqlalchemy_database_error
"accepted formats : * iso 8601 subset - yyyy - mm - dd[thh : mm ] * ' today ' , ' yesterday ' , ' tomorrow ' and ' now ' * days in the future / past : ' [ + /-]ddhhhmmm '",classmethod def _parseDateTime cls dateTime allowNegativeOffset now now_utc if dateTime in cls _deltas return ctx now cls _deltas dateTime elif dateTime now return abs now elif dateTime today return ctx now m re match d 1 3 d d 1 2 h d 1 2 m dateTime if m mod 1 if m group 1 else 1 if not allowNegativeOffset and mod 1 raise ArgumentParseError End date cannot be a negative offset atoms list 0 if a is None else int a mod for a in m groups 1 if atoms 1 23 or atoms 2 59 raise ArgumentParseError Invalid time return ctx timedelta days atoms 0 hours atoms 1 minutes atoms 2 else try return abs datetime strptime dateTime Y m dT H M except ValueError pass try return ctx datetime strptime dateTime Y m d except ValueError raise ArgumentParseError Impossible to parse s dateTime
will return each i d that was n't found in the database .,def challenge self ids for id_ in ids if self read id_ first continue yield id_
try to import `` helpers.py `` from each app in installed_apps .,def load_helpers u global _helpers_loaded if _helpers_loaded return _helpers_loaded True for config in apps get_app_configs if not has_helpers config continue import_module u s helpers config name
"same as pickle.dump(theobject , fhandle).takes filename as parameter",def pickledump theobject fname fhandle open fname wb pickle dump theobject fhandle
read automatic with monkhorstpack grid centered on gamma,def test1 os chdir os path join jaspdir tests calc Vasp calc read_kpoints kpoints files k1 assert calc input_params kpts np array 4 4 4 all assert calc input_params gamma is True
"return the index in the _ saledata array corresponding to this ( l , b )",def _lbIndx self l b if l self _lmin or l self _lmax or b self _bmin or b self _bmax raise IndexError Given l b pair not within the region covered by the Sale et al 2014 dust map return numpy argmin l self _saledata GLON 2 0 self _dl 2 0 b self _saledata GLAT 2 0 self _db 2 0
restore all classes to their default implementation,def restore_default_classes self self classes for class_object in self default_models role get_role class_object self classes role class_object self base_name_to_plugin_class self plugin_name_to_base_class self nodes self default_node_classes copy self edge_class self default_edge_class self update_node_info
"x(th)% , x is in range of [ 0,100 ] , it would be more fair if it is [ 0,100 )",def get_x_th_percentile objlist x nseg len objlist segsize 100 0 nseg segindex int x segsize if segindex nseg segindex 1 return objlist segindex
"uniform quantization from float [ 0 , 1 ] to int [ 0 , levels-1 ] .",def quantize img levels 32 dtype np uint8 img np asarray img assert np issubsctype img np floating img dtype assert np all img 0 and np all img 1 img min img max return img levels clip 0 levels 1 astype dtype
"returns the ' genesis ' block for this testcase , including any alloc 's ( prestate ) required",def genesis self key None if self raw_genesis is None fields_to_fix nonce coinbase hash mixHash parentHash receiptTrie stateRoot transactionsTrie uncleHash raw_genesis self data genesisBlockHeader for key in fields_to_fix v raw_genesis key if len v 2 and v 2 0x raw_genesis key 0x raw_genesis key alloc for addr in self data pre v self data pre addr if addr 2 0x addr addr 2 if storage in v keys storage for slot data in v storage items _slot padHash slot _data padHash data storage _slot _data v storage storage alloc addr v raw_genesis alloc alloc self raw_genesis raw_genesis if key is None return self raw_genesis return self raw_genesis key
tests that exclusive ranges do not count the start value .,def test_in_range_exclusive_equal_to_start_invalid self instance Range 10 20 assert not instance in_range 10
print the data type of a dataset .,options def do_dtype self args opts None print self explorer args 0 dtype
"this function ( which will be auto - called on import of : mod:`pyalm ` ) , will attempt to pull the api keys from a few places .",def _attempt_key_load try fp os path expanduser pyalm config PYALM_LOCATION fd open fp r vals fd read splitlines pyalm config APIS dict iter i split for i in vals except IOError as e if e errno 2 warnings warn pyalm file s exists but could not be opened s pyalm config PYALM_LOCATION str e try pyalm config APIS _get_env_vars except KeyError as e pass
prepare a new response ( ) instance .,def __init__ self response command_map if not response message raise ValueError No message payload in the response WTF logger info Processing message message_id from first_name last_name format message_id response message message_id first_name response message from first_name encode utf 8 last_name response message from last_name encode utf 8 if last_name in response message from else self response response message self command_map command_map self message_type self _get_message_type logger info Message message_id is a type message format message_id response message message_id type self message_type self sender_information self _get_sender_information self plugins self _find_applicable_plugins return
the name used in passregistry .,property def name self try return self __name except AttributeError return
call the vendor interface to load time - series data,def _performload self loader handler None vfid loader vfid if vfid ci vfid vendor interface if ci self logger debug s s s to s vfid field vfid vendor loader start loader end return ci history vfid loader start loader end self holder else self logger error Cannot load rate Vendor s has no interface available vid vendor else self logger error Cannot load rate No data vendor available
determines if the given fqdn matches the schema for a production slice,def is_production_slice slice_fqdn fqdn_parts slice_fqdn split for i in range 1 len fqdn_parts if is_production_site fqdn_parts i server_id fqdn_parts i 1 return re match mlab 123 server_id re IGNORECASE None return False
"performs a permutation test on the given or the default dependent variables . if two_samples is true , will conduct a two - sample test . otherwise a one - sample test will be conducted . if ranked is true , a wilcoxon / wilcoxon - mann - whitney test will be used for the one - sample / two - sample case , respectively . otherwise a fisher / pitman test will be conducted .",def permutation_test self other variables None ranked False two_samples False limit 1000 variables self _np1d variables fallback self dependent for var in variables A self get var B other get var if not two_samples D a b for a b in zip A B if ranked D self _signed_rank D result perm_test one_sample D progress_bar self _progress_bar limit limit else if ranked D self _rank np concatenate A B A B D len A D len A result perm_test two_sample A B progress_bar self _progress_bar limit limit return result
check if a state is the goal state,def terminal self state return False
get sources for loadable modules .,def _windowsLdmodSources target source env for_signature return _dllSources target source env for_signature LDMODULE
": param x : the test set . 2d , array - like consisting of two eleents in each row corresponding to the userid and itemid",def predict self X formatizer user 0 item 1 users X ix formatizer user tolist items X ix formatizer item tolist if self method default values for i in range len users user users i item items i if user in self user_index if item in self item_index values append self UsV self user_index user self item_index item else values append self user_means self user_index user elif item in self item_index and user not in self user_index values append self item_means self item_index item else values append np mean self item_means 0 6 np mean self user_means 0 4 return values
needed for using basedimensions as hash keys .,def __hash__ self return self _index
call all the actions registered for the exit of the mode .,def execute_exit_actions self parent self _execute_actions self exit_actions parent
summarize long table according to thresholds,def _summary lines labels category sample counts df pd DataFrame from_records lines columns labels df counts df counts astype int df_sum df groupby category sample as_index False sum df_sum category s_sum r for r in df_sum category df_count df groupby category sample as_index False count df_count category s_count r for r in df_count category df_mean df groupby category sample as_index False mean df_mean category s_mean r for r in df_mean category df pd concat df_sum df_count df_mean return df
"uploads the specified analysis file ( e.g. memory dump , pcap file , dcap file , etc . ) into the g.analyses_collection and inserts the file 's _ i d into the specified field in the specified analysis_doc",def append_analysis_file self analysis_doc_id analysis_file_path analysis_filename if not self contains_doc analysis_doc_id logger error Database does not have sample id s sample_doc_id return file_id self upload_file analysis_file_path analysis_doc self download_doc analysis_doc_id analysis_doc output_files analysis_filename file_id self upload_doc analysis_doc replace True
"* musicpd.org , status section : *",protocol commands add u clearerror def clearerror context u n musicpd org status section n n clearerror n n Clears the current error message in status this is also n accomplished by any command that starts playback n raise exceptions MpdNotImplemented
"given a feedback response and an optional http request , returns an ordered list of suggestions",def get_suggestions feedback request None suggestions for prov in get_suggesters try suggestions extend prov get_suggestions feedback request except Exception logger exception Error in provider 0 format prov __class__ __name__ return suggestions
"errors that occur after the request has been started , so we should assume that the server began processing it .",def _is_read_error self err return isinstance err ReadTimeoutError ProtocolError
run the inner ear model by [ zilany2014]_. return mean firing rate of the auditory nerve fibers .,def run_zilany2014_rate sound fs anf_types cf species cohc 1 cihc 1 powerlaw approximate ffGn False assert np max sound 1000 Signal should be given in Pa assert sound ndim 1 assert species in cat human if isinstance anf_types str anf_types anf_types cfs calc_cfs cf species channel_args signal sound cf cf fs fs cohc cohc cihc cihc anf_types anf_types powerlaw powerlaw species species ffGn ffGn for cf in cfs nested_results map _run_channel channel_args results list itertools chain nested_results columns pd MultiIndex from_tuples r anf_type r cf for r in results names anf_type cf rates np array r rate for r in results T rates pd DataFrame rates columns columns if isinstance np fft fftpack _fft_cache dict np fft fftpack _fft_cache return rates
closely emulate the interactive python console .,def interact self banner None try sys ps1 except AttributeError sys ps1 try sys ps2 except AttributeError sys ps2 cprt Type help copyright credits or license for more information if banner is None self write Python s on s n s n s n sys version sys platform cprt self __class__ __name__ elif banner self write s n str banner more 0 while 1 try if more prompt sys ps2 else prompt sys ps1 try line self raw_input prompt except EOFError self write n break else more self push line except KeyboardInterrupt self write nKeyboardInterrupt n self resetbuffer more 0
descript . : when user double clicks on plate table then sample in corresponding cell is loaded,def sample_table_double_clicked self table_item self plate_manipulator_hwobj load_sample table_item row 1 table_item column self num_drops 1
this method is called before any tests are run .,def setUp self self stylepath os environ get STYLEPATH None
prepend a fixed - length string list with a new string .,def prepend_string_list self key value max_length_key max_len self get max_length_key strings self get_string_list key strings value x for x in strings if x value strings strings max_len self beginWriteArray key for i in range len strings self setArrayIndex i self setValue entry strings i self endArray
replace the current context with another .,def set_context self context self _set_context context emit False self _modified not context load_path self dataChanged emit self CONTEXT_CHANGED self REQUEST_CHANGED self PACKAGES_PATH_CHANGED self LOCKS_CHANGED self LOADPATH_CHANGED self PACKAGE_FILTER_CHANGED
more than one replacement variable is allowed in a template,setup basic_templates def test_basic_syntax03 self output self engine render_to_string basic syntax03 first 1 second 2 self assertEqual output 1 2
the flatpage template tag retrieves unregistered prefixed flatpages by default,def test_get_flatpages_with_prefix self out Template load flatpages get_flatpages location as location_flatpages for page in location_flatpages page title endfor render Context self assertEqual out A Nested Flatpage
test of raw raw query 's tolerance for columns being returned in any order,def test_order_handler self selects dob last_name first_name id last_name dob first_name id first_name last_name dob id for select in selects query SELECT s FROM raw_query_author select authors Author objects all self assertSuccessfulRawQuery Author query authors
convert cnf object ot dimacs cnf string,def tostring self cnf self varname_dict self varobj_dict varis set for d in cnf dis for v in d varis add v name ret p cnf d d len varis len cnf dis varis dict zip sorted list varis map str range 1 len varis 1 for v in varis vo Variable v self varname_dict vo varis v self varobj_dict varis v vo for d in cnf dis ret n vnamelist for v in d vnamelist append if v inverted else varis v name ret join vnamelist 0 return ret
periodically snap goodput ( internal function ),staticmethod def _periodic_internal stream context stream opaque utime stime os times 2 utimediff utime context snap_utime stimediff stime context snap_stime ticks utils ticks timediff ticks context snap_ticks bytesdiff stream bytes_out context snap_count context state setdefault goodput_snap append ticks ticks bytesdiff bytesdiff timediff timediff utimediff utimediff stimediff stimediff logging debug raw_srvr utime stime f f utime stime if timediff 1e 06 speed utils speed_formatter bytesdiff timediff logging debug raw_srvr goodput_snap s speed web100_snap web100 web100_snap web100 WEB100_HEADER context web100_dirname web100_snap ticks ticks context state setdefault web100_snap append web100_snap context snap_count stream bytes_out context snap_ticks ticks context snap_utime utime context snap_stime stime
you can revert your changes ( use revert from git ),def do_undo self args undo_change args self repo
called after a subscribable model is removed .,def handle_post_delete sender instance using kwargs publish_deltas instance _snorky_delta instance _snorky_delta None
add options that are common for several plugins .,classmethod def add_common_opts cls parser for opt in cls common_opt_names cls _parser_add_opt parser opt
generate a sequence from a list of numbers .,def generateFromNumbers self numbers sequence for number in numbers if number None sequence append number else pattern self patternMachine get number sequence append pattern return sequence
this will be called to process events,def post_event self assert len self events 0 No events yet if self events 1 name key_press_event self key_event else self mouse_event
validates a torrent instance before it 's saved to the database . enforcing user - and - such - based validations is more flexible here vs wtform context,def validate_torrent_post_upload torrent upload_form None errors torrent_file minimum_anonymous_torrent_size app config MINIMUM_ANONYMOUS_TORRENT_SIZE if torrent user is None and torrent filesize minimum_anonymous_torrent_size errors torrent_file append Torrent too small for an anonymous uploader if not _validate_torrent_filenames torrent errors torrent_file append Torrent has forbidden characters in filenames errors k v for k v in errors items if v if errors if upload_form for field_name field_errors in errors items getattr upload_form field_name errors extend field_errors upload_form _errors None raise TorrentExtraValidationException errors
set the parameters of this estimator .,def set_params self params for parameter value in params items setattr self parameter value return self
this function is called from c++ when inference is started,def begin self inference print begin
tests loop scheduling after dse - induced expression hoisting .,skipif_yask def test_scheduling_after_rewrite grid Grid 10 10 u1 TimeFunction name u1 grid grid save 10 time_order 2 u2 TimeFunction name u2 grid grid time_order 2 sf1 SparseFunction name sf1 grid grid npoint 1 ntime 10 const Function name const grid grid space_order 2 eqn1 Eq u1 forward u1 sin const eqn2 sf1 inject u1 forward expr sf1 eqn3 Eq u2 forward u2 u1 dt2 sin const op Operator eqn1 eqn2 eqn3 trees retrieve_iteration_tree op assert len trees 4 assert all i dim j for i j in zip trees 0 grid dimensions assert trees 1 0 dim trees 2 0 dim trees 3 0 dim grid time_dim
setup method for pauseserver api samples extension,def setUp self super PauseServerSamplesJsonTest self setUp self uuid self _post_server
hook called immediately after detaching a volume from an instance .,abc abstractmethod def detach_volume self kwargs pass
return a list of links for this image .,def _get_links self request identifier collection_name return rel self href self _get_href_link request identifier collection_name rel bookmark href self _get_bookmark_link request identifier collection_name rel alternate type application vnd openstack image href self _get_alternate_link request identifier
returns datastore path of folder containing the image .,def get_image_cache_folder self datastore image_id return datastore build_path self _base_folder image_id
extract features from each document . return it as a matrix of ( number of docs ) by ( number of features ) .,def docExtract self self fv for doc in self documents self fv append self featureSet extract doc return np array np asmatrix self fv
called after the code generation of all nodes has completed .,def generationFinished self astnodes self outfile close
testtreector : test_02 ( ) : youngestchild raises when no children .,def test_02 self t Tree Tree A try t youngestChild self fail IndexError not raised except IndexError pass
get the versions from github tags,def get_versions self return self _get_github_tags normalize_func self _normalize_tag_name
gets the fashion - mnist dataset .,def get_fashion_mnist withlabel True ndim 1 scale 1 0 dtype None label_dtype numpy int32 rgb_format False train_raw _retrieve_fashion_mnist_training dtype chainer get_dtype dtype train preprocess_mnist train_raw withlabel ndim scale dtype label_dtype rgb_format test_raw _retrieve_fashion_mnist_test test preprocess_mnist test_raw withlabel ndim scale dtype label_dtype rgb_format return train test
subroutine to send jobs to multiple processors using pypar,def multi_proc_mutate_and_integrate self prmt mutation numproc self numproc l len mutation n_mut 0 for index_job in range l nproc 1 index_job numproc 1 args net self genus index_job prmt prmt nnetwork index_job tgeneration self tgeneration mutation mutation index_job pypar send net mutate_and_integrate prmt nnetwork tgeneration mutation args nproc if index_job 1 numproc 1 0 pypar barrier results pypar receive worker for worker in range 1 numproc for i in results n_mut i 0 self genus i 1 i 2 self update_fitness i 1 i 3 if l numproc 1 0 for i in range l numproc 1 numproc 1 pypar send 0 i 1 pypar barrier results pypar receive worker for worker in range 1 numproc for i in range l numproc 1 n_mut results i 0 self genus results i 1 results i 2 self update_fitness results i 1 results i 3 return n_mut
calculate the water pressure and the adjoint forcing of pressure ( if adjoint forcing of density is provided ) .,def pressure hz rho axis None drhodt None drhods None hz np ma array hz rho np ma array rho dpresdt None dpresds None if not axis if hz ndim rho ndim nd rho ndim hz ndim if hz shape rho shape nd axis nd elif hz shape rho shape nd axis nd else axis 1 flip slice None None None for i in range rho ndim flip axis slice None None 1 pres np cumsum scipy constants g rho hz flip axis axis flip 0 0001 if drhodt is not None dpresdt np cumsum scipy constants g drhodt hz flip axis axis flip 0 0001 if drhods is not None dpresds np cumsum scipy constants g drhods hz flip axis axis flip 0 0001 return pres dpresdt dpresds
get neighboring test results n positions away from tsid .,def get_neighboring_tests self tsid test_name positions tsets self get_tsets sort 1 tsid 1 lower higher adj_tests for test in tsets tsid tests test_name test test_name lower test_name higher test_name adj_tests test_name for test_name in lower keys i tsid 1 while i 0 and i tsid and len lower test_name positions for test in tsets i tests if test test_name test_name and test pass test tsid i 1 assert i 1 test tsid lower test_name test lower test_name i 1 i tsid while i len tsets and len higher test_name positions for test in tsets i tests if test test_name test_name and test pass test tsid i 1 higher test_name append test i 1 for test_name in higher keys llen hlen len lower test_name len higher test_name m min llen hlen lindex m hindex m if llen hindex lindex max positions 2 m llen else hindex max positions 2 m hlen print lindex hindex for l in range lindex adj_tests test_name append lower test_name l for h in range hindex adj_tests test_name append higher test_name h return adj_tests
initialize a directory stream on a circuit .,def do_stream self circuit_id stream_id self waiting circuit_id del self waiting circuit_id self trigger_local d_init_stream circuit_id stream_id
determines the number of active users on your site and puts it into the context,def visitors_on_site parser token try tag a varname token split_contents except ValueError raise template TemplateSyntaxError visitors_on_site usage visitors_on_site as visitors return VisitorsOnSite varname
cast to string using the part 's title,def __str__ self return self title
classifies all files in a directory and writes a night log of science images,def FileClassify dir log simThAr_sci simFP_sci biases ob_flats co_flats ob_loc co_loc ThAr_ref FP_ref ThAr_ref_dates ThFP_ref_dates obnames obnames_FP exptimes exptimes_FP flats f open log w bad_files if os access dir bad_files txt os F_OK bf open dir bad_files txt linesbf bf readlines for line in linesbf bad_files append dir line 1 bf close all_files glob glob dir CORALIE fits for archivo in all_files dump False for bf in bad_files if archivo bf dump True break if dump False h pyfits open archivo hd pyfits getheader archivo if h 0 header HIERARCH ESO TPL TYPE OBTH or h 0 header HIERARCH ESO TPL TYPE OBFP obname getObName h ra h 0 header HIERARCH ESO OBS ALPHACAT delta h 0 header HIERARCH ESO OBS DELTACAT airmass h 0 header HIERARCH ESO OBS TARG AIRMASS texp h 0 header HIERARCH ESO OBS TEXP date h 0 header HIERARCH ESO CORA SHUTTER START DATE hour h 0 header HIERARCH ESO CORA SHUTTER START HOUR line 15s 10s 10s 8 2f 4 2f 8s 7 4f s n obname ra delta texp airmass date hour archivo f write line simThAr_sci append archivo obnames append obname exptimes append texp elif h 0 header HIERARCH ESO TPL TYPE BIAS biases append archivo elif h 0 header HIERARCH ESO TPL TYPE FFO ob_flats append archivo elif h 0 header HIERARCH ESO TPL TYPE FFC co_flats append archivo elif h 0 header HIERARCH ESO TPL TYPE FF2 flats append archivo elif h 0 header HIERARCH ESO TPL TYPE LOCO ob_loc append archivo elif h 0 header HIERARCH ESO TPL TYPE LOCC co_loc append archivo elif h 0 header HIERARCH ESO TPL TYPE THA2 ThAr_ref append archivo mjd mjd0 mjd_fromheader h ThAr_ref_dates append mjd elif h 0 header HIERARCH ESO TPL TYPE THFP FP_ref append archivo mjd mjd0 mjd_fromheader h ThFP_ref_dates append mjd f close return biases ob_flats co_flats ob_loc co_loc ThAr_ref FP_ref simThAr_sci simFP_sci ThAr_ref_dates ThFP_ref_dates obnames obnames_FP exptimes exptimes_FP flats
adds or removes the ' from the list of nonpersitent bookmarks,def enable_saving_backtick_bookmark self boolean if boolean if in self nonpersistent_bookmarks self nonpersistent_bookmarks remove else self nonpersistent_bookmarks add
use nibabel.minc1.minc1image.to_filename to save out_minc1_image.mnc .,def minc1_to_filename self u n Use nibabel minc1 Minc1Image to_filename to save n out_minc1_image mnc n file_name os path join self data_dir u out_minc1_image img nib minc1 Minc1Image self get_data np eye 4 img to_filename file_name os remove file_name u minc
parse a str that represents a list of acls,classmethod def extract cls acls return cls extract_acl acl for acl in acls
perform whatever operation this command is supposed to do .,def process self args raise NotImplementedError
wait until a tgmainframe is closed or ctrl - c,def wait_for_frame frame if not frame return dispatcher def close ROOT gSystem ExitLoop if not getattr frame _py_close_dispatcher_attached False frame _py_close_dispatcher_attached True frame Connect CloseWindow TPyDispatcher close Dispatch dispatcher def exit_application_loop Signal handler for CTRL c to cause gApplication Run to finish incpy ignore ROOT gSystem ExitLoop sh ROOT TSignalHandler ROOT kSigInterrupt True sh Add sh Connect Notified TPyDispatcher exit_application_loop Dispatch if not ROOT gROOT IsBatch run_application_until_done frame Disconnect CloseWindow close Dispatch
use the closure webservice - limited to files under 1mb !,def minimize code params urllib urlencode js_code code compilation_level SIMPLE_OPTIMIZATIONS output_format text output_info compiled_code t time time headers Content type application x www form urlencoded conn httplib HTTPConnection closure compiler appspot com conn request POST compile params headers response conn getresponse data response read conn close if data startswith Error raise Exception data sys stderr write 3f seconds to compile n time time t return data
scatter plot of t - sne clustering .,def tsneScatterWithPies model seqs tsne lims None filename None hiddenprobs model motifHitProbs seqs probs hiddenprobs pmax probs max axis 0 2 3 pmedian np median probs max axis 2 3 axis 0 pcurrent probs max axis 2 3 colors cm rainbow np linspace 0 1 probs shape 1 fig plt figure figsize 6 6 ax fig add_axes 0 1 0 1 0 6 0 75 for idx col in zip list range probs shape 1 colors markx 0 np cos idx 2 np pi probs shape 1 2 np pi idx 1 probs shape 1 tolist marky 0 np sin idx 2 np pi probs shape 1 2 np pi idx 1 probs shape 1 tolist markxy list zip markx marky s 150 pcurrent idx pmedian idx pmax idx pmedian idx s s 0 0 0 plt scatter tsne 0 tsne 1 marker markxy 0 s s color col label Motif str idx 1 alpha 0 6 if lims plt xlim lims 0 0 lims 1 0 plt ylim lims 0 1 lims 1 1 plt legend bbox_to_anchor 1 05 1 loc 2 borderaxespad 0 0 plt axis off if filename fig savefig filename dpi 700 else plt show
basic tests for properties conditioned on multiple other properties .,def test_multiple_conditions t BoostBuild Tester ignore regular config toolset testToolset pass_toolset False use_test_config False t write testToolset jam import feature feature extend toolset testToolset rule init t write jamroot jam import feature import notfile import toolset feature feature description free incidental feature feature aaa 1 0 incidental feature feature bbb 1 0 incidental feature feature ccc 1 0 incidental rule buildRule name targets properties for local description in feature get values description properties ECHO description description notfile testTarget1 buildRule description d aaa 0 description a0 aaa 1 description a1 aaa 0 bbb 0 description a0 b0 aaa 0 bbb 1 description a0 b1 aaa 1 bbb 0 description a1 b0 aaa 1 bbb 1 description a1 b1 aaa 0 bbb 0 ccc 0 description a0 b0 c0 aaa 0 bbb 0 ccc 1 description a0 b0 c1 aaa 0 bbb 1 ccc 1 description a0 b1 c1 aaa 1 bbb 0 ccc 1 description a1 b0 c1 aaa 1 bbb 1 ccc 0 description a1 b1 c0 aaa 1 bbb 1 ccc 1 description a1 b1 c1 t run_build_system aaa 1 bbb 1 ccc 1 t expect_output_line description d t expect_output_line description a0 False t expect_output_line description a1 t expect_output_line description a0 b0 False t expect_output_line description a0 b1 False t expect_output_line description a1 b0 False t expect_output_line description a1 b1 t expect_output_line description a0 b0 c0 False t expect_output_line description a0 b0 c1 False t expect_output_line description a0 b1 c1 False t expect_output_line description a1 b0 c1 False t expect_output_line description a1 b1 c0 False t expect_output_line description a1 b1 c1 t run_build_system aaa 0 bbb 0 ccc 1 t expect_output_line description d t expect_output_line description a0 t expect_output_line description a1 False t expect_output_line description a0 b0 t expect_output_line description a0 b1 False t expect_output_line description a1 b0 False t expect_output_line description a1 b1 False t expect_output_line description a0 b0 c0 False t expect_output_line description a0 b0 c1 t expect_output_line description a0 b1 c1 False t expect_output_line description a1 b0 c1 False t expect_output_line description a1 b1 c0 False t expect_output_line description a1 b1 c1 False t run_build_system aaa 0 bbb 0 ccc 0 t expect_output_line description d t expect_output_line description a0 t expect_output_line description a1 False t expect_output_line description a0 b0 t expect_output_line description a0 b1 False t expect_output_line description a1 b0 False t expect_output_line description a1 b1 False t expect_output_line description a0 b0 c0 t expect_output_line description a0 b0 c1 False t expect_output_line description a0 b1 c1 False t expect_output_line description a1 b0 c1 False t expect_output_line description a1 b1 c0 False t expect_output_line description a1 b1 c1 False t cleanup
"usage : - show the size of a object - e.g. showsize(img_stack , ' 1-l - red.tif ' ) args : - obj : a variable - name : the name you want to print",def showsize obj name sz sys getsizeof obj if type obj is np ndarray sz obj nbytes 0 0 if sz 1024 0 print s 2f B name sz elif sz 1024 1024 print s 2f K name sz 1024 0 elif sz 1024 1024 1024 print s 2f M name sz 1024 0 1024 0 else print s 2f G name sz 1024 0 1024 0 1024 0
linear interpolation between a and b 0 < = t < = 1,def line a t l return a t l
get ( part of ) an array from store via dask and compare .,def get_dask_array self var_name slices array_name dask_array offset self make_dask_array var_name slices pull self store get_dask_array array_name dask_array chunks dask_array dtype offset array_retrieved pull compute array dask_array compute assert_array_equal array_retrieved array Error retrieving format array_name offset dask_array chunks
update the pool configuration with a worker configuration .,def processConfig self worker_config self config headless worker_config get headless False if self config headless if not self discovery_thread self discovery_thread discovery Advertise port join str a for a in self getPorts
regression test for a boost build bug causing it to not use a generator with a source type derived from one of the generator 's sources but created only after already using the generateor .,def test_using_a_derived_source_type_created_after_generator_already_used t BoostBuild Tester t write dummy xxx Hello My name is Peter Pan n t write jamroot jam import common import generators import type type register XXX xxx type register YYY yyy generators register standard common copy XXX YYY Building this dummy target must not cause a later defined XXX2 target type not to be recognized as a viable source type for building YYY targets yyy dummy dummy xxx alias the test output Other other t write Other source xxx2 Hello My name is Tinkerbell n t write Other jamfile jam import type type register XXX2 xxx2 XXX We are careful not to do anything between defining our new XXX2 target type and using the XXX YYY generator that could potentially cover the Boost Build bug by clearing its internal viable source target type state yyy other source xxx2 t run_build_system t expect_addition bin toolset debug dummy yyy t expect_addition Other bin toolset debug other yyy t expect_nothing_more t cleanup
lookup an error code or class code and return its symbolic name .,def lookup code _cache if _cache return _cache code for k v in globals iteritems if isinstance v str and len v in 2 5 _cache v k return lookup code
"return true if the given line is part of a multi - line block , via backslash or triple - quote .",def _in_multi_line self line current_state self backslashed or self triplequoted if re search line self backslashed True else self backslashed False triples len re findall line if triples 1 or triples 2 0 self triplequoted not self triplequoted return current_state
get doc string from customized query,def get_doc_string self if self custom_query __doc__ is not None return self custom_query __doc__ else return no docstring found in query function
: param string name : name to demangle : returns string : demangled name,def demangle name return demangle_cache name
preprocess ( ) emulate the pre - processing occuring in the vgg16 caffe prototxt .,def preprocess self im im np float32 im im im 1 im self mean im self scale im im transpose 2 0 1 return im
return the indices where ravel(condition ) is true,def find condition res np nonzero np ravel condition return res
( ) - > graph object base clase,def __init__ self label handlegenerator HandleGenerator self handle handlegenerator next self parent None self label label
returns receiver standard deviation in degrees .,def getSigma self return self getBearingStandardDeviationRadians 180 0 math pi
tell the state machine it can write to the socket .,def inWriteEvent self try self _checkAssert if self handshaker self _doHandshakeOp elif self closer self _doCloseOp elif self reader self _doReadOp elif self writer self _doWriteOp else self outWriteEvent except self _clear raise
powerups with ' _ _ getpowerupinterfaces _ _ ' methods can be installed on the interfaces in the iterable that method returns .,def test_dynamicAutomaticPowerupInstall self s Store mm Summer store s s powerUp mm ISumProducer p PlusOneTimesFour store s s powerUp p self assertEquals mm doSum 4
@param reactor : an l{ireactortcp } provider .,def __init__ self reactor host port username password vhost heartbeat 0 auth_mechanism AMQPLAIN timeout 30 self _reactor reactor self _host host self _port port self _username username self _password password self _vhost vhost self _heartbeat heartbeat self _auth_mechanism auth_mechanism self _timeout timeout
creates map of room to bookings where each booking overlaps with the given time range,def _create_map_of_overlapping_bookings bookings start end u n Creates map of room to bookings where each booking overlaps n with the given time range n bookings_map for booking in bookings booking_start _localize_time booking u start_time booking_end _localize_time booking u end_time if _overlaps start1 booking_start end1 booking_end start2 start end2 end roomid siteid booking u roomid booking u siteid bookings_map roomid siteid bookings_map get roomid siteid booking return bookings_map
tests fetching non - existing value in the conf .,raises KeyError def test_fetch_nonexisting_config_val msaf configparser fetch_val_for_key caca delete_key False
edit values of an existing connection .,db_create_close def edit_connection agent_id None web_port None host_port None status None process_id None customer settings Default Customer conn None try new_connection if web_port new_connection CollectionKeys WebPort web_port if host_port new_connection CollectionKeys HostPort host_port if status new_connection CollectionKeys Status status if process_id new_connection CollectionKeys ProcessId process_id result r table Collection KnownConnections get agent_id update new_connection run conn if replaced in result if result replaced 0 return True except Exception as e logger error Unable to edit an existing connection logger error str e return False
loads mnist files into a 3d numpy array .,def load_mnist dataset training digits None path None asbytes False selection None return_labels True return_indices False files training train images idx3 ubyte train labels idx1 ubyte testing t10k images idx3 ubyte t10k labels idx1 ubyte if path is None try path os environ MNIST except KeyError raise ValueError Unspecified path requires environment variable MNIST to be set try images_fname os path join path files dataset 0 labels_fname os path join path files dataset 1 except KeyError raise ValueError Data set must be testing or training if return_labels or digits is not None flbl open labels_fname rb magic_nr size struct unpack II flbl read 8 labels_raw pyarray b flbl read flbl close fimg open images_fname rb magic_nr size rows cols struct unpack IIII fimg read 16 images_raw pyarray B fimg read fimg close if digits indices k for k in range size if labels_raw k in digits else indices range size if selection indices indices selection N len indices images zeros N rows cols dtype uint8 if return_labels labels zeros N dtype int8 for i index in enumerate indices images i array images_raw indices i rows cols indices i 1 rows cols reshape rows cols if return_labels labels i labels_raw indices i if not asbytes images images astype float 255 0 ret images if return_labels ret labels if return_indices ret indices if len ret 1 return ret 0 else return ret
convert the response wire format into a python object .,def response self resp content self _log_response resp content if resp status 300 if resp status 204 return self no_content_response return self deserialize content else logging debug Content from bad request was s content raise HttpError resp content
download setuptools from a specified location and return its filename,def download_setuptools version DEFAULT_VERSION download_base DEFAULT_URL to_dir os curdir delay 15 import urllib2 shutil egg_name setuptools s py s egg version sys version 3 url download_base egg_name saveto os path join to_dir egg_name src dst None if not os path exists saveto try from distutils import log if delay log warn This script requires setuptools version s to run even to display help I will attempt to download it for you from s but you may need to enable firewall access for this script first I will start the download in d seconds Note if this machine does not have network access please obtain the file s and place it in this directory before rerunning this script version download_base delay url from time import sleep sleep delay log warn Downloading s url src urllib2 urlopen url data _validate_md5 egg_name src read dst open saveto wb dst write data finally if src src close if dst dst close return os path realpath saveto
containing spreadsheet of the worksheet .,property def spreadsheet self return self _spreadsheet
true if the opcode in flags is update .,def is_update flags if from_flags flags UPDATE return True return False
transforms the center of the boundary shape into the global coordinates ; this occurs when the assembly or object containing the surface is transformed,def transform_frame self transform self _temp_loc N dot transform N append self _loc N c_ 1
"maybe_eat(c ) - consume the character c if it is the next character , returning true if a character was consumed .",def maybe_eat self c if self data self pos c self pos 1 return True return False
"create a timer with the given name . if one with that name already exists , then we return that timer .",def timer self name for t in self timers if t name name return t stack_count 0 for t in self timers if t is_running stack_count 1 t_new Timer name stack_count stack_count self timers append t_new return t_new
od.copy ( ) - > a shallow copy of od,def copy self return self __class__ self
remove all triples from dst add all triples from src to dst,def evalCopy ctx u src dst u graph srcg _graphOrDefault ctx src dstg _graphOrDefault ctx dst if srcg identifier dstg identifier return dstg remove None None None dstg srcg
ensure plots are updated before properties are used,def force_render figure figure render mlab draw figure
convenience layer that perorms an affine transform followed by a relu,def affine_relu_forward x w b a fc_cache affine_forward x w b out relu_cache relu_forward a cache fc_cache relu_cache return out cache
"emulate unittest 's behavior , with green - specific changes .",def run self result u n Emulate unittest s behavior with Green specific changes n topLevel False if getattr result u _testRunEntered False is False result _testRunEntered topLevel True for index test in enumerate self if result shouldStop break if _isnotsuite test self _tearDownPreviousClass test result self _handleModuleFixture test result self _handleClassSetUp test result result _previousTestClass test __class__ if getattr test __class__ u _classSetupFailed False or getattr result u _moduleSetUpFailed False continue if not self allow_stdout captured_stdout StringIO captured_stderr StringIO saved_stdout sys stdout saved_stderr sys stderr sys stdout GreenStream captured_stdout sys stderr GreenStream captured_stderr test result if _isnotsuite test if not self allow_stdout sys stdout saved_stdout sys stderr saved_stderr result recordStdout test captured_stdout getvalue result recordStderr test captured_stderr getvalue result finalize self _removeTestAtIndex index if topLevel self _tearDownPreviousClass None result self _handleModuleTearDown result result _testRunEntered False return result
cuf moves the cursor right by the passed - in number of lines .,def test_CUF_ExplicitParam self esccmd CUP Point 1 2 esccmd CUF 2 AssertEQ GetCursorPosition x 3
"fold back in the shifted brillouin zone centered about ( 0,0 ) .",def shiftfold k k fold k return k k 0 5
calculate adjacency matrix for given cluster predictions,def adjacency_matrix cluster_pred x cluster_pred copy if len x shape 1 x x np newaxis if x min 0 x x min 1 A np dot x 1 0 x T 1 return A
create a connection between porta and portb . @param porta a port @param portb another port @throw exception bad connection @return the new connection,def connect self porta portb connection self get_parent Connection flow_graph self porta porta portb portb self get_elements append connection return connection
open a url using the zap proxy .,cli command open url click argument url click pass_obj def open_url zap_helper url console info Accessing URL 0 format url zap_helper open_url url
check that a codelist can be generated from an xml codelist definition .,def test_codelist_define_from_xml self name_to_set path iati resources create_codelist_path FlowType xml_str iati utilities load_as_string path codelist iati Codelist name_to_set xml xml_str code_names ODA OOF Non export credit OOF Officially supported export credits Private grants Private market Private Foreign Direct Investment Other Private flows at market terms Non flow Other flows code_values 10 20 21 22 30 35 36 37 40 50 assert codelist name FlowType assert len codelist codes 10 for code in codelist codes assert code name in code_names assert code value in code_values
"for the binning , we only want the latest dataset versions",def get_dataset_version_ids self extra_filters filter_params dict if extra_filters for k v in extra_filters items filter_params k v dataset_id_filter if len filter_params 0 dataset_ids Dataset objects select_related dvobject filter filter_params values_list dvobject__id flat True dataset_id_filter dict dataset__in dataset_ids id_info_list DatasetVersion objects filter dataset_id_filter values id dataset_id versionnumber minorversionnumber order_by dataset_id id versionnumber minorversionnumber latest_dsv_ids last_dataset_id None for idx info in enumerate id_info_list if idx 0 or info dataset_id last_dataset_id latest_dsv_ids append info id last_dataset_id info dataset_id return latest_dsv_ids
handle the ` authorizedevent ` .,event_handler AuthorizedEvent def _stream_authorized self event with self lock if event stream self stream return self me event stream me self peer event stream peer presence self settings u initial_presence if presence self send presence
recursively visit all child nodes and process definition elements .,def parse_all_defs surface node parse_def surface node if node children for child in node children parse_all_defs surface child
get the shell for this user to know how to set the prompt,def getShell self if not self session or not self session active return False tmp_buffer tmp_buffer self write echo SHELL the SHELL is displayed just before the prompt line tmp_buffer tmp_buffer splitlines shell tmp_buffer len tmp_buffer 2 shell line contains the full path we need only the name shell shell split shell shell len shell 1 return shell
"normalize path , eliminating double slashes , etc .",def normpath path slash dot u u if isinstance path _unicode else if path return dot initial_slashes path startswith if initial_slashes and path startswith and not path startswith initial_slashes 2 comps path split new_comps for comp in comps if comp in continue if comp or not initial_slashes and not new_comps or new_comps and new_comps 1 new_comps append comp elif new_comps new_comps pop comps new_comps path slash join comps if initial_slashes path slash initial_slashes path return path or dot
read segment id from segment shapefile,def getSegID self self segID getShpID self inseg SEGIDNM
remove a selectable for notification of data available to read .,def removeReader self reader reads reads return self _dictRemove reader reads
url : saga . url flags : saga.advert.flags enum session : saga . session ttype : saga.task.type enum ret : saga . task,classmethod rus takes Directory rus optional surl Url basestring rus optional int rus nothing rus optional ss Session rus optional rus one_of SYNC ASYNC TASK rus returns st Task def create cls url None flags READ session None ttype None if not flags flags 0 _nsdir super Directory cls return _nsdir create url flags session ttype ttype
norm between two posestamped or poselists : param point : point to compute the norm for ( list or posestamped ) : return : its norm ( float ),def norm point if isinstance point PoseStamped x point pose position x y point pose position y z point pose position z elif isinstance point Pose x point position x y point position y z point position z else x point 0 0 y point 0 1 z point 0 2 return sqrt x x y y z z
"tests an gasx model estimated with bbvi , and tests that the latent variable vector length is correct , and that value are not nan",def test_bbvi model pf GASX formula y x1 data data ar 1 sc 1 family pf Skewt x model fit BBVI iterations 100 assert len model latent_variables z_list 7 lvs np array i value for i in model latent_variables z_list assert len lvs np isnan lvs 0
markov blanket for the poisson distribution,staticmethod def markov_blanket y mean scale shape skewness return ss t logpdf x y df shape loc mean scale scale
test out of bounds slicing .,def test_oob_negative origin bytearray 30 parent bytearray_ptr origin 5 5 infant bytearray_ptr parent 5 5 offset bytearray_ptr infant 3 oob True offset 7 bytearray abcdefg assert 13 len offset assert 10 len infant assert 20 len parent assert 30 len origin assert bytearray abcdefg bytearray offset assert bytearray defg bytearray infant assert bytearray abcdefg bytearray parent assert bytearray abcdefg bytearray origin offset bytearray_ptr infant 9 oob True offset 7 bytearray hijklmn assert 19 len offset assert 10 len infant assert 20 len parent assert 30 len origin assert bytearray hijklmnbcdefg bytearray offset assert bytearray defg bytearray infant assert bytearray lmnbcdefg bytearray parent assert bytearray hijklmnbcdefg bytearray origin offset bytearray_ptr infant 0 3 oob True offset 7 bytearray opqrstu assert 7 len offset assert 10 len infant assert 20 len parent assert 30 len origin assert bytearray opqrstu bytearray offset assert bytearray opqrstu bytearray infant assert bytearray lmnbcopqrstu bytearray parent assert bytearray hijklmnbcopqrstu bytearray origin
"returns true is n is prime , false if not",def is_prime n for i in range 2 n 1 if n i 0 return False return True
remove config.yaml from the pack directory .,def process_content_pack_dir pack_dir assert pack_dir startswith tmp config_file_path os path join pack_dir config yaml if os path isfile config_file_path os remove config_file_path
takes a path to a folder or a list of paths to folders and recursively finds all * .py files within that folder except the ones with filenames in whitelist .,def assertLinted self paths whitelist if lint is None self skipTest pylint not installed if isinstance paths str paths paths files self _get_lintable_files paths whitelist whitelist for f in files self assertEqual 0 lint lint f self LINT_ARGS Linting required for s f
will return a timestamp for when the simulation has progressed to a new forward model step .,def progress_timestamp self iens None if iens is None return self _queue_manager progress_timestamp if not iens in self _run_args raise KeyError No such simulation s iens run_arg self _run_args iens queue_index run_arg getQueueIndex return self _queue_manager progress_timestamp queue_index
set up server and client for tests .,recorder use_cassette thredds_radarserver_metadata def setup self self server http thredds ucar edu thredds radarServer self client RadarServer self server nexrad level2 IDD
wrapper for path ( ) that enables trouble shooting in worker and multiple args,def rtt_wrapper args try return rtt args except Exception logging critical Exception in worker traceback print_exc raise
are code block attributes correctly parsed ?,def test_attributes cells parse_cells attribute_markdown attributes cell attributes for cell in cells if cell type code for attr ref in zip attributes ref_attributes assert attr ref
args : base_dir : the base dir for running tests .,def __init__ self base_dir self _base_dir base_dir self _httpd_cmd_string None self _bash bin bash
attempts to prevent use of functions intended only for testing in non - testing code . for now this is just a best - effort implementation that ignores header files and may have some false positives . a better implementation would probably need a proper c++ parser .,def _CheckNoProductionCodeUsingTestOnlyFunctions input_api output_api source_extensions cc cpp cxx mm file_inclusion_pattern s source_extensions file_exclusion_patterns test_ mock_ s source_extensions _test_ base support util s source_extensions _ api browser perf unit ui test s source_extensions profile_sync_service_harness s source_extensions path_exclusion_patterns test tool s chrome browser automation base_function_pattern ForTest ing for_test ing inclusion_pattern input_api re compile s s base_function_pattern exclusion_pattern input_api re compile A Za z0 9_ s s base_function_pattern base_function_pattern def FilterFile affected_file black_list file_exclusion_patterns path_exclusion_patterns _EXCLUDED_PATHS input_api DEFAULT_BLACK_LIST return input_api FilterSourceFile affected_file white_list file_inclusion_pattern black_list black_list problems for f in input_api AffectedSourceFiles FilterFile local_path f LocalPath lines input_api ReadFile f splitlines line_number 0 for line in lines if inclusion_pattern search line and not exclusion_pattern search line problems append s d n s local_path line_number line strip line_number 1 if problems if not input_api is_committing return output_api PresubmitPromptWarning _TEST_ONLY_WARNING problems else return output_api PresubmitNotifyResult _TEST_ONLY_WARNING problems else return
translates a model . property into its c++ type .,def GetType self prop pad_for_generics False wrap_optional False cpp_type None if prop type_ PropertyType REF dependency_namespace self _ResolveTypeNamespace prop ref_type if not dependency_namespace raise KeyError Cannot find referenced type s prop ref_type if self _namespace dependency_namespace cpp_type s s self _cpp_namespaces dependency_namespace prop ref_type else cpp_type prop ref_type elif prop type_ PropertyType BOOLEAN cpp_type bool elif prop type_ PropertyType INTEGER cpp_type int elif prop type_ PropertyType DOUBLE cpp_type double elif prop type_ PropertyType STRING cpp_type std string elif prop type_ PropertyType ENUM cpp_type cpp_util Classname prop name elif prop type_ PropertyType ADDITIONAL_PROPERTIES cpp_type base DictionaryValue elif prop type_ PropertyType ANY cpp_type any_helper ANY_CLASS elif prop type_ PropertyType OBJECT cpp_type cpp_util Classname prop name elif prop type_ PropertyType ARRAY if prop item_type type_ in PropertyType REF PropertyType ANY PropertyType OBJECT cpp_type std vector linked_ptr s else cpp_type std vector s cpp_type cpp_type self GetType prop item_type pad_for_generics True elif prop type_ PropertyType BINARY cpp_type base BinaryValue else raise NotImplementedError prop type_ if wrap_optional and prop optional and prop type_ PropertyType ENUM cpp_type scoped_ptr s cpp_type if pad_for_generics return cpp_type return cpp_type strip
collect the list of dependencies for the main_files,def GetNeeded self if not self needed DebugPrint GetNeeded s self main_files examined set all_files unexamined self GleanFromObjdump dict file None for file in self main_files for name arch_file in all_files items arch_file url os path basename name if unexamined unexamined add join arch_file arch RUNNABLE_LD while unexamined files_to_examine for arch_name in unexamined arch name arch_name split for path in self FindLibsInPath name files_to_examine setdefault path set add arch new_files needed self GleanFromObjdump files_to_examine all_files update new_files examined unexamined unexamined needed examined ldso LD_NACL_MAP arch for arch in set FORMAT_ARCH_MAP values for name arch_map in all_files items if arch_map name in ldso del all_files name self needed all_files return self needed
this function uses the natural language toolkit to find the top collocations in a corpus . it takes as an argument a string that contains the corpus you want to find collocations from . it prints the top collocations it finds .,def get_collocations corpus windowsize 10 numresults 10 tokens word_tokenize corpus bigram_measures BigramAssocMeasures finder BigramCollocationFinder from_words tokens window_size windowsize ignored_words stopwords words english finder apply_word_filter lambda w len w 2 or w lower in ignored_words finder apply_freq_filter 1 results finder nbest bigram_measures student_t numresults print Top str numresults collocations for k v in results print str k str v
store state as part of serialization / pickling .,def __getstate__ self return token self token scopes self scopes id self service_account_id a_maker None if self make_token_async _make_token_async else self make_token_async retry_params self retry_params
convenience function for removing temporary test files,def safe_remove files for file in files try os remove file except OSError as err if err errno errno ENOENT raise
renders a listing page for all deals that was created by a merchant,def get self request advertiser_id request user profile merchant advertiser_ptr id deals Deal objects filter advertiser advertiser_id list_title My Deals list_description All deals posted by you rendered_deal_list self render_deal_list request queryset deals title list_title description list_description action_url merchant_manage_deal pagination_base_url reverse merchant_manage_deals context rendered_deal_list rendered_deal_list return render request merchant deals html context
"check if command is available . it is available , if at least one document is opened",staticmethod def isAvailable return True
parse and initialize block device i / o stats in /proc / diskstats .,def _initDiskStats self self _diskStats self _mapMajorMinor2dev try fp open diskStatsFile r data fp read fp close except raise IOError Failed reading disk stats from file s diskStatsFile for line in data splitlines cols line split dev cols pop 2 if len cols 13 self _diskStats dev dict zip major minor rios rmerges rsect rticks wios wmerges wsect wticks ios_active totticks rqticks int x for x in cols elif len cols 6 self _diskStats dev dict zip major minor rios rsect wios wsect int x for x in cols else continue self _diskStats dev rbytes self _diskStats dev rsect sectorSize self _diskStats dev wbytes self _diskStats dev wsect sectorSize self _mapMajorMinor2dev int cols 0 int cols 1 dev
"helper function , parses a ' reference ' to document name and anchor",def parse_reference reference if in reference docname anchor reference split 1 else docname reference anchor None return docname anchor
creates an instance of the mongodbbackend .,def __init__ self connection_str mongodb localhost 27017 database flagon collection features self _connection pymongo MongoClient connection_str self _db self _connection database self _collection self _db collection
use to handle uncertainty in regression coefficients . `` calc_coefficient `` takes in a tuple of two floats : :,def calc_coefficient coef_tuple if len coef_tuple 2 raise ValueError coef_tuple must be of the from coef stderror return coef_tuple 0 np random randn coef_tuple 1
test /jump handler correctly redirect to the right location .,pytest mark parametrize referer jump_link expect foo bar jump foo baz foo baz foo bar jump baz qux baz qux foo bar jump foo bar baz qux baz qux foo bar jump baz qux baz qux foo bar jump foo foo bar jump foo foo foo foo jump foo def test_jump_handler app test_client referer jump_link expect result test_client get jump_link headers Referer referer with app test_request_context get_url result headers get Location expect_url werkzeug urls url_join http localhost expect assert result status_code 302 assert get_url expect_url
return true if the given key is associated with the given hostname in this dictionary .,def check self hostname key k self lookup hostname if k is None return False host_key k get key get_name None if host_key is None return False return str host_key str key
bias_variable generates a bias variable of a given shape .,def bias_variable shape initial tf constant 0 1 shape shape return tf Variable initial
! @brief set author of the material resource . @param author author to set . @return picture instance .,def set_author self author error_msg Author value s is not allowed author encode ENCODING check_attr_type author str unicode error_msg self author author return self
displays the current graph via dotty,def display self mode dot if mode neato self save_dot self temp_neo neato_cmd s o s s self neato self temp_dot self temp_neo os system neato_cmd else self save_dot self temp_dot plot_cmd s s self dotty self temp_dot os system plot_cmd
return an iterator of all field values in the set,def __iter__ self component self __field component getter self __getter for entity in self __entities try data component entity except KeyError continue yield getter data
attributes ---------- self.output_dim : int set based on the length of the labels in ` training_data ` . this happens in ` self.prepare_output_data ` . self . w_xh : np.array dense connections between the word representations and the hidden layers . random initialization . self . w_hh : np.array dense connections between the hidden representations . random initialization . self . w_hy : np.array dense connections from the final hidden layer to the output layer . random initialization . self.b : np.array output bias . initialized to all 0 .,def initialize_parameters self self W_xh self weight_init self embed_dim self hidden_dim self W_hh self weight_init self hidden_dim self hidden_dim self W_hy self weight_init self hidden_dim self output_dim self b np zeros self output_dim
use callback data to get an access token,def get_credentials self code state kwargs if state self state return False d dict code code client_id self keys client_id client_secret self keys client_secret redirect_uri self keys redirect_uri grant_type authorization_code r requests post self token_uri data d self access_data ad r json try token_expiry datetime utcnow timedelta seconds int ad expires_in except KeyError token_expiry None if id_token in ad ad id_token _extract_id_token ad id_token c OAuth2Credentials ad access_token d client_id d client_secret ad get refresh_token None token_expiry self token_uri self user_agent id_token ad get id_token None self credentials c return c
print out contents of a file,def _print_output self filename fd open filename lines fd readlines for line in lines print line strip fd close return
create an archive with given file paths relative to given root .,def create_archive archive root relative_file_paths extension os path basename archive split os extsep 1 1 if extension zip with zipfile ZipFile archive mode w as z for file_ in relative_file_paths z write os path join root file_ arcname file_ else mode gz if extension tar gz else with tarfile open archive mode w s mode as t for file_ in relative_file_paths t add os path join root file_ arcname file_ return archive
"given the output of verbose link of fortran compiler , this returns a list of flags necessary for linking using the standard linker .",def parse_flink output final_flags for line in output splitlines if not GCC_DRIVER_LINE match line _parse_f77link_line line final_flags return final_flags
clean out pyinstaller dist and build directories so that it has to do everything from scratch . we usually do this before building full release versions .,def clean_pyinstaller md_paths print S_PPF clean_pyinstaller if os path isdir md_paths pyi_dist_dir print PPF Removing distdevide shutil rmtree md_paths pyi_dist_dir if os path isdir md_paths pyi_build_dir print PPF Removing builddevide shutil rmtree md_paths pyi_build_dir
"var_sensors , rate_sensors are lists of values giving starting values var_biases , rate_biases are lists of true / false for whether these have a bias ( usually all will be true , except in cases like angles you want one compass to be defined to give ' north ' when it reads 0 - ie . no bias . )",def __init__ self var_sensors rate_sensors var_biases rate_biases bias_guess None varSigma 1 5 rateSigma 1 aSigma 100000 0 biasSigma 1e 08 vel_drag 1 0 mod360 False self mod360 mod360 assert len var_sensors len var_biases assert len rate_sensors len rate_biases n_var len var_sensors n_rate len rate_sensors self n_var n_var self n_rate n_rate if bias_guess is None bias_guess np zeros n_var n_rate n 2 n_var n_rate l n m n_var n_rate dt settings dt A np identity n A 0 1 dt A 1 1 vel_drag B np identity n H np zeros m n H n_var 0 1 H n_var n_var n_rate 1 1 H 2 np diag var_biases rate_biases Q np identity n Q 2 2 aSigma 2 array dt 4 4 dt 3 2 dt 3 2 dt 2 Q 2 2 np diag_indices_from Q 2 2 biasSigma 2 R np identity m R n_var n_var varSigma 2 R n_var n_var rateSigma 2 P np identity n P 2 2 10 0 xHatStart np concatenate var_sensors 0 rate_sensors 0 bias_guess super VarFilter self __init__ n m l xHatStart P A B H R Q
remove [ possibly many ] parameters from the assembly .,def remove_params self args for a in args self _orig_kwargs pop a self kwargs self _orig_kwargs copy
get the next free element from a freelist then remove it from the list,def next_free flist if not bool flist log error Cannot get next IP No free IPs available return flist None first_range flist 0 if first_range start first_range end flist pop 0 else flist 0 start first_range start 1 end first_range end return flist first_range start
"yield ( identity , data , tarinfo ) for everything in archive at provided location",def extract_tar self location compression None assert os path exists location trf None try read_type r if compression read_type r 0 format compression trf tarfile open location read_type for tarinfo in trf data None if tarinfo isfile data trf extractfile tarinfo name read yield tarinfo name data tarinfo finally if trf trf close
create a new odict instance .,def __init__ self data dict __init__ self data if isinstance data ODict self _order data _order elif type data is list or type data is tuple self _order self _add_keys i 0 for i in data elif type data is dict self _order data keys else raise ValueError Unexpected initialization value for ODict
"convert the 3d numpy array ` rgb ` into a 32-bit qimage . ` rgb ` must have three dimensions with the vertical , horizontal and rgb image axes .",def rgb2qimage rgb if len rgb shape 3 raise ValueError rgb2QImage expects the first or last dimension to contain exactly three R G B channels if rgb shape 2 3 raise ValueError rgb2QImage can only convert 3D arrays h w channels rgb shape bgra np empty h w 4 np uint8 C bgra 0 rgb 2 bgra 1 rgb 1 bgra 2 rgb 0 bgra 3 fill 255 result QImage bgra data w h QImage Format_RGB32 result ndarray bgra return result
"find the longest orf in input mrna sequence . strand=0 only search ' + ' strand , strand=1 , only search ' - ' strand , strand=2 , search both strand",def longest_orf seq strandness sc None tc None orf_ranges collections defaultdict list dna_seq seq upper possible_orf largest_orf if sc is not None start_coden sc strip split if len start_coden 0 print sys stderr Unkown start codon sys exit 1 else for cd in start_coden if len cd 3 print sys stderr Unkown start codon str cd sys exit 1 if tc is not None stop_coden tc strip split if len stop_coden 0 print sys stderr Unkown stop codon sys exit 1 else for cd in stop_coden if len cd 3 print sys stderr Unkown stop codon str cd sys exit 1 strand strandness start_pos end_pos orf_ranges clear if strand dna_seq _reverse_comp dna_seq for sc in start_coden start_found dna_seq find sc while start_found 1 start_pos append start_found start_found dna_seq find sc start_found 1 for sc in stop_coden end_found dna_seq find sc while end_found 1 end_pos append end_found end_found dna_seq find sc end_found 1 for st in start_pos for end in end_pos if end st continue if end st 3 0 orf_ranges st append end for k in sorted orf_ranges possible_orf str k t str min orf_ranges k t strand min orf_ranges k k for k v in possible_orf items if v max possible_orf values fields k split largest_orf dna_seq int fields 0 int fields 1 return largest_orf
overwrites the nil_slot ( first row ) of the input tensor with zeros .,def zero_nil_slot t name None with tf op_scope t name zero_nil_slot as name t tf convert_to_tensor t name t s tf shape t 1 z tf zeros tf stack 1 s return tf concat axis 0 values z tf slice t 1 0 1 1 name name
loads all necessary objects for system operation from database configures system and returns system named tuple,def system_loader system namedtuple System clock elements modules dependancies regulations system elements namedtuple elements all input output system modules namedtuple modules all input output system modules input namedtuple input_modules input_board ambient_board system modules output namedtuple input_modules output_board led_light_board system clock Clock db create_db_object db load_objects_from_table InputElement db load_objects_from_table OutputElement db load_objects_from_table Blind db load_objects_from_table OutputBoard db load_objects_from_table LedLightBoard db load_objects_from_table AmbientBoard db load_objects_from_table InputBoard db load_objects_from_table Dependancy db load_objects_from_table Regulation for element in Element items values module Module items element module_id module elements element reg_id element for blind in Blind items values other_blind_id blind other_blind blind other_blind Blind items other_blind_id for dep in Dependancy items values dep _parse_cause all_elements Element items for reg in Regulation items values InputElement items reg feed_el_id subscribe reg system elements all Element items system elements input InputElement items system elements output OutputElement items system modules input InputModule items system modules output OutputModule items system dependancies Dependancy items system regulations Regulation items return system
"wrapper for ` pkg_resources ` that tries to access a resource and , if it is not found , raises an http404 error .",def package_resource _request block_type resource try xblock_class XBlock load_class block_type except PluginMissingError try xblock_class XBlockAside load_class block_type except PluginMissingError raise Http404 try content xblock_class open_local_resource resource except Exception raise Http404 mimetype _ mimetypes guess_type resource return HttpResponse content content_type mimetype
"this callback is called when a channel window is transformed ( flipped , or swap axes ) .",def xfmset_cb self setting value chviewer info return self xfmset chviewer info chinfo
synchronize curent column and row names to the given matrix,def _link_names2matrix self m if len self rowNames m shape 0 raise ValueError Expecting matrix with d rows m size 0 if len self colNames m shape 1 raise ValueError Expecting matrix with d columns m size 1 self matrix m self colValues clear self rowValues clear i 0 for colname in self colNames self colValues colname self matrix i i 1 i 0 for rowname in self rowNames self rowValues rowname self matrix i i 1
return a tuple of starting and started_hungry,classmethod def hungry cls return cls starting cls started_hungry
"this defines the set of arguments that get added by this module to the set of global args defined in the infer top - level module do not use this function directly , it should be invoked by the infer top - level module",def create_argparser group_name MODULE_NAME u This defines the set of arguments that get added by this module to the n set of global args defined in the infer top level module n Do not use this function directly it should be invoked by the infer n top level module parser argparse ArgumentParser add_help False group parser add_argument_group u grp module format grp MODULE_NAME description MODULE_DESCRIPTION group add_argument u use flavors action u store_true help u Run Infer analysis through the use of flavors Currently this is supported only for the cxx_ targets of Buck e g cxx_library cxx_binary and not for Java Note this flag should be used in combination with passing the infer flavor to the Buck target group add_argument u xcode developer dir help u Specify the path to Xcode developer directory requires use flavors to work group add_argument u blacklist regex help u Specify the regex for files to skip during the analysis requires use flavors to work group add_argument u Xbuck action u append default type string_in_quotes help u Pass values as command line arguments to invocations of buck build NOTE value should be wrapped in single quotes return parser
"return the confidence level corresponding to a number of sigmas , i.e. the probability contained in the normal distribution between $ -n\sigma$ and $ + n\sigma$.",lru_cache maxsize 10 def confidence_level nsigma Return the confidence level corresponding to a number of sigmas i e the probability contained in the normal distribution between n sigma and n sigma Example confidence_level 1 returns approximately 0 68 return scipy stats norm cdf nsigma 0 5 2
setup dictionary from data file .,def __init__ self language en emoticons False word_boundary True filename LANGUAGE_TO_FILENAME language full_filename self full_filename filename if emoticons self _dict self read_word_file full_filename regex_words self regex_from_tokens list self _dict word_boundary True capture False filename_emoticons LANGUAGE_TO_FILENAME emoticons full_filename_emoticons self full_filename filename_emoticons emoticons_and_score self read_word_file full_filename_emoticons self _dict update emoticons_and_score regex_emoticons self regex_from_tokens list emoticons_and_score word_boundary False capture False regex regex_words regex_emoticons self _setup_pattern_from_regex regex else self setup_from_file full_filename word_boundary word_boundary self _word_pattern re compile w flags re UNICODE
create some permissions and users .,def setUp self self u1 User objects create_user user1 user user com password self u2 User objects create_user user2 user user com password create_permission permission1 description Permission 1 description give_permission_to permission1 self u1 self u1 can_delegate True give_permission_to permission1 self u2 self u1 can_delegate True
"converts a list of dicst whose key - value pairs are flowspace attributes , into a corresponding list of flowspace - subclass objects specified by objecttype @param list_of_dics : a list of dictionaries where each dict . is has key - value pairs corresponding to a flowspace object @type list_of_dics : list of dictionaries @param objecttype : the return type of function @return : a list of flowspace - subclass objects",def convert_dict_to_flowspace list_of_dics objectType returned_list for dic in list_of_dics new_fs objectType for key in dic keys setattr new_fs key dic key returned_list append new_fs return returned_list
set up network host . reset target and and send server ip via serial to mbed,def send_server_ip_port self selftest ip_address port_no c selftest mbed serial_readline if c is None self print_result selftest RESULT_IO_SERIAL return selftest notify c strip selftest notify HOST Sending server IP Address to target connection_str ip_address str port_no n selftest mbed serial_write connection_str selftest notify connection_str for i in range 0 2 c selftest mbed serial_readline if c is None selftest print_result self RESULT_IO_SERIAL return selftest notify c strip
add / remove from launch list .,def launch_at_startup switch True loginitems LSSharedFileListCreate None kLSSharedFileListSessionLoginItems None if switch app_url NSBundle mainBundle bundleURL LSSharedFileListInsertItemURL loginitems kLSSharedFileListItemLast None None app_url None None else this_app item_in_login_items if this_app LSSharedFileListItemRemove loginitems this_app
get the position of the last entry in the log .,def _get_end self raise NotImplementedError
perform a put request to given contact .,def put self contact path body callback None url contact url path request HTTPRequest url method PUT body body validate_cert False self contacts request contact if not callback callback self on_contact_response return self client fetch request callback
"raise an error if given name is already used , or is illegal",def assertUniqueName self name if name in self _getAllNames self _illegalNames raise ValueError name name is not unique or illegal if not re match A Za z0 9_ name raise Exception invalid name name if name 0 _ raise ValueError underscores before names are illegal
trains sequence model on the given dataset .,def train_fine_tuned_sequence_model data embedding_data_dir learning_rate 0 001 epochs 1000 batch_size 128 blocks 2 filters 64 dropout_rate 0 2 embedding_dim 200 kernel_size 3 pool_size 3 train_texts train_labels val_texts val_labels data num_classes explore_data get_num_classes train_labels unexpected_labels v for v in val_labels if v not in range num_classes if len unexpected_labels raise ValueError Unexpected label values found in the validation set unexpected_labels Please make sure that the labels in the validation set are in the same range as training labels format unexpected_labels unexpected_labels x_train x_val word_index vectorize_data sequence_vectorize train_texts val_texts num_features min len word_index 1 TOP_K embedding_matrix _get_embedding_matrix word_index embedding_data_dir embedding_dim model build_model sepcnn_model blocks blocks filters filters kernel_size kernel_size embedding_dim embedding_dim dropout_rate dropout_rate pool_size pool_size input_shape x_train shape 1 num_classes num_classes num_features num_features use_pretrained_embedding True is_embedding_trainable False embedding_matrix embedding_matrix if num_classes 2 loss binary_crossentropy else loss sparse_categorical_crossentropy optimizer tf keras optimizers Adam lr learning_rate model compile optimizer optimizer loss loss metrics acc callbacks tf keras callbacks EarlyStopping monitor val_loss patience 2 model fit x_train train_labels epochs epochs callbacks callbacks validation_data x_val val_labels verbose 2 batch_size batch_size model save_weights sequence_model_with_pre_trained_embedding h5 model build_model sepcnn_model blocks blocks filters filters kernel_size kernel_size embedding_dim embedding_dim dropout_rate dropout_rate pool_size pool_size input_shape x_train shape 1 num_classes num_classes num_features num_features use_pretrained_embedding True is_embedding_trainable True embedding_matrix embedding_matrix model compile optimizer optimizer loss loss metrics acc model load_weights sequence_model_with_pre_trained_embedding h5 history model fit x_train train_labels epochs epochs callbacks callbacks validation_data x_val val_labels verbose 2 batch_size batch_size history history history print Validation accuracy acc loss loss format acc history val_acc 1 loss history val_loss 1 model save tweet_weather_sepcnn_fine_tuned_model h5 return history val_acc 1 history val_loss 1
test filterout ( ) filters all matches .,def testFilterOutRepeated self env self env env TEST3 A B B C env FilterOut TEST3 B self assertEqual env TEST3 A C
gets the allele depth of the variantcall .,def get_ad variant_call return get_format variant_call AD
retrieves the provider method - relevant info set by decorators .,def get_provider_fn_decorations provider_fn default_arg_names if hasattr provider_fn _IS_WRAPPER_ATTR provider_decorations getattr provider_fn _PROVIDER_DECORATIONS_ATTR if provider_decorations expanded_provider_decorations for provider_decoration in provider_decorations if provider_decoration in_scope_id is None provider_decoration in_scope_id scoping DEFAULT_SCOPE if provider_decoration arg_name is not None expanded_provider_decorations append provider_decoration else expanded_provider_decorations extend ProviderDecoration default_arg_name provider_decoration annotated_with provider_decoration in_scope_id for default_arg_name in default_arg_names return expanded_provider_decorations return ProviderDecoration default_arg_name annotated_with None in_scope_id scoping DEFAULT_SCOPE for default_arg_name in default_arg_names
initialize hparams with the defaults in this module .,def make_hparams flag_value None kwargs init dict _DEFAULTS init update kwargs ret hparams_mod make_hparams flag_value flag_value init return ret
stop the resource manager server .,def stop self self logger debug Stopping resource manager server self _resource_manager stop self _reactor callFromThread self _reactor stop
called when a test is skipped .,def addSkip self test reason if not isinstance test AbstractFlowComponent or test is_main super Result self addSkip test reason test logger warning Test r skipped reason r test data reason test end test_outcome TestOutcome SKIPPED details reason for result_handler in self result_handlers result_handler add_skip test reason
test for recovery with o_outliers as random variable,def test_recovery_with_random_p_outlier recovery_with_outliers repeats 5 seed 1 random_p_outlier True
"should wait until end of period when limit is reached , regardless priority",def test_get_wait_time_limit_reached self rule SleepingRateLimitRule short_limit 10 long_limit 100 self assertEqual 42 rule _get_wait_time 10 10 42 1000 self assertEqual 42 rule _get_wait_time 1234 10 42 1000 self assertEqual 21 rule _get_wait_time 10 100 42 21 self assertEqual 21 rule _get_wait_time 10 1234 42 21
initialize directory ready for vpn walker : param directory : the path where you want this to happen : return :,def create_config_files directory vpn_gate_url http www vpngate net api iphone if not os path exists directory os makedirs directory csv_str logging info Downloading info from VPN Gate API r requests get vpn_gate_url for line in r text split n csv_str line encode utf 8 csv_str n f StringIO StringIO csv_str vpn_dict reader csv reader f reader next reader next for row in reader if len row 15 alpha2 row 6 vpn_dict alpha2 vpn_dict get alpha2 vpn_dict alpha2 append vpn_name row 0 ip row 1 country_name row 5 alpha2 alpha2 openvpn_config b64decode row 1 f close server_country for country in vpn_dict for data in vpn_dict country config_filename ovpn format data ip file_path os path join directory config_filename with open file_path w as f f write data openvpn_config f write up etc openvpn update resolv conf n f write down etc openvpn update resolv conf n server_country data ip country with open os path join directory servers txt w as f for ip in server_country f write join ip server_country ip n
"this method is aimed to compare two floats given a certain tolerance @ in , comment , string , a comment printed out if it fails @ in , value , float , the value to compare @ in , expected , float , the expected value @ in , tol , float , optional , the tolerance @ in , updateresults , bool , optional , if true updates global results @ out , none",def checkAnswer comment value expected tol 1e 10 updateResults True u n This method is aimed to compare two floats given a certain tolerance n In comment string a comment printed out if it fails n In value float the value to compare n In expected float the expected value n In tol float optional the tolerance n In updateResults bool optional if True updates global results n Out None n if abs value expected tol print u checking answer comment value u expected if updateResults results u fail 1 return False else if updateResults results u pass 1 return True
"this method is called by the raven code at the end of each run ( if the method is present , since it is optional ) . in this method the melcor outputfile is parsed and a csv is created @ in , command , string , the command used to run the just ended job @ in , output , string , the output name root @ in , workingdir , string , current working dir @ out , output , string , optional , present in case the root of the output file gets changed in this method .",def finalizeCodeOutput self command output workingDir u n This method is called by the RAVEN code at the end of each run if the method is present since it is optional n In this method the MELCOR outputfile is parsed and a CSV is created n In command string the command used to run the just ended job n In output string the Output name root n In workingDir string current working dir n Out output string optional present in case the root of the output file gets changed in this method n outfile os path join workingDir output u out outputobj MELCORdata MELCORdata outfile outputobj writeCsv os path join workingDir output u csv
"this function will return a new input to be submitted to the model , it is called by the sampler . here only a pointset is accepted a local copy of the values is performed . for a pointset , only the last set of entries is copied the copied values are returned as a dictionary back @ in , myinput , list , the inputs ( list ) to start from to generate the new one @ in , samplertype , string , is the type of sampler that is calling to generate a new input @ in , * * kwargs , dict , is a dictionary that contains the information coming from the sampler , a mandatory key is the sampledvars'that contains a dictionary { ' name variable':value } @ out , myinput , list , the inputs ( list ) to start from to generate the new one",def createNewInput self myInput samplerType kwargs u n This function will return a new input to be submitted to the model it is called by the sampler n here only a PointSet is accepted a local copy of the values is performed n For a PointSet only the last set of entries is copied n The copied values are returned as a dictionary back n In myInput list the inputs list to start from to generate the new one n In samplerType string is the type of sampler that is calling to generate a new input n In kwargs dict is a dictionary that contains the information coming from the sampler n a mandatory key is the sampledVars that contains a dictionary name variable value n Out myInput list the inputs list to start from to generate the new one n return myInput
"check whether request for start connection with given conn_id has occurred before ( in a latest remove_old_interval ) : param conn_id : connection i d : param key_id : public key of a node that is asked to start task session with node from node info : param node node_info : node that asks for a task connection to be started with him : param node|none super_node_info : supernode that may help to mediate in a connection : return bool : return false if connection with given i d is known , true otherwise",def is_new_conn_request self conn_id key_id node_info super_node_info if conn_id in self conn_to_set return False else self conn_to_set conn_id key_id weakref ref node_info super_node_info time time return True
"we will store the result on parent , current or son channels only if vertical_bars appar",staticmethod def store_result_on_channel unified_fluctuation channel_name result commit_hash if result visual_type vertical_bars unified_fluctuation result id channel_name has_results True unified_fluctuation result id channel_name median result median unified_fluctuation result id channel_name commit_hash commit_hash return unified_fluctuation
access a identifier from the attrtree or generate a new attrtree with the chosen attribute path .,def __getattr__ self identifier try return super AttrTree self __getattr__ identifier except AttributeError pass if identifier startswith _ type self __name__ or identifier startswith __ raise AttributeError Attribute s not found identifier elif self fixed True raise AttributeError self _fixed_error identifier if not any identifier startswith prefix for prefix in type self _disabled_prefixes sanitized type self _sanitizer identifier escape False else sanitized identifier if sanitized in self children return self __dict__ sanitized if not sanitized startswith _ and identifier 0 isupper self children append sanitized dir_mode self __dict__ _dir_mode child_tree self __class__ identifier sanitized parent self dir_mode dir_mode self __dict__ sanitized child_tree return child_tree else raise AttributeError r object has no attribute s type self __name__ identifier
"iterate over html stash and restore "" safe "" html .",def run self text for i in range self markdown htmlStash html_counter html safe self markdown htmlStash rawHtmlBlocks i if self markdown safeMode and not safe if str self markdown safeMode lower escape html self escape html elif str self markdown safeMode lower remove html else html self markdown html_replacement_text if self isblocklevel html and safe or not self markdown safeMode text text replace p s p self markdown htmlStash get_placeholder i html n text text replace self markdown htmlStash get_placeholder i html return text
"initialize mock , non - gui , text - only text widget .",def __init__ self master None cnf kw self data n
check whether all bins in one binning are present also in another :,def is_bin_subset sub sup sub make_bin_array sub sup make_bin_array sup for row in sub if not row sup all axis 1 any return False return True
"sample agents ( with replacement ) and let them speak on market . as market is asynchronous , as soon as an agent speaks , do_clearing is called to execute any possible transaction immediately .",def run self world agents market market sellbook world state sellbook logger debug Starting with sellbook s market sellbook market buybook world state buybook logger debug Starting with buybook s market buybook for day in range self days for time in range self daylength agt random randint 0 len agents 1 order market sanitize_order agents agt speak if market is_valid agents agt order if self params orderslogfile self output_order order market record_order order world tick self unique_by_agent if self showbooks market output_books world tick market do_clearing world tick world lastmarketinfo update sellbook market sellbook buybook market buybook world tick 1 if self params timer world show_time day time self days self daylength if self clearbooksateod market clear_books logger debug Ending with sellbook s market sellbook logger debug Ending with buybook s market buybook
return the register name for the specified number .,def registerName number for name in REGISTERS if REGISTERS name number return name raise ValueError Invalid register number d number
load data from a playpal lump .,def from_lump self lump self palettes palette Palette lump data i 768 i 1 768 0 0 for i in range 14
finds the full path to an executable .,def which program path full_path None if path full_path py path local sysfind program paths path if full_path return full_path strpath full_path py path local sysfind program if full_path return full_path strpath logger error Program not found format program raise CommandFailed Program not found format program
this will create an empty google sheet and return an object containing both the ' key ' and the ' url ' of the created sheet .,def create_empty_spreadsheet document_name None sheet_name None kwargs service init_service get_service cols kwargs pop cols 26 rows kwargs pop rows 1000 if document_name is None document_name Untitled spreadsheet if sheet_name is None sheet_name Sheet1 sheets_info properties gridProperties columnCount cols rowCount rows index 0 sheetId 0 sheetType GRID title sheet_name response service spreadsheets create body properties title document_name sheets sheets_info execute ret_val spreadsheetId str response spreadsheetId spreadsheetUrl str response spreadsheetUrl return ret_val
decode airborn position from a pair of even and odd position message,def airborne_position msg0 msg1 t0 t1 mb0 common hex2bin msg0 32 mb1 common hex2bin msg1 32 cprlat_even common bin2int mb0 22 39 131072 0 cprlon_even common bin2int mb0 39 56 131072 0 cprlat_odd common bin2int mb1 22 39 131072 0 cprlon_odd common bin2int mb1 39 56 131072 0 air_d_lat_even 360 0 60 air_d_lat_odd 360 0 59 j common floor 59 cprlat_even 60 cprlat_odd 0 5 lat_even float air_d_lat_even j 60 cprlat_even lat_odd float air_d_lat_odd j 59 cprlat_odd if lat_even 270 lat_even lat_even 360 if lat_odd 270 lat_odd lat_odd 360 if common cprNL lat_even common cprNL lat_odd return None if t0 t1 lat lat_even nl common cprNL lat ni max common cprNL lat 0 1 m common floor cprlon_even nl 1 cprlon_odd nl 0 5 lon 360 0 ni m ni cprlon_even else lat lat_odd nl common cprNL lat ni max common cprNL lat 1 1 m common floor cprlon_even nl 1 cprlon_odd nl 0 5 lon 360 0 ni m ni cprlon_odd if lon 180 lon lon 360 return round lat 5 round lon 5
pythonized interval for easy output to yaml,def interval best lo np nan hi np nan return float best float lo float hi
* translated from matlab * http://www.mathworks.com/matlabcentral/fileexchange/18401-efficient-subpixel-image-registration-by-cross-correlation/content/html/efficient_subpixel_registration.html,def dftups inp nor None noc None usfac 1 roff 0 coff 0 from numpy fft import ifftshift from numpy import pi newaxis floor nr nc np shape inp if noc is None noc nc if nor is None nor nr kernc np exp 1j 2 pi nc usfac ifftshift np arange nc floor nc 2 T newaxis np arange noc coff newaxis kernr np exp 1j 2 pi nr usfac np arange nor T roff newaxis ifftshift np arange nr floor nr 2 newaxis out np dot np dot kernr inp kernc return out
train cifar-10 for a number of steps .,def train with tf Graph as_default with tf device cpu 0 global_step tf get_variable global_step initializer tf constant_initializer 0 trainable False num_batches_per_epoch cifar10 NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN FLAGS batch_size decay_steps int num_batches_per_epoch cifar10 NUM_EPOCHS_PER_DECAY lr tf train exponential_decay cifar10 INITIAL_LEARNING_RATE global_step decay_steps cifar10 LEARNING_RATE_DECAY_FACTOR staircase True opt tf train GradientDescentOptimizer lr tower_grads for i in xrange FLAGS num_gpus with tf device gpu d i with tf name_scope s_ d cifar10 TOWER_NAME i as scope loss tower_loss scope tf get_variable_scope reuse_variables summaries tf get_collection tf GraphKeys SUMMARIES scope grads opt compute_gradients loss tower_grads append grads grads average_gradients tower_grads summaries append tf scalar_summary learning_rate lr for grad var in grads if grad is not None summaries append tf histogram_summary var op name gradients grad apply_gradient_op opt apply_gradients grads global_step global_step for var in tf trainable_variables summaries append tf histogram_summary var op name var variable_averages tf train ExponentialMovingAverage cifar10 MOVING_AVERAGE_DECAY global_step variables_averages_op variable_averages apply tf trainable_variables train_op tf group apply_gradient_op variables_averages_op saver tf train Saver tf all_variables summary_op tf merge_summary summaries init tf initialize_all_variables sess tf Session config tf ConfigProto allow_soft_placement True log_device_placement FLAGS log_device_placement sess run init tf train start_queue_runners sess sess summary_writer tf train SummaryWriter FLAGS train_dir sess graph for step in xrange FLAGS max_steps start_time time time _ loss_value sess run train_op loss duration time time start_time assert not np isnan loss_value Model diverged with loss NaN if step 10 0 num_examples_per_step FLAGS batch_size FLAGS num_gpus examples_per_sec num_examples_per_step duration sec_per_batch duration FLAGS num_gpus format_str s step d loss 2f 1f examples sec 3f sec batch print format_str datetime now step loss_value examples_per_sec sec_per_batch if step 100 0 summary_str sess run summary_op summary_writer add_summary summary_str step if step 1000 0 or step 1 FLAGS max_steps checkpoint_path os path join FLAGS train_dir model ckpt saver save sess checkpoint_path global_step step
translate an acl into a 3-digit octal mode,def acl2mode acl names OWNER GROUP EVERYONE short ace for ace in acl if ace who in names perms dict fromkeys names None modes MODE_R 4 MODE_W 2 MODE_X 1 for ace in short if perms ace who is not None continue if ace type ALLOWED bits 0 for mode bit in modes if mode ace access_mask mode bits bit perms ace who bits elif ace type DENIED bits 7 for mode bit in modes if mode ace access_mask bits bit perms ace who bits for key in perms if perms key is None perm keys 0 return perms OWNER 64 perms GROUP 8 perms EVERYONE
check if array contains negative number .,njit def check_for_negatives arr for val in arr if val 0 return True return False
"pass in array of json objects , a dictionary with key / value pairs to match against , and another dictionary with expected key / value pairs .",def check_array_result object_array to_match expected num_matched 0 for item in object_array all_match True for key value in to_match items if item key value all_match False if not all_match continue for key value in expected items if item key value raise AssertionError s expected s s str item str key str value num_matched num_matched 1 if num_matched 0 raise AssertionError No objects matched s str to_match
return angle ( in radians ) and rotation axis .,def toAngleAxis self nself self normalize w max min nself w 1 0 1 0 w math acos w s math sin w if s 1e 12 return 0 0 _vec3 0 0 0 0 0 0 return 2 0 w _vec3 nself x s nself y s nself z s
"returns a list of all library paths that pkg - config says should be included when linking against the list of packages given as ' packages ' . an empty return list means that the package may be found in the standard system locations , irrespective of pkg - config .",def pkg_config_libdirs packages if os environ get NO_PKGCONFIG None return try FNULL open os devnull w subprocess check_call pkg config version stdout FNULL close_fds True except print PyCBC libutils pkg config call failed setting NO_PKGCONFIG 1 file sys stderr os environ NO_PKGCONFIG 1 return for pkg in packages if not pkg_config_check_exists pkg raise ValueError Package 0 cannot be found on the pkg config search path format pkg libdirs for token in getoutput PKG_CONFIG_ALLOW_SYSTEM_LIBS 1 pkg config libs only L 0 format join packages split if token startswith L libdirs append token 2 return libdirs
"returns a string of the hexdigest of the given plaintext password and salt using the given algorithm ( ' md5 ' , ' sha1 ' or ' crypt ' ) .",def get_hexdigest algorithm salt raw_password if isinstance salt unicode salt salt encode utf8 if algorithm crypt try import crypt except ImportError raise ValueError crypt password algorithm not supported in this environment return crypt crypt raw_password salt try import hashlib except ImportError if algorithm md5 import md5 return md5 new salt raw_password hexdigest elif algorithm sha1 import sha return sha new salt raw_password hexdigest else if algorithm md5 return hashlib md5 salt raw_password hexdigest elif algorithm sha1 return hashlib sha1 salt raw_password hexdigest raise ValueError Got unknown password algorithm type in password
get all decisions that have been made on a poll .,classmethod def for_poll cls poll at_time None user_filter None query model meta Session query User if user_filter query user_filter query query query distinct join Vote query query filter Vote poll_id poll id if at_time query query filter Vote create_time at_time return Decision u poll at_time at_time for u in query
relative symlinks are not considered unsafe .,def test_is_unsafe_symlink fs fs CreateFile parent target os symlink parent target parent link assert is_unsafe_symlink parent link parent is False
a float is written as 4 bytes .,def read_float fo schema bits ord fo read 1 MASK ord fo read 1 MASK 8 ord fo read 1 MASK 16 ord fo read 1 MASK 24 return unpack f pack I bits 0
compute matrix factorization . return fitted factorization model .,def factorize self self v multiply self V self V sum 2 0 for run in range self n_run self W self H self seed initialize self V self rank self options p_obj c_obj sys float_info max best_obj c_obj if run 0 else best_obj iter 0 if self callback_init self final_obj c_obj self n_iter iter mffit mf_fit Mf_fit self self callback_init mffit while self is_satisfied p_obj c_obj iter p_obj c_obj if not self test_conv or iter self test_conv 0 else p_obj self update iter 1 c_obj self objective if not self test_conv or iter self test_conv 0 else c_obj if self track_error self tracker track_error run c_obj if self callback self final_obj c_obj self n_iter iter mffit mf_fit Mf_fit self self callback mffit if self track_factor self tracker track_factor run W self W H self H final_obj c_obj n_iter iter if c_obj best_obj or run 0 best_obj c_obj self n_iter iter self final_obj c_obj mffit mf_fit Mf_fit copy deepcopy self mffit fit tracker self tracker return mffit
get a list of all directories,def getAllDirs self return Tagging getTagsForTags self tagList
add data to the layer .,def add_data self x_data y_data self x_data append np array x_data self y_data append np array y_data
prefix the provided string with working directory and return a str .,def _get_dst_dir dst_dir wd os getcwd _makedirs dst_dir return os path join wd dst_dir
"load a mesh or vectorized path into objects : trimesh , path2d , path3d , scene",def load file_obj file_type None kwargs out_types Trimesh Path Scene if any util is_instance_named file_obj t for t in out_types log info Loaded called on s object returning input file_obj __class__ __name__ return file_obj file_obj file_type metadata opened _parse_file_args file_obj file_type if isinstance file_obj dict kwargs update file_obj loaded load_kwargs kwargs elif file_type in path_formats loaded load_path file_obj file_type file_type kwargs elif file_type in mesh_loaders loaded load_mesh file_obj file_type file_type kwargs elif file_type in compressed_loaders loaded load_compressed file_obj file_type file_type kwargs metadata elif file_type in svg dxf load_path else raise ValueError File type s not supported file_type for i in util make_sequence loaded i metadata update metadata if opened file_obj close return loaded
display the correct order summary .,get_or_empty_db_cart Cart objects for_display validate_voucher validate_cart add_voucher_form def checkout_summary request cart if cart is_shipping_required view validate_shipping_method summary_with_shipping_view view validate_shipping_address view return view request cart if request user is_authenticated return summary_without_shipping request cart return anonymous_summary_without_shipping request cart
test seeding vms from multiple threads,begin subcommand config def seed_multithread machine_name machine_username machine_password seed_count threads args machine_name machine_username machine_password 1 for i in range seed_count t Thread target seed args args t start threads append t for t in threads t join
pre - process for simpler template logic,property def pretty_body_text self _body self body if not self disable_auto_linebreaks _body linebreaks _body return _body
return the value given a 32 bit arinc 429 message value,def unpack self A429word if A429word 0 raise Exception A429MsgRangeError self name 0 A429word elif A429word 4294967295 raise Exception A429MsgRangeError self name 4294967295 A429word else return A429word self _mask self lsb 1
return index of sub_string in string .,def _find string sub_string start_index u Return index of sub_string in string n n Raise TokenError if sub_string is not found n result string find sub_string start_index if result 1 raise TokenError u expected 0 format sub_string return result
return a int32 scalar variable .,def iscalar name None return scalar name int32
"returns the path to test datasets , terminated with separator ( / vs \ )",def get_test_data_path Returns the path to test datasets terminated with separator vs return join dirname __file__ data pathsep
"given a list of clsid , create and register class factories .",def RegisterClassFactories clsids flags None clsctx None if flags is None flags pythoncom REGCLS_MULTIPLEUSE pythoncom REGCLS_SUSPENDED if clsctx is None clsctx pythoncom CLSCTX_LOCAL_SERVER ret for clsid in clsids if clsid 0 not in factory pythoncom MakePyFactory clsid regId pythoncom CoRegisterClassObject clsid factory clsctx flags ret append factory regId return ret
"make sure all modules owned by the execution engine are fully processed and "" usable "" for execution .",def finalize_object self ffi lib LLVMPY_FinalizeObject self
return an approximate key value for key .,def approximate self key precision None if key is None return None key self round_timestamp key if key in self _dict or precision 0 return key if precision is None precision self precision best min pos abs pos key for pos in self _dict keys if abs pos key precision key operator itemgetter 1 default key 0 return best 0
select graph 's nodes by attribute value,def nodes_by_attribute self attr_val attr type temp_nodes getattr self node nodes list filter None map lambda x x if temp_nodes x attr attr_val else None temp_nodes keys return nodes
return the size of the group .,def size self include_failed return sum 1 for m in self _members include_failed
return a reverse topologically sorted iterator .,def __reversed__ self return Graph toposort self graph reverse True
returns a client session that can be used to query for image information .,def _get_session self _context return glance get_default_image_service
populate a libvirtconfigguestinterface instance with host backend details for an 802.1qbh device .,def set_vif_host_backend_802qbh_config conf net_type devname profileid tapname None conf net_type net_type if net_type direct conf source_mode passthrough conf source_dev pci_utils get_ifname_by_pci_address devname conf driver_name vhost else conf source_dev devname conf model None conf vporttype 802 1Qbh conf add_vport_param profileid profileid if tapname conf target_dev tapname
return list of detailed image information .,def detail self context kwargs return copy deepcopy list self images values
test iperf client using the default tcp window size ( tcp window scaling is normally enabled by default so setting explicit window size is not going to help achieve better results ) : return : a dictionary containing the results of the run,def run_client self label dest_ip target_instance mss None bandwidth 0 bidirectional False az_to None if I in self config protocols ping_res self ping run_client dest_ip else ping_res None if self tp_tool and not ping_res or error not in ping_res tp_tool_res self tp_tool run_client dest_ip target_instance mss mss bandwidth bandwidth bidirectional bidirectional else tp_tool_res res ip_to dest_ip if self internal_ip res ip_from self internal_ip if label res desc label if self az res az_from self az if az_to res az_to az_to res distro_id self ssh distro_id res distro_version self ssh distro_version if multicast_addr in self config res multicast_address self config multicast_addr if ping_res tp_tool_res append ping_res res results tp_tool_res return res
"when searching for atoms with matching bond patterns graphmatcher often returns redundant results . we must define a "" canonical_order "" function which sorts the atoms and bonds in a way which is consistent with the type of n - body interaction being considered . the atoms ( and bonds ) in a candidate match are rearranged by the canonical_order ( ) . then the re - ordered list of atom and bond ids is tested against the list of atom / bond ids in the matches - found - so - far , before it is added to the list of interactions found so far . in this case we assume the second atom is the central atom ( the "" hub "" ) , and the energy is invariant with respect to permutations of the other 3 atoms . so we arbitrarily sort these other 3 atoms in increasing order ( as well as the bonds which connect the central atom to them ) .",def canonical_order match atom0 match 0 0 atom1 match 0 1 atom2 match 0 2 atom3 match 0 3 bonds match 1 ab atom0 0 atom2 1 atom3 2 ab sort return ab 0 0 atom1 ab 1 0 ab 2 0 bonds ab 0 1 bonds ab 1 1 bonds ab 2 1
stop host(s ) from doing the current task .,command connected def kill self server args ret None 0 hosts server get_selected for host in hosts try host send host command_dict KILL except sock_error host purge ret 0 basic ret 1 2 return ret
checks the hash in virustotal and returns the results,def check_virustotal exe_hash api_key url https www virustotal com vtapi v2 file report parameters resource exe_hash apikey api_key vt_res requests get url params parameters if vt_res status_code in 200 201 return json loads vt_res text else print vt_res status_code vt_res text return False
return the electrostatic potential for each atom .,def get_potential self return self phi_a
returns true if character is unicode ( non - ascii ) character,def _unicode_char char try char encode ascii except UnicodeDecodeError return True return False
return true if input service has login i d and this has not .,def superseeded_by self other_service if not other_service or other_service __class__ self __class__ or other_service protocol self protocol or other_service port self port return False return not self device_credentials and other_service device_credentials
check if all environment are exists .,def check_environment for key in SUPERVISOR_SHARE SUPERVISOR_NAME HOMEASSISTANT_REPOSITORY try os environ key except KeyError _LOGGER fatal Can t find s in env key return False if not SOCKET_DOCKER is_socket _LOGGER fatal Can t find docker socket return False return True
finds the class folders in a dataset .,def _find_classes self dir classes d for d in os listdir dir if os path isdir os path join dir d classes sort class_to_idx classes i i for i in range len classes return classes class_to_idx
sets marker number marker to frequency,def set_marker self marker frequency self _visainstrument write calc mark i x e marker frequency self enable_marker marker
a generator function for listing versions in a bucket .,def versioned_bucket_lister bucket prefix delimiter key_marker version_id_marker headers None more_results True k None while more_results rs bucket get_all_versions prefix prefix key_marker key_marker version_id_marker version_id_marker delimiter delimiter headers headers max_keys 999 for k in rs yield k key_marker rs next_key_marker version_id_marker rs next_version_id_marker more_results rs is_truncated
ensure ` is_valid ` fails when ` call.is_valid ( ) ` fails .,def test_is_valid_invalid_call_is_valid self c CallFile Call channel wait_time 10 self action spool_dir self spool_dir self assertFalse c is_valid
microsoft word document reader ( no markup ),def __init__ self filename self io CfbIO filename self cp self length None self _start_of_pcd None self _read_clx self _position 0 self seek 0
"encode message and return as a string of hex numbers , separated by the string sep . the default separator is a single space .",def hex self sep return sep join 02X format byte for byte in self bytes
invoke a remote method that does not return anything .,def cast_to_server context server_params topic msg return _get_impl cast_to_server cfg CONF context server_params topic msg
concatenate the imgs together into one big image separated by borders,def plot_concat_imgs imgs border_thickness 2 axis None normalize False sns set_style dark assert isinstance border_thickness int assert int np sqrt len imgs np sqrt len imgs assert imgs 0 shape 0 imgs 0 shape 1 if normalize imgs np array imgs imgs np sum imgs 2 axis 1 2 reshape 1 1 1 img_length imgs 0 shape 0 layer_length int np sqrt len imgs concat_length layer_length img_length layer_length 1 border_thickness border_color np nan concat_rf np ones concat_length concat_length border_color for x_idx y_idx in itertools product xrange layer_length xrange layer_length flat_idx x_idx layer_length y_idx x_offset border_thickness x_idx y_offset border_thickness y_idx concat_rf x_idx img_length x_offset x_idx 1 img_length x_offset y_idx img_length y_offset y_idx 1 img_length y_offset imgs flat_idx if axis is not None axis imshow concat_rf interpolation none aspect auto else plt imshow concat_rf interpolation none aspect auto
"load dataframe , and read lines from input_filename or stdin . if the first word of a line matches to an index in the dataframe , append the label and importance information to the line , and let it through in the vw format .",def vw_filter df_filename input_filename try df pd read_hdf df_filename df except df pd read_pickle df_filename r re compile id with input_filename as f for line in f ids r findall line assert len ids 0 assert id_ ids 0 for id_ in ids if ids 0 in df index clean_line r sub line labels df label ix ids 0 importances df importance ix ids 0 if not hasattr labels __iter__ labels labels importances importances for label importance in zip labels importances whole_label 6f format label importance ids 0 sys stdout write whole_label clean_line 1
reads a number of data from the given endpoint .,def read_endpoint self length endpoint ep self interface endpoint 1 0 return ep read length
return the config scope that commands should modify by default .,def default_modify_scope return spack config config highest_precedence_scope name
"export the main hypre header , hypre.h ; all other headers can be found in the same directory . sample usage : spec['hypre'].headers.cpp_flags",property def headers self hdrs find_headers HYPRE self prefix include recursive False return hdrs or None
before session.main ( ) is called .,def pytest_sessionstart session
"get one peer 's message statistic , include sending and receiving .",blueprint route peer peer_ip statistic auth login_required api_utils log_request def get_peer_statistic peer_ip return flask jsonify api_utils get_peer_msg_statistic peer_ip
default : return max . weight unmodified,def weight self dirlist return self maxweight
find_currency creates a dict with the inputs that forex - python accepts,def find_currencies with open os path join FILE_PATH data currencies csv mode r as infile reader csv reader infile mydict r upper row 2 for row in reader for r in row 0 3 return mydict
remove groups for a particular community instance using its name,transaction atomic def remove_groups community_name name 0 format community_name Group objects filter name__startswith name delete
"parameters ---------- ctn_type : { ' figure','table','note','box ' } , optional box content type source : str , optional string ( as single stream ) containing the source",def __init__ self ctn_type box source None self number 0 self ctn_type ctn_type self style None self ctn_options None self cap_options None self cap_position None self cap_type None self ctn None self cap None if self ctn_type box Box boxes_number 1 self number Box boxes_number if source self get source source return
method for updating config state from command line arguments .,def update self cliargs self verbose cliargs verbose self indented cliargs indented self online_mathjax cliargs online_MathJax self set_highlight_style style cliargs highlight_style self set_theme theme cliargs theme self toc_at_sec_beginning cliargs toc_at_sec_beginning self toc_at_subsec_beginning cliargs toc_at_subsec_beginning return
"kubernetes api requires authentication using a token available in every pod , or with a client x509 cert / key pair . we authenticate using the service account token by default and replace this behavior with cert authentication if the user provided a cert / key pair in the instance .",def retrieve_json_auth self url timeout 10 verify self tls_settings get apiserver_cacert if not verify verify self CA_CRT_PATH if os path exists self CA_CRT_PATH else False log debug ssl validation format verify cert self tls_settings get apiserver_client_cert bearer_token self tls_settings get bearer_token if not cert else None headers Authorization Bearer format bearer_token if bearer_token else None r requests get url timeout timeout headers headers verify verify cert cert r raise_for_status return r json
returns the length of the longest common subsequence between sequences x and y. source : http://www.algorithmist.com/index.php/longest_common_subsequence,def _len_lcs x y u n Returns the length of the Longest Common Subsequence between sequences x n and y n Source http www algorithmist com index php Longest_Common_Subsequence n n Args n x sequence of words n y sequence of words n n Returns n integer Length of LCS between x and y n table _lcs x y n m len x len y return table n m
retrieve the digest of the hash .,def digest self return self md5 digest
test management ds parameter set getter / setter methods,def test_15 self self assertEqual self management_probe_response get_ds_parameter_set 6 self management_probe_response set_ds_parameter_set 40 self assertEqual self management_probe_response get_ds_parameter_set 40 self assertEqual self management_probe_response get_header_size 209
create the generator for message flattening .,def __init__ self outfp mangle_from_ True maxheaderlen 78 self _fp outfp self _mangle_from_ mangle_from_ self _maxheaderlen maxheaderlen
return true if the scope uses exec,def has_exec self return bool self _table optimized OPT_EXEC OPT_BARE_EXEC
return an iterator that yields the weak references to the values .,def itervaluerefs self with _IterationGuard self for wr in self data itervalues yield wr
decode a quoted - printable string .,def decode encoded eol NL Decode a quoted printable string Lines are separated with eol which defaults to n if not encoded return encoded decoded for line in encoded splitlines line line rstrip if not line decoded eol continue i 0 n len line while i n c line i if c decoded c i 1 elif i 1 n i 1 continue elif i 2 n and line i 1 in hexdigits and line i 2 in hexdigits decoded unquote line i i 3 i 3 else decoded c i 1 if i n decoded eol if not encoded endswith eol and decoded endswith eol decoded decoded 1 return decoded
read up to nchars bytes of data from the device . can return fewer if timedout . use getqueuestatus to find how many bytes are available,def read self nchars raw True b_read _ft DWORD b c c_buffer nchars call_ft _ft FT_Read self handle b nchars c byref b_read return b raw b_read value if raw else b value b_read value
distance from a point to a line .,def dst p l x y a b c p ransac points_to_line l return abs a x b y c sqrt a a b b
"returns min_val , max_valfor iterable a",def minmax_vals a min_val a 0 max_val min_val for i in range len a if a i min_val min_val a i elif a i max_val max_val a i return min_val max_val
get the ip adddress that is [ offset ] units before or after the given one .,def getIpAddress ip offset return str IPAddress ip offset
fetches the corresponding target sentence and resets the current history .,def initialize self src_sentence self cur_trg_sentence self trg_sentences self current_sen_id self n_consumed 0
parser : argparse . argumentparser return a parser added with args required by fit,def add_fit_args parser train parser add_argument_group Training model training train add_argument network type str help the neural network to use train add_argument num layers type int help number of layers in the neural network required by some networks such as resnet train add_argument gpus type str help list of gpus to run e g 0 or 0 2 5 empty means using cpu train add_argument kv store type str default device help key value store type train add_argument num epochs type int default 100 help max num of epochs train add_argument lr type float default 0 1 help initial learning rate train add_argument lr factor type float default 0 1 help the ratio to reduce lr on each step train add_argument lr step epochs type str help the epochs to reduce the lr e g 30 60 train add_argument optimizer type str default sgd help the optimizer type train add_argument mom type float default 0 9 help momentum for sgd train add_argument wd type float default 0 0001 help weight decay for sgd train add_argument batch size type int default 128 help the batch size train add_argument disp batches type int default 20 help show progress for every n batches train add_argument model prefix type str help model prefix parser add_argument monitor dest monitor type int default 0 help log network parameters every N iters if larger than 0 train add_argument load epoch type int help load the model on an epoch using the model load prefix train add_argument top k type int default 0 help report the top k accuracy 0 means no report train add_argument test io type int default 0 help 1 means test reading speed without training train add_argument dtype type str default float32 help precision float32 or float16 return train
dispatch stop actions to urbi break system .,def stop self stopping False job self current_job for i ub in enumerate self urbi_breaks stopping self callback stop ub job or stopping if stopping and self lastJob job self lastJob job print Inside Job s job return stopping
get returns 200 with current weekly article short html,def get self request args kwargs article get_article_of_week_by_request request if article return self html_response article else return data_not_found
tabs should be a list of fieldtabs .,def __init__ self tabs self type self __class__ __name__ self tabs tabs if len tabs 0 raise ValueError Tabs are empty if not all isinstance t FieldTab for t in tabs raise ValueError Tabs should all be instances of FieldTab self _firstfield tabs 0 field_names 0 self _fieldnames for tab in self tabs self _fieldnames extend tab field_names
list of targets connected to the population .,property def targets self return self population targets
create a message with a small byte array and encode it . decode it and verify that the decoded message matches the original .,def test_fill self msg lcmtest byte_array_t msg num_bytes 5 msg data struct pack bbbbb 1 2 3 4 5 data msg encode decoded lcmtest byte_array_t decode data self assertEqual 5 decoded num_bytes self assertEqual msg data decoded data
builds a logistic regression estimator for binary classification .,def LogisticRegressor model_fn thresholds None model_dir None config None feature_engineering_fn None return estimator Estimator model_fn _get_model_fn_with_logistic_metrics model_fn model_dir model_dir config config params thresholds thresholds feature_engineering_fn feature_engineering_fn
"log provided ' op_log ' , and add additional model information below .",def write_op_log graph log_dir op_log None run_meta None op_log _merge_default_with_oplog graph op_log run_meta with gfile Open os path join log_dir tfprof_log w as log log write op_log SerializeToString
returns the directory where event file will be written .,def get_logdir self return self event_writer get_logdir
check if this chipid can be handled by this class,staticmethod def test chipID return chipID 65280 33024
enable / disable defined feature(s ) of the bridge domain .,def set_bd_flags self bd_id args for flag in args if flag learn feature_bitmap 1 0 elif flag forward feature_bitmap 1 1 elif flag flood feature_bitmap 1 2 elif flag uu_flood feature_bitmap 1 3 elif flag arp_term feature_bitmap 1 4 else raise ValueError Unknown feature used s flag is_set 1 if args flag else 0 self vapi bridge_flags bd_id is_set feature_bitmap self logger info Bridge domain ID d updated bd_id
"make a request to the sos , returns an xml document wrapped in a python file object .",def getobservation
update the allow_saml_uid_and_internal_password setting . this function is called when saving the form .,def set_allow_saml_uid_and_internal_password self cr uid ids context None dlg self browse cr uid ids context context 0 setting_value 1 if dlg allow_saml_uid_and_internal_password else 0 config_obj self pool ir config_parameter config_ids config_obj search cr uid key _SAML_UID_AND_PASS_SETTING limit 1 context context if config_ids config_obj write cr uid config_ids value setting_value context context else config_obj create cr uid key _SAML_UID_AND_PASS_SETTING value setting_value context context
save the source to file and render with the graphviz engine .,def render self filename None directory None view False cleanup False filepath self save filename directory rendered backend render self _engine self _format filepath if cleanup os remove filepath if view self _view rendered self _format return rendered
checks whether the key generated by the key material matches the expected derived key . raises an exception if they do not match .,abc abstractmethod def verify self key_material expected_key
encode a string using the standard base64 alphabet .,def standard_b64encode s return b64encode s
return true if the parameters are supported by the backend for dsa .,abc abstractmethod def dsa_parameters_supported self p q g
register a set of configurations with the default config module .,def register prefix mapping return _default_registry register prefix mapping
load the indexes listed in this dataset 's image set file .,def _load_image_set_index self image_set_file os path join self _lov_path self _image_set txt assert os path exists image_set_file Path does not exist format image_set_file with open image_set_file as f image_index x rstrip n for x in f readlines return image_index
delete a message from the queue .,def delete_message self message return self connection delete_message self message
ensure that the err constructor produces a result that unwraps to the error we expect .,def test_err_constructor self class VarianceError TypeError Just for testing equality on subclasses of an Exception def __init__ self args kwargs TypeError __init__ self args kwargs errors TypeError T E ValueError Value error VarianceError Type T is not covariant with type U for error in errors wrapped Err error self assertEqual wrapped err error
apply reaction to reactant and return products,def _react self reactant reaction ps reaction RunReactants reactant products for product in ps frags Chem GetMolFrags product 0 asMols True sanitizeFrags False for p in frags q copy copy p try Chem SanitizeMol q products append q except pass return products
add a flipped symmetric copy on the right add a border,def to_map self for row in range self r for col in range self c 1 1 1 self grid self r row 1 append self grid row col self c 2 for row in range self r self grid row W self grid row W self c 2 self grid insert 0 W for c in range self c self grid append W for c in range self c self r 2
"performs a request using the get method , returns an http response .",def get self uri None auth_token None http_request None kwargs return self request method GET uri uri auth_token auth_token http_request http_request kwargs
this example shows the full range of operations of pulsegen objects with a reimplementation of corresponding genesis demo .,def main pulse0 moose PulseGen pulse0 pulse0 level 0 50 0 pulse0 width 0 3 0 pulse0 delay 0 5 0 pulse0 level 1 20 0 pulse0 width 1 5 0 pulse0 delay 1 8 0 pulse0 baseLevel 10 0 pulse0 trigMode 0 trig moose PulseGen trig trig level 0 20 0 trig width 0 1 0 trig delay 0 5 0 trig width 1 30 0 pulse1 moose PulseGen pulse1 pulse1 level 0 50 0 pulse1 width 0 3 0 pulse1 delay 0 5 0 pulse1 level 1 20 0 pulse1 width 1 5 0 pulse1 delay 1 8 0 pulse1 baseLevel 10 0 pulse1 trigMode 1 trig connect output pulse1 input gate moose PulseGen gate gate level 0 20 0 gate width 0 30 0 gate delay 0 15 0 gate width 1 30 0 pulse2 moose PulseGen pulse2 pulse2 level 0 50 0 pulse2 width 0 3 0 pulse2 delay 0 5 0 pulse2 level 1 20 0 pulse2 width 1 5 0 pulse2 delay 1 8 0 pulse2 baseLevel 10 0 pulse2 trigMode 2 gate connect output pulse2 input plot0 moose Table plot0 plot0 connect requestOut pulse0 getOutputValue plot1 moose Table plot1 plot1 connect requestOut pulse1 getOutputValue plot2 moose Table plot2 plot2 connect requestOut pulse2 getOutputValue plotGate moose Table plotGate plotGate connect requestOut gate getOutputValue plotTrig moose Table plotTrig plotTrig connect requestOut trig getOutputValue moose useClock 0 TYPE PulseGen process moose useClock 1 TYPE Table process moose setClock 0 SIMDT moose setClock 1 SIMDT moose reinit moose start RUNTIME pylab subplot 511 pylab plot plot0 vector pylab title Free Run pylab subplot 512 pylab plot plot1 vector pylab title Triggered below pylab subplot 513 pylab plot plotTrig vector pylab title Free Running Trigger pylab subplot 514 pylab plot plot2 vector pylab title Gated below pylab subplot 515 pylab plot plotGate vector pylab title Free Running Gate pylab tight_layout pylab show print pulsegen py finished simulation
return a widget for central widget of mainwindow .,def getCentralWidget self raise NotImplementedError method must be reimplemented in subclass
abstract method that starts the application main loop . any child class overriding this method should call the ` _ do_main ` method where the proper starting and any cleaning actions take place .,def main self raise NotImplementedError
"construct query for sqlite database for a specific stage run from a journal possible sql injection here , but since its sqlite and if someone had control of the python script and the sqlite database , they can just open the database / modify it without using our program",def query_for_stage_results self tablename q SELECT FROM s WHERE stage AND test_id tablename return q
initialize qdevice on local host with specified model string model qdevice model to initialize bool enable make qdevice service start on boot bool start start qdevice now,def qdevice_setup lib_env model enable start _ensure_not_cman lib_env _check_model model qdevice_net qdevice_setup lib_env cmd_runner lib_env report_processor process reports qdevice_initialization_success model if enable _service_enable lib_env qdevice_net qdevice_enable if start _service_start lib_env qdevice_net qdevice_start
set the resource not to be managed by the cluster etree resource_el -- resource element,def unmanage resource_el nvpair arrange_first_nvset meta_attributes resource_el is managed false
method that sanitizes the input parameters and returns the policies that match them . matches the input dictionary with the policies configuration in the cs . it returns a list of policy dictionaries that matched .,def getPoliciesThatApply decisionParams decisionParams _sanitizedecisionParams decisionParams gLogger debug Sanitized decisionParams s str decisionParams policiesThatApply policiesConfig RssConfiguration getPolicies if not policiesConfig OK return policiesConfig policiesConfig policiesConfig Value gLogger debug All policies s str policiesConfig for policyName policySetup in policiesConfig items try policyType policySetup policyType 0 except KeyError policyType policyName policyMatchParams policySetup get matchParams gLogger debug matchParams of s s policyName str policyMatchParams policyConfigParams policyMatch Utils configMatch decisionParams policyMatchParams gLogger debug PolicyMatch for decisionParams s s decisionParams str policyMatch policyFilter _filterPolicies decisionParams policyMatchParams if policyMatch and policyFilter policiesThatApply append policyName policyType policyConfigParams gLogger debug policies that apply s str policiesThatApply policiesToBeLoaded for policyName policyType _policyConfigParams in policiesThatApply try configModule Utils voimport DIRAC ResourceStatusSystem Policy Configurations policies copy deepcopy configModule POLICIESMETA policyMeta policies policyType except KeyError continue policyDict name policyName type policyType args policyDict update policyMeta policiesToBeLoaded append policyDict return S_OK policiesToBeLoaded
returns jobs accounting info for sites in the last 24h,def doCommand self granularity self args 0 name self args 1 accounting self args 2 plot self args 3 period self args 4 grouping self args 5 if period Format LastHours fromT datetime utcnow timedelta hours period hours toT datetime utcnow elif period Format Periods pass if self args 6 is not None conditions self args 6 else conditions if accounting Job or accounting Pilot if granularity Resource conditions GridCE name elif granularity Service conditions Site name split pop elif granularity Site conditions Site name else return S_ERROR s is not a valid granularity granularity elif accounting DataOperation conditions Destination name return self rClient getReport accounting plot fromT toT conditions grouping
get history data from an external source to be defined in a derived class,def _getHistoryData self timeSpan groupToUse return S_ERROR Not implemented
returns from the operationshelper : < _ rssconfigpath>/notification,def getNotifications return Utils getCSTree s Notification _rssConfigPath
print out the contents of the internal cached information,def dump self print Job status info for status minor timeStamp in self jobStatusInfo print status ljust 20 minor ljust 30 timeStamp print Application status info for status timeStamp in self appStatusInfo print status ljust 20 timeStamp print Job parameters for pname value in self jobParameters items pvalue timeStamp value print pname ljust 20 pvalue ljust 30 timeStamp
test that a serializable containing a serializable class can be serialized,given data nestedStrategyJson def test_nestedSerializable data subObj Serializable instAttr data objData Serializable instAttr subObj agnosticTestFunction jsonTuple objData
returns default queryset for djacketuser objects .,def get_queryset self return super RepositoryManager self get_queryset
test whether a model is constructed successfully .,unittest skip This test needs attention def test_construct self file_path join MODULE_PATH data air rho json model testee PolynomialModelT read file_path testee PolynomialModelT model material model property model symbol model display_symbol model units model references model datasets model _coeffs self _test_properties model
captures the current input then replaces it with entries that have passed the delay .,plugin priority 1 def on_task_input self task config u if task entries log verbose u Delaying s new entries for s len task entries config task no_entries_ok True expire_time datetime now self get_delay config for entry in task entries log debug u Delaying s entry u title if not task session query DelayedEntry filter DelayedEntry title entry u title filter DelayedEntry task task name first delay_entry DelayedEntry delay_entry title entry u title delay_entry entry entry delay_entry task task name delay_entry expire expire_time task session add delay_entry task all_entries passed_delay task session query DelayedEntry filter datetime now DelayedEntry expire filter DelayedEntry task task name delayed_entries item entry for item in passed_delay all for entry in delayed_entries entry u passed_delay True log debug u Releasing s entry u title passed_delay delete if delayed_entries log verbose u Restoring s entries that have passed delay len delayed_entries return delayed_entries
function to terminate the program .,def quit global die die True sys exit
returns a printable string informing the user which tags are allowed,def xtags self self forbidden_tags sort tg for x in self forbidden_tags tg x if x in self allowed_attributes for y in self allowed_attributes x tg s y tg return xssescape tg strip
"run rangrid directly on xyz ` gxvv < geosoft.gxapi.gxvv > ` data , output to an ` gximg < geosoft.gxapi.gximg > ` .",classmethod def create_img cls vv_x vv_y vv_z ipj ctl grid ret_val gxapi_cy WrapRGRD _create_img GXContext _get_tls_geo vv_x vv_y vv_z ipj ctl encode grid encode return GXIMG ret_val
set the document from a file source .,def set_file self type name file self _set_file type encode name encode file encode
reads a sequential fortran binary file record,def read_fortran_record binfile count dtype filetype if filetype sequential rec_start np fromfile binfile count 1 dtype np int32 content np fromfile binfile count count dtype dtype rec_end np fromfile binfile count 1 dtype np int32 assert rec_start rec_end record incomplete wrong count or datatype else content np fromfile binfile count count dtype dtype return content
write the data to the data.json file,def write_data data sorted_dict sort_recursive data with open _datafile w as file _json dump sorted_dict file indent 2
compile all llvm nrt functions and return a library containing them . the library is created using the given target context .,def compile_nrt_functions ctx ir_mod library create_nrt_module ctx library add_ir_module ir_mod library finalize return library
"the spherical volume bounded by this circle , float .",property def volume self return 4 0 3 0 math pi self radius 3
retrieve the inventory from a set of regions in an ansible dynamic inventory compliant format ( see http://docs.ansible.com/ansible/developing_inventory.html#script-conventions ) .,def get_inventory self cluster_id inventory instances region_instances self ec2 instances filter Filters Name tag ec2_pod Values cluster_id Name instance state name Values running instances i for i in region_instances for instance_name instance_name_instances in self _instances_by_name instances inventory instance_name hosts x public_ip_address for x in instance_name_instances hostvars instance public_ip_address self _get_instance_vars instance for instance in instances if hostvars inventory _meta hostvars hostvars return inventory
args : filename : filename for database . args : program arguments . version : version of file .,def __init__ self filename args version self args args self version version self filename filename try with open self filename rb as file self data json load file except IOError self data
return true if a point is inside the rectangle .,def contains self pt x y pt as_tuple return self left x self right and self top y self bottom
second time derivative ( acceleration ) of the configuration variable .,property def ddq self return self _ddq
return static model as a json object,def as_dict self sketch_dict sketch_dict id self id sketch_dict filename self filename if self callback is not None sketch_dict callback self callback sketch_dict capture_status self capture_status sketch_dict job_status self job_status sketch_dict created_at str self created_at sketch_dict retry self retry sketch_dict modified_at str self modified_at sketch_dict sketch_url self sketch_url sketch_dict scrape_url self scrape_url sketch_dict html_url self html_url return sketch_dict
remove all signals from this interface ( used after unit is synthesized and its parent is connecting its interface to this unit ),def _clean self rmConnetions True lockNonExternal True if self _interfaces for i in self _interfaces i _clean rmConnetions rmConnetions lockNonExternal lockNonExternal else self _sigInside self _sig del self _sig for e in self _arrayElemCache e _clean rmConnetions rmConnetions lockNonExternal lockNonExternal
returns a new list of enums . cryptographicusagemask enums . this converts the integer value into the list of enums .,def process_result_value self value dialect masks list if value for e in enums CryptographicUsageMask if e value value masks append e return masks
test that the inequality operator returns false when comparing two bigintegers with the same values .,def test_not_equal_on_equal self a primitives BigInteger 1 b primitives BigInteger 1 self assertFalse a b self assertFalse b a
"remove and return the ` ( key , value ) ` pair least recently used .",def popitem self with self __lock root self __root link root next if link is root raise KeyError cache is empty key link data return key self pop key
validate rasa training data format to ensure proper training .,def validate_rasa_nlu_data data u Validate rasa training data format to ensure proper training n n Raises exception on failure from jsonschema import validate from jsonschema import ValidationError try validate data _rasa_nlu_data_schema except ValidationError as e e message u Failed to validate training data make sure your data is valid For more information about the format visit https github com RasaHQ rasa_nlu blob master docs dataformat rst raise e
user login page : this is a basic login page,public_blueprint route def index_redirect data active clean_header True loggedin False return render_template public index html data data
"if necessary , fetch and read the playbook file",def get_playbook self playbook self config playbook if isinstance playbook list self playbook playbook elif isinstance playbook str and playbook startswith http https response requests get playbook response raise_for_status self playbook yaml safe_load response text elif isinstance playbook str try playbook_path os path expanduser playbook if not playbook_path startswith pb_in_repo os path join self repo_path playbook_path if os path exists pb_in_repo playbook_path pb_in_repo self playbook_file file playbook_path playbook_yaml yaml safe_load self playbook_file self playbook playbook_yaml except Exception log error Unable to read playbook file s playbook raise else raise TypeError playbook value must either be a list URL or a filename log info Playbook s self playbook
call the loader for the file type of path .,def load self path format None loaders if format is None try loaders self lookup path except ValueError as e pass else try loaders self loaders format except KeyError as e pass last_exc None for fn in loaders try return fn path except Exception as e last_exc e pass if last_exc is not None and len loaders 0 raise last_exc raise NoKnownLoaderException e message
provide help on opencl options .,def on_help self event TreeLocation user sasgui perspectives fitting gpu_setup html anchor device selection DocumentationWindow self 1 TreeLocation anchor OpenCL Options Help
"ensure that a folder exists and create it if it does n't , including any parent folders , as necessary .",def create_folder target_folder try os makedirs target_folder except OSError as e pass return os path exists target_folder
"hessian at y , given link(f ) , w.r.t link(f ) i.e. second derivative logpdf at y given link(f_i ) and link(f_j ) w.r.t link(f_i ) and link(f_j ) the hessian will be 0 unless i = = j",def d2logpdf_dlink2 self link_f y Y_metadata None Hessian at y given link f w r t link f i e second derivative logpdf at y given link f_i and link f_j w r t link f_i and link f_j The hessian will be 0 unless i j math frac d 2 ln p y_ i lambda f_ i d 2 lambda f frac y_ i lambda f_ i 2 param link_f latent variables link f type link_f Nx1 array param y data type y Nx1 array param Y_metadata Y_metadata which is not used in poisson distribution returns Diagonal of hessian matrix second derivative of likelihood evaluated at points f rtype Nx1 array Note Will return diagonal of hessian since every where else it is 0 as the likelihood factorizes over cases the distribution for y_i depends only on link f_i not on link f_ j i return y link_f 2
retrieves footers from the patch description .,def get_footers self patch_text None if patch_text is None patch_text self m gerrit get_change_description self m properties patch_gerrit_url self m properties patch_issue self m properties patch_set result self m python parse description self package_repo_resource git_footers py args json self m json output stdin self m raw_io input data patch_text return result json output
return whether to show extension in gui ( can be overridden through digits configuration options ),staticmethod def get_default_visibility return True
: param trader_id : the trader i d who created the order : param transaction_number : the number of the transaction created : type trader_id : traderid : type transaction_number : transactionnumber,def __init__ self trader_id transaction_number super TransactionId self __init__ self _trader_id trader_id self _transaction_number transaction_number
returns the channel search results over the events endpoint .,def on_search_results_channels self subject changetype objectID results query join results keywords for channel in results result_list channel_json convert_db_channel_to_json channel include_rel_score True if self session config get_family_filter_enabled and self session lm category xxx_filter isXXX channel_json name continue if channel_json dispersy_cid not in self channel_cids_sent self write_data type search_result_channel event query query result channel_json self channel_cids_sent add channel_json dispersy_cid
return network representation of a counter trade,def to_network self return self _trader_id self _timestamp self _order_id order_number self _recipient_order_id self _proposal_id self _assets
here all commandline & help - messages arguments are defined .,def get_parser u n Here all commandline help messages arguments are defined n n returns an instance of argparse ArgumentParser n parser argparse ArgumentParser parser add_argument u files nargs u help u One or more cg coord files parser add_argument u reference type str help u A cg file containing a project line or a png Used as a reference against which all files are compared If not present compare everything against everything Note that only square png images are supported parser add_argument u global search action u store_true help u Perform global optimization over all possible projection directions Note This is default for every cg file that does not contain a project entry parser add_argument u dpi type int help u Dots per Image cloumn Number of cells for rasterization per column and row If reference is a png image this is not required and would trigger rescaling of the image parser add_argument u scale type int help u The width of the whole image in Angstrom This is required if reference is a png image parser add_argument u outfile type str help u Currently only used if no reference is present Write the resulting distance matrix to this file parser add_argument u show action u store_true help u Show a figure The figure does not show all calculated distances parser add_argument u cores type int default 1 help u Only used for many to many comparison Number of cores for paralellization return parser
"automatically insert tasks asynchronously . depending on batch_size , insert or wait until next call .",def _auto_insert_check self if not self batch_size return if len self _tasks self batch_size self _handle_tasks
"read the type string from the json format , and find what class it maps to going through type_dictionary - > question_classes",staticmethod def _get_question_class question_type_str question_type_dictionary question_type question_type_dictionary get question_type_str control_dict question_type get u control control_tag control_dict get u tag u if control_tag u upload and control_dict get u mediatype osm control_tag u osm return SurveyElementBuilder QUESTION_CLASSES control_tag
"given a base folder which has a directory called "" miso "" where all the miso output is , search for bad events in the subfolders and then write them to a "" nan_events.txt "" file for that sample and event type .",def __init__ self directory miso_subdirectory miso downsampled False directory directory rstrip glob_command summary miso_summary format directory miso_subdirectory bad_events_template directory miso_subdirectory bad_events txt dfs for i filename in enumerate iglob glob_command if os path getsize filename 113 df read_miso_summary filename splice_type os path basename filename split 0 sample_id filename split 4 if downsampled fragments sample_id split _ real_id _ join fragments 2 probability float fragments 2 lstrip prob iteration int fragments 3 lstrip iter sys stdout write t t t t n format i real_id probability iteration else real_id filename sys stdout write t t n format i real_id try with open bad_events_template format sample_id splice_type as f bad_events map lambda x x lstrip rstrip miso re findall miso f read df df ix df index isin bad_events except IOError if downsampled sys stdout write t t t t no nan events file n format real_id probability iteration splice_type else sys stdout write t t no nan events file n format i real_id df sample_id sample_id df splice_type splice_type if downsampled df probability probability df iteration iteration dfs append df reset_index summary pd concat dfs summary to_csv miso_summary_raw csv format directory summary filter_miso_summary summary if downsampled summary summary sort columns probability iteration summary index np arange summary shape 0 def remove_inconsistent x thresh 0 8 Remove iterations with fewer events than the threshold fraction size x groupby iteration size return x groupby iteration filter lambda y len y thresh size mean summary summary groupby splice_type probability apply remove_inconsistent summary to_csv miso_summary_filtered csv format directory if not downsampled psi summary pivot_table rows event_name splice_type cols sample_id values miso_posterior_mean psi to_csv psi csv format directory
returns the parameters of the ideal observer as dict .,def get_params self return k self k q self q sigma_s self sigma_s m self m
start up all the bots .,def start self if not self running for name bot in self bots items bot inst connect self running True
"the width of a typical character in the current font , transformed to text space and then to user - space",property def _avg_width self w0 self _gs_to_ts self active_font avg_width 1 0 return w0 self ts fs self ts h self ts m a
discover count of relays on module by setting all relays to position 1 and examining length of status byte retuns false on error,def __set_relay_count__ self if not self __send_relay_command__ commands setPosition 1 0 return False response self __send_relay_command__ commands getStates True if response False return False responseBits convert_hex_to_bin_str response self relayCount len responseBits if not self __send_relay_command__ commands setPosition 0 0 return False return True
get a list of backup target types this driver supports,def get_supported_target_types self return BackupTargetType VOLUME
this feature does not exist in ecp . returns hard coded dummy location .,def list_locations self return NodeLocation id 1 name Cloud country driver self
callback for bridge enter events .,def on_enter bridge ev if ev channel name startswith Announcer return bridge play media sound ascending 2tone
test that sampclienterror can be instantiated,def test_SAMPClientError SAMPClientError test
this function checks that the builtin sites registry is consistent with the remote registry ( or a registry at some other location ) .,def check_builtin_matches_remote download_url True builtin_registry EarthLocation _get_site_registry force_builtin True dl_registry EarthLocation _get_site_registry force_download download_url in_dl matches for name in builtin_registry names in_dl name name in dl_registry if in_dl name matches name quantity_allclose builtin_registry name dl_registry name else matches name False if not all matches values print In builtin registry but not in download for name in in_dl if not in_dl name print name print In both but not the same value for name in matches if not matches name and in_dl name print name builtin builtin_registry name download dl_registry name assert False Builtin and download registry aren t consistent failures printed to stdout
get the id of the selected features based on the ensemble list ( + user and event count ),def _get_feature_column_ids ensemble_list selected_features feature_ids index 0 for feature in ensemble_list index 1 if feature in selected_features feature_ids append index return feature_ids
test computing a spike - triggered average .,def test_sta np random seed 0 time np arange 100 spikes np array 0 30 70 stimulus np random randn 100 filter_length 5 sta tax flt sta time stimulus spikes filter_length tmp np zeros sta shape for ix in spikes 1 tmp stimulus ix filter_length ix tmp len spikes assert np allclose tmp sta assert np allclose tax np arange filter_length 1 1
get a perf message for the given datetime .,def _get_minute_message self dt algo perf_tracker rvars algo recorded_vars minute_message perf_tracker handle_minute_close dt self data_portal minute_message minute_perf recorded_vars rvars return minute_message
start extract every chapter in epub,def parse_content self print Start parsing chapters th if not self single_thread for i link in enumerate self chapter_links t threading Thread target self extract_chapter args link i t daemon True t start th append t for t in th t join else for i link in enumerate self chapter_links self extract_chapter link i
calculates the fid of two paths .,def calculate_fid_given_paths paths inception_path inception_path check_or_download_inception inception_path for p in paths if not os path exists p raise RuntimeError Invalid path s p create_inception_graph str inception_path with tf Session as sess sess run tf global_variables_initializer m1 s1 _handle_path paths 0 sess m2 s2 _handle_path paths 1 sess fid_value calculate_frechet_distance m1 s1 m2 s2 return fid_value
read defaults for options from environment,def _read_environment for key in options env PYGLET_ s key upper try value os environ env if _option_types key is tuple options key value split elif _option_types key is bool options key value in true TRUE True 1 elif _option_types key is int options key int value except KeyError pass
"start a server serving the given html , and ( optionally ) open a browser",def serve html ip 127 0 0 1 port 8888 n_retries 50 files None ipython_warning True open_browser True http_server None port find_open_port ip port n_retries Handler generate_handler html files if http_server is None srvr server HTTPServer ip port Handler else srvr http_server ip port Handler if ipython_warning try __IPYTHON__ except pass else print IPYTHON_WARNING print Serving to http 0 1 Ctrl C to exit format ip port sys stdout flush if open_browser b lambda webbrowser open http 0 1 format ip port threading Thread target b start try srvr serve_forever except KeyboardInterrupt SystemExit print nstopping Server srvr server_close
the task should generate a total count stat record,def test_task_count_total self tasks count_total stat StatBookmark query first self assertEqual stat attrib stats TOTAL_CT self assertEqual stat data 4
classic style pop - up menu,def build_document_menu printerport fileport menu_group gui menutraditional MenuGroup Document menu_group add doc_cut_mi menu_group add doc_copy_mi menu_group add doc_paste_mi menu_group add save_mi menu_group add print_mi return menu_group
returns the * alcohol degradation * ( per mill ) of a person with the given stats in the given number of * minutes*.,def get_degradation age weight height sex minutes return gramm_to_promille calculate_degradation weight minutes age weight height sex
construct a zipfile or contextualzipfile as appropriate .,def __new__ cls args kwargs if hasattr zipfile ZipFile __exit__ return zipfile ZipFile args kwargs return super ContextualZipFile cls __new__ cls
"executes the json - rpc and returns the output received from remote device . : name : rpc method to be executed over connection plugin that implements jsonrpc 2.0 : args : ordered list of params passed as arguments to rpc method : kwargs : dict of valid key , value pairs passed as arguments to rpc method",def __rpc__ self name args kwargs response self _exec_jsonrpc name args kwargs if error in response err response get error msg err get data or err message code err code raise ConnectionError to_text msg errors surrogate_then_replace code code return response result
"remove blank lines from table ( included for "" human readability "" but useless to us ... returns a single string joined by newlines",def _strip_blanks table numbersletters re compile 0 9A Za z if isinstance table str table table split n table line for line in table if numbersletters search line return n join table
adds a handler function to be called when any of the given signals are received .,def add_handler self signals func if type signals is int signals signals for signal_ in signals signal signal signal_ self default_handler handler Handler self func signals log debug Installing handler s repr handler self handlers append handler return handler
return the first ami id given its name,throttling_retry def get_ami_id conn name images conn get_all_images filters name name conn close if len images 0 return images 0 id else raise RuntimeError AMI not found format name
take the intersection of the edges of this graph and the input graph . resulting edge weights are ignored and only adjacencies are stored .,def intersect self graph newGraph self multiply graph newGraph W newGraph W 0 astype newGraph W dtype return newGraph
change the color of each atom by a certain value . * value * should be a tuple .,def change_color self selections value if atoms in selections atms selections atoms mask if value is None self atom_colors array atms 0 3 self color_scheme get t colors deep_pink 0 3 for t in self system type_array atms else self atom_colors array atms 0 3 value 0 3 self atom_renderer update_colors self atom_colors array self on_atom_colors_changed
read in a molecule from a string .,def readstring format string if format iupac raise ValueError s is not a recognised OPSIN format format result _nametostruct parseChemicalName string if str result getStatus FAILURE raise IOError Failed to convert s to format s n s string format result getMessage return Molecule result
@summary : connection request for client send a connection request packet,def connect self self sendConnectionRequest
rewrites ' old_file ' with ' new_file ' without invalidating metadata and verifies that querying the table results in the expected error . ' expected_error ' only needs to be a substring of the full error message .,def __overwrite_file_and_query self db_name table_name old_file new_file expected_error expected_new_count table_location self __get_test_table_location db_name self __create_test_table db_name table_name table_location self __copy_file_to_test_table old_file table_location self client execute refresh s s db_name table_name self __copy_file_to_test_table new_file table_location try result self client execute select from s s db_name table_name assert False Query was expected to fail except ImpalaBeeswaxException as e assert expected_error in str e self client execute refresh s s db_name table_name result self client execute select count from s s db_name table_name assert result data str expected_new_count
extracts and returns the version of the catalog object 's ' thrift_txt ' representation .,def extract_catalog_object_version self thrift_txt result re search catalog_version i64 d thrift_txt assert result Unable to find catalog version in object thrift_txt return int result group 1
when the parent changes try to add it to the dungeon .,def on_parent_changed self self _signal_dungeon_level_changed
return none if no missing declarations are discovered . otherwise raise an exception .,def scan_bom bom kwargs roots _get_roots bom is_source_dist kwargs get is_source_dist scan_components kwargs get scan_components add_declarations kwargs get add_declarations coalesce kwargs get coalesce run_in_parallel kwargs get run_in_parallel False scanned_data copy deepcopy bom data root_dir bom root_dir if bom license_file is None subroots os path relpath x root_dir for x in roots if x root_dir pos root in bom data and bom get_key_position root or bom file_position new_deps walk_for_license root_dir subroots coalesce run_in_parallel if add_declarations for dep in new_deps _add_license dep scanned_data elif new_deps dep new_deps 0 license_id dep license license_id_str license_id Unknown and license_id or p os path normpath os path join dep root dep license file normRoot os path normpath root_dir raise BomError Undeclared license file in directory format license_id_str p normRoot pos else licenseFile bom license_file if bom license is None license_id confidence identify_license licenseFile license_ids pos bom get_key_position license file license_id_str confidence _MATCH_THRESHOLD and license_id or if add_declarations scanned_data license confidence _MATCH_THRESHOLD and license_id or Unknown else raise BomError Undeclared license in license file format license_id_str licenseFile pos deps is_source_dist and bom all_dependencies or bom dependencies for dep in deps if scan_components or dep base_dir bom base_dir scan_bom dep kwargs if add_declarations return scanned_data
handler function for clock enable / disable events,def _clk_events_handler self self _clk_intervals_by_clock defaultdict IntervalList for clock events in self _clk_events_by_clock iteritems last_timestamp self _trace interval start for clk_event in events state ClockState DISABLED if clk_event data state else ClockState ENABLED interval Interval last_timestamp clk_event timestamp clk_interval ClkInterval clock state interval self _clk_intervals_by_clock clock append clk_interval last_timestamp clk_event timestamp if events state ClockState ENABLED if clk_event data state else ClockState DISABLED end_interval ClkInterval clock clock state state interval Interval clk_event timestamp self _trace duration self _clk_intervals_by_clock clock append end_interval return self _clk_intervals_by_clock
test case where a file pattern matches a directory .,def testNonDirError self src_struct file1 dest_struct path chrome_util Path file1 self _CopyAndVerify path src_struct dest_struct error chrome_util MustNotBeDirError
"returns whether current line is part of the current suite . this can be false when we are in a generated suite outside of cxxtest_code ( ) blocks if the suite is generated , adds the line to the list of lines",def lineBelongsToSuite suite lineNo line if not suite generated return 1 global inBlock if not inBlock inBlock lineStartsBlock line if inBlock inBlock addLineToBlock suite lineNo line return inBlock
parse a peak list file .,def read_file self filename with open filename as input return self read input read
this method will be called for every message before the message payload deserialization .,def handle_message_header self message_header payload pass
"this function loads all images in a directory that contain a string in part of their name , and returns a 3d np array with dimensions corresponding to x , y , and framenumber . in the case of a single image , it returns a 2d numpy array .",def readMultiImageTifStack textInName files glob glob s textInName npArray readImagesFromList files return npArray
"ensures the macro expansions into none ( deletions ) , other nodes or list of nodes are expanded too .",def _visit_expansion self expansion target if expansion is not None is_node isinstance expansion AST expansion expansion if is_node else expansion expansion map lambda n copy_location n target expansion expansion map fix_missing_locations expansion expansion map self visit expansion expansion list expansion pop if is_node else list expansion return expansion
"decorator for views that checks that the logged in user is a teacher , redirects to the log - in page if necessary .",def servidor_required function None redirect_field_name REDIRECT_FIELD_NAME login_url actual_decorator user_passes_test lambda u u is_active and u tipo_usuario 0 login_url login_url redirect_field_name redirect_field_name if function return actual_decorator function return actual_decorator
make sure that the filelock instance does n't leave a lockfile lying around .,def __del__ self self release
get the project slug from the project id . this function assumes that the project id is passed as the keyword argument ` project_id ` .,def get_project_slug_from_project_id args kwargs project_id kwargs project_id project Project get project_id if project is None raise ResourceNotFound Project with ID not found format project_id return project slug
remove * key * from maps[0 ] and return its value . raise keyerror if * key * not in maps[0 ] .,def pop self key args try return self maps 0 pop key args except KeyError raise KeyError Key not found in the first mapping r format key
return a string sort key for the query tree .,def sortkey self return self _root sortkey
"when enable_auto_auth is set to true , the view should create and authenticate a new user with superuser permissions .",override_settings ENABLE_AUTO_AUTH True def test_setting_enabled self original_user_count User objects count response self client get self AUTO_AUTH_PATH self assertEqual response status_code 302 self assertEqual User objects count original_user_count 1 user User objects latest self assertEqual int self client session _auth_user_id user pk self assertTrue user username startswith settings AUTO_AUTH_USERNAME_PREFIX self assertTrue user is_superuser
testing using multiple instructions elements in a data form .,def testMultipleInstructions self msg self Message msg form instructions Instructions nSecond batch self check msg message x xmlns jabber x data type form instructions Instructions instructions instructions Second batch instructions x message
test setting the bare jid with a user .,def testJIDBareUser self j JID user domain resource j bare otheruser otherdomain self check_jid j otheruser otherdomain resource otheruser otherdomain otheruser otherdomain resource otheruser otherdomain resource
do some tests with the buffer,def test import sys def on_close widget event method called when the window is closed sys exit 0 window gtk Window window set_default_size 640 480 window connect delete event on_close textview gtk TextView buff RichBuffer textview set_buffer buff window add textview window show_all buff put_text buenas como va CCCCCC 000000 Arial 12 buff put_text esto es una prueba CC0000 AAAAAA Purisa 14 buff put_text un poco de formato 00CC00 FFFFFF Andale Mono 8 True True True True buff put_text un poco mas CCCCCC 0000CC Andale Mono 16 False True False True text i ital b i b c i br u under s lin b ed b s u br em emph strong as span style color CC0000 background color 00CC00 is span strong em br span style font size 14 size span style font family Arial test span span img src themes emotes default face sad png alt lt see that it is an image b asd b buff put_formatted text while buff widgets textview add_child_at_anchor buff widgets pop gtk main
create a comment in the emd file .,def put_comment self msg timestamp None if not isinstance msg str raise TypeError msg needs to be a string if not timestamp timestamp datetime datetime utcnow strftime Y m d H M S UTC else try timestamp str timestamp except raise if timestamp in self comments attrs self comments attrs timestamp np string_ n msg else self comments attrs timestamp np string_ msg
decorates optionparser with apk option used to install the apk .,def AddInstallAPKOption option_parser AddBuildTypeOption option_parser option_parser add_option apk help The name of the apk containing the application with the apk extension option_parser add_option apk_package help The package name used by the apk containing the application option_parser add_option keep_data action store_true default False help Keep the package data when installing the application
"given a rsync change report , returns the names of stale test packages .",def GetStalePackageNames change_list autotest_sysroot exp os path abspath autotest_sysroot client site_tests matches re match exp change absolute_path for change in change_list return match group 1 for match in matches if match
"creates a fixed version of the file , invokes |confirm_function| to decide whether to use the new file , and cleans up .",def FixFileWithConfirmFunction filename confirm_function perform_safety_checks if perform_safety_checks and IsUnsafeToReorderHeaders filename print Not reordering headers in s as the script thinks that the order of headers in this file is semantically significant filename return fixfilename filename new infile open filename rb outfile open fixfilename wb SortHeader infile outfile infile close outfile close try if confirm_function filename fixfilename if sys platform win32 os unlink filename os rename fixfilename filename finally try os remove fixfilename except OSError pass
export the current configuration into a swarm - readable manifest file,def to_json self cmd python RUN_TEST_NAME hash self manifest_hash remote self data_server_retrieval rstrip gzip if self verbose or self profile cmd append verbose self add_task Run Test cmd self add_task Clean Up python CLEANUP_SCRIPT_NAME hostname socket gethostname lower split 1 0 vlan None if hostname endswith m1 vlan m1 elif hostname endswith m4 vlan m4 test_case test_case_name self test_name data self data_server_retrieval urllib quote self zip_file_hash swarm_data zip tests self tasks env_vars configurations min_instances self shards config_name self target_platform dimensions os self target_platform working_dir self working_dir restart_on_failure True cleanup root if self test_filter and self test_filter test_case env_vars GTEST_FILTER self test_filter if self shards 1 test_case env_vars GTEST_SHARD_INDEX instance_index s test_case env_vars GTEST_TOTAL_SHARDS num_instances s if vlan test_case configurations 0 dimensions vlan vlan return json dumps test_case
"given a section header , find this section 's name in the file 's string table",def _get_section_name self section_header name_offset section_header sh_name return self _file_stringtable_section get_string name_offset
fetches member list for corporation or alliance .,def _member_list self ext_id api_type if api_type not in corplist allilist raise ValueError not valid api type valid api types corplist and allilist member_count 0 page 0 members while page member_count 200 data self _get ext_id api_type page info data info if info member_count int info member_count 1 else return members for member in data characters members append name str member name char_id int member character_id corp_id int member corporation_id alli_id int member alliance_id page 1 return members
get pseudo random content of given length .,def getContent length rv None length for i in xrange length rv i random choice letters return join rv
"assert that the next token is an instance of |expected| , and advance to the next token .",def advance self expected if not isinstance self token expected raise Exception Unexpected token self token self iter next
return the incidence matrix of a hypergraph .,def incidence_matrix H V sorted list H vertices E sorted list H edges dV for i in range len V dV V i i incidence numpy zeros len V len E if H directed for e in range len E incidence dV E e head e 1 for v in E e tail incidence dV v e 1 else for e in range len E for v in E e incidence dV v e 1 return incidence
test that we can create ` scattergather ` classes,def test_collect_sg_classes from fermipy jobs target_collect import CollectSED_SG CollectSED_SG create
creates a shunt capacitor from center conductor to ground,def gen_shunt_full self pos x0 pos 0 y0 pos 1 shuntcell cad core Cell SHUNT shuntbase self gen_shunt_base x0 y0 shunttop self gen_shunt_top x0 self gapwidth 2 self shunt 0 2 self shunt 4 2 y0 self shunt 5 2 shunttype self shunttype shuntins self gen_shunt_ins x0 self gapwidth 2 self shunt 2 self shunt 0 2 y0 self shunt 3 2 shuntcell add toadd for toadd in shuntbase shuntins shunttop return shuntcell
parse command line arguments . : return : argument namespace ( access members with dot ) .,def parseargs parser argparse ArgumentParser description Python AWS Lambda Emulator At present AWS Lambda supports Python 2 7 only parser add_argument lambdapath help An import path to your function as you would give it to AWS module function parser add_argument eventfile help A JSON file to give as the event argument to the function parser add_argument contextfile help A JSON file to give as the context argument to the function nargs parser add_argument s stream help Treat eventfile as a Line Delimited JSON stream action store_true parser add_argument r role help ARN of the role to execute your Lambda function your user must have AssumeRole priviledge and your user ARN must be in Lambda s execution role TrustedPolicy type str parser add_argument t timeout help Execution timeout in seconds Default is 300 the AWS maximum type int default 300 parser add_argument v verbose help Verbose mode Provides exact function run timing etc action store_true return parser parse_args
multiplies an encrypted counter by a public value,def mul c1 val a1 b1 c1 return val a1 val b1
validate data against given value directly,def _validate_value value data passed False if data value value passed True return passed
returns the heartbeat interval for the `` task `` . if more than two heartbeats are missed then the state will fail with a `` states . timeout `` error .,def get_heartbeat_seconds self return self _heartbeat_seconds
returns preferred mime content - type for resource type,def content_type typeuri return resource_types get typeuri default_types 0 1
"checks that adding table cards works , and that quads always win",def test_constructor_with_table self hand Hand Card 10 C SPADES Card 3 C SPADES table_cards Card 3 C CLUBS Card 3 C HEARTS Card 3 C DIAMONDS simulator HandSimulator hand table_cards self assertEqual len simulator deck 47 win_percentage simulator simulate 5 self assertEqual win_percentage 100
change opacity @param widget as gtk . widget @param event as gdk . event,def _on_button_leave_notify self widget event widget set_opacity 0 2
return a list of each disjoint set,def sets self ret defaultdict list for k _ in self parents iteritems ret self k append k return ret values
extra whitespace does n't break the parsing .,def testReadAutmountEntryWithExtraWhitespace self parser file_formats FilesAutomountMapParser file_entry scratch fileserver scratch map_entry parser _ReadEntry file_entry self assertEqual map_entry key scratch self assertEqual map_entry options None self assertEqual map_entry location fileserver scratch
decode a json value to a python value .,def decode_field self field value if isinstance field messages EnumField try return field type value except TypeError raise messages DecodeError Invalid enum value s value or elif isinstance field messages BytesField try return base64 b64decode value except binascii Error TypeError as err raise messages DecodeError Base64 decoding error s err elif isinstance field message_types DateTimeField try return util decode_datetime value except ValueError as err raise messages DecodeError err elif isinstance field messages MessageField and issubclass field type messages Message return self __decode_dictionary field type value elif isinstance field messages FloatField and isinstance value six integer_types six string_types try return float value except pass elif isinstance field messages IntegerField and isinstance value six string_types try return int value except pass return value
test if certificates can be accurately created and deleted,def test_create_and_delete_certificates self cert iot create_keys_and_certificate cert_desc iot describe_certificate cert self assertEqual cert certificateArn cert_desc certificateArn self assertEqual cert_desc status ACTIVE iot delete_certificate cert try iot describe_certificate cert except Exception as e self assertTrue s does not exist cert certificateId in e message
verify arguments passed to the geom,def _verify_arguments self kwargs keys six viewkeys unknown keys kwargs self aesthetics keys self DEFAULT_PARAMS self _stat aesthetics keys self _stat DEFAULT_PARAMS data mapping show_legend inherit_aes if unknown msg Parameters are not understood by either the geom stat or layer raise PlotnineError msg format unknown
"tries to create dumps in range [ start ; end ] , every step bytes end < start generally , only 1 dump should be created this is used to claim empty space",def create_dumps rop start end step use_repeat False r rop c rop caller d rop data if use_repeat size r pre_alloc_var p32 start iters start end step r repeat iters G pop_r1_pc size G pop_r5_r6_r7_r8_sb_pc 0 0 0 0 G pop_pc G ldr_r1_r1_blx_sb G pop_r0_pc d empty_str G pop_r2_pc 0 G pop_r4_pc F sceNetDumpCreate_svc G blx_r4_pop_r4_pc 0 G pop_r0_pc size G ldr_r0_r0_pop_r4_pc 0 G pop_r1_pc step 4294967295 G pop_r4_pc G adds_r0_r1 G blx_r4_pop_r4_pc 0 G pop_r1_pc size G str_r0_r1_pop_r4 0 else for dump_sz in range start end 1 step c sceNetDumpCreate_svc d empty_str dump_sz 0
"loads trainer states ( e.g. optimizer , momentum ) from a file .",def load_states self fname if self _update_on_kvstore self _kvstore load_optimizer_states fname self _optimizer self _kvstore _updater optimizer else with open fname rb as f states f read for updater in self _updaters updater set_states states updater optimizer self _updaters 0 optimizer self _optimizer self _updaters 0 optimizer
"look up a manufacturer part record by part number and manufacturer part number : param mpn : a manufacturer part number : return : a tuple containing : ( part number , manufacturer name , manufacturer part number , manufacturer id )",def lookup_part_by_pn_mpn self pn mpn self cur execute SELECT PartNumber Manufacturer MPN FROM pnmpn WHERE PartNumber AND MPN pn mpn res self cur fetchone if res is None return None pn res 0 mid res 1 mpn res 2 res self lookup_mfg_by_id mid if res is not None mname res 0 else raise ValueError return pn mname mpn mid
"given a mask with the same self.shape , update self.masks to include the union with this new mask .",def add_mask self new_mask assert new_mask shape self shape new_mask shape must be the same shape as spectrum format new_mask shape self shape self masks self masks new_mask
< purpose > parses an mpi ( multi - precision integer ) buffer and returns the appropriate length . this is mostly done to perform bitwise to byte - wise conversion .,def get_mpi_length data bitlength int struct unpack H data 0 return int bitlength 1 8 1
"f_locals is not guaranteed to have .get ( ) , but it will always support _ _ getitem__. even if it does n't , we return `` default `` .",def _getitem_from_frame f_locals key default None try return f_locals key except Exception return default
convert julian day to modified julian day,def jd_to_mjd jd return jd 2400000 5
clears out a dir . makes it if it does n't exist . : param dir_path : dir to clear out : return : true on success,def rm_mk_tree dir_path count 0 LOGGER debug removing s s dir_path os path abspath dir_path while os path exists dir_path and count 30 try shutil rmtree dir_path except FileNotFoundError pass except IOError if count 1 LOGGER info retrying removal of s perhaps you need to run this as sudo dir_path time sleep 2 count 1 if os path exists dir_path raise Exception error could not remove exiting format dir_path LOGGER info making s s dir_path os path abspath dir_path os makedirs dir_path return count 0
generate stats with values flattened for `` flatten_key `` .,def flatten_gen stats flatten_key for s in stats yield flatten_dict s flatten_key
"discards unnecessary tree data at the root , at the cost of losing track of anything we knew about bounds .",def reroot self l list self children_no_bounds s sum isinstance x BlobEmpty for x in l if s 7 for x in l if not isinstance x BlobEmpty return x reroot else return self
return the task that creates the validation set,def val_db_task self for t in self tasks if isinstance t tasks CreateDbTask and val in t name lower return t return None
predicate : ' [ ' expr ' ] ',def p_predicate p p 0 ast Predicate p 2
return the dtype information for a variable length class .,staticmethod def _determine_dtype_vlen datatype_msg vlen_type datatype_msg class_bit_field_0 1 if vlen_type 1 return VLEN_SEQUENCE 0 0 padding_type datatype_msg class_bit_field_0 4 character_set datatype_msg class_bit_field_1 1 return VLEN_STRING padding_type character_set
clean up the input variable .,def cleanup arg arg numpy asarray arg if len arg shape 1 arg arg reshape arg size 1 elif len arg shape 2 raise ValueError shapes must be smaller than 3 return arg
merge the config overrides wth the default configuration,def _merge_config self defaults overrides for key values in overrides items if key in defaults for value in values defaults key value overrides key value else defaults key overrides key return defaults
test locations of the phantom center .,def test_phan_center self known_phan_center Point 257 255 self cbct analyze self assertAlmostEqual self cbct ctp404 phan_center x known_phan_center x delta 0 7 self assertAlmostEqual self cbct ctp404 phan_center y known_phan_center y delta 0 7
test installing current directory ( ' . ' ) into usersite after installing distribute,pytest mark network def test_install_subversion_usersite_editable_with_distribute self script virtualenv tmpdir virtualenv system_site_packages True result script pip install user e s egg initools dev local_checkout svn http svn colorstudy com INITools trunk tmpdir join cache result assert_installed INITools use_user_site True
modifyadmins adds or removes admins from the cluster,def ModifyAdmins self request context context set_code grpc StatusCode UNIMPLEMENTED context set_details Method not implemented raise NotImplementedError Method not implemented
"the input parameters describe a ' package list ' option , thus they are returned with the correct converter and validater appended . the result is usable for input to opts . add ( ) .",def ListVariable key help default names map names_str allowed names s join names if SCons Util is_List default default join default help n join help all none comma separated list of names names_str return key help default None lambda val _converter val names map
filter for deviation from neighbours and mark filtered as outliers threshold is compared to difference from localmean normalized with standard deviation of neighbours,def meanfilter self threshold ni nj self shape for i in range 0 ni for j in range 0 nj meandx stddx n self localmean i j if stddx 0 0 and stddx 1 0 devdx0 abs meandx 0 self dx 0 i j stddx 0 devdx1 abs meandx 1 self dx 1 i j stddx 1 if devdx0 threshold or devdx1 threshold self outlier i j True
returns xpath match for ` selector ` within ` html ` .,def xpath_selector selector html from lxml import etree encoded html encode utf 8 root etree fromstring encoded parser etree HTMLParser elements root xpath selector if elements return True etree tostring next iter elements method html pretty_print True encoding unicode else logger warning XPath selector not found r selector return False html
unwind ` multipleerrors ` to have a plain list of ` invalid `,classmethod def flatten cls errors ers for e in errors if isinstance e MultipleInvalid ers extend cls flatten e errors else ers append e return ers
creates the function definition if it 's not created yet .,def _create_definition_if_needed self if self _definition is not None return temp_graph _ExperimentalFuncGraph capture_by_value self _capture_by_value with temp_graph as_default inputs for argname argtype in self _args argholder array_ops placeholder argtype name argname inputs append argholder with vs variable_scope custom_getter temp_graph getvar outputs self _func inputs if not isinstance outputs list tuple outputs outputs if any _ is None for _ in outputs raise ValueError Function can not return None outputs ops convert_to_tensor _ for _ in outputs self _extra_inputs temp_graph extra_inputs inputs extend temp_graph extra_args self _sub_functions temp_graph _functions self _definition function _graph_to_function_def temp_graph temp_graph get_operations inputs outputs out_names self _out_names sig_pre_func_name self _func_name or function _get_func_name self _func kwargs_attr function _parse_kwargs_as_attrs sig_pre_func_name self _extra_kwargs for k in kwargs_attr self _definition attr k CopyFrom kwargs_attr k self _hash_str self _create_hash_str self _definition signature input_arg self _definition signature output_arg self _definition node_def if not self _func_name self _func_name _ join function _get_func_name self _func self _hash_str self _definition signature name self _func_name if self _func __doc__ self _definition signature description self _func __doc__
no enable mode on brocade vdx .,def exit_enable_mode self args kwargs u pass
`` name `` of `` ' a.b.c ' `` = > `` mapping['a']['b']['c ' ] ``,def _crawl name mapping key _ rest name partition value mapping key if not rest return value return _crawl rest value
read the grid spacing from a gebco netcdf file .,def _read_netcdf_grid_spacing root return root variables spacing
"examples -------- > > > from landlab.grid.unstructured.nodes import nodegrid > > > ngrid = nodegrid(([0 , 0 , 1 ] , [ 0 , 1 , 0 ] ) ) > > > ngrid.point array ( [ [ 0 . , 0 . ] , [ 0 . , 1 . ] , [ 1 . , 0 . ] ] ) > > > ngrid.point[1 ] array ( [ 0 . , 1 . ] )",property def point self return self _coords T
the definition of the sequence to sequence model : param source_dict_dim : the dictionary size of the source language : type source_dict_dim : int : param target_dict_dim : the dictionary size of the target language : type target_dict_dim : int : param beam_size : the width of beam expansion : type beam_size : int : param is_generating : whether in generating mode : type is_generating : bool : return : the last layer of the network : rtype : layeroutput,def seqToseq_net source_dict_dim target_dict_dim beam_size is_generating False src_word_id paddle layer data name source_language_word type paddle data_type integer_value_sequence source_dict_dim src_embedding paddle layer embedding input src_word_id size word_vector_dim src_forward paddle networks simple_gru input src_embedding size encoder_size src_reverse paddle networks simple_gru input src_embedding size encoder_size reverse True encoded_vector paddle layer concat input src_forward src_reverse encoded_proj paddle layer fc input encoded_vector size decoder_size act paddle activation Linear bias_attr False reverse_first paddle layer first_seq input src_reverse decoder_boot paddle layer fc input reverse_first size decoder_size act paddle activation Tanh bias_attr False def gru_decoder_with_attention_train enc_vec enc_proj true_word true_token_flag The decoder step for training param enc_vec the encoder vector for attention type enc_vec LayerOutput param enc_proj the encoder projection for attention type enc_proj LayerOutput param true_word the ground truth target word type true_word LayerOutput param true_token_flag the flag of using the ground truth target word type true_token_flag LayerOutput return the softmax output layer rtype LayerOutput decoder_mem paddle layer memory name gru_decoder size decoder_size boot_layer decoder_boot context paddle networks simple_attention encoded_sequence enc_vec encoded_proj enc_proj decoder_state decoder_mem gru_out_memory paddle layer memory name gru_out size target_dict_dim generated_word paddle layer max_id input gru_out_memory generated_word_emb paddle layer embedding input generated_word size word_vector_dim param_attr paddle attr ParamAttr name _target_language_embedding current_word paddle layer multiplex input true_token_flag true_word generated_word_emb decoder_inputs paddle layer fc input context current_word size decoder_size 3 act paddle activation Linear bias_attr False gru_step paddle layer gru_step name gru_decoder input decoder_inputs output_mem decoder_mem size decoder_size out paddle layer fc name gru_out input gru_step size target_dict_dim act paddle activation Softmax return out def gru_decoder_with_attention_gen enc_vec enc_proj current_word The decoder step for generating param enc_vec the encoder vector for attention type enc_vec LayerOutput param enc_proj the encoder projection for attention type enc_proj LayerOutput param current_word the previously generated word type current_word LayerOutput return the softmax output layer rtype LayerOutput decoder_mem paddle layer memory name gru_decoder size decoder_size boot_layer decoder_boot context paddle networks simple_attention encoded_sequence enc_vec encoded_proj enc_proj decoder_state decoder_mem decoder_inputs paddle layer fc input context current_word size decoder_size 3 act paddle activation Linear bias_attr False gru_step paddle layer gru_step name gru_decoder input decoder_inputs output_mem decoder_mem size decoder_size out paddle layer fc name gru_out input gru_step size target_dict_dim act paddle activation Softmax return out decoder_group_name decoder_group group_input1 paddle layer StaticInput input encoded_vector is_seq True group_input2 paddle layer StaticInput input encoded_proj is_seq True if not is_generating trg_embedding paddle layer embedding input paddle layer data name target_language_word type paddle data_type integer_value_sequence target_dict_dim size word_vector_dim param_attr paddle attr ParamAttr name _target_language_embedding true_token_flags paddle layer data name true_token_flag type paddle data_type integer_value_sequence 2 group_inputs group_input1 group_input2 trg_embedding true_token_flags decoder paddle layer recurrent_group name decoder_group_name step gru_decoder_with_attention_train input group_inputs lbl paddle layer data name target_language_next_word type paddle data_type integer_value_sequence target_dict_dim cost paddle layer classification_cost input decoder label lbl return cost else trg_embedding paddle layer GeneratedInput size target_dict_dim embedding_name _target_language_embedding embedding_size word_vector_dim group_inputs group_input1 group_input2 trg_embedding beam_gen paddle layer beam_search name decoder_group_name step gru_decoder_with_attention_gen input group_inputs bos_id 0 eos_id 1 beam_size beam_size max_length max_length return beam_gen
current scope name as list returns : list,property def scopename self return r __current__ for r in self if r __current__
issue a signal to hangup the specified process,def hangup self unique_id configs None self _send_signal unique_id signal SIGHUP configs
returns an exponentially distributed time strictly between two bounds .,def strictExp min_wait max_wait mu 1 while True x random expovariate mu increment max_wait min_wait mu 6 0 result min_wait x increment if result max_wait break return result
creates a small hash of a string .,def StringIdentity string return b64encode sha1 string digest 8
kills the chrome driver after after the test method has been called .,def tearDown self print nTerminating Chrome Driver self driver quit print nKilling Proxy Server subprocess Popen kill self proxy_server try shutil rmtree self temp_data_dir except OSError as e if e errno 2 raise
returns true if the device has been thermally throttled .,def HasBeenThermallyThrottled self return self _platform_backend HasBeenThermallyThrottled
sign out from netflix login .,def SignOut self self _pyauto NavigateToURL self SIGNOUT_PAGE
restarts the forwarder if it 's not open .,def RestartHttpServerForwarderIfNecessary self if not ports IsDevicePortUsed self adb self _forwarder_device_port self StartForwarderForHttpServer
extends the range of a deletion if the deleted element was part of a list .,def _ExtendDeletionIfElementIsInList contents offset char_before char_after None left_trim_count 0 for byte in reversed contents offset left_trim_count 1 if byte in _WHITESPACE_BYTES continue if byte in ord ord ord ord char_before chr byte break right_trim_count 0 for byte in contents offset right_trim_count 1 if byte in _WHITESPACE_BYTES continue if byte ord char_after chr byte break if char_before if char_after del contents offset offset right_trim_count elif char_before in del contents offset left_trim_count offset
used for predefining event masks .,def SDL_EVENTMASK x return 1 x
write the given ` data ` to ` dest ` .,def write_raw self name dest data self m path assert_absolute dest self _run name copy self m raw_io input data dest self m path mock_add_paths dest
"writes a list of unixfiles to the disk , unpacking known archive files",def writeFileTree files path files path file path file for file in files for fn file in files if S_ISDIR file mode mkdirs fn elif S_ISREG file mode mkdirs os path dirname fn with open fn wb as dstFile shutil copyfileobj file contents dstFile for fn file in files if S_ISREG file mode with open fn rb as dstFile if archive isArchive dstFile print Unpacking s fn writeFileTree archive readArchive dstFile fn _unpacked for fn file in files if S_ISDIR file mode or S_ISREG file mode setmtime fn file mtime
delim : delim fwsp comma | delim fwsp semicolon | comma | semicolon,def p_delim p
"validates all models that are part of the specified app . if no app name is provided , validates all models of all installed apps . writes errors , if any , to outfile . returns number of errors .",def get_validation_errors outfile app None from django conf import settings from django db import models connection from django db models loading import get_app_errors from django db models fields related import RelatedObject e ModelErrorCollection outfile for app_name error in get_app_errors items e add app_name error for cls in models get_models app opts cls _meta for f in opts local_fields if f name id and not f primary_key and opts pk name id e add opts s You can t use id as a field name because each model automatically gets an id field if none of the fields have primary_key True You need to either remove rename your id field or add primary_key True to a field f name if f name endswith _ e add opts s Field names cannot end with underscores because this would lead to ambiguous queryset filters f name if isinstance f models CharField and f max_length in None 0 e add opts s CharFields require a max_length attribute f name if isinstance f models DecimalField if f decimal_places is None e add opts s DecimalFields require a decimal_places attribute f name if f max_digits is None e add opts s DecimalFields require a max_digits attribute f name if isinstance f models FileField and not f upload_to e add opts s FileFields require an upload_to attribute f name if isinstance f models ImageField try from PIL import Image except ImportError e add opts s To use ImageFields you need to install the Python Imaging Library Get it at http www pythonware com products pil f name if f choices if isinstance f choices basestring or not is_iterable f choices e add opts s choices should be iterable e g a tuple or list f name else for c in f choices if not type c in tuple list or len c 2 e add opts s choices should be a sequence of two tuples f name if f db_index not in None True False e add opts s db_index should be either None True or False f name if settings DATABASE_ENGINE mysql db_version connection get_server_version if db_version 5 0 3 and isinstance f models CharField models CommaSeparatedIntegerField models SlugField and f max_length 255 e add opts s s cannot have a max_length greater than 255 when you are using a version of MySQL prior to 5 0 3 you are using s f name f __class__ __name__ join str n for n in db_version 3 if f rel if f rel to not in models get_models e add opts s has relation with model s which has not been installed f name f rel to if isinstance f rel to str unicode continue rel_opts f rel to _meta rel_name RelatedObject f rel to cls f get_accessor_name rel_query_name f related_query_name for r in rel_opts fields if r name rel_name e add opts Accessor for field s clashes with field s s Add a related_name argument to the definition for s f name rel_opts object_name r name f name if r name rel_query_name e add opts Reverse query name for field s clashes with field s s Add a related_name argument to the definition for s f name rel_opts object_name r name f name for r in rel_opts local_many_to_many if r name rel_name e add opts Accessor for field s clashes with m2m field s s Add a related_name argument to the definition for s f name rel_opts object_name r name f name if r name rel_query_name e add opts Reverse query name for field s clashes with m2m field s s Add a related_name argument to the definition for s f name rel_opts object_name r name f name for r in rel_opts get_all_related_many_to_many_objects if r get_accessor_name rel_name e add opts Accessor for field s clashes with related m2m field s s Add a related_name argument to the definition for s f name rel_opts object_name r get_accessor_name f name if r get_accessor_name rel_query_name e add opts Reverse query name for field s clashes with related m2m field s s Add a related_name argument to the definition for s f name rel_opts object_name r get_accessor_name f name for r in rel_opts get_all_related_objects if r field is not f if r get_accessor_name rel_name e add opts Accessor for field s clashes with related field s s Add a related_name argument to the definition for s f name rel_opts object_name r get_accessor_name f name if r get_accessor_name rel_query_name e add opts Reverse query name for field s clashes with related field s s Add a related_name argument to the definition for s f name rel_opts object_name r get_accessor_name f name for i f in enumerate opts local_many_to_many if f rel to not in models get_models e add opts s has m2m relation with model s which has not been installed f name f rel to if isinstance f rel to str unicode continue rel_opts f rel to _meta rel_name RelatedObject f rel to cls f get_accessor_name rel_query_name f related_query_name if rel_name is not None for r in rel_opts fields if r name rel_name e add opts Accessor for m2m field s clashes with field s s Add a related_name argument to the definition for s f name rel_opts object_name r name f name if r name rel_query_name e add opts Reverse query name for m2m field s clashes with field s s Add a related_name argument to the definition for s f name rel_opts object_name r name f name for r in rel_opts local_many_to_many if r name rel_name e add opts Accessor for m2m field s clashes with m2m field s s Add a related_name argument to the definition for s f name rel_opts object_name r name f name if r name rel_query_name e add opts Reverse query name for m2m field s clashes with m2m field s s Add a related_name argument to the definition for s f name rel_opts object_name r name f name for r in rel_opts get_all_related_many_to_many_objects if r field is not f if r get_accessor_name rel_name e add opts Accessor for m2m field s clashes with related m2m field s s Add a related_name argument to the definition for s f name rel_opts object_name r get_accessor_name f name if r get_accessor_name rel_query_name e add opts Reverse query name for m2m field s clashes with related m2m field s s Add a related_name argument to the definition for s f name rel_opts object_name r get_accessor_name f name for r in rel_opts get_all_related_objects if r get_accessor_name rel_name e add opts Accessor for m2m field s clashes with related field s s Add a related_name argument to the definition for s f name rel_opts object_name r get_accessor_name f name if r get_accessor_name rel_query_name e add opts Reverse query name for m2m field s clashes with related field s s Add a related_name argument to the definition for s f name rel_opts object_name r get_accessor_name f name if opts ordering for field_name in opts ordering if field_name continue if field_name startswith field_name field_name 1 if opts order_with_respect_to and field_name _order continue if _ in field_name continue try opts get_field field_name many_to_many False except models FieldDoesNotExist e add opts ordering refers to s a field that doesn t exist field_name for ut in opts unique_together for field_name in ut try f opts get_field field_name many_to_many True except models FieldDoesNotExist e add opts unique_together refers to s a field that doesn t exist Check your syntax field_name else if isinstance f rel models ManyToManyRel e add opts unique_together refers to s ManyToManyFields are not supported in unique_together f name if f not in opts local_fields e add opts unique_together refers to s This is not in the same model as the unique_together statement f name return len e errors
"redirects the user to the login page , passing the given ' next ' page",def redirect_to_login next login_url None redirect_field_name REDIRECT_FIELD_NAME if not login_url login_url settings LOGIN_URL return HttpResponseRedirect s s s login_url urlquote redirect_field_name urlquote next
convert an < object > node to a deserializedobject .,def _handle_object self node Model self _get_model_from_node node model pk node getAttribute pk if not pk raise base DeserializationError object node is missing the pk attribute data Model _meta pk attname Model _meta pk to_python pk m2m_data for field_node in node getElementsByTagName field field_name field_node getAttribute name if not field_name raise base DeserializationError field node is missing the name attribute field Model _meta get_field field_name if field rel and isinstance field rel models ManyToManyRel m2m_data field name self _handle_m2m_field_node field_node field elif field rel and isinstance field rel models ManyToOneRel data field attname self _handle_fk_field_node field_node field else if field_node getElementsByTagName None value None else value field to_python getInnerText field_node strip data field name value return base DeserializedObject Model data m2m_data
returns the currently active script prefix . useful for client code that wishes to construct their own urls manually ( although accessing the request instance is normally going to be a lot cleaner ) .,def get_script_prefix return _prefixes get currentThread u
"wait for the given state(s ) , keyboardinterrupt or systemexit .",def wait self state interval 0 1 channel None if isinstance state tuple list if self state not in state events tuple self _get_state_event s for s in state win32event WaitForMultipleObjects events 0 win32event INFINITE elif self state state event self _get_state_event state win32event WaitForSingleObject event win32event INFINITE
"probability density for for next birth at time ' t ' given ' n ' lineages starting at time 0 , evolving until time ' t ' with a ' birth ' and ' death ' rates for a reconstructed process .",def birth_wait_time t n T birth death if birth death t2 t T nl 1 0 birth return birth n nl t2 n nl T n 1 0 birth t2 l birth u death r l u a u l return n r exp n r t 1 0 a exp r T t n 1 1 0 a exp r T n
generate a document : 1 ) sample topic proportions from the dirichlet distribution . 2 ) sample a topic index from the multinomial with the topic proportions from 1 ) . 3 ) sample a word from the multinomial corresponding to the topic index from 2 ) . 4 ) go to 2 ) if need another word .,def gen_document word_dist n_topics vocab_size length DOCUMENT_LENGTH alpha 0 1 theta np random mtrand dirichlet alpha n_topics v np zeros vocab_size for n in range length z sample_index theta w sample_index word_dist z v w 1 return v
make sure we can route to the given endpoint or url .,def can_route self endpoint method None kwargs view flask current_app view_functions get endpoint if not view endpoint args flask _request_ctx top match endpoint view flask current_app view_functions get endpoint if not view return False return self can http method or GET lower view kwargs
doppler broadens the windowed multipole curvefit . the curvefit is a polynomial of the form a / e + b / sqrt(e ) + c + d sqrt(e ) ...,def broaden_wmp_polynomials E dopp n factors np zeros n dtype np float64 _dll broaden_wmp_polynomials_c E dopp n factors return factors
helper for django 's `` reverse `` in templates .,library global_function def url viewname args kwargs return reverse viewname args args kwargs kwargs
returns whether the jsonp function name is valid,def jsonp_is_valid funcname func_regex re compile a zA Z_ a zA Z0 9_ a zA Z0 9_ a zA Z0 9_ a zA Z0 9_ re VERBOSE return bool func_regex match funcname
"create a new post , if the thread is unlocked .",def new_post self creator content if self is_locked raise ThreadLockedError return self post_set create creator creator content content
"dump an object to json , and ensure the dump is less than `` max_length `` .",def truncated_json_dumps obj max_length key ensure_ascii False orig json dumps obj ensure_ascii ensure_ascii diff len orig max_length if diff 0 return orig dupe json loads orig if len dupe key diff raise TruncationException Can t truncate enough to satisfy max_length dupe key dupe key diff return json dumps dupe ensure_ascii ensure_ascii
"element change page loads without error , contains name .",def test_change_page self e self F ElementFactory create name Linux self get self change_url e mustcontain Linux
can add product with initial environment profile .,def test_add_product_with_profile self profile self F ProfileFactory create envs self F EnvironmentFactory create_full_set OS OS X Linux profile profile f self form name Two version 1 0 profile profile id cc_version 0 version f save versions get self assertEqual set version environments all set envs
"if fall_through is set , post falls through untouched if no action .",def test_fall_through self dec self actions self mock_model doit fall_through True req self req post the url data other thing res self view req decorator dec self assertEqual self mock_model _base_manager get call_count 0 self assertEqual res status_code 200 self assertEqual res request method POST self assertEqual res request POST other thing
add some convenience fields to the return json .,def dehydrate self bundle suite bundle obj bundle data suite_id suite id bundle data case_count suite case_count bundle data filter_cases filter_url manage_cases suite return bundle
serialize text elements and placeables into a simple string .,def _serialize_elements elements response for element in elements if isinstance element ast TextElement response element value elif isinstance element ast Placeable if isinstance element expression ast ExternalArgument response element expression id name elif isinstance element expression ast MessageReference response element expression id name elif isinstance element expression ast CallExpression ast StringExpression ast NumberExpression ast VariantExpression ast AttributeExpression response serializer serialize_expression element expression elif hasattr element expression variants variant_elements filter lambda x x default element expression variants 0 value elements response _serialize_elements variant_elements return response
returns an ordereddict of model attributes,def dictify self data OrderedDict data id self id data created self created isoformat if self user data user self user dictify else data user None if self project data project self project dictify else data project None data content self htmlify return data
generate a ` robots.txt ` .,def robots request template render request site robots txt return HttpResponse template content_type text plain
# include < stdio.h > int puts(const char * s ) ;,def xxx_puts jitter ret_addr args jitter func_args_systemv target output jitter get_str_ansi args target line expected next if output line rstrip print Expected line print Obtained output raise RuntimeError Bad semantic return jitter func_ret_systemv ret_addr 1
test a dict value for being lower than another value .,def __lt__ self rhs return self _generate_test lambda value value rhs tuple self _path rhs
read - only property . is the file closed ?,property def closed self return self _closed
loads the credentials from the configured file .,def _loadCredentials self try with open self filename rb as f for line in f line line rstrip parts line split self delim if self ufield len parts or self pfield len parts continue if self caseSensitive yield parts self ufield parts self pfield else yield parts self ufield lower parts self pfield except IOError as e self _log error Unable to load credentials db e r e e raise error UnauthorizedLogin
returns the bar 's page information .,def get_page_number self return self _page_info
string representation of a progress object .,def __repr__ self repr_str Progress 0 1f r self _completed self _open_items_completion self _items return repr_str
return homogeneous rotation matrix from quaternion .,def quaternion_matrix quaternion u Return homogeneous rotation matrix from quaternion n n M quaternion_matrix 0 99810947 0 06146124 0 0 n np allclose M rotation_matrix 0 123 1 0 0 n True n M quaternion_matrix 1 0 0 0 n np allclose M np identity 4 n True n M quaternion_matrix 0 1 0 0 n np allclose M np diag 1 1 1 1 n True n n q np array quaternion dtype np float64 copy True n np dot q q if n np finfo float eps 4 0 return np identity 4 q np sqrt 2 0 n q np outer q q return np array 1 0 q 2 2 q 3 3 q 1 2 q 3 0 q 1 3 q 2 0 q 1 2 q 3 0 1 0 q 1 1 q 3 3 q 2 3 q 1 0 q 1 3 q 2 0 q 2 3 q 1 0 1 0 q 1 1 q 2 2
tests calling scalefiledescription.is_media_type_allowed ( ) when accepting specific media types .,def test_accept_specific self u file_desc ScaleFileDescription file_desc add_allowed_media_type None file_desc add_allowed_media_type u application json file_desc add_allowed_media_type u text plain self assertTrue file_desc is_media_type_allowed u application json self assertTrue file_desc is_media_type_allowed u text plain self assertFalse file_desc is_media_type_allowed u application x some crazy thing
adds the value for this connection to the data,abstractmethod def add_value_to_data self data recipe_input_data node_outputs u Adds the value for this connection to the data n n param data The data to add the value to n type data class data data data Data n param recipe_input_data The input data for the recipe n type recipe_input_data class data data data Data n param node_outputs The RecipeNodeOutput tuples stored in a dict by node name n type node_outputs dict n n raises class data data exceptions InvalidData If there is a duplicate data value n raise NotImplementedError
indicates whether more jobs can fit in this message,def can_fit_more self u Indicates whether more jobs can fit in this message n n return True if more jobs can fit False otherwise n rtype bool n return len self _requeue_jobs MAX_NUM
tests the nodemanager where an unknown node was lost,def test_lost_unknown_node self u manager NodeManager manager register_agents self agent_1 self agent_2 manager lost_node self agent_2 agent_id manager sync_with_database scheduler_mgr config nodes manager get_nodes self assertEqual len nodes 1 node_1 manager get_node self agent_1 agent_id self assertEqual node_1 hostname self node_1 hostname self assertTrue node_1 _is_online self assertIsNone manager get_node self agent_2 agent_id
"creates a job interface from the given definition . if the definition is invalid , a : class:`job.configuration.interface.exceptions . invalidinterfacedefinition ` exception will be thrown .",def __init__ self definition u Creates a job interface from the given definition If the definition is invalid a n class job configuration interface exceptions InvalidInterfaceDefinition exception will be thrown n n param definition The interface definition n type definition dict n self definition definition self _param_names set self _property_validation_dict self _input_file_validation_dict self _output_file_validation_list self _output_file_manifest_dict if u version not in self definition self definition u version SCHEMA_VERSION if self definition u version SCHEMA_VERSION self convert_interface definition try validate definition JOB_INTERFACE_SCHEMA except ValidationError as validation_error raise InvalidInterfaceDefinition validation_error self _populate_default_values self _populate_settings_defaults self _populate_env_vars_defaults self _check_param_name_uniqueness self _check_setting_name_uniqueness self _check_env_var_uniqueness self _validate_command_arguments self _create_validation_dicts
creates a scale file and recipe input file model for unit testing,def create_input_file recipe None input_file None recipe_input None file_name u my_test_file txt media_type u text plain file_size 100 file_path None workspace None countries None is_deleted False data_type u last_modified None source_started None source_ended None u Creates a Scale file and recipe input file model for unit testing n n returns The file model n rtype class storage models ScaleFile n if not recipe recipe create_recipe if not recipe_input recipe_input u test_input if not input_file input_file storage_test_utils create_file file_name file_name media_type media_type file_size file_size file_path file_path workspace workspace countries countries is_deleted is_deleted data_type data_type last_modified last_modified source_started source_started source_ended source_ended RecipeInputFile objects create recipe recipe scale_file input_file recipe_input recipe_input return input_file
"load the file into a text string , normalising whitespace .",def read_text filename text open filename read return re sub s text
process fork errors are raised by future.result .,def test_error_decorated self future error_decorated with self assertRaises RuntimeError future result
i am creating a new image sequence ( quicktime movie ) .,def crtimagesequence movpath imgpaths timeval timescale mov err QTMovie alloc initToWritableFile_error_ movpath None if mov None errmsg Could not create movie file s movpath raise IOError errmsg duration QTMakeTime timeval timescale attrs QTAddImageCodecType jpeg for imgpath in imgpaths img NSImage alloc initWithContentsOfFile_ imgpath mov addImage_forDuration_withAttributes_ img duration attrs mov updateMovieFile
converts protobuf message to a json dictionary .,def MessageToDict message including_default_value_fields False preserving_proto_field_name False strict_any_handling False printer _PatchedPrinter including_default_value_fields preserving_proto_field_name strict_any_handling strict_any_handling return printer _MessageToJsonObject message
return list of interfaces listened on : return : list of frameioport objects,def list_interfaces self return self ports
the domain to use in tests .,property def test_domain self return self get test_domain
create an application using a plan resource as a template .,def create_from_plan self plan_obj db_obj objects registry Assembly db_obj uuid uuidutils generate_uuid db_obj user_id self context user db_obj project_id self context tenant db_obj trigger_id uuidutils generate_uuid db_obj username self context user_name db_obj name plan_obj name _application db_obj plan_id plan_obj id db_obj plan_uuid plan_obj uuid db_obj status solum_assem_handler ASSEMBLY_STATES QUEUED db_obj create self context artifacts plan_obj raw_content get artifacts for arti in artifacts self _build_artifact assem db_obj artifact arti return db_obj
"t103 - untranslated exception message . : param logical_line : the logical line to check . : param filename : the file name where the logical line exists . : returns : none if the logical line passes the check , otherwise a tuple is yielded that contains the offending index in logical line and a message describe the check validation failure .",def check_raised_localized_exceptions logical_line filename if _translation_is_not_expected filename return logical_line logical_line strip raised_search re compile raise w match logical_line if raised_search exception_msg raised_search groups 0 if exception_msg startswith or exception_msg startswith msg T103 Untranslated exception message yield logical_line index exception_msg msg
tests the mgmt datastore version create method .,test depends_on test_mgmt_ds_version_list_original_count def test_mgmt_ds_version_create self response self client mgmt_datastore_versions create test_version1 test_ds test_mgr self images 0 vertica 7 1 assert_equal None response assert_equal 202 self client last_http_code new_ds_versions self client mgmt_datastore_versions list assert_equal len self ds_versions 1 len new_ds_versions self created_version self _find_ds_version_by_name test_version1 assert_equal test_version1 self created_version name assert_equal test_ds self created_version datastore_name assert_equal test_mgr self created_version datastore_manager assert_equal self images 0 self created_version image assert_equal vertica 7 1 self created_version packages assert_true self created_version active assert_false self created_version default
remove slave users from master instance .,test runs_after test_backup_deleted def cleanup_master_instance self self test_runner run_cleanup_master_instance
: parameters : : solvers : a list of file names containing solver statistics failures must be indicated with negative statistics : options : a dictionary of options . currently recognized options are listed below .,def __init__ self solvers opts parameters solvers a list of file names containing solver statistics Failures must be indicated with negative statistics options a dictionary of options Currently recognized options are listed below options datacol the 1 based column index containing the relevant metric in the solver files logscale True if log scale ratios are requested sep the column separator as a regexp default s bw True if a black and white plot is requested title string containing the plot title returns A PerformanceProfile object on which plot may be called self solvers solvers self options default_options copy for opt in opts self options opt opts opt self metrics self ratios None map self add_solver solvers self compute_ratios
get the file name of the summary file,def get_result_file self return self result_file
"install package dependencies , source files , and startup configuration .",when_not ntpmon installed def install_ntpmon hookenv log installing ntpmon dependencies apt_install python3 psutil hookenv log installing ntpmon host rsync src ntpmon_dir if host init_is_systemd hookenv log installing ntpmon systemd configuration host rsync src service_name systemd systemd_config subprocess call systemd daemon reload else hookenv log installing ntpmon upstart configuration host rsync src service_name upstart upstart_config set_state ntpmon installed remove_state ntpmon configured
"not not ( s1 = = s1 ) , s1 = expand((x+y+z)**10 ) , 20x",def test_compare_eq1 n 20 while n not not s1 s1 n 1
default test for the streamingavrage class .,def test_default self values_01 np asarray 1 2 3 4 5 1000 dtype np float32 weights_01 np asarray 1 1 1 1 1 0 dtype np float32 avg_01 3 0 values_02 np asarray 1000 1000 8 9 10 1000 dtype np float32 weights_02 np asarray 0 0 1 1 1 0 dtype np float32 avg_02 9 0 avg 5 25 values tf placeholder dtype tf float32 shape 2 3 name values weights tf placeholder dtype tf float32 shape 2 3 name weights streaming_avg streaming StreamingAverage name StreamingAvg streaming_avg compute values weights with tf Session as sess sess run tf global_variables_initializer sess run tf local_variables_initializer feed_dict values values_01 weights weights_01 sess run streaming_avg update_op feed_dict self assertEqual avg_01 sess run streaming_avg batch_value feed_dict self assertEqual avg_01 sess run streaming_avg value feed_dict feed_dict values values_02 weights weights_02 sess run streaming_avg update_op feed_dict self assertEqual avg_02 sess run streaming_avg batch_value feed_dict self assertEqual avg sess run streaming_avg value feed_dict sess run streaming_avg reset_op self assertEqual 0 0 sess run streaming_avg value self assertEqual 0 sess run streaming_avg count feed_dict values values_02 weights weights_02 sess run streaming_avg update_op feed_dict self assertEqual avg_02 sess run streaming_avg batch_value feed_dict self assertEqual avg_02 sess run streaming_avg value feed_dict
add a sample x to myself . must be overwritten by subclasses,def add self x raise NotImplementedError
returns the processor module for a given achievement .,def get_processor aid try path get_achievement aid aid show_disabled True processor base_path api config get_settings achievements processor_base_path return SourceFileLoader path 3 join base_path path load_module except FileNotFoundError raise InternalException Achievement processor is offline
this is the generic method to initialize the dynamic dispatcher,v on node def visit self node
returns an object with default linear regression fit options,def default_fit_options reg_type D opts opts Display None opts verbose False opts TolFun 0 001 opts MaxIter 200 opts Method lbfgs opts MaxFunEvals 2000 opts TolX 0 001 if reg_type lower l1 opts order 1 if D 1000 opts corrections 10 return opts
a filtered mapping towards performaction of the underlying environment .,def performAction self action if self actor_limits action self denormalize action self env performAction action
"calls the gradient calculation function and executes a step in direction of the gradient , scaled with a small learning rate alpha .",def learn self assert self dataset None assert self module None gradient self calculateGradient if max gradient 1000 gradient gradient max gradient 1000 p self gd gradient flatten self network _setParameters p self network reset
"prepares a game data for databse . recursively walks the node tree to collect moves and comments . arguments : node - list ( a tree of lboards created by the pgn parser ) arr - array(""h "" ) ( 2 byte unsigned ints representing lmove objects or comment , vari_start , vari_end , nag+nag ) txt - list ( comment strings )",def walk node arr txt arr_append arr append while True if node is None break if node prev is None for child in node children if isinstance child str arr_append COMMENT txt append child node node next continue arr_append node lastMove for nag in node nags if nag arr_append NAG int nag 1 for child in node children if isinstance child str arr_append COMMENT txt append child else arr_append VARI_START walk child 0 arr txt arr_append VARI_END if node next node node next else break
return print - friendly version of a thread - related `` kwargs `` dict .,def _printable_kwargs kwargs printable for key value in six iteritems kwargs item value if key args item for arg in value new_arg arg if hasattr arg __len__ and len arg 10 msg remainder truncated during error display new_arg arg 10 msg item append new_arg printable key item return printable
verifies the authenticity of a notification message .,def verify self secret_key verification_input NotificationMessage SERVICE_NAME verification_input NotificationMessage OPERATION_NAME verification_input self timestamp h hmac new key secret_key digestmod sha h update verification_input signature_calc base64 b64encode h digest return self signature signature_calc
converts different condition types to callback,def condition2checker condition if type condition in str unicode def smatcher info return fnmatch fnmatch info filename condition return smatcher elif type condition in list tuple and type condition 0 in int long def imatcher info return info index in condition return imatcher elif callable condition return condition else raise TypeError
decorator to deactivate a test method . the test is still run if the test module is invoked directly .,def disable func def _exclude self args kwargs if runtest py in sys argv 0 sys stderr write disabled else func self args kwargs return _exclude
returns twiml instructions to twilio 's post requests,csrf_exempt def call request response twiml Response phone_number request POST get phoneNumber lstrip 1 if phone_number If the browser sent a phoneNumber param we know this request is an outgoing call from the pyphone for c in phone_number phone_number replace c phone_number 1 phone_number direction outgoing with response dial callerId settings TWILIO_NUMBER as r r number request POST phoneNumber else Otherwise we assume this request is an incoming call direction incoming with response dial as r r client caller phone_number request GET get From try contact Contact objects get number phone_number except ObjectDoesNotExist contact Contact number phone_number contact save call Call contact contact direction direction call save return HttpResponse str response
log level < 10 produces traceback on error .,def test_trace_log_level arg_list blah ctx string log 5 with patch pypyr pipelinerunner main as mock_pipeline_main with patch traceback print_exc as mock_traceback mock_pipeline_main side_effect AssertionError Test Error Mock val pypyr cli main arg_list assert val 255 mock_traceback assert_called_once
returns whether this node is trainable .,def is_trainable self return False
"given bytes and the current bytes offset , return the type , state , path , and new offset",classmethod def deserialize cls bytes offset type state int_int_struct unpack_from bytes offset offset int_int_struct size path offset read_string bytes offset return cls type state path offset
handles add parameter as well as update parameter . parmeters for features will be stored as part of personality as features/<feature_name>/<path >,def set_parameter session parameter db_paramdef path value update False retval db_paramdef parse_value path value if db_paramdef activation rebuild validate_rebuild_required session path parameter personality_stage parameter set_path path retval update if db_paramdef schema new_value parameter get_path db_paramdef path try validate new_value db_paramdef schema except ValidationError as err raise ArgumentError err
"like plt.scatter , but with nicer default color & transparency",def scatter x y kwargs import matplotlib pyplot as plt kwargs setdefault c blue kwargs setdefault alpha 0 95 kwargs setdefault edgecolors none plt scatter x y kwargs
"execute a command in the application 's sub - shell . if an empty command is passed , start the application 's sub - shell in a cmdloop line : a command in the application 's sub - shell , or an empty string",def cmd self line if self console if line self console onecmd line else self console cmdloop
decompresses all deflated streams and returns the updated pdf file,def DecompressStreams pdf L streams for m in re finditer Filter FlateDecode Length d n stream pdf re M start m start 2 7 streams start m start start int m group 1 L start delta 0 for i in L start i delta end streams i 1 delta stream zlib decompress pdf start end before len pdf pdf pdf replace pdf streams i 0 delta end Length d nstream n len stream stream delta len pdf before return pdf
add a list of uris .,def add_uris self urls self _cursor executemany INSERT INTO queue url etag mod_date next_date priority VALUES urls
called when the process 's standard output is ready for reading .,def handle_stdout self fd iomap try buf os read fd BUFFER_SIZE if buf if self inline self outputbuffer buf if self outfile self writer write self outfile buf if self print_out sys stdout write s s self host buf if buf 1 n sys stdout write n else self close_stdout iomap except OSError IOError _ e _ sys exc_info if e errno EINTR self close_stdout iomap self log_exception e
takes the diagonal values of the outer product matrix between ` a ` and ` b ` .,def diagouter A B return np sum A B conjugate axis 1
generate a private key using a secure random number generator .,def genPrivateKey self bits return secure_random bits
"@param cond : ok , fail , error @param captured_output : output captured from stdout @param captured_output : output captured from stderr @param file : the tests file ( c:/temp / test.py ) @param test : the test ran ( i.e. : testcase.test1 ) @param time : float with the number of seconds elapsed",def notifyTest cond captured_output error_contents file test time assert cond is not None assert captured_output is not None assert error_contents is not None assert file is not None if test is None test assert time is not None try captured_output _encode_if_needed captured_output error_contents _encode_if_needed error_contents _ServerHolder SERVER notifyTest cond captured_output error_contents file test time except traceback print_exc
"check makewebservice.make method , using git",testutil run_in_tempdir def test_make_git self class DummySourceControl GitSourceControl def _run_git_command self cmd cwd None self cmds append cmd class Dummy MakeWebService def _get_install_dir self return dummy m Dummy modfoo ModFoo git True msc DummySourceControl modfoo modfoo m source_control msc m user root os mkdir m topdir msc cmds oldstderr sys stderr try sys stderr StringIO StringIO m make finally sys stderr oldstderr config saliweb backend Config modfoo conf live conf for end in front back config _read_db_auth end for f in conf live conf conf frontend conf conf backend conf lib modfoo pm python modfoo __init__ py txt help txt txt contact txt SConstruct lib SConscript python modfoo SConscript txt SConscript test SConscript test frontend SConscript test backend SConscript os unlink modfoo f
automatically find / download setuptools and make it available on sys.path,def use_setuptools version DEFAULT_VERSION download_base DEFAULT_URL to_dir os curdir download_delay 15 was_imported pkg_resources in sys modules or setuptools in sys modules def do_download egg download_setuptools version download_base to_dir download_delay sys path insert 0 egg import setuptools setuptools bootstrap_install_from egg try import pkg_resources except ImportError return do_download try pkg_resources require setuptools version return except pkg_resources VersionConflict as e if was_imported print sys stderr The required version of setuptools s is not available and can t be installed while this script is running Please install a more recent version first using easy_install U setuptools Currently using r version e args 0 sys exit 2 else del pkg_resources sys modules pkg_resources return do_download except pkg_resources DistributionNotFound return do_download
read multiple tags sqlite3 uses ? placeholder for parameters substitution,def read_statedb PID None NAME None SCOPE TODO with sqlite3 connect STATE_DB_PATH as conn try cursor conn cursor par_temp cmd SELECT FROM Tag boolean False if PID is not None cmd WHERE PID par_temp append PID boolean True if NAME is not None if boolean cmd AND NAME else cmd WHERE NAME par_temp append NAME par_sub tuple par_temp cursor execute cmd par_sub records cursor fetchall return records except sqlite3 Error as e logger warning Error s e args 0
"if and only if a job already has other dependencies , this will add more jids to the list of this job 's dependencies .",def depend self args return self client depends self jid on args or False
the 4 dimensional rosenbrock function as a toy model,def rosenbrock_4d x1 x2 x3 x4 val 100 x2 x1 2 2 x1 1 2 100 x3 x2 2 2 x2 1 2 100 x4 x3 2 2 x3 1 2 return val
return all activities for this set of group members . i.e. all activities that any member is a member for .,def all_activities members return set m activity for m in members if m activity deleted False
apply combine to list of timestamps .,def combine_all self merging_timestamps combined_output_time None for output_time in merging_timestamps if combined_output_time is None combined_output_time output_time else combined_output_time self combine combined_output_time output_time return combined_output_time
removes a pvalue from the cache .,def clear_pvalue self pvalue if self is_cached pvalue del self _cache self key pvalue
this function extract the mapped reads from the sam file which is got from mapping using aligners . input map_result is a list of mapped sam file,def extract_mapped map_result returnFile cmd for mapfile in map_result filename mapfile 9 mapped sort bam returnFile append filename cmd cmd samtools view F 4 bh input output format input mapfile output filename subprocess check_call cmd wait shell True return returnFile
"given a string a subspace in liouville space or a mapping between subspaces , returns the minimal containing hilbert space subspace",def extract_subspace subspaces_string return sorted set subspaces_string key excitation_to_number
learn a model for coreference resolution from training data .,def learn training_corpus instance_extractor perceptron logging info Learning logging info tExtracting instances and features substructures arc_information instance_extractor extract training_corpus logging info tFitting model parameters perceptron fit substructures arc_information return perceptron get_model
initialize instance of economy class and attach the agent population as a class attribute .,def __init__ self agent_objs integrity_checks __init__ agent_objs self population agent_objs
makes an indra statement from a geneways action and action mention .,def make_statement self action mention u Makes an INDRA statement from a Geneways action and action mention n n Parameters n n action GenewaysAction n The mechanism that the Geneways mention maps to Note that n several text mentions can correspond to the same action if they are n referring to the same relationship there may be multiple n Geneways action mentions corresponding to each action n mention GenewaysActionMention n The Geneways action mention object corresponding to a single n mention of a mechanism in a specific text We make a new INDRA n statement corresponding to each action mention n n Returns n n statement indra statements Statement n An INDRA statement corresponding to the provided Geneways action n mention or None if the action mention s type does not map onto n any INDRA statement type in geneways_action_type_mapper n statement_generator is_direct geneways_action_to_indra_statement_type mention actiontype action plo if statement_generator is None return None text None if get_ft_mention try content content_type get_full_text mention pmid u pmid if content is not None ftm FullTextMention mention content sentences ftm find_matching_sentences if len sentences 1 text sentences 0 except Exception logger warning u Could not fetch full text for PMID mention pmid epistemics dict epistemics u direct is_direct annotations mention make_annotation annotations u plo action plo evidence Evidence source_api u geneways source_id mention actionmentionid pmid mention pmid text text epistemics epistemics annotations annotations upstream_agent get_agent mention upstream action up downstream_agent get_agent mention downstream action dn return statement_generator upstream_agent downstream_agent evidence
test running sparser in parallel .,attr u nonpublic def test_sparser_parallel u db get_db_with_pubmed_content sparser_reader SparserReader n_proc 2 tc_list db select_all db TextContent result sparser_reader read process_content tc for tc in tc_list verbose True log True N_exp len tc_list N_res len result assert N_exp N_res u Expected to get d results but got d N_exp N_res
the task list is allowed to just be a list .,def test_no_tasks_header tasklist nightbus tasks TaskList name print hello commands echo hello assert tasklist names print hello
callback from gui after user selected a specific device .,def select_device_done self device next_state self model set_device device self check next_state
"the argument is the proto object for topology . returns the number of stream managers for the topology . this is equal to the number of containers . if not present , return 1 as default .",def get_nstmgrs topology return int get_topology_config topology api_constants TOPOLOGY_STMGRS or 1
rename ` src ` to ` dest ` using ` os.rename ( ) ` .,def rename_if_empty src dest allowable_errors errno EEXIST errno ENOTEMPTY try os rename src dest except OSError as e if e errno in allowable_errors safe_rmtree src else raise
write the touchpad mode to the node path .,def _write_touchpad_mode_str mode_str try node_file_handle open NODE_PATH w except IOError as e logging error Error opening s for writing s NODE_PATH e return node_file_handle write mode_str node_file_handle close
make sure that airports are listed in alphabetical order . see # 1193 .,def test_airport_ordering self first_airport Airport objects all 0 assert first_airport iata AAA
"generate a generic flat file html for an abf parent . you could give this a single abf id , its parent id , or a list of abf ids . if a child abf is given , the parent will automatically be used .",def html_single_basic self abfID launch False overwrite False if type abfID is str abfID abfID for thisABFid in cm abfSort abfID parentID cm parent self groups thisABFid saveAs os path abspath s s_basic html self folder2 parentID if overwrite is False and os path basename saveAs in self files2 continue filesByType cm filesByType self groupFiles parentID html html div style background color DDDDDD html span class title summary of data from s span br parentID html code s code os path abspath self folder1 parentID abf html div catOrder experiment plot tif other categories cm list_order_by filesByType keys catOrder for category in x for x in categories if len filesByType x if category experiment html h3 Experimental Data h3 elif category plot html h3 Intrinsic Properties h3 elif category tif html h3 Micrographs h3 elif category other html h3 Additional Files h3 else html h3 h3 for fname in filesByType category html self htmlFor fname html br 3 print creating saveAs style save html saveAs launch launch
"detect the version of the raspberry pi . returns either 1 , 2 or none depending on if it 's a raspberry pi 1 ( model a , b , a+ , b+ ) , raspberry pi 2 ( model b+ ) , or not a raspberry pi .",def isRPi try with open proc cpuinfo r as infile cpuinfo infile read match re search Hardware s s w cpuinfo flags re MULTILINE re IGNORECASE if not match return None if match group 1 BCM2708 return True elif match group 1 BCM2709 return True else return False except return False
convert a file size into natural readable format . multiple formats are supported .,def filesize value format decimal digits 2 if format not in FILESIZE_SUFFIX raise TypeError base FILESIZE_BASE format size int value sign size 0 and u or size abs size for i suffix in enumerate FILESIZE_SUFFIX format unit base i 1 if size unit result u join sign _format base size float unit digits u suffix if format gnu result result replace return result raise OverflowError
calls self.command_run ( ) and logs the action . then calls functions that correspond to the options found in the self.options variable .,def main self time_executed self time_executed time_executed self command_run viento_utils log trans_success args self method self source self destination if adjust in self options self interval_adjust if learn in self options self interval_learn
pads all sentences to the same length . the length is defined by the longest sentence . returns padded sentences .,def _pad_sentences sentences padding_word PAD sequence_length max len x for x in sentences padded_sentences for i in range len sentences sentence sentences i num_padding sequence_length len sentence new_sentence sentence padding_word num_padding padded_sentences append new_sentence return padded_sentences
"resolve all mixins in a preset , fully expanding the arguments list .",def _resolve_preset_mixins self raw_preset u Resolve all mixins in a preset fully expanding the arguments list n assert isinstance raw_preset _RawPreset args for option in raw_preset options if isinstance option _Mixin args self _get_preset option name args elif isinstance option _Argument args append option name option value else raise ValueError u invalid argument type option __class__ return Preset raw_preset name args
can save the model itself by using tensorflow saver,def checkpoint self step None ckpt_file tmp rlflow model ckpt save_path self saver save self sess ckpt_file global_step step print Session saved in file s save_path
returns the factorization ` l `,def L self return self _solver L
get a prompt for asking a question with y / n as accepted answer .,def yes_no question default yes valid yes True y True ye True no False n False if default is None prompt y n elif default yes prompt Y n elif default no prompt y N else raise ValueError invalid default answer s default while True sys stdout write question prompt choice input lower if default is not None and choice return valid default elif choice in valid return valid choice else sys stdout write Please respond with yes or no or y or n n
perform ' touch ' on { chroot}/dest with optional label .,def touch self dst label None self write dst label mode a
test that directories are correctly ignored as config files .,def test_invalid_config_file self self launch_process self proc wait self assertEqual self proc returncode 1 self launch_process etc passwd self proc wait self assertEqual self proc returncode 1
"module proxy does not contain any functions of remote object , they are created at runtime upon reception of remote object description",def __init__ self self log logging getLogger module name format module self __class__ __module__ name self __class__ __name__ self uuid None self type None self name None self node None self _callIdGen 0 self _callingCtx CallingContext self _clear_call_context self _currentNode None self functions self in_events self out_events
: type password : str : type text : str,def encode password text enc for i in range len text key_c password i len password enc_c chr ord text i ord key_c 256 enc append enc_c return base64 urlsafe_b64encode join enc encode decode
truncates a string after a certain number of words . : rtype str,def truncate_words content length 10 suffix split content split if len split length return join split length else return join split length suffix
return the selected world either by its name or location .,def get_world self name name name lower for world in self worlds values if world name lower name return world elif world location name return world return None
iterates through our parsed configuration options and cast any options with marked cast types .,def _cast self for configName configDict in self configs items if configDict cast is not None configValue getattr self _config configName if configValue is not None try self _setConfig configName configDict cast configValue except raise InvalidConfigurationException s r configName configValue
crops images into subimages of size ' inputsize'x'inputsize,def crop inputFile inputSizeX inputSizeY outputFolder x 0 y 0 img Image open inputFile width height img size print width height while not x inputSizeX width or y inputSizeY height img_small img crop x y x inputSizeX y inputSizeY saveFile outputFolder os path split inputFile 1 4 ___ str x _ str y png img_small save saveFile if x 2 inputSizeX width x 0 y y inputSizeY else x x inputSizeX image_index find_before_convert os path split inputFile 1 png with open imagesizes a as f f write image_index str width str height n
adds a link to source 's token representations using default settings .,def add_token_link self source None source_layer None kwargs if source_layer is None source_layer source default_source_layer self spec linked_feature add name source spec name source_component source spec name source_layer source_layer source_translator source default_token_translator kwargs
non - raising rmdir ( ) .,def _rmdir path util SMlog lock removing lock dir s path try os rmdir path except Exception as e util SMlog Failed to rmdir s s path e
backwards - compatibility for the old retries format .,classmethod def from_int cls retries redirect True default None if retries is None retries default if default is not None else cls DEFAULT if isinstance retries Retry return retries redirect bool redirect and None new_retries cls retries redirect redirect log debug Converted retries value r r retries new_retries return new_retries
os - specific conversion from a relative url of the ' file ' scheme to a file system path ; not recommended for general use .,def url2pathname url tp urllib splittype url 0 if tp and tp file raise RuntimeError Cannot convert non local URL to pathname if url 3 url url 2 elif url 2 raise RuntimeError Cannot convert non local URL to pathname components string split url if not components 0 if in components del components 0 else components 0 i 0 while i len components if components i del components i elif components i and i 0 and components i 1 not in del components i 1 i 1 i 1 elif components i components i i 1 elif components i and i 0 and components i 1 del components i else i 1 components map lambda x urllib unquote x translate __slash_dot components return join components
quit : quit navigator keyword argument _ attributes : appleevent attribute dictionary,def quit self _no_object None _attributes _arguments _code aevt _subcode quit if _arguments raise TypeError No optional args expected if _no_object is not None raise TypeError No direct arg expected _reply _arguments _attributes self send _code _subcode _arguments _attributes if _arguments get errn 0 raise aetools Error aetools decodeerror _arguments if _arguments has_key return _arguments
"parse a url into 6 components : < scheme>://<netloc>/<path>;<params>?<query>#<fragment > return a 6-tuple : ( scheme , netloc , path , params , query , fragment ) . note that we do n't break the components up in smaller bits ( e.g. netloc is a single string ) and we do n't expand % escapes .",def urlparse url scheme allow_fragments True tuple urlsplit url scheme allow_fragments scheme netloc url query fragment tuple if scheme in uses_params and in url url params _splitparams url else params return ParseResult scheme netloc url params query fragment
return the line number where the current event ends .,def getLineNumber self return 1
stop the listening server which was created with a call to listen ( ) .,def stopListening global _listener if _listener logging _acquireLock _listener abort 1 _listener None logging _releaseLock
returns the absolute path of the directory where the .py files are .,def GetSourceDir return os path abspath GetFlag source_dir
self test of this class .,def test verbose utils lib mlm_client_test verbose
add an aux param to .params file . example : moving_mean in batchnorm layer,def add_aux_param self param_name layer_index blob_index self add_param aux s param_name layer_index blob_index
load class names from text file,def _load_class_names self filename dirname full_path osp join dirname filename classes with open full_path r as f classes l strip for l in f readlines return classes
generates a random synchronization marker .,staticmethod def GenerateSyncMarker return os urandom SYNC_SIZE
format a number with grouped thousands and given decimal places,def number_format num places 0 places max 0 places tmp f places num point tmp find integer point 1 and tmp or tmp point decimal point 1 and tmp point or count 0 formatted for i in range len integer 0 1 count 1 formatted append integer i 1 if count 3 0 and i 1 formatted append integer join formatted 1 return integer decimal
find the nth rank ordered element ( the least value has rank 0 ) .,def select data n data list data if not 0 n len data raise ValueError not enough elements for the given rank while True pivot random choice data pcount 0 under over uappend oappend under append over append for elem in data if elem pivot uappend elem elif elem pivot oappend elem else pcount 1 if n len under data under elif n len under pcount return pivot else data over n len under pcount
"construct , start must be < = end .",def __init__ self start end if start end raise ValueError Start s must not be greater than end s start end self _start start self _end end
join content from a range of lines between start and end,def combine_range lines start end srow scol erow ecol start end if srow erow return lines srow 1 scol ecol end rows lines srow 1 scol lines srow erow 1 lines erow 1 ecol return join rows end
"in the http protocol , a request is complete if the "" end of headers "" sequence ( ' ' ) has been received if the request is post , stores the request body in a stringio before returning true",def request_complete self In the HTTP protocol a request is complete if the end of headers n sequence r n r n has been received n If the request is POST stores the request body in a StringIO before n returning True terminator self incoming find r n r n if terminator 1 return False lines self incoming terminator split r n self requestline lines 0 try self method self url self protocol lines 0 strip split except self method None return True self headers for line in lines 1 k v line split 1 self headers k lower strip v strip close_conn self headers get connection if self protocol HTTP 1 1 and close_conn lower keep alive self close_when_done False scheme netloc path params query fragment urlparse urlparse self url self path self rest path params query fragment if self method POST content_length int self headers get content length 0 body self incoming terminator 4 if len body content_length return False f_body cStringIO StringIO body f_body seek 0 sys stdin f_body return True
suspend job for the given number of seconds and return elapsed time .,def sleep_task secs def _task task_return start_time time time def _on_timeout task_return time time start_time gobject timeout_add int secs 1000 _on_timeout return _task
compute the suffix for a certain power of bytes .,def format_suffix power number return PREFIX power byte capitalize s number 1
x.__init _ _ ( ... ) initializes x,def __init__ self host port self address host port
private function to initialize the states of self._next_element and self._has_next . we poke our self._myiter to see if it 's still alive and kicking .,def _prime self try self _next_element self _myiter next self _has_next 1 except StopIteration self next_element None self _has_next 0
takes care of incoming connections .,def client self sock name args kwargs self recv sock try self send sock self services name args kwargs except self send sock None
indicates whether the named section is present in the configuration .,def has_section self section return self _store has_key section
return the index of the child configinfo object ' child ',def getIndex self child if child in self _children return self _children index child else return 1
"extract command from file and replace all macros pargs -- args passed to program except file path # ! key and any arguments pfilepath -- file to use in macro expansion psearchpath -- file to scan for command ' pcount -- number of lines at the start of the file to scan psep -- string used to identify end of command , extra arguments will not be appended plist -- true to display available commands pwidth -- number of columns to scan for # !",def Expand pArgs pFilePath pSearchPath pCount pSep pDefault pList False pWidth 15 pVerbose False if len pArgs 1 0 lKey pDefault lStart 1 elif pArgs 1 startswith pDefault lKey pArgs 1 lStart 2 else lKey pDefault lStart 1 lCommand FindCommand lKey pFilePath pSearchPath pCount pDefault pDefault pList pList pWidth pWidth pVerbose pVerbose if lCommand print pb py Command lKey not found if len lCommand 0 if len pArgs lStart for lArg in pArgs lStart if lArg find 0 lArg Do2 ExpandArg lArg pFilePath lPos lCommand find if lPos 0 lCommand lCommand 0 lPos lArg lCommand lPos 2 else lCommand lArg lPos lCommand rfind pSep if lPos 0 lCommand lCommand 0 lPos if lCommand find 0 lCommand Do Expand lCommand pFilePath return lCommand
run a simple demo that shows evaluator 's capability .,def test from sys import exc_info stderr from traceback import format_exception_only local while True try evaluate input local except EOFError break except stderr write format_exception_only exc_info 2 1
iterate over the key names .,def __iter__ self return iter tuple _winreg EnumKey self __key index for index in xrange _winreg QueryInfoKey self __key 0
gets the intent that matches the specified text .,def intent_for app_name text try return app_map app_name intent_for text except KeyError raise IntentNotFound
checks if the type column of raw data block has an element of type soma,def has_soma_points data_wrapper db data_wrapper data_block return CheckResult POINT_TYPE SOMA in db COLS TYPE None
constructor - set completed operations to 0,def __init__ self self completed_operations 0
: param url_hash : : return : if we have seen enough of an url or not,def need_more_urls_of_this_type self url_hash return self calculate_cluster_per_visited_urls url_hash CLUSTER_THRESHOLD
refreshes and updates the objects tree from the current path .,def ui_command_refresh self self refresh
add builders and construction variables for sun f90 compiler to an environment .,def generate env add_all_to_env env fcomp env Detect compilers or f90 env FORTRAN fcomp env F90 fcomp env SHFORTRAN FORTRAN env SHF90 F90 env SHFORTRANFLAGS SCons Util CLVar FORTRANFLAGS KPIC env SHF90FLAGS SCons Util CLVar F90FLAGS KPIC
two type here : section or tutorials . sections are defining the differents type of tutorials,def processTutorialInfo self message logger debug Processing TutorialInfo if section in message section message section desc message description area util THEME loadUi tutorials tutorialarea ui tabIndex self addTab area section self setTabToolTip tabIndex desc area listWidget setItemDelegate TutorialItemDelegate self area listWidget itemDoubleClicked connect self tutorialClicked self sections section area listWidget elif tutorial in message tutorial message tutorial section message tutorial_section if section in self sections self tutorials tutorial TutorialItem tutorial self tutorials tutorial update message self client self sections section addItem self tutorials tutorial
computes the total cost from the node and message costs,def add_cost self if self comp_cost nvars len self msg_hdl_list for i in range nvars var_costi gradi coni self msg_hdl_list i get_cost_terms self var_cost i var_costi 0 var_costi 1 self grad i gradi self con i coni self cost np sum self node_cost np sum self var_cost np sum self Hgauss
get a bitmap version of images by scaling it with input width and height,def get_bmp self width None height None img self gradient_img if width None and height None img img Scale width height wx IMAGE_QUALITY_HIGH bmp wx BitmapFromImage img return bmp
fetches a file from the repo,def fetch_file self key k normalize_key key self fetch_tree dic dict self _tree if k not in dic return Result Err p run svn cat k if p returncode return Result Err return Result Ok p stdout
return all public config settings return : list of config settings dictionaries,app route ThreatKB cfg_settings methods GET auto doc login_required admin_only def get_all_cfg_settings entities cfg_settings Cfg_settings query filter_by public True all return Response json dumps entity to_dict for entity in entities mimetype application json
use the assigned i d if we have one .,def GetId self if self assigned_id return self assigned_id return BaseMessage GetId self
returns the ephemeris dataframe for a single campaign .,def get_ephemeris_dataframe target first last step_size 4 fileobj get_ephemeris_file target first last step_size return jpl2pandas fileobj
custom version since the default limits to 10 services per call,def describe_services ecs cluster services result for services_slice in slice_iterable services 10 response ecs describe_services cluster cluster services services_slice result extend response services return result
delete a record . : param i d : i d of record to delete . : return : delete warning dialogue page .,app route record id delete methods GET POST login_required requires_roles r a def delete_record id record models Record query get_or_404 id form RecordForm obj record if form is_submitted for image in record images db session delete image db session commit db session delete record db session commit flash u has been deleted format id return redirect url_for list_records return render_template delete_warning html form form objType Record objId id
calculates radiative forcing from oxidation of methane to h2o.,def linear F_CH4 ratio 0 15 F_H2O ratio F_CH4 return F_H2O
"helper , returns a list of all superclasses of a given class",def _superclasses_for_subject self graph typeof classes superclass typeof while True found False for p o in self schema_def ontology superclass if self schema_def lexicon subclass str p found True classes append o superclass o if not found break return classes
create an interpreter from the commandline arguments .,def interpreter_from_args nlu_model nlu_endpoint u Create an interpreter from the commandline arguments n n Depending on which values are passed for model and endpoint this n will create the corresponding interpreter either loading the model n locally or setting up an endpoint based interpreter if isinstance nlu_model NaturalLanguageInterpreter return nlu_model if nlu_model name_parts nlu_model split u else name_parts if len name_parts 1 if nlu_endpoint return RasaNLUHttpInterpreter name_parts 0 nlu_endpoint else return NaturalLanguageInterpreter create nlu_model elif len name_parts 2 if nlu_endpoint return RasaNLUHttpInterpreter name_parts 0 nlu_endpoint name_parts 1 else return NaturalLanguageInterpreter create nlu_model elif nlu_endpoint raise Exception u You have configured an endpoint to use for the NLU model To use it you need to specify the model to use with nlu project model else return None
"test example commands in "" run manually "" readme section .",pytest mark usefixtures cdemu def test_manual tmpdir with pytest ROOT join README md open as handle for line in handle if line strip Now go ahead and run the image break partial handle read 1024 contents re compile n bash n n n re DOTALL findall partial 0 script tmpdir join script sh script write contents if OUTPUT check OUTPUT remove pytest run bash script assert OUTPUT check pytest verify OUTPUT gid os getgid uid os getuid modes drwxr xr x rw r r
returns true is tweet has at least one ' urls ' entity,def contains_url tweet if entities not in tweet return False if urls in tweet entities and len tweet entities urls 0 return True return False
"return an iterator of shapely geometries that intersect with the given extent . the extent is assumed to be in the crs of the feature . if extent is none , the method returns all geometries for this dataset .",def intersecting_geometries self extent if extent is not None extent_geom sgeom box extent 0 extent 2 extent 1 extent 3 return geom for geom in self geometries if geom is not None and extent_geom intersects geom else return self geometries
"used to set ownership of an object , the ownership of an object applies all effects down the tree additively for numeric values .",def set_owner self owner object __setattr__ self _owner owner owner _children append self
return the current user run configuration value for the given key .,def smvGetRunConfig self key return self smvApp getConf key
create a dir with specified permissions if it does not already exist,def createDirIfNeeded path perms None recursive False f os mkdir if recursive is True f os makedirs if os path isdir path return if not os path isdir path and os path exists path raise Exception Cannot create directory object at path s path if perms is None f path else setUIDGID perms oldumask os umask 0 if perms mode is not None f path perms mode else f path uid perms uid gid perms gid if uid is None uid 1 if gid is None gid 1 os chown path uid gid os umask oldumask
given a dataset name and a split_name returns a dataset .,def get_dataset name split_name dataset_dir file_pattern None reader None if name not in datasets_map raise ValueError Name of dataset unknown s name return datasets_map name get_split split_name dataset_dir file_pattern reader
log msg to this pos 's logger .,def warn self msg if self log_fp is not None self log_fp write warning n format self msg
defines the type of field .,def get_type self return radio
remove all points with do no have a corresponding point at the same x - value in the other hist,def remove_non_mutual_points g1 g2 points_to_remove1 points_to_remove2 xs1 p 0 for p in g1 xs2 p 0 for p in g2 for i x in enumerate xs1 if x not in xs2 points_to_remove1 append i for i x in enumerate xs2 if x not in xs1 points_to_remove2 append i for p in points_to_remove1 1 g1 RemovePoint p for p in points_to_remove2 1 g2 RemovePoint p
"> > > list(tokenwithposition('asdf ' , 0 ) ) [ ' a ' , ' s ' , ' d ' , ' f ' ]",def __iter__ self return iter self __iter
test dependency disconnecting using two actor items,def test_dependency_disconnect self actor1 self create items ActorItem uml2 Actor actor2 self create items ActorItem uml2 Actor dep self create items DependencyItem self connect dep dep head actor1 self connect dep dep tail actor2 dep_subj dep subject self disconnect dep dep tail self assertTrue dep subject is None self assertTrue self get_connected dep tail is None self assertTrue dep_subj not in self element_factory select self assertTrue dep_subj not in actor1 subject supplierDependency self assertTrue dep_subj not in actor2 subject clientDependency
"create new text element with bounds ( 0 , 0 , 10 , 10 ) and empty text .",def __init__ self attr style None pattern None visible None editable False super TextElement self __init__ self _bounds Rectangle 0 0 width 15 height 10 self _style Style self _style add text padding 2 2 2 2 self _style add text align ALIGN_CENTER ALIGN_TOP self _style add text outside False self _style add text rotated False self _style add text align str None self _style add font DEFAULT_TEXT_FONT if style self _style update style self attr attr self _text if visible self is_visible visible if pattern self _pattern pattern else self _pattern s self editable editable
"returns a devinfo instance , a named tuple with the following items : - bustype : one of bus_usb , bus_hil , bus_bluetooth or bus_virtual - vendor : device 's vendor number - product : device 's product number",def getInfo self devinfo _hidraw_devinfo self _ioctl _HIDIOCGRAWINFO devinfo True return DevInfo devinfo bustype devinfo vendor devinfo product
request an image given some specs and redirects to it,def image request pk specs image get_object_or_404 get_image_model pk pk rendition get_rendition_or_not_found image specs return redirect rendition url
returns a tuple containing the result code and a pre - formatted result label,def execute configurations parameters host_name None if configurations is None return UNKNOWN There were no configurations supplied to the script ranger_link None ranger_auth_link None ranger_get_user None admin_username None admin_password None ranger_admin_username None ranger_admin_password None security_enabled False stack_version_formatted Script get_stack_version stack_supports_ranger_kerberos stack_version_formatted and check_stack_feature StackFeature RANGER_KERBEROS_SUPPORT stack_version_formatted if RANGER_ADMIN_URL in configurations ranger_link configurations RANGER_ADMIN_URL if ranger_link endswith ranger_link ranger_link 1 ranger_auth_link 0 1 format ranger_link service public api repository count ranger_get_user 0 1 format ranger_link service xusers users if ADMIN_USERNAME in configurations admin_username configurations ADMIN_USERNAME if ADMIN_PASSWORD in configurations admin_password configurations ADMIN_PASSWORD if RANGER_ADMIN_USERNAME in configurations ranger_admin_username configurations RANGER_ADMIN_USERNAME if RANGER_ADMIN_PASSWORD in configurations ranger_admin_password configurations RANGER_ADMIN_PASSWORD if SECURITY_ENABLED in configurations security_enabled str configurations SECURITY_ENABLED upper TRUE label None result_code OK try if security_enabled and stack_supports_ranger_kerberos result_code UNKNOWN label This alert will get skipped for Ranger Admin on kerberos env else admin_http_code check_ranger_login ranger_auth_link admin_username admin_password if admin_http_code 200 get_user_code get_ranger_user ranger_get_user admin_username admin_password ranger_admin_username if get_user_code user_http_code check_ranger_login ranger_auth_link ranger_admin_username ranger_admin_password if user_http_code 200 result_code OK label Login Successful for users 0 and 1 format admin_username ranger_admin_username elif user_http_code 401 result_code CRITICAL label User 0 credentials on Ambari UI are not in sync with Ranger format ranger_admin_username else result_code WARNING label Ranger Admin service is not reachable please restart the service else result_code OK label Login Successful for user 0 User 1 user not yet synced with Ranger format admin_username ranger_admin_username elif admin_http_code 401 result_code CRITICAL label User 0 credentials on Ambari UI are not in sync with Ranger format admin_username else result_code WARNING label Ranger Admin service is not reachable please restart the service except Exception as e label str e result_code UNKNOWN logger exception label return result_code label
parse the line of ' hdfs rebalancer ' output . the example output being parsed :,def parseProgressLog self line m m re match self PROGRESS_PATTERN line if m self date m group date self iteration int m group iteration self bytesAlreadyMoved self parseMemory m group memory_1 m group mult_1 self bytesLeftToMove self parseMemory m group memory_2 m group mult_2 self bytesBeingMoved self parseMemory m group memory_3 m group mult_3 self bytesAlreadyMovedStr m group memmult_1 self bytesLeftToMoveStr m group memmult_2 self bytesBeingMovedStr m group memmult_3 else raise AmbariException Failed to parse line s
builds a list of extension directories,def list_extensions self root_dir try return self _list_metainfo_dirs root_dir except Exception as err raise KeeperException Can not list extensions 0 format str err
sets the integer byte order to the endianness specified for all non - binary types . can be either config.byteorder.bigendian or config.byteorder.littleendian .,def setbyteorder endianness module setbyteorder endianness for module in ptype pint pfloat
test wheter an object is an instance of the rat class .,def isRat x return isinstance x Rat
process list of free vars from nested scope .,def add_frees self names child_globals for name in names sc self check_name name if self nested if sc SC_UNKNOWN or sc SC_FREE or isinstance self ClassScope self frees name 1 elif sc SC_GLOBAL child_globals append name elif isinstance self FunctionScope and sc SC_LOCAL self cells name 1 elif sc SC_CELL child_globals append name elif sc SC_LOCAL self cells name 1 elif sc SC_CELL child_globals append name return child_globals
create a new control panel . @param parent the wx parent window,def __init__ self parent self parent parent wx Panel __init__ self parent style wx SUNKEN_BORDER parent SHOW_CONTROL_PANEL_KEY True parent subscribe SHOW_CONTROL_PANEL_KEY self Show control_box wx BoxSizer wx VERTICAL control_box AddStretchSpacer options_box forms static_box_sizer parent self sizer control_box label Trace Options bold True orient wx VERTICAL forms check_box sizer options_box parent self label Peak Hold ps parent key PEAK_HOLD_KEY forms check_box sizer options_box parent self label Average ps parent key AVERAGE_KEY avg_alpha_text forms static_text sizer options_box parent self label Avg Alpha converter forms float_converter lambda x 4f x ps parent key AVG_ALPHA_KEY width 50 avg_alpha_slider forms log_slider sizer options_box parent self min_exp AVG_ALPHA_MIN_EXP max_exp AVG_ALPHA_MAX_EXP num_steps SLIDER_STEPS ps parent key AVG_ALPHA_KEY for widget in avg_alpha_text avg_alpha_slider parent subscribe AVERAGE_KEY widget Enable widget Enable parent AVERAGE_KEY parent subscribe AVERAGE_KEY widget ShowItems widget ShowItems True parent subscribe AVERAGE_KEY self _update_layout forms check_box sizer options_box parent self label Persistence ps parent key USE_PERSISTENCE_KEY persist_alpha_text forms static_text sizer options_box parent self label Persist Alpha converter forms float_converter lambda x 4f x ps parent key PERSIST_ALPHA_KEY width 50 persist_alpha_slider forms log_slider sizer options_box parent self min_exp PERSIST_ALPHA_MIN_EXP max_exp PERSIST_ALPHA_MAX_EXP num_steps SLIDER_STEPS ps parent key PERSIST_ALPHA_KEY for widget in persist_alpha_text persist_alpha_slider parent subscribe USE_PERSISTENCE_KEY widget Enable widget Enable parent USE_PERSISTENCE_KEY parent subscribe USE_PERSISTENCE_KEY widget ShowItems widget ShowItems True parent subscribe USE_PERSISTENCE_KEY self _update_layout for trace in TRACES trace_box wx BoxSizer wx HORIZONTAL options_box Add trace_box 0 wx EXPAND forms check_box sizer trace_box parent self ps parent key TRACE_SHOW_KEY trace label Trace s trace trace_box AddSpacer 10 forms single_button sizer trace_box parent self ps parent key TRACE_STORE_KEY trace label Store style wx BU_EXACTFIT trace_box AddSpacer 10 control_box AddStretchSpacer y_ctrl_box forms static_box_sizer parent self sizer control_box label Axis Options bold True orient wx VERTICAL forms incr_decr_buttons parent self sizer y_ctrl_box label dB Div on_incr self _on_incr_db_div on_decr self _on_decr_db_div forms incr_decr_buttons parent self sizer y_ctrl_box label Ref Level on_incr self _on_incr_ref_level on_decr self _on_decr_ref_level y_ctrl_box AddSpacer 2 forms single_button sizer y_ctrl_box parent self label Autoscale callback self parent autoscale control_box AddStretchSpacer forms toggle_button sizer control_box parent self true_label Stop false_label Run ps parent key RUNNING_KEY self SetSizerAndFit control_box def on_mouse_wheel event if event GetWheelRotation 0 self _on_incr_ref_level event else self _on_decr_ref_level event parent plotter Bind wx EVT_MOUSEWHEEL on_mouse_wheel
add a facebook login provider to the application .,def add_facebook_login config consumer_key consumer_secret scope None login_path login facebook callback_path login facebook callback name facebook provider FacebookProvider name consumer_key consumer_secret scope config add_route provider login_route login_path config add_view provider attr login route_name provider login_route permission NO_PERMISSION_REQUIRED config add_route provider callback_route callback_path use_global_views True factory provider callback register_provider config name provider
return the ' slots ' defined for this object,def slotnames self return methods_env slotNames self
"this function sets up the event handling necessary to handle scrolling properly . it should be called within the _ _ init _ _ function of any class that is derived from scrolledpanel , once the controls on the panel have been constructed and thus the size of the scrolling area can be determined .",def SetupScrolling self scroll_x True scroll_y True rate_x 20 rate_y 20 scrollToTop True scrollIntoView True self scrollIntoView scrollIntoView if not scroll_x rate_x 0 if not scroll_y rate_y 0 sizer self GetSizer if sizer w h sizer GetMinSize if rate_x w rate_x w rate_x if rate_y h rate_y h rate_y self SetVirtualSize w h self SetScrollRate rate_x rate_y wx CallAfter self _SetupAfter scrollToTop
this decorator modifies the decorated function 's docstring by replacing occurrences of ' % ( super)s ' with the docstring of the method of the same name from the class ` cls ` .,def inherit_docstring_from cls def _doc func cls_docstring getattr cls func __name__ __doc__ func_docstring func __doc__ if func_docstring is None func __doc__ cls_docstring else new_docstring func_docstring dict super cls_docstring func __doc__ new_docstring return func return _doc
create a new figure manager instance for the given figure .,def new_figure_manager_given_figure num figure canvas FigureCanvasGTK3Agg figure manager FigureManagerGTK3Agg canvas num return manager
return the next item in the cache without modifying the currently managed position . @return : cache object,def PeekNext self if self HasNext return self _list self cpos 1 else return None
"recursively walk a sequence , stringifying each element .",def strseq object convert join joinseq if type object in types ListType types TupleType return join map lambda o c convert j join strseq o c j object else return convert object
make sure that string - to - object functions are properly recognized,def test_string_to_object self conv StringConverter _bytes_to_date assert_equal conv _mapper 2 0 0 0j assert_ hasattr conv default
are commands case sensitive or not @return : bool,def GetCaseSensitive self return self _case_sensitive
"returns a copy of row i of the matrix , as a ( 1 x n ) csr matrix ( row vector ) .",def getrow self i return self _get_submatrix i slice None
return f = r*bt at given value(s ) of normalised psi .,def fpol self psinorm out None if self f_func is not None return self f_func psinorm return super ProfilesPprimeFfprime self fpol psinorm out
isnan : : realfloat a = > a - > bool,sig H RealFloat a a bool def isNaN x return RealFloat x isNan x
test roundtrip value and type preservation for string types,def test_string self self helper self data string basic str data self data string cell_array incoming self oc roundtrip data assert isinstance incoming Cell assert incoming tolist data tolist
"creates update sql for a given user , ' table ' is the table name , username is the username of the user making the change , cond is the where condition eg :",def make_update_user_sql dbo table username cond s stampRecordVersion True l list s l append LastChangedBy ds username l append LastChangedDate ddt i18n now dbo timezone if stampRecordVersion l append RecordVersion di dbo get_recordversion return make_update_sql table cond l
test easy direction with 1 best molecules just near actual position : return :,def test_route_direct_route self test_data NORTH_WEST _p CENTER MOLECULES_DIRECTION PHEROMON_DIR_EXPLO 10 1 0 _p NORTH_WEST MOLECULES_DIRECTION PHEROMON_DIR_EXPLO 9 1 0 NORTH _p CENTER MOLECULES_DIRECTION PHEROMON_DIR_EXPLO 10 1 0 _p NORTH MOLECULES_DIRECTION PHEROMON_DIR_EXPLO 9 1 0 NORTH_EST _p CENTER MOLECULES_DIRECTION PHEROMON_DIR_EXPLO 10 1 0 _p NORTH_EST MOLECULES_DIRECTION PHEROMON_DIR_EXPLO 9 1 0 WEST _p CENTER MOLECULES_DIRECTION PHEROMON_DIR_EXPLO 10 1 0 _p WEST MOLECULES_DIRECTION PHEROMON_DIR_EXPLO 9 1 0 EST _p CENTER MOLECULES_DIRECTION PHEROMON_DIR_EXPLO 10 1 0 _p EST MOLECULES_DIRECTION PHEROMON_DIR_EXPLO 9 1 0 SOUTH_WEST _p CENTER MOLECULES_DIRECTION PHEROMON_DIR_EXPLO 10 1 0 _p SOUTH_WEST MOLECULES_DIRECTION PHEROMON_DIR_EXPLO 9 1 0 SOUTH _p CENTER MOLECULES_DIRECTION PHEROMON_DIR_EXPLO 10 1 0 _p SOUTH MOLECULES_DIRECTION PHEROMON_DIR_EXPLO 9 1 0 SOUTH_EST _p CENTER MOLECULES_DIRECTION PHEROMON_DIR_EXPLO 10 1 0 _p SOUTH_EST MOLECULES_DIRECTION PHEROMON_DIR_EXPLO 9 1 0 for direction_wanted in test_data self _test_direction_for_point test_data direction_wanted direction_wanted
: py : class:`~kubeshift.queries.base . query ` clusterresourcequotas .,base queryapi version v1 kind ClusterResourceQuota nsarg False def clusterresourcequotas self
helper for local connections that are sometimes needed to operate on local hosts,def get_local_connection logger use_sudo False return get_connection socket gethostname None logger logger threads 1 use_sudo use_sudo detect_sudo False
read a g4beamline tracking ' one ' file to a dataframe .,def read_g4beamline_tracking file column_names X Y S PX PY PZ t PDGid EventID TrackID ParentID Weight tmp np nan if os path isfile file data pd read_csv file skiprows G4BEAMLINE_SKIP_ROWS delimiter header None names column_names query TrackID 1 and ParentID 1 if len data 0 return tmp data X 1000 data Y 1000 data S 1000 data P np sqrt data PX 2 data PY 2 data PZ 2 data PX data P data PY data P tmp beam Beam data X PX Y PY P return tmp
generates a cache key for a model instance .,def cache_key model pk app model _meta app_label name model _meta module_name return api 0 1 2 format app name pk
add builders and construction variables for zip to an environment .,def generate env try bld env BUILDERS Zip except KeyError bld ZipBuilder env BUILDERS Zip bld env ZIP zip env ZIPFLAGS SCons Util CLVar env ZIPCOM zipAction env ZIPCOMPRESSION zipcompression env ZIPSUFFIX zip
check if an rpm package is installed .,def is_installed pkg_name manager MANAGER with settings hide running stdout stderr warnings warn_only True res run rpm query pkg_name s locals if res succeeded return True return False
index.scan ( ) should not fail when the dir does not exist,def test_index_scan_when_there_is_no_dir u index Index u I know this directory does not exist index scan
perform a ( blocking ) read on the pty,def read self size return os read self _fd size
invoke a qmp command and return the result dict,def qmp self cmd args qmp_args dict for k in args keys qmp_args k translate self underscore_to_dash args k return self _qmp cmd cmd args qmp_args
"get size , in bytes , of the given variable .",def get_var_nbytes self var_name pass
"returns a list of 2-tuples ( attr_name , attr_value ) .",def get_bibliography self plugin_api corpus item_id raise NotImplementedError
sample from a poisson distribution . algorithm is due to donald knuth - see wikipedia / poisson_distribution,def poissonSample lamb l exp lamb k 0 p 1 while True k 1 p rand if p l break return k 1
"fetch the specified entry attribute , converting from .sconsign format to in - memory format .",def get_entry self filename entry Dir get_entry self filename entry convert_from_sconsign self dir filename return entry
"return basic test data : - 1d wave[nwave ] - 2d flux[nspec , nwave ] - 2d ivar[nspec , nwave ]",def _get_data nspec 10 nwave 100 wave np linspace 0 np pi nwave y np sin wave flux np tile y nspec reshape nspec nwave ivar np ones flux shape mask np zeros flux shape dtype int return wave flux ivar mask
forward iterator support to the dictionary .,def next self return self _device_types_iter next
initialize the sniffer thread object .,def __init__ self arg super Sniffer self __init__ self daemon True self arg arg try self interface str arg interface self source_ip str arg source_ip self destination_host str arg destination_host self destination_port int arg destination_port except KeyError raise ValueError Invalid argument dictionary Not enough parameters try self destination_ip socket gethostbyname self destination_host except socket herror as err raise ValueError socket herror format str err if not all self interface self source_ip self destination_host self destination_port raise ValueError Invalid argument dictionary Invalid parameters self port_streams collections defaultdict lambda self _recording False self record_lock threading Lock
test comparing two passages with the sliding window strategy,def test_distance_sliding_window self t TextReuse comparisons t compare_sliding_window demo_verg demo_prop self assertEqual comparisons 19 3 ratio 0 64
test filter : returns arguments as a concatenated string .,register def argtest args return join str arg for arg in args
returns the horizontal header ( of type qheaderview ) .,def _horizontal_header self return self horizontalHeader
compute the binary separation change induced by the orbital motion of the lens .,def orbital_motion_2D_separation_shift to_om time ds_dt dseparation ds_dt time to_om return dseparation
get the root of the git repository ( edx - platform ) .,def repo_root file_path path __file__ attempt 1 while True try absolute_path file_path abspath break except OSError print Attempt 180 to get an absolute path failed format attempt if attempt 180 attempt 1 sleep 1 else print Unable to determine the absolute path of the edx platform repo aborting raise return absolute_path parent parent parent
"return the bytes of the course code library file , if it exists .",def get_python_lib_zip contentstore course_id python_lib_filename getattr settings PYTHON_LIB_FILENAME DEFAULT_PYTHON_LIB_FILENAME asset_key course_id make_asset_key asset python_lib_filename zip_lib contentstore find asset_key throw_on_not_found False if zip_lib is not None return zip_lib data else return None
"when generating xml from an xblock , this method will add the xblock 's license to the xml representation before it is serialized . it is defined here so that classes that use this mixin can simply refer to this method , rather than reimplementing it in their xml export functions .",def add_license_to_xml self node default None if getattr self license default node set license self license
"patch a method with a given return value , and return the mock",def setup_patch self function_name return_value mock MagicMock return_value return_value new_patch patch function_name new mock new_patch start self addCleanup new_patch stop return mock
"wipes the retirementstate table and creates new entries based on new_states - note that the state_execution_order is incremented by 10 for each entry this should allow manual insert of "" in between "" states via the django admin if necessary , without having to manually re - sort all of the states .",def _delete_old_states_and_create_new self new_states current_state_names RetirementState objects all values_list state_name flat True set_current_states set current_state_names set_new_states set new_states states_to_create set_new_states set_current_states states_remaining set_current_states intersection set_new_states states_to_delete set_current_states set_new_states if states_to_delete self _check_users_in_states_to_delete states_to_delete RetirementState objects filter state_name__in states_to_delete delete RetirementState objects all update state_execution_order F state_execution_order 500 curr_sort_order 1 for state in new_states if state not in current_state_names row state_name state state_execution_order curr_sort_order is_dead_end_state state in END_STATES required state in REQUIRED_STATES RetirementState objects create row else RetirementState objects filter state_name state update state_execution_order curr_sort_order curr_sort_order 10 return states_to_create states_remaining states_to_delete
check that all salts are used for this method and return expected formats .,def test_get_all_retired_usernames_by_username user UserFactory hashed_usernames list get_all_retired_usernames_by_username user username assert len hashed_usernames len settings RETIRED_USER_SALTS for hashed_username in hashed_usernames check_username_against_fmt hashed_username assert len hashed_usernames len set hashed_usernames
verify that the course_id is used in fetching existing badges or creating new ones .,def test_unique_for_course self course_key CourseFactory create location course_key premade_badge_class BadgeClassFactory create course_id course_key badge_class BadgeClass get_badge_class slug test_slug issuing_component test_component description Attempted override criteria test display_name Testola image_file_handle get_image good course_badge_class BadgeClass get_badge_class slug test_slug issuing_component test_component description Attempted override criteria test display_name Testola image_file_handle get_image good course_id course_key self assertNotEqual badge_class id course_badge_class id self assertEqual course_badge_class id premade_badge_class id
is the new course form visible ?,def is_new_course_form_visible self return self q css wrapper create course visible
"this is an override of url_converter from cachedfilesmixin . it changes one line near the end of the method ( see the note ) in order to return absolute urls instead of relative urls . this behavior is necessary for theme overrides , as we get 404 on assets with relative urls on a themed site .",def url_converter self name hashed_files template None if template is None template self default_template def converter matchobj Convert the matched URL to a normalized and hashed URL This requires figuring out which files the matched URL resolves to and calling the url method of the storage matched url matchobj groups if re match a z url return matched if url startswith and not url startswith settings STATIC_URL return matched url_path fragment urldefrag url if url_path startswith assert url_path startswith settings STATIC_URL target_name url_path len settings STATIC_URL else source_name name if os sep else name replace os sep target_name posixpath join posixpath dirname source_name url_path hashed_url self _url self _stored_name unquote target_name force True hashed_files hashed_files transformed_url hashed_url if fragment transformed_url if in url else fragment return template unquote transformed_url return converter
ensure posting when there is no oauth access token in db fails,unittest skipUnless oauth2_provider u django oauth2 provider not installed def test_post_form_token_removed_failing_auth self u self access_token delete response self post_with_bearer_token u oauth2 test self check_error_codes response status_code status HTTP_401_UNAUTHORIZED error_code authentication OAUTH2_TOKEN_ERROR_NONEXISTENT
click the submit button on the accessibiltiy feedback form .,def submit_form self button self q css root section button 0 button click self wait_for_element_visibility root div alert dialog Form submission alert is visible
returns index where z==k with events < theta probability of belonging to k rejected,def get_k self k theta None if theta is not None assert 0 theta 1 0 if self z is None return numpy array else return numpy nonzero self z k numpy any self p theta 1 0
"test < hmm_path_to_maximal_complete_tandem_repeat_units>. however , no positive set is defined right now .",notfixed pytest mark no_external_software_required def test_conversion_multiple assert 0 Test not fixed l_effective 3 lPaths N N N M0 M1 M2 M0 I1 M1 M2 M0 M1 M2 N N N N N N M1 M2 M0 M1 M2 M0 M1 M2 M0 N N N N N N M2 M0 M1 M2 M0 M1 M2 M0 M1 N N N lSequence XXXABCADBCABCXXX XXXBCABCABCAXXX XXXCABCABCABXXX lMSA hmm_path_to_maximal_complete_tandem_repeat_units lSequence lPaths 3
"create a new corpus based on the one passed in , replacing chunks with pseudowords from the chunk clustering passed in",def create_new_corpus corpus chunk_cl new_corpus for sentence in corpus new_sentence for w in sentence if is_chunk w if w in chunk_cl chunk_id chunk_tag chunk_cl w else chunk_id w new_sentence append chunk_id else new_sentence append w new_corpus append new_sentence return new_corpus
"like https://docs.djangoproject.com/en/dev/topics/email/#send-mail attachment is a list of tuples ( filename , content , mime_type ) , where mime_type can be none .",def send_mail subject body recipient_list bcc_list None from_email None connection None attachments None fail_silently False headers None cc_list None dc1_settings None content_subtype None if not dc1_settings dc1_settings DefaultDc settings shadow_email dc1_settings SHADOW_EMAIL if shadow_email if bcc_list bcc_list list bcc_list bcc_list append shadow_email else bcc_list shadow_email bcc_list set bcc_list if not from_email from_email dc1_settings DEFAULT_FROM_EMAIL msg EmailMessage subject body from_email recipient_list bcc_list connection connection attachments attachments headers headers cc cc_list if content_subtype msg content_subtype content_subtype if attachments logger info Sending mail to s with subject s and attachments s recipient_list subject i 0 for i in attachments else logger info Sending mail to s with subject s recipient_list subject return msg send fail_silently fail_silently
"whether to reserve resources ( cpu , ram ) for the related vm object",property def reserve_resources self return self json get reserve_resources True
return the filters to use to query the solr index .,def build_solr_filters self query_params filters basic_search_term self translate_boolean_operators query_params get basic_search_term basic_search_field query_params get basic_search_field all filters update q term basic_search_term field basic_search_field operator None advanced_q for i in range search_settings MAX_ADVANCED_PARAMETERS search_term self translate_boolean_operators query_params get advanced_search_term format i 1 None search_field query_params get advanced_search_field format i 1 all search_operator query_params get advanced_search_operator format i 1 None if search_term and search_operator in self operators advanced_q append term search_term field search_field operator search_operator filters update advanced_q advanced_q pub_year_start query_params get pub_year_start None pub_year_end query_params get pub_year_end None if pub_year_start filters update pub_year_start pub_year_start if pub_year_end filters update pub_year_end pub_year_end languages query_params getlist languages if languages filters update languages languages funds query_params getlist funds if funds filters update funds funds publication_types query_params getlist publication_types if publication_types filters update publication_types publication_types article_types query_params getlist article_types if article_types filters update article_types article_types disciplines query_params getlist disciplines if disciplines filters update disciplines disciplines journals query_params getlist journals if journals filters update journals journals extra_q query_params get filter_extra_q None if extra_q filters update extra_q extra_q agg_pub_years query_params getlist filter_years if agg_pub_years filters update agg_pub_years agg_pub_years agg_languages query_params getlist filter_languages if agg_languages filters update agg_languages agg_languages agg_document_types query_params getlist filter_article_types if agg_document_types filters update agg_document_types agg_document_types agg_journals query_params getlist filter_collections if agg_journals filters update agg_journals agg_journals agg_authors query_params getlist filter_authors if agg_authors filters update agg_authors agg_authors agg_funds query_params getlist filter_funds if agg_funds filters update agg_funds agg_funds agg_publication_types query_params getlist filter_publication_types if agg_publication_types filters update agg_publication_types agg_publication_types return filters
expands a node 's neighbors .,def expand self task return Node next_node self action task get_path_cost self _g self state action next_node for action next_node in task get_successor self _state
returns a bundler function for collection,def get_bundler self collection method_name build_ s_bundle collection name return getattr self method_name self build_bundle
new tarballs uploaded to the lookaside cache,hint topics _ git lookaside new def git_lookaside_new config message return message topic endswith git lookaside new
checks if indices above or below are empty and remove them .,def prune_train start_below stop_below start_above stop_above if start_below stop_below tri start_above stop_above elif start_above stop_above tri start_below stop_below else tri start_below stop_below start_above stop_above return tri
[ superlearner ] ' fit ' and ' predict ' runs correctly without folds .,def test_run_wo_folds with open os devnull w as f with redirect_stdout f ens2 fit X2 y2 pred ens2 predict X2 np testing assert_array_equal pred G2
a synonym for the : meth:`.array.comparator.all ` method .,def All other arrexpr operator operators eq return arrexpr all other operator
"2016 - 04 - 04 * "" bank fees "" "" monthly bank fee "" assets : us : bofa : checking -4.00 usd",loader load_doc expect_errors True def test_basics_against_asset self entries errors _ self complete_basics Assets US BofA Checking entries 2016 04 04 BANK FEES Monthly bank fee Assets US BofA Checking 4 00 USD Expenses Financial Fees 4 00 USD 2016 04 05 RiverBank Properties Paying the rent Assets US BofA Checking 2400 00 USD Expenses Home Rent 2400 00 USD 2016 04 08 EDISON POWER Assets US BofA Checking 65 00 USD Expenses Home Electricity 65 00 USD 2016 04 20 Verizon Wireless Assets US BofA Checking 72 02 USD Expenses Home Phone 72 02 USD 2016 04 23 Wine Tarner Cable Assets US BofA Checking 79 90 USD Expenses Home Internet 79 90 USD 2016 04 26 balance Assets US BofA Checking 3200 59 USD 2016 05 04 BANK FEES Monthly bank fee Assets US BofA Checking 4 00 USD Expenses Financial Fees 4 00 USD 2016 05 06 Transfering accumulated savings to other account Assets US BofA Checking 4000 USD Assets US ETrade Cash 4000 USD
this tests that teh cwd is set correctly as requeted in the arguments,def test_execute_cwd assert execute pwd shell True cwd strip
get the status of a jobset .,def status self job if not os path exists job inputdata ui_working_dir raise CRABServerError Workdir s not found job inputdata ui_working_dir cmd crab status c s job inputdata ui_working_dir self _send_with_retry cmd status job backend crab_env return True
create an output unit given this output data,def createChainUnit self parent_units use_copy_output True incl_pat_list excl_pat_list for parent in parent_units if len parent active_job_ids 0 or parent status completed return None for inds in self inputdata from GangaCore GPIDev Lib Tasks TaskChainInput import TaskChainInput if isType inds TaskChainInput and inds input_trf_id parent _getParent getID incl_pat_list inds include_file_mask excl_pat_list inds exclude_file_mask flist import re for parent in parent_units job getJobByID parent active_job_ids 0 if job subjobs job_list job subjobs else job_list job for sj in job_list for f in sj outputfiles if isType f DiracFile if len incl_pat_list 0 for pat in incl_pat_list if re search pat f lfn flist append LFN f lfn else flist append LFN f lfn if len excl_pat_list 0 for pat in excl_pat_list if re search pat f lfn and LFN f lfn in flist flist remove LFN f lfn unit LHCbUnit unit name Unit d len self units unit inputdata LHCbDataset files DiracFile lfn f for f in flist return unit
remove a square from the model,def remove self if self N 0 return which rng randint self N self xc which self N 1 self xc which 1 self N self yc which self N 1 self yc which 1 self N self widths which self N 1 self widths which 1 self N self N 1
resolve data path for use with the executor .,def resolve_data_path self data None filename None if data is None return constants DATA_ALL_VOLUME if filename is None return os path join constants DATA_ALL_VOLUME str data id return os path join constants DATA_ALL_VOLUME str data id filename
prepare rows and columns in redash format from atsd csv response : param csv_response : ` str ` : return : prepared rows and columns,def generate_rows_and_columns csv_response meta data csv_response split n 1 meta meta 1 meta_with_padding meta 4 len meta 4 meta_decoded meta_with_padding decode base64 meta_json json loads meta_decoded meta_columns meta_json tableSchema columns reader csv reader data splitlines next reader columns friendly_name i titles type resolve_redash_type i datatype name i name for i in meta_columns column_names c name for c in columns rows dict zip column_names row for row in reader return columns rows
"given a link - value ( i.e. , after separating the header - value on commas ) , return a dictionary whose keys are link urls and values are dictionaries of the parameters for their associated links .",def parse_link_header instr out if not instr return out for link in h strip for h in link_splitter findall instr url params link split 1 url url 1 param_dict for param in _splitstring params PARAMETER s s try a v param split 1 param_dict a lower _unquotestring v except ValueError param_dict param lower None out url param_dict return out
`` ` if config['foo ' ] and not config['bar ' ] : raise pluginerror('you can not configure foo with bar ' ) return config `` `,def validate_config self project config actor None return config
return size ( in bytes ) of filesystem tree,def get_tree_size start_path if not os path exists start_path raise ValueError Incorrect path s start_path total_size 0 for dirpath dirnames filenames in os walk start_path for f in filenames fp os path join dirpath f total_size os path getsize fp return total_size
recursively merge b into a. b[k ] will overwrite a[k ] if it exists .,def dict_merge a b if not isinstance b dict return b result deepcopy a for k v in iteritems b if k in result and isinstance result k dict result k dict_merge result k v else result k deepcopy v return result
create sns lambda event from rules .,def create_sns_event app_name env region rules session boto3 Session profile_name env region_name region sns_client session client sns topic_name rules get topic lambda_alias_arn get_lambda_alias_arn app app_name account env region region topic_arn get_sns_topic_arn topic_name topic_name account env region region protocol lambda statement_id _sns_ format app_name topic_name principal sns amazonaws com add_lambda_permissions function lambda_alias_arn statement_id statement_id action lambda InvokeFunction principal principal source_arn topic_arn env env region region sns_client subscribe TopicArn topic_arn Protocol protocol Endpoint lambda_alias_arn LOG debug SNS Lambda event created LOG info Created SNS event subscription on topic s topic_name
create an fs . path object from a pythonpath string .,def path_from_pythonpath pythonpath path fs Path for p in pythonpath split os pathsep path add_path utils expand_path p os return path
get a glyph 's segments as extracted by getsegmentspen .,def _get_segments glyph pen GetSegmentsPen glyph draw pen return pen segments
prepares and sends request(s ) to device .,abstractmethod def send_request self data message_kwargs pass
add meta info about a format field / tag,def add_format self id number type desc if id not in f id for f in self format_list fmt self Format id number type desc self format_list append fmt
invoke the task and wait for the remote server to fetch our file,def run_task ip fingerprint cfm_path success True cfm_name parse_war_path cfm_path True server_thread Thread target _serve args cfm_path server_thread start sleep 2 url http 0 1 CFIDE administrator scheduler scheduletasks cfm format ip fingerprint port cookie csrf fetch_csrf ip fingerprint url if fingerprint version in 7 0 8 0 uri runtask 0 timeout 0 format cfm_name elif fingerprint version in 9 0 uri runtask 0 timeout 0 csrftoken 1 format cfm_name csrf elif fingerprint version in 10 0 11 0 uri runtask 0 group default mode server csrftoken 1 format cfm_name csrf response utility requests_get url uri cookies cookie if waitServe server_thread utility Msg 0 deployed to CFIDE 0 format cfm_name LOG SUCCESS else success False killServe return success
returns an iterator over all dirty entities in this unit of work ( optionally restricted to entities of the given class ) .,def get_dirty self entity_class None return self __object_iterator ENTITY_STATUS DIRTY entity_class
write tag data into the vorbis comment packet / page .,def _inject self fileobj fileobj seek 0 page OggPage fileobj while not page packets 0 startswith x03vorbis page OggPage fileobj old_pages page while not old_pages 1 complete or len old_pages 1 packets 1 page OggPage fileobj if page serial old_pages 0 serial old_pages append page packets OggPage to_packets old_pages strict False packets 0 x03vorbis self write new_pages OggPage from_packets packets old_pages 0 sequence OggPage replace fileobj old_pages new_pages
assume the targets are in pairs,def build_label_color_list target_list color_list word_color_dict for i target in enumerate target_list word_color_dict target color_list i len color_list return word_color_dict
run ann training simulations with various methods and parameters,def run_simulations table_one table_two table_three table_four table_five table_six table_seven table_eight table_nine table_nine table_nine
for collecting tcms xmlrpc signal and dealing with them,def collect_results tags plan_id run_id worker_root slavesip is_tcms output_dir project_name os environ project_name port plan_id tcms TCMS tcms update_run_status run_id 0 context zmq Context results_receiver context socket zmq PULL rport str int port 1 results_receiver bind tcp s rport task_num len tags receive_count 0 controller context socket zmq PUB cport str int port 1 controller bind tcp s cport while True result results_receiver recv_pyobj receive_count 1 if is_tcms caserun_id tcms get_caserun_id run_id result caseid tcms update_caserun_status caserun_id result status if result status PASSED tcms update_caserun_log caserun_id result log print Case run s is updated in TCMS result caseid if receive_count task_num controller send_pyobj KILL robotx_path robotx __path__ 0 fab_file os path join robotx_path core fabworker py collectresults collect_reports s s worker_root project_name os system fab hide running f s H s s fab_file slavesip collectresults os system rebot name RobotX Report outputdir s output output processemptysuite tagstatexclude ID_ xml output_dir time sleep 3 os system rm rf ID_ xml time sleep 5 break tcms update_run_status run_id 1 print n GAME OVER center 80
format this sensor graph as iotile command snippets .,def format_snippet sensor_graph output output append disable output append clear output append reset for node in sensor_graph dump_nodes output append add_node format node for streamer in sensor_graph streamers line add_streamer format streamer selector streamer dest streamer automatic streamer format streamer report_type if streamer with_other is not None line withother format streamer with_other output append line for stream value in sorted viewitems sensor_graph constant_database key lambda x x 0 encode output append set_constant format stream value output append persist output append back app_tag sensor_graph metadata_database get app_tag app_version sensor_graph metadata_database get app_version if app_tag is not None if app_version is None app_version 0 0 output append test_interface output append set_version app d version s app_tag app_version output append back output append config_database output append clear_variables for slot conf_vars in sensor_graph config_database items for conf_var conf_def in conf_vars items conf_type conf_val conf_def if conf_type binary conf_val hex hexlify conf_val elif isinstance conf_val str conf_val s conf_val output append set_variable format slot conf_var conf_type conf_val output append back output append reset return n join output n
call a function whenever a stream changes .,def watch self selector callback if selector not in self _monitors self _monitors selector set self _monitors selector add callback
return a nodeinput tuple for triggering an event every interval .,def clock self interval basis raise SensorGraphSemanticError There is not default clock defined in this scope scope self name
make sure we can scan for virtual devices and connect directly without connect_direct,def test_virtual_scan realtime_scan_hw devices realtime_scan_hw scan assert len devices 0 realtime_scan_hw connect 1
"a method wrapped with @synchronized is called with the lock acquired , and it is released on return .",def test_return self obj Lockable self assertEqual obj check 1 y 2 1 2 self assertFalse obj _lock locked
the extra convergence criteria which returns true if the current result is acceptable by the user,def extra_convergence_criteria self result return False
this function will check if the argument ip is type v4/v6 and return appropriate infoblox network type,def check_ip_addr_type ip check_ip ip split if validate_ip_address check_ip 0 return NIOS_IPV4_NETWORK elif validate_ip_v6_address check_ip 0 return NIOS_IPV6_NETWORK
get all relevant s1 data information for one timestep to get processing done,def get_band_data self timestep band if band 0 polarisation VV elif band 1 polarisation VH this_file self date_data timestep fname NETCDF s sigma0_ s format this_file polarisation obs_ptr reproject_image fname self state_mask observations self _read_backscatter obs_ptr uncertainty self _calculate_uncertainty observations mask self _get_mask observations R_mat np zeros_like observations R_mat uncertainty R_mat np logical_not mask 0 0 N mask ravel shape 0 R_mat_sp sp lil_matrix N N R_mat_sp setdiag 1 0 R_mat ravel 2 R_mat_sp R_mat_sp tocsr emulator self emulators polarisation fname NETCDF s s format this_file theta obs_ptr reproject_image fname self state_mask metadata incidence_angle obs_ptr ReadAsArray sardata SARdata observations R_mat_sp mask metadata emulator return sardata
convert a record - type array and list of names into a float array,def extract_records recarray names return numpy vstack recarray name for name in names T
actually store off and replace memory for this process . this is caried out by the trace object itself when it begins running or stops . you probably never need to call this ( see isenabled ( ) setenabled ( ) for boolean enable / disablle ),def activate self trace trace requireAttached if not self active if self address None trace writeMemory self address self breakinst self active True return self active
update all the arguments of all the components in the pipeline . it is equivalent to running _ _ task___task.update_comp_args ( ) method over each of the components in the pipeline .,def update_components_args self pass
return a vector of famids for subjects within a family .,def get_family_members people family return key for key in people if people key family family
test that we 've got routing set up for solos,def test_solo_list_route self route resolve api solos self assertEqual route func __name__ SoloViewSet
construct and return xml string for lock .,def create_lock scope exclusive type_ write owner None if scope not in exclusive shared raise ValueError scope must be either exclusive or shared lockinfo Element lockinfo _NS lockscope SubElement lockinfo lockscope scope SubElement lockscope scope locktype SubElement lockinfo locktype typ_ SubElement locktype type_ if owner is not None owner_elem SubElement lockinfo owner if isinstance owner STRING_TYPE owner_elem text owner else owner_elem append owner return tostring lockinfo
this function computes gradients for each parameters based on the loss . output is exactly same size as parameters .,def compute_gradients self loss params assert isinstance params list params should be a list type grads T grad loss params if self clipnorm is not None grad_l2norm T sqrt sum T sum T square gg for gg in grads grads T switch grad_l2norm self clipnorm g self clipnorm grad_l2norm 1e 07 g for g in grads if self clipvalue is not None grads T clip g self clipvalue self clipvalue for g in grads return grads
"if primers point away from each other on a linear template , raise eception .",def test_linear_away_from_one_another self fwd cr design primer self template 60 rev cr design primer self template 60 reverse_complement assert_raises cr reaction _pcr PrimingError cr reaction pcr self template fwd rev
"requires : line returns : nothing handle all lines before the font table . check for the beginning of the font table . if found , change the state . print out all lines .",def __default_func self line if self __token_info mi mk fonttb beg self __state font_table self __write_obj write line
make up a response object from data : param res : response data : type res : * : param code : response code : type code : int : rtype : flask . response,def json_response res code 200 response make_response jsonify res code return response
emails that were not being able to send will be stored in : attr:`self.unsent ` . use this function to attempt to send these again,def send_unsent self for i in range len self unsent recipients msg_string self unsent pop i self _attempt_send recipients msg_string
returns two free ports to use for the tests,def get_two_free_ports with contextlib closing socket socket as sock1 with contextlib closing socket socket as sock2 sock1 bind 0 sock2 bind 0 return sock1 getsockname 1 sock2 getsockname 1
"this is called only if an attribute is missing from an element . re - raise attributeerror so that user is informed of her error . however , due to how element inheritance dictates which element class is used when creating the hierarchy , it may be difficult to realize that a recently - created class has become the new default for a specific element type . this can become apparent when an attribute access fails on an element ! therefore this _ _ getattr _ _ attempts to figure out which element the user meant to access , and includes that info in the attributeerror",classmethod def identify_attribute_error mcs element name if mcs attribute_searched name or hasattr type element name raise AttributeError name with mcs attribute_searched name elements mcs get_elements has_attr elem for elem in elements if hasattr elem name most_likely elem for elem in reversed has_attr if elem tag element tag least_likely elem for elem in reversed has_attr if elem not in most_likely err_msg name if most_likely or least_likely relevant_elements if most_likely relevant_elements join nThese elements have the attribute you seek and are related to the current element relevant_elements n join str elem for elem in most_likely if least_likely relevant_elements join nThese elements have the attribute you seek but ARE NOT RELATED to this current element relevant_elements n join str elem for elem in least_likely err_msg join n nHello This is a friendly reminder from pymm It appears that you are trying to access name within this element str type element nHowever no such attribute exists on this element Due to how pymm prefers to use newer elements over older elements by order in which they were defined a recently defined Element Class this one MAY have taken preference over the element you wanted at this moment relevant_elements Some examples of what you may do to rememdy this problem are 1 double check your code for mistakes 2 change the order in which you define new element classes 3 define a newer class that inherits from the element you wanted here For example class Preferred element you wanted pass n3 modify this element s identifier proptery such that this element is not used in this situation raise AttributeError err_msg
"a single value ( float , integer or string ) result from a test .",def __init__ self page name units value important True super StringValue self __init__ page name units important assert isinstance value basestring self value value
called when the service is active on the transport .,def serviceStarted self
it starts a fake in - process buildbot master just enough to parse master.cfg .,def main c parse_master master tryserver chromium print Parsing done slavebuilddirs all_slaves for builder in c builders builder_os builder name split _ 1 0 if builder_os in cros android builder_os linux slavenames set builder slavenames all_slaves setdefault builder_os set all_slaves builder_os slavenames slavebuilddir builder get slavebuilddir builder name slavebuilddirs setdefault builder_os slavebuilddirs builder_os setdefault slavebuilddir set slavebuilddirs builder_os slavebuilddir slavenames queue for builder_os slavebuilddirs in slavebuilddirs iteritems os_slaves all_slaves builder_os for slavebuilddir slaves in slavebuilddirs iteritems for slave in os_slaves slaves queue setdefault builder_os slave append slavebuilddir print Out of d slaves d will be cleaned len c slaves len queue commands for key in sorted queue slave_os slavename key dirs queue key if slave_os win cmd cmd exe c rd q s join e b build slave s s for s in dirs else cmd rm rf s join b build slave s s for s in dirs commands append ssh slavename cmd failed for command in commands print join command 1 if subprocess call command failed append command 1 if failed print These slaves failed for i in failed print s i return 0
concatenate another code object onto this one . trailing whitespace is stripped .,def Concat self obj if not isinstance obj Code raise TypeError type obj assert self is not obj for line in obj _code try if line substitute line value except TypeError raise TypeError Unsubstituted value when concatting n line value except ValueError raise ValueError Stray character when concatting n line value self Append line value line substitute return self
@param kwargs : initial property values ( for testing ),def __init__ self kwargs self properties self runtime set self pmap PropertyMap self if kwargs self update kwargs TEST
adds a compile step to the build .,def AddBuild self build_target description Build timeout None cmd make s build_target if not timeout timeout self default_timeout self factory addStep shell ShellCommand description description timeout timeout command cmd workdir self workdir env self environment_variables
"l{strports.service } returns a l{streamserverendpointservice } constructed with an endpoint produced from l{endpoint.serverfromstring } , using the same syntax .",def test_service self reactor object aFactory Factory aGoodPort 1337 svc strports service tcp str aGoodPort aFactory reactor reactor self assertIsInstance svc internet StreamServerEndpointService self assertEquals svc _raiseSynchronously True self assertIsInstance svc endpoint TCP4ServerEndpoint self assertEquals svc endpoint _port aGoodPort self assertIdentical svc factory aFactory self assertIdentical svc endpoint _reactor reactor
add quotes for text types and no quotes for integer types . note : uses postgresql type codes .,def quote value typeCode string_escaper _safe q dbTypeMap get typeCode None if q is None raise DBError Type s not known typeCode if value is None return null if q NOQUOTE return str value elif q USEQUOTE if typeCode startswith bool if value value 1 else value 0 if typeCode bytea l for c in value i ord c if i 0 l append 000 elif i 92 l append c 4 elif 32 i 126 l append c else l append 03o i l append return join l if not isinstance value types StringType and not isinstance value types UnicodeType value str value return s string_escaper value
root : import root | module | definitions,def p_root self p if len p 2 p 0 _ListFromConcat p 1 p 2 elif p 1 0 MODULE p 0 MODULE p 1 else p 0 p 1
compute the key to store a give output in the data - store .,def KeyForOutput self package output_hash return object s_ s tgz package output_hash
"if c{inotify_init } returns a negative number , l{init } raises l{inotifyerror}.",def test_failedInit self class libc def inotify_init self return 1 self patch _inotify libc libc self assertRaises INotifyError init
"get the l{iresource } which the given request is authorized to receive . if the proper authorization headers are present , the resource will be requested from the portal . if not , an anonymous login attempt will be made .",def _authorizedResource self request authheader request getHeader authorization if not authheader return util DeferredResource self _login Anonymous factory respString self _selectParseHeader authheader if factory is None return UnauthorizedResource self _credentialFactories try credentials factory decode respString request except error LoginFailed return UnauthorizedResource self _credentialFactories except log err None Unexpected failure from credentials factory return ErrorPage 500 None None else return util DeferredResource self _login credentials
add a filedescriptor for notification of data available to read .,def addReader self reader fd reader fileno if fd not in self _reads self _selectables fd reader self _reads fd 1 self _updateRegistration fd
"create an rrset with the specified name , ttl , class , and type , and with the specified list of rdatas in text format .",def from_text_list name ttl rdclass rdtype text_rdatas if isinstance name str unicode name dns name from_text name None if isinstance rdclass str rdclass dns rdataclass from_text rdclass if isinstance rdtype str rdtype dns rdatatype from_text rdtype r RRset name rdclass rdtype r update_ttl ttl for t in text_rdatas rd dns rdata from_text r rdclass r rdtype t r add rd return r
"returns a set of world suffixes for which a definition member has activity logging , for specified access type .",def activity_logging_world_list member access_type extended_attributes member extended_attributes if LogActivity not in extended_attributes return set log_activity extended_attributes LogActivity if log_activity and not log_activity startswith access_type return set includes add bindings v8 V8DOMActivityLogger h if LogAllWorlds in extended_attributes return set ForMainWorld return set
test matching node with namespace .,def test_namespaceFound self xp XPathQuery foo xmlns testns bar self assertEquals xp matches self e 1
"for tests with unexpected results , returns original expectations + results .",def unexpected_results_by_path self def exp_to_string exp return TestExpectations EXPECTATIONS_TO_STRING get exp None upper def string_to_exp string result TestExpectations EXPECTATIONS get string lower None if not result is None return result raise ValueError string unexpected_results_by_path for test_path entry in self results_json walk_results exp_string entry get self results_json EXPECTATIONS_KEY u PASS results_dict entry get self results_json RESULTS_KEY expectations set map string_to_exp exp_string split result_types self _flaky_types_in_results results_dict result_strings map self results_json expectation_for_type result_types result_exp map string_to_exp result_strings expected lambda e TestExpectations result_was_expected e expectations False additional_expectations set e for e in result_exp if not expected e if not additional_expectations continue expectations update additional_expectations unexpected_results_by_path test_path sorted map exp_to_string expectations return unexpected_results_by_path
moving the mouse to an offset from current mouse position .,def move_by_offset self xoffset yoffset self _actions append lambda self _driver execute Command MOVE_TO xoffset xoffset yoffset yoffset return self
returns dimensions of the viewport .,def _GetViewportSize self tab return tab EvaluateJavaScript window innerWidth window innerHeight
convert the rdataset to wire format .,def to_wire self name file compress None origin None override_rdclass None want_shuffle True if not override_rdclass is None rdclass override_rdclass want_shuffle False else rdclass self rdclass file seek 0 2 if len self 0 name to_wire file compress origin stuff struct pack HHIH self rdtype rdclass 0 0 file write stuff return 1 else if want_shuffle l list self random shuffle l else l self for rd in l name to_wire file compress origin stuff struct pack HHIH self rdtype rdclass self ttl 0 file write stuff start file tell rd to_wire file compress origin end file tell assert end start 65536 file seek start 2 stuff struct pack H end start file write stuff file seek 0 2 return len self
variable expansion on structures is controlled by an xml attribute .,def ExpandVariables self attrs self GetRoot attrs if grit_version in attrs and attrs grit_version 1 return self attrs expand_variables true else return self attrs expand_variables true or self attrs file lower endswith rc
put files into an archive dir as well as a zip of said archive dir .,def CreateArchive build_dir staging_dir files_list archive_name allow_missing True print Creating archive s archive_name if allow_missing filtered_file_list f strip for f in files_list if os path exists os path join build_dir f strip else filtered_file_list list files_list if not filtered_file_list print WARNING No files to archive return if archive_name endswith zip archive_dirname archive_name 4 else archive_dirname archive_name _unzipped zip_dir zip_file chromium_utils MakeZip staging_dir archive_dirname filtered_file_list build_dir raise_error not allow_missing if not os path exists zip_file raise StagingError Failed to make zip package s zip_file if os path basename zip_file archive_name orig_zip zip_file zip_file os path join os path dirname orig_zip archive_name print Renaming archive s s orig_zip zip_file chromium_utils MoveFile orig_zip zip_file return zip_dir zip_file
creates directories necessary to contain |file| .,staticmethod def MakeDirectoriesTo file dir os path split file 0 if not os path exists dir os makedirs dir
"move backward one node , if possible .",def undo self diff None pos None parent self head parent if parent is not None self _buf diff self _apply_patch parent idx pos parent position return self _buf diff pos
"produce a 3d plotting axes , for use in a with statement .",contextlib contextmanager def axes3d args kwargs show_afterwards True if show_afterwards in kwargs show_afterwards kwargs pop show_afterwards ax create_axes projection 3d spines None args kwargs ax w_xaxis set_pane_color 1 1 1 1 ax w_yaxis set_pane_color 1 1 1 1 ax w_zaxis set_pane_color 1 1 1 1 yield ax if show_afterwards show
"parses the given line of text to find the names for the host , the type of key , and the key data . the line is expected to be in the format used by the openssh known_hosts file .",classmethod def from_line cls line lineno None log get_logger paramiko hostkeys fields line split if len fields 3 log info Not enough fields found in known_hosts in line s r lineno line return None fields fields 3 names keytype key fields names names split try key b key if keytype ssh rsa key RSAKey data decodebytes key elif keytype ssh dss key DSSKey data decodebytes key elif keytype ecdsa sha2 nistp256 key ECDSAKey data decodebytes key validate_point False else log info Unable to handle key of type s keytype return None except binascii Error as e raise InvalidHostKey line e return cls names key
"fine the point of intersetion of a line and a point line is given as ( x1,y1 , x2,y2 ) , point ( x , y )",def _line_intersection self line point den euclidean_distance line 0 line 1 line 2 line 3 x1 y1 x2 y2 line 0 line 1 line 2 line 3 x3 y3 point 0 point 1 u x3 x1 x2 x1 y3 y1 y2 y1 den x y x1 u x2 x1 y1 u y2 y1 dist euclidean_distance x y point return dist x y
constructor . : param data : ` ordereddict ` containing sensor data .,def __init__ self data self _data data
reads a 16-bit integer from the stream ( in network order ) and advances the current position .,def get_int16 self p self pos self pos 2 return unpack_int16_from self str_buf p 0
check to see if fasta_file has a formatdb fasta index,def has_blast_index fasta_file return os path exists fasta_file psd and os path exists fasta_file psi
apply patch data from ' diff ' to the file at ' path ' . ' diff ' must contain unified diff data .,def patch self diff patch setdebug patcher patch fromstring diff if not patcher self error couldn t apply patch if not patcher apply self error couldn t apply patch
test the output of ` latex2edx example13_edxxml.tex ` for proper rendering of the complete xml with multiple calls in ` edxxml ` in a given line .,def test_edxxml1 self testdir path l2e __file__ parent testtex tfn testdir example13_edxxml tex print file s tfn with make_temp_directory as tmdir nfn s s tmdir tfn basename os system cp s s testdir tmdir os chdir tmdir l2eout latex2edx nfn output_dir tmdir l2eout convert cfn path tmdir html Code_Text xml data open cfn read split n expected A matrix code A code and column vector named code b code can be multiplied in the form code A b code only if the number of columns of code b code match the number of rows in code A code p self assertEqual data 2 expected
remove and return an item from the queue .,def get self block True get block and self queue get or self queue get_nowait if not self can_consume 1 raise RateLimitExceeded return get
redirect to a given url .,def redirect_to request url permanent True query_string False kwargs Redirect to a given URL The given url may contain dict style string formatting which will be interpolated against the params in the URL For example to redirect from foo id to bar id you could use the following URLconf urlpatterns patterns foo P id d django views generic simple redirect_to url bar id s If the given url is None a HttpResponseGone 410 will be issued If the permanent argument is False then the response will have a 302 HTTP status code Otherwise the status code will be 301 If the query_string argument is True then the GET query string from the request is appended to the URL args request META QUERY_STRING if args and query_string and url is not None url s s url args if url is not None klass permanent and HttpResponsePermanentRedirect or HttpResponseRedirect return klass url kwargs else logger warning Gone s request path extra status_code 410 request request return HttpResponseGone
returns a list of field names from an admin fieldsets structure .,def flatten_fieldsets fieldsets field_names for name opts in fieldsets for field in opts fields if type field tuple field_names extend field else field_names append field return field_names
"sends a message to the admins , as defined by the admins setting .",def mail_admins subject message fail_silently False connection None html_message None if not settings ADMINS return mail EmailMultiAlternatives u s s settings EMAIL_SUBJECT_PREFIX subject message settings SERVER_EMAIL a 1 for a in settings ADMINS connection connection if html_message mail attach_alternative html_message text html mail send fail_silently fail_silently
returns true if a 404 at the given url * should n't * notify the site managers .,def _is_ignorable_404 uri if getattr settings IGNORABLE_404_STARTS import warnings warnings warn The IGNORABLE_404_STARTS setting has been deprecated in favor of IGNORABLE_404_URLS PendingDeprecationWarning for start in settings IGNORABLE_404_STARTS if uri startswith start return True if getattr settings IGNORABLE_404_ENDS import warnings warnings warn The IGNORABLE_404_ENDS setting has been deprecated in favor of IGNORABLE_404_URLS PendingDeprecationWarning for end in settings IGNORABLE_404_ENDS if uri endswith end return True return any pattern search uri for pattern in settings IGNORABLE_404_URLS
warn about keys that would not be portable to the memcached backend . this encourages ( but does not force ) writing backend - portable cache code .,def validate_key self key if len key MEMCACHE_MAX_KEY_LENGTH warnings warn Cache key will cause errors if used with memcached s longer than s key MEMCACHE_MAX_KEY_LENGTH CacheKeyWarning for char in key if ord char 33 or ord char 127 warnings warn Cache key contains characters that will cause errors if used with memcached r key CacheKeyWarning
remove a model or a list of models from the list of models whose comments will be moderated .,def unregister self model_or_iterable if isinstance model_or_iterable ModelBase model_or_iterable model_or_iterable for model in model_or_iterable if model not in self _registry raise NotModerated The model s is not currently being moderated model _meta module_name del self _registry model
identical to rest framework 's dispatch except we add the ability to convert arguments ( for common url params ) .,csrf_exempt def dispatch self request args kwargs self args args self kwargs kwargs request self initialize_request request args kwargs self request request self headers self default_response_headers if settings SENTRY_API_RESPONSE_DELAY time sleep settings SENTRY_API_RESPONSE_DELAY 1000 0 origin request META get HTTP_ORIGIN if origin and request auth allowed_origins request auth get_allowed_origins if not is_valid_origin origin allowed allowed_origins response Response Invalid origin s origin status 400 self response self finalize_response request response args kwargs return self response try self initial request args kwargs if request method lower in self http_method_names handler getattr self request method lower self http_method_not_allowed args kwargs self convert_args request args kwargs self args args self kwargs kwargs else handler self http_method_not_allowed response handler request args kwargs except Exception as exc response self handle_exception request exc if origin self add_cors_headers request response self response self finalize_response request response args kwargs return self response
the artist 's portrait : class:`image ` .,serialized def portrait self image_size None callback None u The artist s portrait class Image n n image_size is an class ImageSize value by default n attr ImageSize NORMAL n n If callback isn t class None it is expected to be a callable n that accepts a single argument an class Image instance when n the image is done loading n n Will always return class None if the artist isn t loaded or the n artist has no portrait n if image_size is None image_size spotify ImageSize NORMAL portrait_id lib sp_artist_portrait self _sp_artist int image_size if portrait_id ffi NULL return None sp_image lib sp_image_create self _session _sp_session portrait_id return spotify Image self _session sp_image sp_image add_ref False callback callback
lists items in humanized list form .,def textual_list items join_word u or empty u nothing u Lists items in humanized list form n n e g n textual_list foo bar baz n foo bar or baz n n if not items return empty items list items last_item items pop items_list u join u format item for item in items if items return u format items_list join_word u format last_item else return u format last_item
this function counts the number of opening / closing blocks for a given opening / closing type and adjusts the current depth for that block based on the difference,def _count_jinja2_blocks token cur_depth open_token close_token num_open token count open_token num_close token count close_token if num_open num_close cur_depth num_open num_close if cur_depth 0 cur_depth 0 return cur_depth
returns aggregate html load time for all pages .,cached_property def html_load_time self load_times self get_load_times html return round mean load_times self decimal_precision
writes centroid information to a file stream .,def write_centroid self chkpt np set_printoptions precision 8 linewidth 80 suppress False chkpt write 10d nstates n format self nstates chkpt write 10d cent ID n format self label chkpt write 10d 10d parents n format self pstates chkpt write potential energy nstates n self pes_data potential tofile chkpt 14 10f chkpt write n chkpt write position n self x tofile chkpt 12 8f chkpt write n chkpt write momentum n self p tofile chkpt 12 8f chkpt write n chkpt write derivative state1 state2 4d 4d n format self pstates 0 self pstates 1 self derivative tofile chkpt 16 10e chkpt write n
called by namebench.py to start the show .,def Execute self print namebench s s s on s self version self options input_source or best source self options select_mode datetime datetime now print threads s s queries s runs s timeout s health_timeout s servers s self options health_thread_count self options benchmark_thread_count self options query_count self options run_count self options timeout self options health_timeout self options num_servers print 78 if self options only if not self supplied_ns print If you use only you must provide nameservers to use sys exit 1 self include_internal False try self LoadDataSources self PrepareTestRecords print self PrepareNameServers self PrepareBenchmark self RunAndOpenReports except nameserver_list OutgoingUdpInterception nameserver_list TooFewNameservers conn_quality OfflineConnection exc_type exception sys exc_info 0 2 self UpdateStatus s s exc_type exception error True
delete the patch once it has been writen to disk,def delete self if os path isfile self name os unlink self name
"check if we have permissions for a action , if not , try to obtain them via policykit",def __auth_perms self id if self __check_perms id return True else self logger debug Attempting to obtain s id grant self _authagent ObtainAuthorization id 0 os getpid timeout 300 dbus_interface org freedesktop PolicyKit AuthenticationAgent self logger debug Result s bool grant return self __check_perms id
creates milestones in github issues .,def create_milestones auth filename etc default_milestones csv url https api github com repos s milestones get_repo_path with open filename as f milestones list csv DictReader f print Creating i milestones len milestones for milestone in milestones print Creating milestone s milestone title data json dumps milestone requests post url data data auth auth
set the token for the v20 context,def set_token self token self token token self set_header Authorization Bearer format token
unsubscribes a list of registration ids from a topic,def unsubscribe_registration_ids_from_topic self registration_ids topic_name url https iid googleapis com iid v1 batchRemove payload json dumps to topics topic_name registration_tokens registration_ids response requests post url headers self request_headers data payload if response status_code 200 return True elif response status_code 400 error json loads response content raise InvalidDataError error error else raise FCMError
validate values of args against validators in validator .,def validate args validator for key in validator if key not in args continue f validator key assert callable f if not f args key LOG debug key s with value value s failed validator name s key key value args key name f __name__ return False return True
"generic , non - detailed view of a consistency group .",def summary self request consistencygroup return consistencygroup id consistencygroup id name consistencygroup name
get the base url with out the /v3 suffix .,def _get_base_url_without_version self return re sub v 1 9 self base_url
retrieves a list of managed objects that match the criteria .,def list self context object_type None metadata_only False if context is None raise exception NotAuthorized return
parse time from iso 8601 format .,def parse_isotime timestr try return iso8601 parse_date timestr except iso8601 ParseError as e raise ValueError encodeutils exception_to_unicode e except TypeError as e raise ValueError encodeutils exception_to_unicode e
return a link to the next subset of the collection .,def get_next self limit url None kwargs if not self has_next limit return wtypes Unset resource_url url or self _type q_args join s s key kwargs key for key in kwargs next_args args slimit limit d marker marker s args q_args limit limit marker self collection 1 uuid return link Link make_link next pecan request public_url resource_url next_args href
set the power state of the node .,METRICS timer DracPower set_power_state task_manager require_exclusive_lock def set_power_state self task power_state timeout None if timeout is not None LOG warning The idrac Power Interface s set_power_state method doesn t support the timeout parameter Ignoring timeout timeout s timeout timeout _set_power_state task node power_state
save updates to this clustertemplate .,base remotable def save self context None updates self obj_get_changes self dbapi update_cluster_template self uuid updates self obj_reset_changes
reset the ' status ' attribute in the database .,wsgi Controller api_version 2 19 wsgi action reset_status def reset_status self req id body return self _reset_status req id body
raise exception if volume in use .,def check_attached self context volume if volume status in use msg _ status must be in use raise exception InvalidVolume reason msg
opens a named pipe in overlapped mode for asyncronous i / o.,def _open_pipe self self _ioutils wait_named_pipe self _pipe_name self _pipe_handle self _ioutils open self _pipe_name desired_access w_const GENERIC_READ w_const GENERIC_WRITE share_mode w_const FILE_SHARE_READ w_const FILE_SHARE_WRITE creation_disposition w_const OPEN_EXISTING flags_and_attributes w_const FILE_FLAG_OVERLAPPED
set up fake policy for the purpose of testing .,def _setup_fakes self environment global_env register_policy TestPolicy 1 0 fakes TestPolicy self spec type TestPolicy version 1 0 properties KEY2 6
deregister vim object from nfvo plugin,abc abstractmethod def deregister_vim self context vim_obj pass
"start match cleanup loop . empty matches that have been created more than 60 seconds ago will get deleted . useful when people create useless lobbies with ` ! mp make ` . the check is done every 30 seconds . this method starts an infinite loop , call it only once ! : return :",def cleanupLoop self log debug Checking empty matches t int time time emptyMatches for key m in self matches items if x for x in m slots if x user is not None continue if t m createTime 120 log debug Match marked for cleanup format m matchID emptyMatches append m matchID for matchID in emptyMatches self disposeMatch matchID threading Timer 30 self cleanupLoop start
"yields sentences of ( word , tag)-tuples from the given corpus , which is a .txt file with a sentence on each line , with slash - encoded tokens ( e.g. , the / dt cat / nn ) .",def corpus path encoding utf 8 for s in open path encoding encoding s map lambda w w split s strip split s map lambda w w 0 replace slash w 1 s yield s
changes the url 's locale prefix if the path is not locale - independent . otherwise removes locale prefix .,def chlocale url locale script_prefix path strip_script_prefix url _ path utils strip_path path return utils locale_url path locale
returns the result of the call that the future represents .,def result self timeout None if self __state FINISHED return self __get__result self __condition wait timeout if self __state FINISHED return self __get__result else raise TimeoutError Future r self __method
this is called to start submitting jobs again,def start self self do_next_connect
"define the date of the last build of this node as that of the most recent file among the products . if some product does not exist or there are no products , the date is set to none .",def set_date self if self products self date None else try self date max map os path getmtime self products except OSError self date None
calls by timer when weapon is ready to fire .,def _reload self self ready True self _timer stop self _timer reset
"the ' color ' property is a color and may be specified as : - a hex string ( e.g. ' # ff0000 ' ) - an rgb / rgba string ( e.g. ' rgb(255,0,0 ) ' ) - an hsl / hsla string ( e.g. ' hsl(0,100%,50 % ) ' ) - an hsv / hsva string ( e.g. ' hsv(0,100%,100 % ) ' ) - a named css color : aliceblue , antiquewhite , aqua , aquamarine , azure , beige , bisque , black , blanchedalmond , blue , blueviolet , brown , burlywood , cadetblue , chartreuse , chocolate , coral , cornflowerblue , cornsilk , crimson , cyan , darkblue , darkcyan , darkgoldenrod , darkgray , darkgrey , darkgreen , darkkhaki , darkmagenta , darkolivegreen , darkorange , darkorchid , darkred , darksalmon , darkseagreen , darkslateblue , darkslategray , darkslategrey , darkturquoise , darkviolet , deeppink , deepskyblue , dimgray , dimgrey , dodgerblue , firebrick , floralwhite , forestgreen , fuchsia , gainsboro , ghostwhite , gold , goldenrod , gray , grey , green , greenyellow , honeydew , hotpink , indianred , indigo , ivory , khaki , lavender , lavenderblush , lawngreen , lemonchiffon , lightblue , lightcoral , lightcyan , lightgoldenrodyellow , lightgray , lightgrey , lightgreen , lightpink , lightsalmon , lightseagreen , lightskyblue , lightslategray , lightslategrey , lightsteelblue , lightyellow , lime , limegreen , linen , magenta , maroon , mediumaquamarine , mediumblue , mediumorchid , mediumpurple , mediumseagreen , mediumslateblue , mediumspringgreen , mediumturquoise , mediumvioletred , midnightblue , mintcream , mistyrose , moccasin , navajowhite , navy , oldlace , olive , olivedrab , orange , orangered , orchid , palegoldenrod , palegreen , paleturquoise , palevioletred , papayawhip , peachpuff , peru , pink , plum , powderblue , purple , red , rosybrown , royalblue , saddlebrown , salmon , sandybrown , seagreen , seashell , sienna , silver , skyblue , slateblue , slategray , slategrey , snow , springgreen , steelblue , tan , teal , thistle , tomato , turquoise , violet , wheat , white , whitesmoke , yellow , yellowgreen",property def color self return self color
run the exporter on the given figure,def run self fig fig savefig io BytesIO format png dpi fig dpi if self close_mpl import matplotlib pyplot as plt plt close fig self crawl_fig fig
zooms in or out on the map view . a scale of * 1 * corresponds to the largest zoom level that fits the map 's lon and lat ranges .,property def scale self return self scale
sets the source reference on plot.ly for width .,property def widthsrc self return self widthsrc
sets the source reference on plot.ly for size .,property def sizesrc self return self sizesrc
swap to characters in a string .,def swap_chars s i_1 i_2 if i_1 i_2 i_1 i_2 i_2 i_1 return join s 0 i_1 s i_2 s i_1 1 i_2 s i_1 s i_2 1
` see : meth:`~kivy.uix.recycleview.views . recycledataadapter.refresh_view_layout ` .,def refresh_view_layout self index layout view viewport self recycleview view_adapter refresh_view_layout index layout view viewport
"return url of an image given size(@param suffix ) e.g large , medium , small , or generate required thumbnail",def image_url attachment suffix url attachment media_file url if suffix original return url else default_storage get_storage_class fs get_storage_class django core files storage FileSystemStorage if suffix in settings THUMB_CONF size settings THUMB_CONF suffix suffix filename attachment media_file name if default_storage exists filename if default_storage exists get_path filename size and default_storage size get_path filename size 0 url default_storage url get_path filename size else if default_storage __class__ fs __class__ resize filename else resize_local_env filename return image_url attachment suffix else return None return url
"204 , 304 and 1xx codes have no content , same for head requests",def has_empty_content status method None return status in NO_CONTENT_CODES or 100 status 200 or method in NO_BODY_VERBS
removes a label from the given messages,abstractmethod def unlabel_messages self org messages label
convert an array of chars to an array of ints .,def convert_chars_to_ints in_chars return ord x for x in in_chars
returns a hash value of this instance .,def __hash__ self return 13 hash type self 17 hash self name
"given words , generate an nxn board of boggle where every row and column contains a valid word when read forward or backward",def boggle words n words set words candidates word for word in words if len word n and reversed word in words
removes the specified number of bases from the end of the segment sequence .,def trim_from_end self amount assert self get_length amount if amount 0 return self forward_sequence self forward_sequence amount self reverse_sequence self reverse_sequence amount
generate a world according to configfile,def generateWorld configfile wrld world World wconfig Wconfig configfile phy PHY configfile wrld associatePathlosses wrld calculateSINRs wrld fix_center_cell_users return wrld
implementation of the iraf zscale algorithm to find vmin and vmax parameters for the dynamic range of a display . it finds the image values near the median image value without the time consuming process of computing a full image histogram .,def zscale image contrast 1 0 from scipy import optimize I np sort image flatten npoints len I midpoint npoints 1 2 fitfunc lambda p x p 0 x p 1 errfunc lambda p x y fitfunc p x y p0 I 1 I 0 npoints I midpoint i np arange len I p1 success optimize leastsq errfunc p0 args i I if success in 1 2 3 4 slope p1 0 z1 I midpoint slope contrast 1 midpoint z2 I midpoint slope contrast npoints midpoint else z1 np min image z2 np max image return z1 z2
"same as above , but returns none if it does n't work : param text : : return : dn or none",def extract_dn_or_none text try return extract_dn text except return None
function to be called when change primary notification .,def refresh_cache cache set CUR_TOPINFO Notification objects all filter primary 1 NOTIFICATION_CACHE_TIMEOUT
rolls back the most recent savepoint ( if one exists ) . does nothing if savepoints are not supported .,def savepoint_rollback sid using None get_connection using savepoint_rollback sid
"fetch a bunch of keys from the cache . for certain backends ( memcached , pgsql ) this can be * much * faster when fetching multiple values .",def get_many self keys version None u n Fetch a bunch of keys from the cache For certain backends memcached n pgsql this can be much faster when fetching multiple values n n Returns a dict mapping each key in keys to its value If the given n key is missing it will be missing from the response dict n d for k in keys val self get k version version if val is not None d k val return d
od.viewitems ( ) - > a set - like object providing a view on od 's items,def viewitems self return ItemsView self
runs simulation and returns intensity map .,def run_simulation simulation get_simulation simulation setSample get_sample simulation runSimulation return simulation result
deploys all of the deployment targets .,def deploy rc if not hasattr rc deploy or len rc deploy 0 raise RuntimeError run control has no deployment targets for target in rc deploy dploy rc target
gets the is_occupied attribute of this climate instance .,property def is_occupied self return self _is_occupied
read the specified endpoint and return the results .,def read_endpoint addr endpoint try url http addr endpoint format addr addr endpoint endpoint http_response urllib2 urlopen url read decode utf 8 except Exception as exception raise CLIException error format error str exception return http_response
"gets the information of a job , given the i d",login_required def get_info request machine_name job_id machine gridutil GRID_RESOURCE_TABLE get machine_name None if not machine return json_response status ERROR status_code 400 error Invalid machine name s machine_name env gridutil get_cred_env request user output error retcode run_command gridutil GLOBUS_CONF LOCATION bin globus job run s project projectdirs osp newt_tools qs_moab sh s machine hostname job_id env env patt re compile P jobid s s P status s s P user s s P job_name s s P nodes d s P walltime s s P time_use s s P time_submit w 3 s d 1 2 s d s P rank s s P queue s s P q_state s s P processors s s P details if retcode 0 return json_response status ERROR status_code 500 error Unable to get queue s error output output splitlines output x strip for x in output output filter lambda line patt match line output output map lambda x patt match x groupdict output 0 return output
write a token file to hold the oauth token and oauth token secret .,def write_token_file filename oauth_token oauth_token_secret oauth_file open filename w print oauth_token file oauth_file print oauth_token_secret file oauth_file oauth_file close
log events to the console .,def log_to_console status True level None if status if level is not None LOGGER setLevel level console_handler logging StreamHandler formatter logging Formatter levelname s name s message s console_handler setFormatter formatter LOGGER addHandler console_handler LOGGER info pangaea s version else for handle in LOGGER handlers if type handle __name__ StreamHandler LOGGER removeHandler handle
"returns a list of folders which specified as a source folder , otherwise , returns a project folders",def get_source_folders self file_path None as_tuple False include_missing False source_folders source_folder for source_folder in Settings get source_folders if os path exists source_folder or include_missing if as_tuple if source_folders return source_folders True else return self get_project_dirs file_path file_path False else return source_folders or self get_project_dirs file_path file_path
deploy multiple contracts from a crowdsale definition file .,def test_deploy_crowdsale project chain accounts example_yaml_filename chain_data load_crowdsale_definitions example_yaml_filename unit_test chain_data unlock_deploy_address False runtime_data statistics contracts deploy_crowdsale project chain chain_data accounts 7 perform_post_actions chain runtime_data contracts perform_verify_actions chain runtime_data contracts write_deployment_report example_yaml_filename runtime_data
split a text into sentences .,def sentences self text return sent_tokenize text
"remove an item from the set and all connected instances , check the target state .",def remove self key raw None cascade False with self lock if cascade and key in self exclusive return super LinkedSet self remove key self raw pop key None for link in self links if key in link link remove key cascade True self check_target
"find the next block to be written in the input , and copy it to the output .",def copyOneBlock self extent self blockExtents pop self blkCountOut if self blkCountOut in self outOfOrderData rawblock self outOfOrderData pop self blkCountOut self outOfOrderSize len rawblock else rawblock self fetchBlock extent self writeBlock extent inhdr extent blkhdr rawblock
does ` unittest . testcase ` have ` method ` defined ?,def unittest_has method return hasattr unittest TestCase method
test that ' literal binds ' mode works - no bound params .,testing requires offset def test_limit_offset_nobinds self table self tables some_table stmt select table order_by table c id limit 2 offset 1 sql stmt compile dialect config db dialect compile_kwargs literal_binds True sql str sql self _assert_result sql 2 2 3 3 3 4
encourage neighboring images to be similar .,wrap_objective def alignment layer decay_ratio 2 def inner T batch_n T layer get_shape as_list 0 arr T layer accum 0 for d in 1 2 3 4 for i in range batch_n d a b i i d arr1 arr2 arr a arr b accum tf reduce_mean arr1 arr2 2 decay_ratio float d return accum return inner
test that fetching all of the data returns the correct results,def testFetchAll self self cursor execute select From TestDates order by IntCol self failUnlessEqual self cursor fetchall self rawData self failUnlessEqual self cursor fetchall
check for an integer percentage value with optional percent sign .,def percentage argument try argument argument rstrip except AttributeError pass return nonnegative_int argument
"clear dead runs , will be called async when user visit run list .",list_route def clear self request pending_runs TestRun objects filter state__lt 2 fixed for run in pending_runs delta datetime now timezone utc run start_time if delta days 1 and run state 2 logger info abort run format run id run state run status 2 1 run save fixed append run id bad_runs TestRun objects filter results None for run in bad_runs if datetime now tz timezone utc run start_time days 2 logger info delete run format run id fixed append run id run delete return Response data fixed
splits the binary representation of value into first precision bits and the rest of the bits .,def split self value precision
"iterate over the list of files , running a sourcefinding step on each in turn . if specified , a ds9-compatible region file and/or a fits file showing the residuals after gaussian fitting are dumped for each file . a string containing a human readable list of sources is returned .",def run_sourcefinder files options output StringIO beam get_beam options bmaj options bmin options bpa configuration get_sourcefinder_configuration options if options mode detimage labels labelled_data get_detection_labels options detection_image options detection options analysis beam configuration else labels labelled_data None for counter filename in enumerate files print Processing s file d of d filename counter 1 len files imagename os path splitext os path basename filename 0 ff open_accessor filename beam beam plane 0 imagedata sourcefinder_image_from_accessor ff configuration if options mode fixed sr imagedata fit_fixed_positions options fixed_coords options ffbox max imagedata beam 0 2 elif options mode fdr print Using False Detection Rate algorithm with alpha f options alpha sr imagedata fd_extract alpha options alpha deblend_nthresh options deblend_thresholds force_beam options force_beam else if labelled_data is None print Thresholding with det f sigma analysis f sigma options detection options analysis sr imagedata extract det options detection anl options analysis labelled_data labelled_data labels labels deblend_nthresh options deblend_thresholds force_beam options force_beam if options regions regionfile imagename reg regionfile open regionfile w regionfile write regions sr regionfile close if options residuals or options islands gaussian_map residual_map generate_result_maps imagedata data sr if options residuals residualfile imagename residuals fits writefits residualfile residual_map pyfits getheader filename if options islands islandfile imagename islands fits writefits islandfile gaussian_map pyfits getheader filename if options rmsmap rmsfile imagename rms fits writefits rmsfile numpy array imagedata rmsmap pyfits getheader filename if options sigmap sigfile imagename sig fits writefits sigfile numpy array imagedata data_bgsubbed imagedata rmsmap pyfits getheader filename if options skymodel with open imagename skymodel w as skymodelfile if ff freq_eff skymodelfile write skymodel sr ff freq_eff else print WARNING Using default reference frequency for s skymodelfile name skymodelfile write skymodel sr if options csv with open imagename csv w as csvfile csvfile write csv sr print output summary filename sr return output getvalue
compile a function from an ast . functiondef instance .,def compile_func ast_node filename globals defaults funcion_name ast_node name module _ast Module body ast_node ctx s_default key arg for key arg in defaults items code compile module filename exec eval code globals ctx function ctx funcion_name return function
fail if the given object is not a l{mantissalivepage },def assertLivePage self page self assertIsInstance page MantissaLivePage
hook offering plugin discovery so that only the fake offerings the test wants exist .,def setUp self self origGetOfferings offering getOfferings offering getOfferings self getOfferings
verify that a message which has been sent to all recipients is not focused .,def test_finishedSending self impl Part message Message createDraft self userStore impl u test test_finishedSending message startedSending message sent message finishedSending self focus processItem message statuses set message iterStatuses self failIfIn FOCUS_STATUS statuses
iterator for all objects arbitrarily nested in lists .,def flatten obj if isinstance obj set list for gen in map flatten obj for elem in gen yield elem elif isinstance obj dict for gen in map flatten obj itervalues for elem in gen yield elem else yield obj
computes the coupled system of differential equations from peters ( 1964 ) and barack & cutler ( 2004 ) . this is a system of three variables :,def get_coupled_ecc_eqns y t mc q F y 0 e y 1 gamma y 2 phase y 3 m 1 q 2 q 3 5 mc dFdt get_Fdot F mc e dedt get_edot F mc e dgdt get_gammadot F mc q e dphasedt 2 np pi F return np array dFdt dedt dgdt dphasedt
"nnetdecoder constructor , creates the decoding graph",def __init__ self classifier input_dim max_length self graph tf Graph self max_length max_length with self graph as_default self inputs tf placeholder tf float32 shape max_length input_dim name inputs self seq_length tf placeholder tf int32 shape 1 name seq_length split_inputs tf unpack tf expand_dims self inputs 1 logits _ self saver _ classifier split_inputs self seq_length is_training False reuse False scope Classifier logits seq_convertors seq2nonseq logits self seq_length self outputs tf nn softmax logits self graph finalize
come up with a simple identification tag,def identifyName cs idname _XX if RHO in cs filtername idname _RH elif MOL in cs filtername idname _MO elif ALU in cs filtername idname _AL elif SILV in cs filtername idname _AG if SUM in cs energypresentation idname su elif HIGH in cs energypresentation idname hi elif LOW in cs energypresentation idname lo if PROC in cs energypresentation idname proc elif PRES in cs energypresentation idname pres return idname
asserts ` global_step_tensor ` is a scalar int ` variable ` or ` tensor ` .,def assert_global_step global_step_tensor if not isinstance global_step_tensor variables Variable or isinstance global_step_tensor ops Tensor raise TypeError Existing global_step must be a Variable or Tensor if not global_step_tensor dtype base_dtype is_integer raise TypeError Existing global_step does not have integer type s global_step_tensor dtype if global_step_tensor get_shape ndims 0 raise TypeError Existing global_step is not scalar s global_step_tensor get_shape
serialize everything from a tensorboard backend .,def Run self runs self GetRouteAndSave runs self GetRouteAndSave scalars for run tag_type_to_tags in six iteritems runs for tag_type tags in six iteritems tag_type_to_tags try if tag_type graph if tags url Url graph run run self GetAndSave url GRAPH_SUFFIX unzip True elif tag_type images for t in tags images self GetRouteAndSave images run run tag t for im in images url individualImage im query self GetAndSave url IMAGE_SUFFIX else for t in tags self GetRouteAndSave tag_type run run tag t except IOError as e PrintAndLog Retrieval failed for s s s tag_type run tags tf logging WARN PrintAndLog Got Exception s e tf logging WARN PrintAndLog continuing tf logging WARN continue
format the traceback part of a message,def format_traceback self msg if msg traceback is not None lines msg traceback split n lines lines 1 return self traceback_prefix join lines else return
rule : nonterminal bar srhs bar trhs bar fpairs,def p_rule_and_weights self p i 0 fmap for k v in p 7 if k fmap 0 1 format self fprefix_ i v i 1 else fmap k v p 0 SCFGProduction create p 1 p 3 p 5 fmap
"srtm data is split into different directories , get a list of all of them and create a dictionary for easy lookup .",def createFileList self if self childFileListDownload is None or not self childFileListDownload is_alive self childFileListDownload multiprocessing Process target self createFileListHTTP args self server self directory self childFileListDownload start
returns a vector in the same direction but of unit length .,def unit self x self X y self Y z self Z l np sqrt x x y y z z if l 1e 06 return pv Point 0 0 0 return 1 0 l self
"gaussian naive bayes . when dealing with continuous data , a typical assumption is that the continuous values associated with each class are distributed according to a gaussian distribution .",def sc_gaussian_nb input_dict from sklearn naive_bayes import GaussianNB classifier GaussianNB return classifier classifier
stem a german word and return the stemmed form .,def stem self word word word lower word word replace u xdf ss for i in range 1 len word 1 if word i 1 in self __vowels and word i 1 in self __vowels if word i u word join word i U word i 1 elif word i y word join word i Y word i 1 r1 r2 self _r1r2_standard word self __vowels for i in range 1 len word if word i not in self __vowels and word i 1 in self __vowels if len word i 1 3 and len word i 1 0 r1 word 3 elif len word i 1 0 return word break for suffix in self __step1_suffixes if r1 endswith suffix if suffix in en es e and word len suffix 4 len suffix niss word word len suffix 1 r1 r1 len suffix 1 r2 r2 len suffix 1 elif suffix s if word 2 in self __s_ending word word 1 r1 r1 1 r2 r2 1 else word word len suffix r1 r1 len suffix r2 r2 len suffix break for suffix in self __step2_suffixes if r1 endswith suffix if suffix st if word 3 in self __st_ending and len word 3 3 word word 2 r1 r1 2 r2 r2 2 else word word len suffix r1 r1 len suffix r2 r2 len suffix break for suffix in self __step3_suffixes if r2 endswith suffix if suffix in end ung if ig in r2 len suffix 2 len suffix and e not in r2 len suffix 3 len suffix 2 word word len suffix 2 else word word len suffix elif suffix in ig ik isch and e not in r2 len suffix 1 len suffix word word len suffix elif suffix in lich heit if er in r1 len suffix 2 len suffix or en in r1 len suffix 2 len suffix word word len suffix 2 else word word len suffix elif suffix keit if lich in r2 len suffix 4 len suffix word word len suffix 4 elif ig in r2 len suffix 2 len suffix word word len suffix 2 else word word len suffix break word word replace u xe4 a replace u xf6 o replace u xfc u replace U u replace Y y return word
delete all training samples in the database .,def delete_all return TrainingSample objects all delete
install / clone any missing git submodule dependencies,def clone_missing_submodules repo for submodule in repo submodules if not submodule module_exists print Cloning format submodule path submodule update
return the list of all cached global names,def get_all_names self result set for module in self names result update set self names module return result
stores the posted data to the mongo,app route createExpensesList methods POST jwt_required def createExpensesList jsonAsDict getDictFromPost request name jsonAsDict get name if name None and name and name undefined storedObjectDict storage createExpensesList name current_identity return json dumps storedObjectDict return Response Wrong format will not store 400
"takes in some parameters that were passed to a component method and checks to see if any of them are actually callbacks . if this is the case , the callbacks done method is invoked .",def tryCallbackParams params compRef from Acssim Corba Generator import getRandomValue compl ACSErr Completion long getTimeStamp value 0L 0L cbId 0L for param in params if isinstance param ACS CBDescIn cbId param id_tag break cbDescOut ACS CBDescOut 0L cbId for param in params if isinstance param ACS _objref_CBvoid param done compl cbDescOut elif isinstance param ACS _objref_CBpattern param done getRandomValue ACS _tc_pattern compRef compl cbDescOut elif isinstance param ACS _objref_CBpattern param done getRandomValue ACS _tc_pattern compRef compl cbDescOut elif isinstance param ACS _objref_CBdouble param done getRandomValue CORBA _tc_double compRef compl cbDescOut elif isinstance param ACS _objref_CBstring param done getRandomValue CORBA _tc_string compRef compl cbDescOut elif isinstance param ACS _objref_CBstringSeq param done getRandomValue ACS _tc_stringSeq compRef compl cbDescOut elif isinstance param ACS _objref_CBlong param done getRandomValue CORBA _tc_long compRef compl cbDescOut elif isinstance param ACS _objref_CBdoubleSeq param done getRandomValue ACS _tc_doubleSeq compRef compl cbDescOut elif isinstance param ACS _objref_CBlongSeq param done getRandomValue ACS _tc_longSeq compRef compl cbDescOut else pass
errortracehelper log does nothing for empty error traces,def test_log_empty self logger mock Mock spec Logger self assertRaises Exception self ethd log logger
do num_iter iterations of gradient descent .,def learn self num_iter 50 for i in range num_iter self iter 1 abs_error 0 sumsq_error 0 for user item rating timestamp in random sample self ratings len self ratings error self prediction user item rating abs_error abs error sumsq_error error error self user_offset user self step_size error self item_offset item self step_size error for f in range self num_features self user_feat user f self step_size error self item_feat item f self item_feat item f self step_size error self user_feat user f for user in range self max_user_index self user_offset user self step_size self reglz self user_offset user for f in range self num_features self user_feat user f self step_size self reglz self user_feat user f for item in range self max_item_index self item_offset item self step_size self reglz self item_offset item for f in range self num_features self item_feat item f self step_size self reglz self item_feat item f self display 1 Iteration self iter Ave Abs AveSumSq training self evaluate self ratings test self evaluate self test_ratings
get all the cpus ' capacities from sysfs as a list of ints,def read_cpu_caps self return self target read_int self _get_cpu_cap_path cpu for cpu in range self target number_of_cpus
value must be a quantity with a valid distance unit . will keep the units given .,distance setter def distance self value if not isinstance value u Quantity raise TypeError Value for distance must an astropy Quantity if not value unit is_equivalent u pc raise u UnitConversionError Given unit is not a valid unit of distance format value unit if not value isscalar raise TypeError Distance must be a scalar quantity self _distance value
"acquire a reference to the system libc , initially to access the filesystem "" sync "" function .",def getLibc logger False if not logger logger CyLogger osFamily sys platform lower strip if osFamily and osFamily startswith darwin try libc ctypes CDLL usr lib libc dylib except raise Exception DAMN IT JIM else print Loading Mac dylib elif osFamily and osFamily startswith linux possible_paths lib x86_64 linux gnu libc so 6 lib i386 linux gnu libc so 6 usr lib64 libc so 6 for path in possible_paths if os path exists path libc ctypes CDLL path break else libc False try if libc libc sync except raise Exception Cannot Sync return libc
check on whether report was correct @param self : essential if you override this definition @param pcompliance : the self.iscompliant value of rule @param prulesuccess : did report run successfully @return : boolean - if successful true ; if failure false @author : ekkehard j. koch,def checkReportForRule self pCompliance pRuleSuccess self logdispatch log LogPriority DEBUG pCompliance str pCompliance self logdispatch log LogPriority DEBUG pRuleSuccess str pRuleSuccess success True return success
check on whether undo was correct @param self : essential if you override this definition @param prulesuccess : did report run successfully @return : boolean - if successful true ; if failure false @author : ekkehard j. koch,def checkUndoForRule self pRuleSuccess self logdispatch log LogPriority DEBUG pRuleSuccess str pRuleSuccess success True return success
checks the status of a service and returns a bool indicating whether or not the service is configured to run or not .,def auditservice self service servicename try servicesuccess True command self launchd list servicename self logdispatcher log LogPriority DEBUG command str command if self ch executeCommand command if self ch getErrorOutput servicesuccess False self logdispatcher log LogPriority DEBUG Blank output service servicename elif self ch findInOutput self findstring 0 or self ch findInOutput self findstring 1 servicesuccess False self logdispatcher log LogPriority DEBUG Cannot Find service service servicename Output is str self ch getErrorOutput else self logdispatcher log LogPriority DEBUG Found service servicename Output is str self ch getErrorOutput self logdispatcher log LogPriority DEBUG service servicename str servicesuccess return servicesuccess except Exception raise
there is no undo method for this rule since we do n't ever want these screensaver files to exist,def undo self try self detailedresults no undo available n self logger log LogPriority INFO self detailedresults except KeyboardInterrupt SystemExit raise except Exception self detailedresults traceback format_exc self logger log LogPriority INFO self detailedresults
"returns uptime in seconds or none , on bsd ( including os x ) .",def _uptime_bsd global __boottime try libc ctypes CDLL libc so except AttributeError return None except OSError try libc ctypes CDLL libc dylib except OSError return None if not hasattr libc sysctlbyname return None sz ctypes c_uint 0 libc sysctlbyname kern boottime None ctypes byref sz None 0 if sz value struct calcsize LL return None buf ctypes create_string_buffer sz value libc sysctlbyname kern boottime buf ctypes byref sz None 0 sec usec struct unpack LL buf raw if usec 1000000 usec 0 0 __boottime sec usec 1000000 0 up time time __boottime if up 0 up None return up
antibody lots should not have associated characterizations for different target labels,audit_checker antibody_lot frame characterizations characterizations target def audit_antibody_lot_target value system if value status in not pursued deleted return if not value characterizations return for char in value characterizations if char target id not in value targets detail The antibody_lot has a characterization with target which is not in the targets list format value id char id char target id yield AuditFailure mismatched target detail level ERROR
"initialize an ordered dictionary . signature is the same as for regular dictionaries , but keyword arguments are not recommended because their insertion order is arbitrary .",def __init__ self args kwds if len args 1 raise TypeError expected at most 1 arguments got d len args try self __root except AttributeError self __root root root root root None self __map self __update args kwds
"instantiates the killerbee class for the apimote platform running goodfet firmware . @type dev : string @param dev : serial device identifier ( ex /dev / ttyusb0 ) @type revision : integer @param revision : the revision number for the apimote , which is used by the called goodfet libraries to properly communicate with and configure the hardware . @return : none @rtype : none",def __init__ self dev revision DEFAULT_REVISION self _channel None self handle None self dev dev self __revision_num revision os environ platform apimote d format self __revision_num os environ board apimote d format self __revision_num self handle GoodFETCCSPI self handle serInit port self dev self handle setup self __stream_open False self capabilities KBCapabilities self __set_capabilities
tests the handling of source data type names .,def testSourceDataTypeHandling self self _relation addSourceDataTypeName name self _relation addSourceDataTypeName name2 self assertEquals len self _relation sourceDataTypeNames 2 self _relation addSourceDataTypeName name2 self assertEquals len self _relation sourceDataTypeNames 2 self _relation removeSourceDataTypeName name self _relation removeSourceDataTypeName name2 self assertEquals len self _relation sourceDataTypeNames 0 self _relation sourceDataTypeNames name name2 self assertEquals len self _relation sourceDataTypeNames 2
emulates the call to the open function .,def __call__ self _ __ if self error raise IOError else return io StringIO u
create an instance of an archive specific metadatastorer .,def createMetadataStorer self identifier return NullMetadataStorer identifier
determines the condition term class .,def __getConditionTermClass operator literal try conditionTermList __daslLeafConditionMapping operator except KeyError errorMessage Operator s is not supported operator raise PersistenceError errorMessage else if len conditionTermList 3 if isinstance literal basestring conditionTermClass conditionTermList 0 elif isinstance literal time struct_time conditionTermClass conditionTermList 2 else conditionTermClass conditionTermList 1 else conditionTermClass conditionTermList 0 return conditionTermClass
@see : l{nulldatastorer < datafinder.persistence.data.datastorer . nulldatastorer > },def copy self destination try targetPersistenceId self _itemIdMapper mapIdentifier destination identifier if self isCollection shutil copytree self _persistenceId targetPersistenceId else shutil copy self _persistenceId targetPersistenceId except IOError OSError EnvironmentError as error reason os strerror error errno or 0 errorMessage Cannot copy item s to item s Reason s self identifier destination identifier reason raise PersistenceError errorMessage
gets the driving route from open street routing machine for an array of pairs of coordinates . decodes the returned polyline routes into an array or lat / lon tuples . saves the resulting paths as a pickle .,def get_routes location_pairs routes_path get_time False routes if os path isfile routes_path routes pickle load open routes_path rb for location_pair_key in location_pairs if location_pair_key not in routes location location_pairs location_pair_key url http router project osrm org route v1 driving s location response requests get url route response json routes 0 if get_time routes location_pair_key duration route duration distance route distance else routes location_pair_key polyline decode route geometry pickle dump routes open routes_path wb return routes
sets up the db for use by a given test subject .,def db_setup test_subj dbname TEST_DB_NAME dbdump TEST_DB_DUMP echo False try pg_createdb dbname except subprocess CalledProcessError pg_dropdb dbname pg_createdb dbname test_subj dbname dbname test_subj db sqlalchemy create_engine postgresql dbname echo echo pg_restore dbname dbdump Session sqlalchemy orm sessionmaker test_subj session Session bind test_subj db
"create a random transaction . returns ( txid , hex - encoded - transaction - data , fee )",def random_transaction nodes amount min_fee fee_increment fee_variants from_node random choice nodes to_node random choice nodes fee min_fee fee_increment random randint 0 fee_variants total_in inputs gather_inputs from_node amount fee outputs make_change from_node total_in amount fee outputs to_node getnewaddress float amount rawtx from_node createrawtransaction inputs outputs signresult from_node signrawtransaction rawtx txid from_node sendrawtransaction signresult hex True return txid signresult hex fee
generates the required text listing all elements that will be deleted .,def body self master if len self id_tuples 0 message_string No elements selected elif len self id_tuples 1 message_string Delete format self tree get_element self id_tuples 0 0 name else message_string Delete the following items n for x level in self id_tuples if level 0 bullet u u25c6 else bullet level 1 u u25c7 message_string u bullet name n format bullet bullet name self tree get_element x name message ttk Label master text message_string justify left message grid row 0 sticky w
"return the red , green and blue components for a color as doubles .",def GetRGBColor colorName rgb 0 0 0 0 0 0 vtk vtkNamedColors GetColorRGB colorName rgb return rgb
build a dict that maps paths to modules .,def FindModules path renderingBackend OpenGL pathToModule dict fileProg re compile module cmake moduleProg re compile module s w re S for root dirs files in os walk path for f in files if fileProg match f fid open os path join root f r contents fid read m moduleProg match contents if m moduleName m group 1 if ExcludeModuleName moduleName renderingBackend continue parts root split pathToModule parts len parts 2 parts len parts 1 moduleName fid close return pathToModule
"return the ipv4 address of the client which made this request , if there is one , otherwise c{none}.",def getClientIP self if isinstance self client IPv4Address return self client host return None
create empty graphs with subplots for global network performance and detailed subtask performance,def __init__ self max_trials n_subtasks self figure self axarr plt subplots 1 2 sharey True self axarr 0 set_title Network performance self axarr 0 set_xlabel Trials self axarr 0 set_ylabel Performance self axarr 0 set_ylim 0 1 05 self filter_size 100 self max_trials max_trials self perf_line self axarr 0 plot range max_trials np zeros self max_trials lw 2 self axarr 1 set_title Trial type performance self axarr 1 set_xlabel Trials self perf_lines self axarr 1 plot np zeros self max_trials n_subtasks lw 2 self figure canvas mpl_connect button_press_event self on_click for ax in self axarr labels ax get_xticklabels plt setp labels rotation 45 self c_epoch 1
display a viseme mouth shape for synched speech args : code ( int ) : 0 = shape for sounds like ' y ' or ' aa ' 1 = shape for sounds like ' aw ' 2 = shape for sounds like ' uh ' or ' r ' 3 = shape for sounds like ' th ' or ' sh ' 4 = neutral shape for no sound 5 = shape for sounds like ' f ' or ' v ' 6 = shape for sounds like ' oy ' or ' ao ',def mouth_viseme self code self ws emit Message enclosure mouth viseme code code
convert latitude and longitude data to utm as a list of coordinates .,def convert_from_latlon_to_utm points None latitudes None longitudes None false_easting None false_northing None old_geo Geo_reference utm_points if points None assert len latitudes len longitudes points map None latitudes longitudes for point in points zone easting northing redfearn float point 0 float point 1 false_easting false_easting false_northing false_northing new_geo Geo_reference zone old_geo reconcile_zones new_geo utm_points append easting northing return utm_points old_geo get_zone
: type nums : list[int ],def __init__ self nums self nums nums
create and initialize a custom progressbar,def get_pbar file_id maxval start_val 0 title Downloading format file_id pbar ProgressBar widgets title Percentage Bar marker left right ETA FileTransferSpeed maxval maxval pbar currval start_val pbar start return pbar
returns the current index of sample .,def cursor_pos_sample pos samplerate hopsize return np int pos samplerate hopsize
method called before iterating through parents list,def reset self pass
helper function for obtaining the git repository hash . for the current directory ( default ) or the directory supplied in the gitpath argument .,def get_git_hash gitpath None label None if gitpath thisdir os getcwd os chdir gitpath try sha subprocess check_output git rev parse HEAD shell False strip except subprocess CalledProcessError as e print ERROR WORKING DIRECTORY NOT A GIT REPOSITORY return if label l format label else l GIT HASH return l sha
"the returned `` monkeypatch `` funcarg provides these helper methods to modify objects , dictionaries or os.environ : :",def pytest_funcarg__monkeypatch request mpatch monkeypatch request addfinalizer mpatch undo return mpatch
shuts down the proxy and closes the port,def close self r requests delete 0 proxy 1 format self host self port return r status_code
"when cross compiling , we zero fill an hfs file , that we will turn into a dmg . to do so we test the size of the staged dir , and add some slight padding to that .",def generate_hfs_file stagedir tmpdir volume_name if is_linux hfs os path join tmpdir staged hfs output subprocess check_output du s stagedir size int output split 0 1000 size int size 1 02 subprocess check_call dd if dev zero of format hfs bs 1M count format size subprocess check_call buildconfig substs MKFSHFS v volume_name hfs
update a job / task with parameters to enable a vcs checkout .,def support_vcs_checkout config job taskdesc u Update a job task with parameters to enable a VCS checkout n n The configuration is intended for tasks using run task and its n VCS checkout behavior n level config params u level if job u worker u implementation in u docker worker u docker engine taskdesc u worker setdefault u caches append u type u persistent u name u level s checkouts v1 level u mount point u home worker checkouts taskdesc u worker setdefault u env update u GECKO_BASE_REPOSITORY config params u base_repository u GECKO_HEAD_REPOSITORY config params u head_repository u GECKO_HEAD_REV config params u head_rev u HG_STORE_PATH u checkouts hg store taskdesc u scopes append u secrets get project taskcluster gecko hgfingerprint if job u worker u implementation in u docker worker u docker engine taskdesc u worker u taskcluster proxy True
returns a list of all annotations for the given |test| . may be empty .,def GetTestAnnotations self test if not self _IsTestMethod test return return self _GetAnnotationMap test
view of the browser used by the executor object . this is needed because the executor runs in a child process and we ca n't ship browser instances between processes on windows .,def __init__ self kwargs for k v in kwargs iteritems setattr self k v
"sets installer , test and symbols urls from the artifacts of bbb based task .",def set_artifacts self installer tests symbols self installer_url self test_packages_url self symbols_url installer tests symbols self info Set installer_url s self installer_url self info Set test_packages_url s self test_packages_url self info Set symbols_url s self symbols_url
clears the dns cache associated with the proxy instance,def clear_dns_cache self r requests delete 0 proxy 1 dns cache format self host self port return r status_code
only files for one foia request,def get_queryset self foia self get_foia queryset super FOIAFileListView self get_queryset return queryset filter comm__foia foia
welcomes a new user to the site .,def test_welcome self mock_send tasks welcome self user mock_send assert_called_with fail_silently False
get the agency user for this agency,def get_user self try return self profile user except Profile DoesNotExist user User objects create_user unique_username self name Profile objects create user user acct_type agency date_update date today agency self return user
extend the rangeset by ' n ' blocks .,def extend self n out self for i in range 0 len self data 2 s e self data i i 2 s1 max 0 s n e1 e n out out union RangeSet str s1 str e1 1 return out
override method for the ethernet ieee802.3 length / type field ( self.ethertype ) .,classmethod def get_packet_type cls type_ if type_ ether ETH_TYPE_IEEE802_3 type_ ether ETH_TYPE_IEEE802_3 return cls _TYPES get type_
the ' clean ' image without any drawing and the image title(a.k . the state ) is inputted by this function,def InputInfo self img imgName state label SavePathDict VisualParamDict self img img self hgt self wid c self img shape self imgName imgName self state state self label label self SavePathDict SavePathDict self lineThickness VisualParamDict LineThickness
takes a dict object and returns a ordereddict with the attributes from the object stored in the [ ' _ _ dict _ _ ' ] location,def create_attribute_dict obj attributes defaultdict dict if isinstance obj dict for key in obj keys attr_dict defaultdict dict if hasattr obj key __dict__ for attr in obj __dict__ if attr not in parent view data stack _OrderedDict__root _OrderedDict__map attr_dict attr obj __dict__ attr attributes __dict__ attr_dict attributes key create_attribute_dict obj key return attributes
calculates a dihedral angles exactly as in protoms,def dihedral_protoms a1 a2 a3 a4 v21 a1 a2 v23 a3 a2 v32 v23 v34 a4 a3 n1 vnorm np cross v21 v23 n2 vnorm np cross v32 v34 phi np dot n1 n2 if phi 1 0 phi 1 elif phi 1 0 phi 1 phi np arccos phi n3 vnorm np cross n1 v23 ang np dot n2 n3 if ang 1 0 ang 1 0 elif ang 1 ang 1 0 ang np arccos ang if ang np pi 2 0 phi 2 np pi phi return phi
constructs a new parameter object .,def __init__ self value self value value
get raw torrent data by determining what self.torrent is,def _get_raw_torrent self if self _is_raw self file_type raw self _raw_torrent self torrent return if os path isfile self torrent self file_type file self _raw_torrent open self torrent rb read elif re search http ftp s self torrent re I self file_type url self _raw_torrent urlopen self torrent read
unref all structs and clear cache,def clear self self __infos clear self __names clear
initialize the channel db using the server connection passed .,def __init__ self server config self config config self server server self account_id self server flow account_id self _data self _get_all config db_keys
schedules an action to be executed at duetime .,def schedule_absolute self duetime action state None duetime self to_datetime duetime return self schedule_relative duetime self now action state
"i , prim , loc , bel 0,fdpe , slice_x12y100,c5ff 1,fdpe , slice_x15y100,a5ff 2,fdpe_1,slice_x16y100,b5ff 3,ldce_1,slice_x17y100,bff",def loadtop f open top txt r f readline ret for l in f i prim loc bel init l split i int i init int init ret loc i prim loc bel init return ret
constructor that generates the map of the config file @param filename : file containing config @type filename : string,def __init__ self fileName configFile FileCacheManager fileName tempConfigContent for line in configFile filecontent lineSplit line split if len lineSplit 1 if UpdateAndSend in tempConfigContent tempConfigContent UpdateAndSend tempConfigContent UpdateAndSend n lineSplit 0 else tempConfigContent UpdateAndSend lineSplit 0 else tempConfigContent lineSplit 0 lineSplit 1 for k v in tempConfigContent iteritems newk k strip newv v strip self configContent newk newv
keys values in a standard way for grouping in merging and summary .,def DefaultKeyFunc value return value name value tir_label
writes the provided blacklist to the blacklist file .,def Write self blacklist with self _blacklist_lock with open self _path w as f json dump blacklist f
reboot from fastboot to normal usage,decorators WithTimeoutAndRetriesDefaults _FLASH_TIMEOUT 0 def Reboot self timeout None retries None self _RunFastbootCommand reboot
starts monitoring network notifications and recording http responses .,def StartMonitoringNetwork self self ClearResponseData self _inspector_websocket RegisterDomain Network self _OnNetworkNotification request method Network enable self _inspector_websocket SyncRequest request
displays the mojo shell logs and returns the process reading the logs .,def ShowLogs self stdout sys stdout logcat subprocess Popen self _CreateADBCommand logcat s join LOGCAT_TAGS stdout stdout atexit register _ExitIfNeeded logcat return logcat
calculate the loss between the feature representation of the content image and the generated image .,def _content_loss self P F self content_loss tf reduce_sum F P 2 4 0 P size
convert the base 64 characters in base64 to a value .,def decode self base64 value 0 first 0 neg False if base64 0 neg True first 1 for i in xrange first len base64 value value 6 value self base64_map base64 i return value if neg else value
write an integer as an unsigned 64-bit value .,def write_longlong self n pack Struct Q pack if 0 n 18446744073709551615L self _output_buffer extend pack n else raise ValueError Longlong d out of range 0 0xFFFFFFFFFFFFFFFF n return self
handle menu item callback by saving text to a file,def start_logger self _widget Terminal savedialog Gtk FileChooserDialog title _ Save Log File As action self dialog_action buttons self dialog_buttons savedialog set_transient_for _widget get_toplevel savedialog set_do_overwrite_confirmation True savedialog set_local_only True savedialog show_all response savedialog run if response Gtk ResponseType OK try logfile os path join savedialog get_current_folder savedialog get_filename fd open logfile w vte_terminal Terminal get_vte col row vte_terminal get_cursor_position self loggers vte_terminal filepath logfile handler_id 0 fd fd col col row row self loggers vte_terminal handler_id vte_terminal connect contents changed self save except e sys exc_info 1 error Gtk MessageDialog None Gtk DialogFlags MODAL Gtk MessageType ERROR Gtk ButtonsType OK e strerror error set_transient_for savedialog error run error destroy savedialog destroy
"extract the binary package content , without the metadata .",def extract self dest_dir raise NotImplementedError
compare two lists of permutations as sets .,def _cmp_perm_lists first second return set tuple a for a in first set tuple a for a in second
"maximize image contrast , based on histogram . this completely ignores the alpha channel .",def autocontrast image cutoff 0 assert image dtype np uint8 output_image np empty image shape 0 image shape 1 3 np uint8 for i in range 0 3 plane image i output_plane output_image i h np histogram plane bins 256 0 if cutoff n 0 for ix in range 256 n n h ix cut n cutoff 100 for lo in range 256 if cut h lo cut cut h lo h lo 0 else h lo h lo cut cut 0 if cut 0 break cut n cutoff 100 for hi in range 255 1 1 if cut h hi cut cut h hi h hi 0 else h hi h hi cut cut 0 if cut 0 break for lo in range 256 if h lo break for hi in range 255 1 1 if h hi break if hi lo output_plane plane else scale 255 0 hi lo offset lo scale lut np arange 256 dtype np float lut scale lut offset lut lut clip 0 255 lut lut astype np uint8 output_plane lut plane return output_image
make sure there are no kernels running at the start,def test__no_kernels self kernels self kern_api list json self assertEqual kernels
load numpy and matplotlib to work interactively .,skip_doctest line_magic magic_arguments magic_arguments magic_arguments argument no import all action store_true default None help Prevent IPython from performing import into the interactive namespace You can govern the default behavior of this flag with the InteractiveShellApp pylab_import_all configurable magic_gui_arg def pylab self line args magic_arguments parse_argstring self pylab line if args no_import_all is None if Application initialized app Application instance try import_all app pylab_import_all except AttributeError import_all True else import_all True else import_all not args no_import_all gui backend clobbered self shell enable_pylab args gui import_all import_all self _show_matplotlib_backend args gui backend print Populating the interactive namespace from numpy and matplotlib if clobbered warn pylab import has clobbered these variables s clobbered matplotlib prevents importing from pylab and numpy
attempts to show the specified call line and docstring at the current cursor location . the docstring is possibly truncated for length .,def show_call_info self call_line None doc None maxlines 20 if doc match re match n n i maxlines doc if match doc doc match end n Documentation continues else doc if call_line doc n n join call_line doc return self show_tip self _format_tooltip doc
write the sources to a log .,def log self line_mod line_ori if self log_raw_input self log_write line_ori else self log_write line_mod
if a sympy ' expr ' is of the form :,def bilinear_product expr fct def bilinear_term expr fct if expr is_zero return expr if isinstance expr Mul coefs bases expr args_cnc coef Mul tuple coefs if isinstance bases 0 Pow args bases 0 args return coef fct args 0 args 0 elif len bases 1 return expr else return coef fct bases 0 bases 1 elif isinstance expr Pow args expr args return fct args 0 args 0 elif isinstance expr Symbol return expr else raise TypeError Cannot compute bilinear_product for str expr n expr expand expand expr if not isinstance expr Add return bilinear_term expr fct else result S Zero for term in expr args tmp bilinear_term term fct result tmp return result
solves a real univariate inequality .,def solve_univariate_inequality expr gen assume True relational True from sympy solvers solvers import solve solns solve expr lhs expr rhs gen assume assume oo S Infinity start oo sol_sets S EmptySet for x in sorted s for s in solns if s is_real end x if expr subs gen start end 2 if start oo else end 1 sol_sets append Interval start end True True if expr subs gen x sol_sets append FiniteSet x start end end oo if expr subs gen start 1 sol_sets append Interval start end True True rv Union sol_sets return rv if not relational else rv as_relational gen
should identify full file as colliding,def test_check_for_collision_empty self self assertRaises RuntimeError self sub check_for_collisions self full_fn
receive a message from the environment or experiment and respond .,def agent_message self inMessage if inMessage lower agent_diverged return str self has_diverged else return name does not understand your message
decode a json document from `` s `` ( a `` str `` or `` unicode `` beginning with a json document ) and return a 2-tuple of the python representation and the index in `` s `` where the document ended .,def raw_decode self s kw kw setdefault context self try obj end self _scanner iterscan s kw next except StopIteration raise ValueError No JSON object could be decoded return obj end
replace items with different items .,def test_change_list_replace_items self changed self _assign_list_test_helper alice bob carol dave self assertEqual changed carol dave
computes gradients from the imperatively defined tape on top of the stack .,def imperative_grad vspace tape target sources output_gradients None with errors raise_exception_on_not_ok_status as status return pywrap_tensorflow TFE_Py_TapeGradient tape _tape vspace target sources output_gradients status
locations of these student 's t distribution(s ) .,property def loc self return self bijector shift
test that centroid_func is callable .,def test_centroid_func_callable self u with pytest raises ValueError find_peaks PEAKDATA 0 1 box_size 2 centroid_func True
add a new content to this bundle .,def add_content self content self _contents append content
download chunks of broadcast replay and assemble into single .ts,def download_replay self if self broadcast private replay_info cookies self _get_chunk_info_private else replay_info cookies self _get_chunk_info server_directory join replay_info url split 1 chunks i strip for i in replay_info text split if chunk in i lower if len chunks 0 raise Exception No chunks available for download May be authentication issue temp_dir os path join self broadcast download_directory periapi format self broadcast filetitle if not os path exists temp_dir os makedirs temp_dir chunk_pool ThreadPool self broadcast title DEFAULT_DL_THREADS len chunks for chunk in chunks path os path join temp_dir chunk url join server_directory chunk chunk_pool add_task grab_chunk url path self headers cookies self broadcast dl_times append time time chunk_pool wait_completion with open ts format self broadcast filepathname wb as handle for chunk in chunks chunk_path os path join temp_dir chunk if not os path exists chunk_path or os path getsize chunk_path 0 break with open chunk_path rb as ts_file handle write ts_file read if chunk_pool is_complete and os path exists temp_dir try shutil rmtree temp_dir except BaseException pass
": param http_status : the recommended http status code . : param request_id : must be the same as the value as the i d member in the request object . if there was an error in detecting the i d in the request object ( e.g. parse error / invalid request ) , it must be null . : param code : a number that indicates the error type that occurred . this must be an integer . : param message : a string providing a short description of the error , eg . "" invalid params "" : param data : a primitive or structured value that contains additional information about the error . this may be omitted .",def __init__ self http_status request_id code message data None debug False super ErrorResponse self __init__ jsonrpc 2 0 error code code message message id request_id if debug and data self error data data self http_status http_status
test if two database files have the same contents .,def _test_eq_db self db1 db2 with connect db1 as o with connect db2 as e co o cursor ce e cursor for table in e execute SELECT name FROM sqlite_master WHERE type table co execute SELECT FROM s table ce execute SELECT FROM s table self assertEqual co fetchall ce fetchall
extract filtered subreads from a bash5 or baxh5 file,def _extract_from_bash5 bash5_file min_length min_score filename os path basename bash5_file log info Extracting subreads from s filename records for zmw in BasH5Reader bash5_file zmwName s s zmw baxH5 movieName zmw holeNumber if zmw readScore min_score continue long_subreads s for s in zmw subreads if len s basecalls min_length if len long_subreads 1 subread long_subreads 0 yield FastaRecord subread readName subread basecalls elif len long_subreads 2 ordered sorted long_subreads key lambda s len s basecalls reverse True subread ordered 0 yield FastaRecord subread readName subread basecalls log info Found s subreads that passed filters len records
return an array with the same data but a new shape .,def reshape self axis raise NotImplementedError
generates the encoded hsms data of the stream / function parameter,def encode self if self data is None return return self data encode
"linearly interpolate y - value at t using line through ( t0 , y0 ) and ( t1 , y1 )",def _linearly_interpolate_y self t t0 t1 y0 y1 if t1 t0 return np nan else m y1 y0 t1 t0 return y0 m t t0
getchangesource for a changesource that exists,defer inlineCallbacks def test_getChangeSource self yield self insertTestData self cs87 cs yield self db changesources getChangeSource 87 validation verifyDbDict self changesourcedict cs self assertEqual cs dict id 87 name lame_source masterid None
identifies if this task is associated with the specified task .,def is_associated_with self other association_key self _association_key_for other if association_key in self _source return self _source association_key other uid return False
"happy scenario , a filename with an extension",def test_extension_file_with_extension self filename the_file ext expected_extension ext extension get_file_extension filename self assertEqual extension expected_extension self assertTrue file_has_extension filename
extract the labels into a vector of int64 label ids .,def extract_labels filename num_images print Extracting filename with gzip open filename as bytestream bytestream read 8 buf bytestream read 1 num_images labels np frombuffer buf dtype np uint8 astype np int64 return labels
lookup a view function in the registry . gets an access function,classmethod def lookup cls view_func if _REGISTRY has_key view_func return _REGISTRY view_func return None
clear ( ) eliminates the progess bar upon completion of a loop .,def clear self sys stdout write r sys stdout write len self label 7 self barWidth sys stdout write r sys stdout flush
"return the thrust of this drive based on self.thrust and self.hp . this number should be considered a full thrust value , not a fraction .",def get_thrust self return self thrust or 1 0 percent self hp self max_hitpoints 100 0 self max_thrust
check if obj is string .,def is_string obj return isinstance obj str
"get features from a given turbine , consisting of the values of the speed of a turbine depending on feature_window size and time horizon and optionally a certain padding .",def get_features_turbine self turbine feature_window horizon padding 0 timesteps len turbine measurements feature_window horizon padding 1 features zeros timesteps feature_window dtype float32 for t in range padding timesteps features t 0 feature_window turbine measurements cs t t feature_window return features
make sure that roundtripping produces identical file,def assertReadWriteSame self props WriteDialogToFile __unittests xml props read_props ReadPropertiesFromFile __unittests xml self assertEquals props read_props
* * pdaniell constructor * *,def __init__ self data P sampling 1 0 window hann NFFT None scale_by_freq True detrend None super pdaniell self __init__ data window window sampling sampling NFFT NFFT scale_by_freq scale_by_freq detrend detrend self P P
compute the isolines of a specified attribute of the vertices of a mesh .,def mesh_isolines_numpy mesh attr_name N 50 xy mesh vertex_coordinates key xy for key in mesh vertices s mesh vertex key attr_name for key in mesh vertices return scalarfield_contours_numpy xy s N
return the number of frames of the file,def get_nframes self return self _sndfile nframes
fit specified model to data with learning algorithm .,def continueRun dataName None allocModelName None obsModelName None algName None doSaveToDisk True doWriteStdOut True kwargs hasReqArgs dataName is not None hasReqArgs allocModelName is not None hasReqArgs obsModelName is not None hasReqArgs algName is not None if hasReqArgs ReqArgs dict dataName dataName allocModelName allocModelName obsModelName obsModelName algName algName else ReqArgs BNPYArgParser parseRequiredArgs dataName ReqArgs dataName allocModelName ReqArgs allocModelName obsModelName ReqArgs obsModelName algName ReqArgs algName parser argparse ArgumentParser parser add_argument jobname default defaultjob parser add_argument taskid default 1 type int parser add_argument startLap default 1 0 type float parser add_argument nLap default 10 type int argDict ignored BNPYArgParser applyParserToKwArgDict parser kwargs hmodel LP Info _continue_task_internal argDict jobname argDict taskid argDict startLap argDict nLap dataName allocModelName obsModelName algName ReqArgs doSaveToDisk doWriteStdOut return hmodel LP Info
first four rhs terms ( inside sum over k ) in bishop 10.74,def E_logpMu self lp np empty self K for k in range self K mWm self comp k dist_mahalanobis self obsPrior m lp k self comp k ElogdetLam self D self obsPrior kappa self comp k kappa self obsPrior kappa self comp k dF mWm lp self D np log self obsPrior kappa LOGTWOPI return 0 5 lp sum
return a 16-character alphanumeric random string generated by the operating system 's secure pseudo random number generator,def generate_password chars uppercase lowercase digits return join SystemRandom choice chars for x in xrange 16
returns the user record for the given username .,require db ddserver db Database def __getitem__ self key db with db cursor as cur cur execute SELECT FROM users WHERE username username s username key row cur fetchone if row return self User row
he normal variance scaling initializer .,def he_normal shape name None u He normal variance scaling initializer n n References n He et al http arxiv org abs 1502 01852 n fan_in fan_out get_fans shape s np sqrt 2 0 fan_in return normal shape s name name
"sample next ( support , test ) pair .",def next self u Sample next support test pair n n Return from internal storage n if self trial_num self n_episodes_per_task raise StopIteration else task self perm_tasks self task_num task_supports task_tests self task_episodes task support test task_supports self trial_num task_tests self trial_num self task_num 1 if self task_num self n_tasks self task_num 0 self perm_tasks np random permutation self tasks self trial_num 1 return task support test
builds a ssd_meta_arch . ssdfeatureextractor based on config .,def _build_ssd_feature_extractor feature_extractor_config is_training reuse_weights None feature_type feature_extractor_config type depth_multiplier feature_extractor_config depth_multiplier min_depth feature_extractor_config min_depth pad_to_multiple feature_extractor_config pad_to_multiple batch_norm_trainable feature_extractor_config batch_norm_trainable conv_hyperparams hyperparams_builder build feature_extractor_config conv_hyperparams is_training if feature_type not in SSD_FEATURE_EXTRACTOR_CLASS_MAP raise ValueError Unknown ssd feature_extractor format feature_type feature_extractor_class SSD_FEATURE_EXTRACTOR_CLASS_MAP feature_type return feature_extractor_class is_training depth_multiplier min_depth pad_to_multiple conv_hyperparams batch_norm_trainable reuse_weights
sends a ping to a device .,def send_ping self dev_id if self show Bus SHOW_COMMANDS log Sending PING to ID format dev_id self fill_and_write_packet dev_id packet Command PING
prompts the local path in which files are stored when pushed to trex server from client,def do_show_trex_files_path self line print self trex get_trex_files_path print termstyle green End of trex_files_path prompt
write averages to netcdf file and zero array,def output self vs variable_metadata key runsum var for key runsum in self average_vars items if not os path isfile self get_output_file_name vs self initialize_output vs variable_metadata variable_mean key runsum sum self average_nitts for key runsum in self average_vars items self write_output vs variable_metadata variable_mean for runsum in self average_vars values runsum sum 0 0 self average_nitts 0
process the transaction and return a processorresponse,def capture_payment self testing False order None amount None if not order order self order if amount is None amount order balance payment None valid_gc False if self order paid_in_full success True reason_code 0 response_text _ No balance to pay self record_payment else try gc GiftCertificate objects from_order self order valid_gc gc valid except GiftCertificate DoesNotExist success False reason_code 1 response_text _ No such Gift Certificate if not valid_gc success False reason_code 2 response_text _ Bad Gift Certificate else gc apply_to_order self order payment gc orderpayment reason_code 0 response_text _ Success success True if not self order paid_in_full response_text _ s balance remains after gift certificate was applied moneyfmt self order balance return ProcessorResult self key success response_text payment payment
send a log message if extra_logging is set in settings .,def log_extra self msg args if self settings EXTRA_LOGGING value self log info Extra logging msg args
"format , encode and deduplicate a message",def msg message global _MESSAGES if message not in _MESSAGES _MESSAGES message s s message str uuid uuid4 return _MESSAGES message encode utf 8
"performs a clone or a fetch , depending on whether the repository has been previously cloned or not .",def init self if os path isdir self path self fetch else self clone
verifies if the browser is on the correct page,def is_browser_on_page self return Top Institutions in self q css hero large h1 text 0
"unpack ` data ` ( byte string , bytearray or list of integers ) according to given format string ` fmt ` , starting at given bit offset ` offset ` . the result is a tuple even if it contains exactly one item .",def unpack_from fmt data offset 0 return CompiledFormat fmt unpack_from data offset
this endpoint gets you a list of all stars in json,def stars base_url http star api herokuapp com api v1 stars return dispatch_http_get base_url
takes a dict of sections ( from load_sections ) and returns a dict keyed by ' key ' with aggregate output size information .,def sizes_by_key sections key result for section in sections values for s in section sources if not s key in result result s key archive result s key if not section name in archive archive section name 0 archive section name s size return result
"split a given url into the protocoll , the hostname and the dir part",def split_url url return map lambda a b a re split url maxsplit 2 None None None
"create a trollius thrift client and return a context manager for it this is a coroutine : param client_klass : thrift client class : param host : hostname / ip , none = loopback : param port : port number : param loop : trollius event loop : returns : a context manager which provides the thrift client",def create_client client_klass host None port None loop None timeouts None client_type None u n create a Trollius thrift client and return a context manager for it n This is a coroutine n param client_klass thrift Client class n param host hostname ip None loopback n param port port number n param loop Trollius event loop n returns a Context manager which provides the thrift client n if not loop loop asyncio get_event_loop coro loop create_connection ThriftClientProtocolFactory client_klass loop loop timeouts timeouts client_type client_type host host port port return async_protocol_manager coro
"convert intensity , inclination and declination to a 3-component vector",def ang2vec intensity inc dec return numpy transpose intensity i for i in dircos inc dec
returns the date of the last sunrise .,def lastSunrise date pos jd eph lastSunrise date jd pos lat pos lon return Datetime fromJD jd date utcoffset
"send a message with topic , payload ` topic is a unicode string . it will be sent as utf-8 encoded byte array . payload is a python dict . it will be sent as a msgpack serialized dict .",def send self topic payload if __raw_data__ not in payload self socket send_string topic flags zmq SNDMORE self socket send serializer dumps payload use_bin_type True else extra_frames payload pop __raw_data__ assert isinstance extra_frames list tuple self socket send_string topic flags zmq SNDMORE self socket send serializer dumps payload flags zmq SNDMORE for frame in extra_frames 1 self socket send frame flags zmq SNDMORE copy True self socket send extra_frames 1 copy True
get details about a given history dataset collection .,click command show_dataset_collection click argument history_id type str click argument dataset_collection_id type str pass_context custom_exception dict_output def cli ctx history_id dataset_collection_id return ctx gi histories show_dataset_collection history_id dataset_collection_id
"apply the action to this state to produce a new state . if monotone , ignore the delete list ( for a * heuristic )",def apply self action monotone False new_preds set self predicates new_preds set action add_effects if not monotone new_preds set action del_effects new_functions dict new_functions update self functions for function value in action num_effects new_functions function value return State new_preds new_functions self cost 1 self action
"the main entry point , performs the appropriate action for the given arguments .",def run self self _unlock_keychain item self keychain item self arguments item fuzzy_threshold self _fuzzy_threshold if item is not None self stdout write s n item password else self stderr write 1pass Could not find an item named s n self arguments item sys exit os EX_DATAERR
"if restrict_to_lanes is not none , restrict to these lanes only",def get_mux_units_from_cfgfile cfgfile restrict_to_lanes None mux_units with open cfgfile as fh_cfg for entry in yaml safe_load fh_cfg mu MuxUnit entry if restrict_to_lanes passed_lanes for lane in mu lane_ids if int lane in restrict_to_lanes passed_lanes append lane if not passed_lanes continue elif passed_lanes mu lane_ids mu mu _replace lane_ids passed_lanes mux_units append mu return mux_units
set the initial size of the widget,def resize_widget self parent u width height qtutils default_size parent 720 445 self resize width height
executor for ` globus task - event - list `,click command event list help List Events for a given task common_options task_id_arg click option limit default 10 show_default True help Limit number of results click option filter errors is_flag True help Filter results to errors click option filter non errors is_flag True help Filter results to non errors def task_event_list task_id limit filter_errors filter_non_errors client get_client if filter_errors and filter_non_errors raise click UsageError Cannot filter by both errors and non errors elif filter_errors filter_string is_error 1 elif filter_non_errors filter_string is_error 0 else filter_string event_iterator client task_event_list task_id num_results limit filter filter_string def squashed_json_details x is_json False try loaded json loads x details is_json True except ValueError loaded x details if is_json return json dumps loaded separators sort_keys True else return loaded replace n n formatted_print event_iterator fields Time time Code code Is Error is_error Details squashed_json_details json_converter iterable_response_to_dict
execute this python flow graph .,def _popen self run_command self page get_flow_graph get_option run_command generator self page get_generator try run_command run_command format python shlex_quote sys executable filename shlex_quote generator file_path run_command_args shlex split run_command except Exception as e raise ValueError Can t parse run command r 0 format run_command e xterm_executable find_executable self xterm_executable if generator generate_options no_gui and xterm_executable run_command_args xterm_executable e run_command Messages send_start_exec join run_command_args return subprocess Popen args run_command_args stdout subprocess PIPE stderr subprocess STDOUT shell False universal_newlines True
| 0001 0101 | 1101 1001 | | 0011 0111 | 1111 1011 | ----------------------- | 0010 0110 | 1110 1010 | | 0000 0100 | 1100 1000,def qam_16_0x0_1_0_2_3 k 0 pi 1 0 2 3 return constellation_map_generator qam_16 0 qam_16 1 k pi
manages an invocation of run_instrumentaiton_tests.py .,def RunInstrumentationSuite options test buildbot_report PrintNamedStep s_instrumentation_tests test name lower InstallApk options test args test apk test test_apk test_data test test_data verbose I if options target Release args append release if options asan args append tool asan if options upload_to_flakiness_server args append flakiness dashboard server s constants UPSTREAM_FLAKINESS_SERVER if test host_driven_root args append python_test_root s test host_driven_root RunCmd build android run_instrumentation_tests py args
return value for given setting name,def get_setting self name return self request registry settings name
testing the ` extent ` geoqueryset aggregates on related geographic models .,no_mysql no_spatialite def test04a_related_extent_aggregate self aggs City objects aggregate Extent location__point all_extent 104 528056 29 763374 79 460734 40 18476 txpa_extent 97 516111 29 763374 79 460734 40 18476 e1 City objects extent field_name location__point e2 City objects exclude state NM extent field_name location__point e3 aggs location__point__extent tol 4 for ref e in all_extent e1 txpa_extent e2 all_extent e3 for ref_val e_val in zip ref e self assertAlmostEqual ref_val e_val tol
"returns a response , using the ` response_class ` for this view , with a template rendered with the given context .",def render_to_response self context response_kwargs u n Returns a response using the response_class for this n view with a template rendered with the given context n n If any keyword arguments are provided they will be n passed to the constructor of the response class n response_kwargs setdefault u content_type self content_type return self response_class request self request template self get_template_names context context response_kwargs
list all files of the storage .,def list self ignore_patterns for path in utils get_files self storage ignore_patterns yield path self storage
changes all windows / mac line endings in s to unix line endings .,def ToUnixLineEnding s return s replace r n n replace r n
return the subpath which contains the `` needle `` directory .,def _get_subdir_path self haystack needle for path dirs files in os walk haystack if needle in dirs return path raise RuntimeError Path s not found in s needle haystack
return the value of the parameter in parameter 's units .,def value self f if np isnan f raise ValueError NaN fraction passed to parameter value np clip f self _max_value self _min_value self _min_value self _min_value self _max_value if self _log value np exp value return value
returns number of elements overlapping each gene name . expects the derived class ( variantcollection or effectcollection ) to have an implementation of groupby_gene_name .,def gene_counts self return gene_name len group for gene_name group in self groupby_gene_name items
handler for int values . parses qlineedit .,def _int_handler self current self _select_widget text try if type ast literal_eval current int raise ValueError new_value int current color FFFFFF self _current_value new_value self _valid True except ValueError color FFB6C1 self _valid False self _select_widget setStyleSheet QLineEdit background color format color
"from each test case ( derived from testcase ) in test_suites , load and run all the test cases within .",def run_test_suites test_suites run_tests None suite unittest TestSuite for test_class in test_suites tests unittest TestLoader loadTestsFromTestCase test_class if run_tests is not None if test_class __name__ in run_tests this_suite_run set run_tests test_class __name__ else this_suite_run set if all in run_tests this_suite_run this_suite_run union run_tests all _tests for each_test in tests if each_test id split 1 in this_suite_run _tests append each_test tests _tests suite addTests tests unittest TextTestRunner verbosity 2 run suite
returns the output of nm_cmd via a pipe .,def getnm nm_cmd nm Cs python s lib py_ver f os popen nm_cmd nm_output f read f close return nm_output
description : describe the output dimension of an input image during pooling or convolution valid padding : pad_along_height = 0 pad_along_width = 0,def valid in_height in_width stride kernel_size assert isinstance stride list tuple assert isinstance kernel_size list tuple out_height ceil float in_height kernel_size 0 1 float stride 0 out_width ceil float in_width kernel_size 1 1 float stride 1 return int out_height int out_width
"returns the size of the file , for use in calls to getattr ( ) .",def size self return len self _get_content
"return all words tokenized , in lowercase and without punctuation",def get_all_words self u return w lower for w in word_tokenize self text if w not in string punctuation
check if command line flag is required to enable c++11 support .,def check_cxx11_flags self return self _check_flags self _cxx11_flags self _cxx11_test_program cpp CXXFLAGS
gets mapping from entity id to entity instances,def getEntityMapping self entityMapping for doc in self documents for e in doc entities entityMapping e entityID e return entityMapping
"if multiple instances of debug is used in same app , some flags might be created multiple time , filter out dupes",def _remove_dupe_flags self unique_flags for f in self debug_flags if f not in unique_flags unique_flags append f self debug_flags unique_flags
check the pairwise distances between two arrays .,def pairwise_distance_check X Y None distance 5 metric cityblock D pairwise_distances X Y metric metric D D distance False D D distance True if isinstance Y np ndarray if D sum D size test True else test False elif isinstance Y type None if D sum D size D shape 0 test True else test False return test
gdb calls this to perform the command .,def invoke self arg from_tty object_re name_re subname_re parse_printer_regexps arg self invoke1 global pretty printers gdb pretty_printers global object_re name_re subname_re cp gdb current_progspace self invoke1 progspace s pretty printers cp filename cp pretty_printers progspace object_re name_re subname_re for objfile in gdb objfiles self invoke1 objfile s pretty printers objfile filename objfile pretty_printers objfile filename object_re name_re subname_re
"create new table - entry of type ' self._dxfname ' , and add new entry to table .",def new_entry self dxfattribs u Create new table entry of type self _dxfname and add new entry n to table n n Does not check if an entry dxfattribs name already exists n Duplicate entries are possible for Viewports n handle self handles next entry self dxffactory new_entity self _dxfname handle dxfattribs self _add_entry entry return entry
"mol_data are data for learning , validation and testing . n_hidden list is removed from the argument list .",def ANN_single mol_data learning_rate 0 001 training_epochs 15 batch_size 100 display_step 1 n_input mol_data train images shape 1 n_classes mol_data train labels shape 1 print n_input n_classes n_input n_classes x tf placeholder float None n_input y tf placeholder float None n_classes weights biases define_singlelayer n_input n_classes pred singlelayer_perceptron x weights biases loss tf reduce_mean tf pow y pred 2 optimizer tf train GradientDescentOptimizer learning_rate learning_rate train optimizer minimize loss init tf initialize_all_variables avg_cost_train_list list avg_cost_val_list list with tf Session as sess sess run init for epoch in range training_epochs avg_cost_train avg_cost_val 0 0 0 0 total_batch int mol_data train data_size batch_size for i in range total_batch batch_xs batch_ys mol_data train next_batch batch_size sess run train feed_dict x batch_xs y batch_ys avg_cost_train sess run loss feed_dict x batch_xs y batch_ys avg_cost_train total_batch avg_cost_val sess run loss feed_dict x mol_data validation images y mol_data validation labels avg_cost_train_list append avg_cost_train avg_cost_val_list append avg_cost_val if epoch display_step 0 print Epoch 04d epoch 1 RMSE train 9e format np sqrt avg_cost_train print Epoch 04d epoch 1 RMSE validation 9e format np sqrt avg_cost_val print Weights sess run weights out avg_cost_list avg_cost_train_list avg_cost_val_list return avg_cost_list
update the config values with the passed in kwargs,def update self kwargs for key value in sorted kwargs items if value if hasattr self key setattr self key value
record a hit . @param timestamp - the current timestamp ( in seconds granularity ) . : type timestamp : int : rtype : void,def hit self timestamp self getHits timestamp if self __dq and self __dq 1 0 timestamp self __dq 1 1 1 else self __dq append timestamp 1 self __count 1
: type nums : list[int ] : rtype : int,def findShortestSubArray self nums counts collections Counter nums left right for i num in enumerate nums left setdefault num i right num i degree max counts values return min right num left num 1 for num in counts keys if counts num degree
: type root : treenode : type l : int : type r : int : rtype : treenode,def trimBST self root L R if not root return None if root val L return self trimBST root right L R if root val R return self trimBST root left L R root left root right self trimBST root left L R self trimBST root right L R return root
the surface brightness of the source assuming it is observed with a beam matched to its size and it has ff=1,property def source_line_brightness_temperature self return self source_line_surfbrightness u sr to u K u brightness_temperature 1 u sr self frequency
original sigmoid gradient test defined in q2_sigmoid.py ;,pytest mark parametrize sigmoid_f sigmoid sigmoid_sol def test_sigmoidgrad sigmoid_f x np array 1 2 1 2 f sigmoid x g sigmoid_grad f assert rel_error g np array 0 19661193 0 10499359 0 19661193 0 10499359 1e 07
"transform the address into a standard , fixed - length form , such as :",def normalize_ip ip theip ip if theip startswith theip 0 theip if theip endswith theip 0 segments theip split if len segments 1 raise ValueError no colons in ipv6 address repr ip fill 8 len segments if fill 0 raise ValueError ipv6 address has too many segments repr ip result for segment in segments if segment if fill 0 raise ValueError unexpected double colon repr ip for n in range fill 1 result append 0000 fill 0 else try int segment 16 except ValueError raise ValueError invalid hex value in repr ip result append segment rjust 4 0 return join result lower
encodes the given data in an encoding understood by the printer .,classmethod def to_bytes cls data u n Encodes the given data in an encoding understood by the printer n return text data encode cls ENCODING
sets the i'th entry of the c vector to a fixed value,def fixC self i value if self coeffPattern 2 None m n self m self n self coeffPattern 2 None m self coeffPattern 2 i value self _updateEstimatorSize i
get open i d connect token for default service account .,def get_service_account_token client_id bootstrap_credentials _ google auth default scopes IAM_SCOPE if isinstance bootstrap_credentials google oauth2 credentials Credentials raise Exception make_iap_request is only supported for service accounts elif isinstance bootstrap_credentials google auth app_engine Credentials requests_toolbelt adapters appengine monkeypatch bootstrap_credentials refresh Request signer_email bootstrap_credentials service_account_email if isinstance bootstrap_credentials google auth compute_engine credentials Credentials signer google auth iam Signer Request bootstrap_credentials signer_email else signer bootstrap_credentials signer service_account_credentials google oauth2 service_account Credentials signer signer_email token_uri OAUTH_TOKEN_URI additional_claims target_audience client_id return get_google_open_id_connect_token service_account_credentials
decorator generator that adds the cli help to the cli plugin based on the decorated function,def cli_plugin_add_help help def decorator func if not isinstance func CLIPluginFuncWrapper func CLIPluginFuncWrapper do_run func func set_help help return func return decorator
apply minimum image convention to an array of distance vectors .,def mic dr cell pbc None rec np linalg inv cell if pbc is not None rec np array pbc dtype int reshape 3 1 dri np round np dot dr rec return dr np dot dri cell
similar to python 's mktime but for utc,def mkUTC year month day hour min sec spec year month day hour min sec 0 0 0 utc time mktime spec time timezone return utc
alternative relu implementation . the most efficient one .,def relu__ x return T switch x 0 0 0 0 x
"load the train , valid , test label data for the dataset ` name ` and return it in ndarray format . this is only available for the toy dataset ule .",def load_ndarray_label name assert name in ule common_path os path join preprocess PYLEARN2_DATA_PATH UTLC filetensor name _ trname vname tename common_path subset tf for subset in trainl validl testl trainl load_filetensor trname validl load_filetensor vname testl load_filetensor tename return trainl validl testl
"instantiate a ` selector ( ) ` , hold - the - mayo please .",def test_instantiate_selector_defaults s selector Selector s mappings s prefix is None s parser __class__ is selector SimpleParser s wrap is None s consume_path is True
pass a jpeg file resource as an argument to the unit tests .,pytest fixture def image_file file os path join os path dirname __file__ test jpg return file
get a marker by identifier .,def marker self id return self _markers id
first value should be one if the offset is 25 % of period .,def test_sinus self N 200 x signalz sinus N period 100 delay 25 self assertEqual x 0 1 0
extremely basic test to ensure that belief / overview printing ( dumping ) do n't crash .,def test_dumps self sys stdout open os devnull w self pomdp belief_dump self pomdp pomdpenv print_summary sys stdout sys __stdout__
"create or append a logfile with name yyyy-mm.log as an excerpt of mediatum.log of lines beginning with period and containing the string ' info ' and containing one of the strings : ' get ' , ' post ' or ' head are excerpted usage : find /home / congkhacdung / logrotated/ -type f -iname ' mediatum.*.log ' | sort | xargs cat | python bin / stats.py --skip - ip 127.0.0.1 --skip - ip 129.187.87.37 2018 2",def main parser argparse ArgumentParser description Extract info needed for statistics parser add_argument skip ip dest skip_ip action append default help ip to skip parser add_argument year type int help year parser add_argument month type int help month args parser parse_args period 4 0 2 format args year args month skip_ip args skip_ip outdir os path join config get logging save config get logging path tmp match re compile period 17 INFO 2 GET POST HEAD format period period match lines sys stdin lines imap match lines lines ifilter None lines lines imap operator methodcaller groups lines skip_ip_pattern map 0 9 0 9 format skip_ip skip_ip_pattern join skip_ip_pattern match re compile skip_ip_pattern match lines ifilter lambda g not match g 2 lines lines imap operator concat lines repeat n lines imap join lines with tempfile NamedTemporaryFile dir outdir as tmpfile tmpfile writelines lines tmpfile close init full_init buildStatAll period tmpfile name
write qm atoms to an xyz file .,def WriteQM self filename qm xyz link False append False caption self _WriteSection filename self qatoms self latoms if link else self qatoms includeCharge False append append caption caption
store state as part of serialization / pickling .,def __getstate__ self return scopes self scopes id self service_account_id a_maker None if self make_token_async _make_token_async else self make_token_async retry_params self retry_params expiration_headroom self expiration_headroom
"run a step of the model feeding the given inputs . args : session : tensorflow session to use . encoder_inputs : list of numpy int vectors to feed as encoder inputs . decoder_inputs : list of numpy int vectors to feed as decoder inputs . target_weights : list of numpy float vectors to feed as target weights . bucket_id : which bucket of the model to use . forward_only : whether to do the backward step or only forward . returns : a triple consisting of gradient norm ( or none if we did not do backward ) , average perplexity , and the outputs . raises : valueerror : if length of encoder_inputs , decoder_inputs , or target_weights disagrees with bucket size for the specified bucket_id .",def step self session encoder_inputs decoder_inputs target_weights bucket_id forward_only encoder_size decoder_size self buckets bucket_id if len encoder_inputs encoder_size raise ValueError Encoder length must be equal to the one in bucket d d len encoder_inputs encoder_size if len decoder_inputs decoder_size raise ValueError Decoder length must be equal to the one in bucket d d len decoder_inputs decoder_size if len target_weights decoder_size raise ValueError Weights length must be equal to the one in bucket d d len target_weights decoder_size input_feed for l in xrange encoder_size input_feed self encoder_inputs l name encoder_inputs l for l in xrange decoder_size input_feed self decoder_inputs l name decoder_inputs l input_feed self target_weights l name target_weights l last_target self decoder_inputs decoder_size name input_feed last_target np zeros self batch_size dtype np int32 if not forward_only output_feed self updates bucket_id self gradient_norms bucket_id self losses bucket_id else output_feed self losses bucket_id for l in xrange decoder_size output_feed append self outputs bucket_id l outputs session run output_feed input_feed if not forward_only return outputs 1 outputs 2 None else return None outputs 0 outputs 1
l{isipaddress } should return c{true } for any decimal dotted representation of an ipv4 address .,def test_decimalDotted self self assertTrue isIPAddress 0 1 2 3 self assertTrue isIPAddress 252 253 254 255
register a listener function for the given target .,def listen target identifier fn args kw _event_key target identifier fn listen args kw
records ' timer ' and returns self as callable timer .,def wrap_timer self timer self saved_timer timer return self
> > > test_address(39 ) 39,cython locals x cython int y cython p_int def test_address x y cython address x return y 0
a function scheduled with l{ireactorthreads.callfromthread } invoked from a delayed call is run immediately in the next reactor iteration .,def test_delayedCallFromThread self reactor self buildReactor def threadCall reactor stop reactor callLater 0 reactor callFromThread threadCall before reactor seconds self runReactor reactor 60 after reactor seconds self assertTrue after before 30
test matching foo with child bar .,def test_locationFooBar self xp XPathQuery foo bar self assertEqual xp matches self e 1
"test array1 _ _ getitem _ _ method , out - of - range index",def testGetBad2 self self assertRaises IndexError self array1 __getitem__ self length 1
test matching foo with attribute .,def test_attribute self xp XPathQuery foo attrib1 self assertEqual xp matches self e True
test scale function with wrong dimensions,def testScaleWrongDim self print self typeStr end file sys stderr scale Matrix __dict__ self typeStr Scale matrix np array 1 2 2 1 self typeCode self assertRaises TypeError scale matrix
"parameter < func > must be a single - argument function that takes a sequence ( i.e. , a sample point ) and returns a boolean . this procedure calls < func > on each element in < data > and returns a list comprising elements for which < func > returns true .",def filter func data out for r in data if func r out append r return out
the protocol factory installs bootstrap event handlers on the protocol .,def test_buildProtocolInstallsBootstraps self called def cb data called append data self factory addBootstrap event myevent cb xs self factory buildProtocol None xs dispatch None event myevent self assertEqual 1 len called
"l{sshagentclient.addidentity } adds the private key it is called with to the ssh agent server to which it is connected , associating it with the comment it is called with .",def test_addDSAIdentityNoComment self d self client addIdentity self dsaPrivate privateBlob self pump flush def _check ignored serverKey self server factory keys self dsaPrivate blob self assertEqual self dsaPrivate serverKey 0 self assertEqual serverKey 1 return d addCallback _check
@param name : the name of the process to be started,def startProcess self name if name in self protocols return args uid gid env self processes name proto LoggingProtocol proto service self proto name name self protocols name proto self timeStarted name self _reactor seconds self _reactor spawnProcess proto args 0 args uid uid gid gid env env
return the peer from my session 's transport .,def getPeer self return self session conn transport getPeer
the callable passed as the value for the c{pumppolicy } parameter to l{loopbackasync } is called with a l{_loopbackqueue } of pending bytes and a protocol to which they should be delivered .,def test_pumpPolicy self pumpCalls def dummyPolicy queue target bytes while queue bytes append queue get pumpCalls append target bytes client Protocol server Protocol finished loopback loopbackAsync server client dummyPolicy self assertEqual pumpCalls client transport write foo client transport write bar server transport write baz server transport write quux server transport loseConnection def cbComplete ignored self assertEqual pumpCalls client baz quux None server foo bar finished addCallback cbComplete return finished
take a list with annotated genetic inheritance patterns for each family and returns a dictionary with family_id as key and a list of genetic models as value .,def build_models_dict annotated_models logger getLogger __name__ logger debug Parsing models 0 format annotated_models parsed_models for family_annotation in annotated_models family_id family_annotation split 0 logger debug Parsing family 0 format family_id models family_annotation split 1 split parsed_models family_id models logger debug Adding models 0 format models return parsed_models
: param widget : the gtk window : param event : : param pipeline : the gst pipeline : return : nothing,def window_closed widget event pipeline widget hide pipeline set_state Gst State NULL Gtk main_quit
take a class with a `` .caller `` method and return a callable decorator object . it works by adding a suitable _ _ call _ _ method to the class ; it raises a typeerror if the class already has a nontrivial _ _ call _ _ method .,def decorator_factory cls attrs set dir cls if __call__ in attrs raise TypeError You cannot decorate a class with a nontrivial __call__ method if call not in attrs raise TypeError You cannot decorate a class without a call method cls __call__ __call__ return cls
"by default , the distribution tools ignore all non - python files .",def package_data file_set for root dirs files in os walk evennia for f in files if git in f split os path normpath os path join root f continue file_name os path relpath os path join root f evennia file_set append file_name return file_set
this is a shortcut instad of calling msg ( ) directly on an object - it will detect if caller is an object or a player and also appends self.sessid automatically .,def msg self msg to_obj None from_obj None sessid None all_sessions False kwargs from_obj from_obj or self caller to_obj to_obj or from_obj if not sessid if hasattr to_obj sessid toobj_sessions to_obj sessid get session_tosend None if len toobj_sessions 1 session_tosend toobj_sessions 0 sessid all_sessions and None or session_tosend elif to_obj self caller sessid all_sessions and None or self sessid else sessid None to_obj msg msg from_obj from_obj sessid sessid kwargs
add or update this : class:`webhook `,def save self if webhook_id not in self _dict return self _add else return self _update
"operator = "" + "" / "" - "" / "" * "" / "" / """,def operator self node children operator operators op add op sub op mul op truediv return operators node text
get a list of currently watched url on the given channel .,def watchedon channel res list for site in DATAS getNodes watch if site hasNode alert for a in site getNodes alert if a channel channel res append s s site url site type break return res
"once a beacon has been verified , place it into the right containers .",def _handle_verified_beacon self pcb with self _rev_seg_lock self beacons add_segment pcb self up_segments add_segment pcb self down_segments add_segment pcb
wrapper around posturl for mulitple arguments,def postURLHelper args postURL args
convert a python object into php serialized code string .,def py2php python_var serialized phpserialize dumps python_var charset encoding default_encoding errors encoding default_errors serialized encoding decode serialized encoded Encode serialized php_loader raw_php_var unserialize s encoded return raw_php_var
"disconnects non critical signals like notifications , websockets and stuff like that . use when managing large chunks of nodes",def pause_disconnectable_signals for signal in DISCONNECTABLE_SIGNALS signal disconnect
usage : spline = bpy.data.curves[0].splines[0 ] points = get_points(spline ),def get_points spline clean True knots spline bezier_points if len knots 2 return r spline resolution_u 1 segments len knots if not spline use_cyclic_u segments 1 master_point_list for i in range segments inext i 1 len knots knot1 knots i co handle1 knots i handle_right handle2 knots inext handle_left knot2 knots inext co bezier knot1 handle1 handle2 knot2 r points interpolate_bezier bezier master_point_list extend points if clean old master_point_list good v for i v in enumerate old 1 if not old i old i 1 good append old 1 return good Edges i i 1 for i in range n_verts 1 if spline use_cyclic_u Edges append i 0 return master_point_list Edges
options used to profile trainable variable parameters .,staticmethod def trainable_variables_parameter return max_depth 10000 min_bytes 0 min_micros 0 min_params 0 min_float_ops 0 min_occurrence 0 order_by name account_type_regexes tfprof_logger TRAINABLE_VARIABLES start_name_regexes trim_name_regexes show_name_regexes hide_name_regexes account_displayed_op_only True select params step 1 output stdout
effective method for printing an error message and having it return the correct error .,def error_print retval the_string check_script_name print s ERROR d SCRIPT_NAME retval print the_string sys stdout flush debug_print debug_print s SCRIPT FAIL SCRIPT_NAME debug_print sys exit retval
"intersectionlines2(p1,v1,p2,v2 ) returns the intersection between one line and the plane that includes the second line and orthogonal to the plane defined by both lines . p1,v1 : the reference point and direction of first line p2,v2 : the reference point and direction of second line",def intersectionLines2 p1 None v1 None p2 None v2 None if None in p1 p2 v1 v2 p1 edges 0 valueAt 0 v1 edges 0 tangentAt 0 p2 edges 1 valueAt 0 v2 edges 1 tangentAt 0 if isParallel v1 v2 FreeCAD Console PrintError Directions are pallel n return None else dist p1 p2 norm v2 cross dist cross v1 return p1 projectToPlane p2 norm
used to replace an attribute the library that : func:`dist.load ` returns . useful for replacing part of the compiled library as part of the test .,def mock_library attributes ffi library dist load return patch object dist load lambda ffi LibraryWrapper library attributes
internal worker for enabling / disabling pretty - printers .,def do_enable_pretty_printer arg flag object_re name_re subname_re parse_printer_regexps arg total 0 if object_re match global total do_enable_pretty_printer_1 gdb pretty_printers name_re subname_re flag cp gdb current_progspace if object_re match progspace total do_enable_pretty_printer_1 cp pretty_printers name_re subname_re flag for objfile in gdb objfiles if object_re match objfile filename total do_enable_pretty_printer_1 objfile pretty_printers name_re subname_re flag if flag state enabled else state disabled print d s s total pluralize printer total state show_pretty_printer_enabled_summary
get a list of volume types .,rest_utils ajax def get self request result api cinder volume_type_list request return items api cinder VolumeType u to_dict for u in result
converts datetime value to string .,def datetime_to_str val sep if isinstance val datetime datetime return val isoformat sep return val
validate a specific logging type on a specific port,def validate_log_type_for_port log_type port log_plugin directory get_plugin alias plugin_const LOG_API drivers log_plugin driver_manager drivers port_binding utils get_port_binding_by_status_and_host port bindings constants ACTIVE raise_if_not_found True port_id port id for driver in drivers vif_type port_binding vif_type if vif_type not in SKIPPED_VIF_TYPES if not _validate_vif_type driver vif_type port id continue else vnic_type port_binding vnic_type if not _validate_vnic_type driver vnic_type port id continue if driver is_logging_type_supported log_type return True return False
n344 - use list comprehension instead of filter(lambda ) .,flake8ext def check_python3_no_filter logical_line msg N344 Use list comprehension instead of filter lambda obj test obj data on python3 if filter_match match logical_line yield 0 msg
converts octavia wsme type to dictionary .,def to_dict self render_unsets False if hasattr self project_id and hasattr self tenant_id if isinstance self project_id wtypes UnsetType and not isinstance self tenant_id wtypes UnsetType self project_id self tenant_id wsme_dict for attr in dir self if attr startswith _ continue value getattr self attr None if attr tenant_id continue if value and callable value continue if value and isinstance value BaseType value value to_dict render_unsets render_unsets if value and isinstance value list value val to_dict render_unsets render_unsets if isinstance val BaseType else val for val in value if isinstance value wtypes UnsetType if render_unsets value None else continue wsme_dict attr value return self translate_dict_keys_to_data_model wsme_dict
deletes an l3 metering label .,def delete_metering_label self metering_label_id uri metering metering labels s metering_label_id return self delete_resource uri
check role of a user on a project .,def check_user_role_existence_on_project self project_id user_id role_id resp body self head projects s users s roles s project_id user_id role_id self expected_success 204 resp status return rest_client ResponseBody resp
a function for returning doctor alarm event generators .,def simple_doctor_alarm_generators update_vals None return _simple_alarm_generators Doctor tg TRANS_DOCTOR_UPDATE_D update_vals
test whether ovk . ovkridge is a valid sklearn estimator .,def test_valid_estimator from sklearn import __version__ if LooseVersion __version__ LooseVersion 0 18 check_estimator ovk OVKRidge else warn sklearn s check_estimator seems to be broken in __version__ 0 17 x skipping
assigns the database instance that this connection serves .,def setDatabase self db self __database db
check if we match ' dtype ' .,classmethod def is_dtype cls dtype dtype getattr dtype dtype dtype if isinstance dtype np dtype return False elif dtype is None return False elif isinstance dtype cls return True try return cls construct_from_string dtype is not None except TypeError return False
"return the next `` n `` bytes of the message ( as a ` str ` ) , without decomposing into an int , decoded string , etc . just the raw bytes are returned . returns a string of `` n `` zero bytes if there were n't `` n `` bytes remaining in the message .",def get_bytes self n b self packet read n max_pad_size 1 20 if len b n max_pad_size return b zero_byte n len b return b
"calculates the kelvin radius of the pore , using the standard form of the kelvin equation .",def kelvin_radius_std pressure meniscus_geometry temperature liquid_density adsorbate_molar_mass adsorbate_surface_tension if meniscus_geometry cylinder geometry_factor 1 0 elif meniscus_geometry sphere geometry_factor 2 0 elif meniscus_geometry slit geometry_factor 0 5 adsorbate_molar_density adsorbate_molar_mass liquid_density coefficient geometry_factor adsorbate_surface_tension adsorbate_molar_density scipy constants gas_constant temperature radius coefficient numpy log pressure return radius
"compute all orderings of m elements with values between [ 0 , k-1 ] : param k : number of alpha - vectors : param m : number of observations : return : list of lists , where each list contains m elements , and each element is in [ 0 , k-1 ] . total should be k^m elements",staticmethod def compute_indices k m x list range k return p for p in product x repeat m
adds an action to be called when this end has no ongoing operations .,abc abstractmethod def add_idle_action self action raise NotImplementedError
create schedule token for a given workflow .,abc abstractmethod def get_schedule_token self workflow return
test that request validation finds and validates parametrized paths even when the api has a base path .,def test_response_validation_with_parametrized_path_and_api_base_path schema SchemaFactory basePath api v1 paths get id get responses 200 description Success parameters name id in PATH description The Primary Key type INTEGER required True response ResponseFactory url http www example com api v1 get 1234 validate_response response response request_method get schema schema
transform features of a table to types with internal support .,def internalize_table table feature_types np array _INTERNALIZE ty for ty in table feature_types np int8 for v old new in enumerate zip table feature_types feature_types TODO
"return the directory job "" i d "" was run in using squeue .",def job_rundir jobid rundir dict if isinstance jobid list for i in jobid stdout _squeue jobid i full True match re search WorkDir stdout rundir i match group 1 else stdout _squeue jobid jobid full True match re search WorkDir stdout rundir i match group 1 return rundir
true if this entry represents a class of effective tlds .,def wild self return self _wild
loading an access point from file,def load self name _fileini defAP json self _fileini _fileini fileini pyu getlong _fileini pstruc DIRSIMUL fp open fileini r ap json load fp self name name dap ap name self p eval dap pos wstd dap wstd self PtdBm dap ptdbm self channels eval dap chan self sensdBm dap snsdbm self nant dap nant standard Wstandard wstd self s standard fp close
delete `` name `` from the environment . raise keyerror it does not exist .,def delenv self name raising True self delitem os environ name raising raising
check if a block can be crawled .,twisted_wrapper def test_crawl self self nodes 1 overlay should_sign lambda x False yield self introduce_nodes self nodes 0 endpoint close my_pubkey self nodes 0 my_peer public_key key_to_bin his_pubkey self nodes 0 network verified_peers 0 public_key key_to_bin self nodes 0 overlay sign_block self nodes 0 network verified_peers 0 public_key his_pubkey transaction yield self deliver_messages self assertIsNone self nodes 1 overlay persistence get my_pubkey 1 self nodes 0 endpoint open self nodes 1 overlay send_crawl_request self nodes 0 my_peer my_pubkey 1 yield self deliver_messages self assertIsNotNone self nodes 1 overlay persistence get my_pubkey 1 self assertEqual self nodes 1 overlay persistence get my_pubkey 1 link_sequence_number UNKNOWN_SEQ
"change the support of the window , returning a new window .",def resize self support return ResampleWindow self kind support
fetch an output from the designated stack .,def handler value provider None context None kwargs if provider is None raise ValueError Provider is required if context is None raise ValueError Context is required d deconstruct value stack_fqn context get_fqn d stack_name output provider get_output stack_fqn d output_name return output
"send in an sql cursor that 's the entire result of a query that has 2 columns : ' rating ' and ' count ' . uses "" rating_map "" from config to map each rating tier 's to the fraction of point(s ) it should get . returns a set : ( points , potential_points )",def rating_calculator ratings point_map config get rating_map points 0 0 potential_points 0 0 for row in ratings tier_points 0 potential_points row count for tier in point_map if row rating tier threshold tier_points row count tier points points tier_points points min potential_points max 0 points return points potential_points
hook to pass arguments to the command interpreter,def getInterpreterArgs self if hasattr self interpreterArgs return self interpreterArgs return self classprefs interpreter_args
for backwards compatilibity with pubsub v1 ( wxpython ) .,def __call__ self return self
special case to add the unique_keywords dict to the list of imports,def replaceImports self extra from peppy editra style_specs import unique_keywords try self header index extra except ValueError dprint Replacing imports for s self lang index self header index from peppy fundamental import self header self header 0 index extra n self header index
"create a configuration for kubernetes based on path using the supplied arguments for values of the kubernetes server , ca , key , certificate , user context and cluster .",def create_kubeconfig kubeconfig server ca key None certificate None user ubuntu context juju context cluster juju cluster password None token None if not key and not certificate and not password and not token raise ValueError Missing authentication mechanism if token and password raise ValueError Token and Password are mutually exclusive cmd kubectl config kubeconfig 0 set cluster 1 server 2 certificate authority 3 embed certs true check_call split cmd format kubeconfig cluster server ca cmd kubectl config kubeconfig 0 unset users check_call split cmd format kubeconfig cmd kubectl config kubeconfig 0 set credentials 1 format kubeconfig user if key and certificate cmd 0 client key 1 client certificate 2 embed certs true format cmd key certificate if password cmd 0 username 1 password 2 format cmd user password if token cmd 0 token 1 format cmd token check_call split cmd cmd kubectl config kubeconfig 0 set context 1 cluster 2 user 3 check_call split cmd format kubeconfig context cluster user cmd kubectl config kubeconfig 0 use context 1 check_call split cmd format kubeconfig context
"given a cgal circulator , loop once through it , yielding elements as if it were an iterator .",def circ_to_gen circ repeat_start False elt0 circ next yield elt0 while True eltN circ next if eltN elt0 if repeat_start yield eltN return yield eltN
return list of chromsome and their sizes as in the wig file .,property def get_chromosomes self return self wig chroms
number of citations for specified years .,property def rangeCount self return self citeInfoMatrix get rangeCount
"` objs ` is a list of ( obj_id , simhash ) obj_id is a string , simhash is an instance of simhash ` f ` is the same with the one for simhash ` k ` is the tolerance",def __init__ self objs f 64 k 2 u n objs is a list of obj_id simhash n obj_id is a string simhash is an instance of Simhash n f is the same with the one for Simhash n k is the tolerance n self k k self f f count len objs logging info u Initializing s data count self bucket collections defaultdict set for i q in enumerate objs if i 10000 0 or i count 1 logging info u s s i 1 count self add q
testing dump and load of timeone types .,unittest skipIf sys version_info 3 0 not supported in Python2 def test_dumps_timezone self try _build_test_dirs dicti utctimezone datetime timezone utc array 1 2 3 string trololo int 1 float 4 32 true True false False null None with open _TEST_FILE w as fileobj morejson dump dicti fileobj with open _TEST_FILE r as fileobj self assertEqual dicti morejson load fileobj finally _dismantle_test_dirs
return this player 's view of the room they are in .,def look_at_room self title room_title_color self location name clear_fcolor if self mode and self mode name BuildMode title s id s s s s s s room_id_color self location id self location area name clear_fcolor room_title_color self location name clear_fcolor exit_list key for key value in self location exits items if value None xits exits None if exit_list xits exits join exit_list xits room_exit_color xits clear_fcolor players for player in self location players values if player name self name position is here if player position 0 sleeping if player position 1 position is here sleeping on s player position 1 name else position is here sleeping on the floor elif player position 0 sitting if player position 1 position is here sitting on s player position 1 name else position is here sitting on the floor players player_color player fancy_name position clear_fcolor n npcs for npc in self location npcs npcs npc_color npc title clear_fcolor n items for item in self location items if item title items item_color item title clear_fcolor n desc room_body_color self location description clear_fcolor look s n s n s n s s s title xits desc items npcs players return look
"function [ n ] = faceinfo(y , a , b , c , d )",def faceInfo xyz A B C D average True normalizeNormals True assert type average is bool average must be a boolean assert type normalizeNormals is bool normalizeNormals must be a boolean AB xyz B xyz A BC xyz C xyz B CD xyz D xyz C DA xyz A xyz D def cross X Y return np c_ X 1 Y 2 X 2 Y 1 X 2 Y 0 X 0 Y 2 X 0 Y 1 X 1 Y 0 nA cross AB DA nB cross BC AB nC cross CD BC nD cross DA CD length lambda x np sqrt x 0 2 x 1 2 x 2 2 normalize lambda x x np kron np ones 1 x shape 1 mkvc length x 2 if average N nA nB nC nD 4 N normalize N elif normalizeNormals N normalize nA normalize nB normalize nC normalize nD else N nA nB nC nD area length nA length nB length nC length nD 4 return N area
parse .input ( ) and .output ( ) directives,def parse_inout s shape var type_ tuple c strip for c in s split if in type_ raise ValueError Failed to parse List lengths are not yet supported format s from tensorflow python framework dtypes import _STRING_TO_TF _TYPE_TO_STRING _TF_TO_NP TF_TYPES _TYPE_TO_STRING values tf_type tensorflow type_ if type_ in TF_TYPES else type_ np_type np _TF_TO_NP _STRING_TO_TF type_ __name__ if type_ in _STRING_TO_TF else type_ shape 1024 if shape is None else shape return InOut var type_ tf_type np_type shape
set terminal status line : request to send,def setRTS self level True if not self _isOpen raise portNotOpenError if self logger self logger info ignored setRTS r level
"accepts the root directory of a pypi package and returns its requirements extracted from its setup.py returns [ ] , { '' , none }",def requirements_from_setup_py rootdir setup_dict err setup_py setup_info_dir rootdir if err is not None return None err reqs if install_requires in setup_dict req_strs setup_dict install_requires for req_str in req_strs reqs append SetupToolsRequirement pr Requirement parse req_str return reqs None
initialize the weights by calculating the range of the data .,def range_initialization X num_weights X_ X reshape 1 X shape 1 min_val max_val X_ min 0 X_ max 0 data_range max_val min_val return data_range np random rand num_weights X shape 1 min_val
disables a snap in the system,def disable snapname hookenv log Disabling snap format snapname if not reactive is_flag_set snap installed format snapname hookenv log Cannot disable snap because it is not installed format snapname hookenv WARNING return subprocess check_call snap disable snapname universal_newlines True reactive set_flag snap disabled format snapname
convert internal value to `` float `` .,def to_representation self value return float value
prints the message on the terminal .,def info msg styles click secho msg styles
put an openai gym environment into the tensorflow graph .,def __init__ self env self _env env observ_shape self _parse_shape self _env observation_space observ_dtype self _parse_dtype self _env observation_space action_shape self _parse_shape self _env action_space action_dtype self _parse_dtype self _env action_space with tf name_scope environment self _observ tf Variable tf zeros observ_shape observ_dtype name observ trainable False self _action tf Variable tf zeros action_shape action_dtype name action trainable False self _reward tf Variable 0 0 dtype tf float32 name reward trainable False self _done tf Variable True dtype tf bool name done trainable False self _step tf Variable 0 dtype tf int32 name step trainable False
gets all records recursively for some topdir .,def GetFilesRecursively topdir assert topdir topdir os path expanduser topdir allpaths for path _ leaffiles in tf gfile Walk topdir if leaffiles allpaths extend os path join path i for i in leaffiles if not allpaths raise ValueError No files found for top directory s topdir return allpaths
embeds x using standard cnn architecture .,def core_builder self x ch1 32 2 ch2 64 2 conv1_weights tf get_variable conv1_w 3 3 self num_channels ch1 initializer self matrix_init conv1_biases tf get_variable conv1_b ch1 initializer self vector_init conv1a_weights tf get_variable conv1a_w 3 3 ch1 ch1 initializer self matrix_init conv1a_biases tf get_variable conv1a_b ch1 initializer self vector_init conv2_weights tf get_variable conv2_w 3 3 ch1 ch2 initializer self matrix_init conv2_biases tf get_variable conv2_b ch2 initializer self vector_init conv2a_weights tf get_variable conv2a_w 3 3 ch2 ch2 initializer self matrix_init conv2a_biases tf get_variable conv2a_b ch2 initializer self vector_init fc1_weights tf get_variable fc1_w self image_size 4 self image_size 4 ch2 self hidden_dim initializer self matrix_init fc1_biases tf get_variable fc1_b self hidden_dim initializer self vector_init x tf reshape x 1 self image_size self image_size self num_channels batch_size tf shape x 0 conv1 tf nn conv2d x conv1_weights strides 1 1 1 1 padding SAME relu1 tf nn relu tf nn bias_add conv1 conv1_biases conv1 tf nn conv2d relu1 conv1a_weights strides 1 1 1 1 padding SAME relu1 tf nn relu tf nn bias_add conv1 conv1a_biases pool1 tf nn max_pool relu1 ksize 1 2 2 1 strides 1 2 2 1 padding SAME conv2 tf nn conv2d pool1 conv2_weights strides 1 1 1 1 padding SAME relu2 tf nn relu tf nn bias_add conv2 conv2_biases conv2 tf nn conv2d relu2 conv2a_weights strides 1 1 1 1 padding SAME relu2 tf nn relu tf nn bias_add conv2 conv2a_biases pool2 tf nn max_pool relu2 ksize 1 2 2 1 strides 1 2 2 1 padding SAME reshape tf reshape pool2 batch_size 1 hidden tf matmul reshape fc1_weights fc1_biases return hidden
labels as true / false positives detection tuples across all classes .,def _compute_tp_fp self detected_box_tuples detected_scores detected_class_tuples groundtruth_box_tuples groundtruth_class_tuples unique_gt_tuples np unique np concatenate groundtruth_class_tuples detected_class_tuples result_scores result_tp_fp_labels result_mapping for unique_tuple in unique_gt_tuples detections_selector detected_class_tuples unique_tuple gt_selector groundtruth_class_tuples unique_tuple selector_mapping np where detections_selector 0 detection_scores_per_tuple detected_scores detections_selector detection_box_per_tuple detected_box_tuples detections_selector sorted_indices np argsort detection_scores_per_tuple sorted_indices sorted_indices 1 tp_fp_labels self _compute_tp_fp_for_single_class detected_box_tuples detection_box_per_tuple sorted_indices groundtruth_box_tuples groundtruth_box_tuples gt_selector result_scores append detection_scores_per_tuple sorted_indices result_tp_fp_labels append tp_fp_labels result_mapping append selector_mapping sorted_indices if result_scores result_scores np concatenate result_scores result_tp_fp_labels np concatenate result_tp_fp_labels result_mapping np concatenate result_mapping else result_scores np array dtype float result_tp_fp_labels np array dtype bool result_mapping np array dtype int sorted_indices np argsort result_scores sorted_indices sorted_indices 1 return result_scores sorted_indices result_tp_fp_labels sorted_indices result_mapping sorted_indices
writes processed wav files to disk as sharded tfrecord files .,def create_tfrecord_from_wavs wavs output_file with tf python_io TFRecordWriter output_file as builder for wav in wavs builder write wav astype np float32 tobytes
converts 6dof transform vector to transformation matrix .,def _egomotion_vec2mat vec batch_size translation tf slice vec 0 0 1 3 translation tf expand_dims translation 1 rx tf slice vec 0 3 1 1 ry tf slice vec 0 4 1 1 rz tf slice vec 0 5 1 1 rot_mat _euler2mat rz ry rx rot_mat tf squeeze rot_mat squeeze_dims 1 filler tf constant 0 0 0 0 0 0 1 0 shape 1 1 4 filler tf tile filler batch_size 1 1 transform_mat tf concat rot_mat translation axis 2 transform_mat tf concat transform_mat filler axis 1 return transform_mat
preprocesses the given image for training .,def preprocess_for_train image output_height output_width resize_side_min _RESIZE_SIDE_MIN resize_side_max _RESIZE_SIDE_MAX resize_side tf random_uniform minval resize_side_min maxval resize_side_max 1 dtype tf int32 image _aspect_preserving_resize image resize_side image _random_crop image output_height output_width 0 image set_shape output_height output_width 3 image tf to_float image image tf image random_flip_left_right image return _mean_image_subtraction image _R_MEAN _G_MEAN _B_MEAN
greatest common divisor using euclid 's algorithm .,def gcd a b while a a b b a a return b
sets default values for options .,def initialize_options self self restructuredtext 0 self metadata 1 self strict 0 self _warnings 0
encode a string with base64 .,def body_encode s maxlinelen 76 eol NL Encode a string with base64 Each line will be wrapped at at most maxlinelen characters defaults to 76 characters Each line of encoded text will end with eol which defaults to n Set this to r n if you will be using the result of this function directly in an email if not s return s encvec max_unencoded maxlinelen 3 4 for i in range 0 len s max_unencoded enc b2a_base64 s i i max_unencoded decode ascii if enc endswith NL and eol NL enc enc 1 eol encvec append enc return EMPTYSTRING join encvec
lookup name in a namespace spanning sys.modules and _ _ main.dict__.,def get_entity self name if name namespace sys modules copy namespace update __main__ __dict__ try return eval name namespace except NameError AttributeError return None
"hook method executed just before the command line is interpreted , but after the input prompt is generated and issued .",def precmd self line return line
write a prompt and read a line .,def raw_input self prompt return input prompt
"initialize an ordered dictionary . signature is the same as for regular dictionaries , but keyword arguments are not recommended because their insertion order is arbitrary .",def __init__ self args kwds if len args 1 raise TypeError expected at most 1 arguments got d len args try self __root except AttributeError self __root root root root root None self __map self __update args kwds
stand - in for dict.get .,staticmethod def get key default None raise KeyError Cannot get r default r on a future key default
restore state as part of deserialization / unpickling .,def __setstate__ self state self __init__ state scopes service_account_id state id token_maker state a_maker retry_params state retry_params self expiration_headroom state expiration_headroom
turn a match in the form = ab to the ascii character with value 0xab,def _unquote_match match u s match group 0 return unquote s
should abort when no nodes with given role found in the environment,raises SystemExit def test_nodes_with_role_in_env_not_found self runner env chef_environment production runner nodes_with_role base
"run the layer comparison on one of the known caffe models . : param model_name : available models are listed in convert_caffe_modelzoo.py : param image_url : image file or url to run inference on : param gpu : gpu to use , -1 for cpu",def test_model_weights_and_outputs model_name image_url gpu logging info test weights and outputs of model s model_name meta_info get_model_meta_info model_name prototxt caffemodel mean download_caffe_model model_name meta_info dst_dir model convert_and_compare_caffe_to_mxnet image_url gpu prototxt caffemodel mean mean_diff_allowed 0 001 max_diff_allowed 0 1 return
returns the number of fibers in this file .,property def fiber_count self if self _fiber_count is None self _fiber_count self header 1 NAXIS2 return self _fiber_count
return nicely formatted repr string .,def __repr__ self return FixedOffset r self __name
called when a coin is added to this thing .,def coinAdded self coin self _currencyCounter 1 if self _currencyCounter 5 and self getContents self _currencyCounter 0 try obj iter self getContents next except StopIteration evt events Success actor self thing target obj otherMessage language Sentence self thing thumps loudly else evt events Success actor self thing target obj otherMessage language Sentence language Noun self thing definiteNounPhrase thumps loudly and spits out obj onto the ground state self closed self closed False try obj moveTo self thing location finally self closed state evt broadcast
calculates the k value for attached probe parameters calibration solution in ms,def do_calk self solution_mS if solution_mS ec calculateK float solution_mS ec tempCoefEC print tK str ec getK
"initialize resource , inferring whichever information was not provided ( e.g. verbose name , endpoint ) .",classmethod def initialize cls cls name cls name or cls __name__ cls endpoint cls endpoint or cls name lower return cls
test basic bit message encoding / decoding,def test_big_endian_payload_decoder self decoder BinaryPayloadDecoder self big_endian_payload endian Endian Big self assertEqual 1 decoder decode_8bit_uint self assertEqual 2 decoder decode_16bit_uint self assertEqual 3 decoder decode_32bit_uint self assertEqual 4 decoder decode_64bit_uint self assertEqual 1 decoder decode_8bit_int self assertEqual 2 decoder decode_16bit_int self assertEqual 3 decoder decode_32bit_int self assertEqual 4 decoder decode_64bit_int self assertEqual 1 25 decoder decode_32bit_float self assertEqual 6 25 decoder decode_64bit_float self assertEqual test decoder decode_string 4 self assertEqual self bitstring decoder decode_bits
od.__iter _ _ ( ) < = = > iter(od ),def __iter__ self root self __root curr root 1 while curr is not root yield curr 2 curr curr 1
register a sub - notifier to get the remote callback 's via our local delivery .,def registerNotifier self event notif nlist self notifiers get event nlist append notif
"tup - ( a , t )",def HPERM_OP tup n m a t tup t a 16 n a m a a t t 16 n return a t
computes the dot product between a matrix and a vector .,def dot matrix vector matrix_ty vector_ty weld_obj WeldObject encoder_ decoder_ matrix_var weld_obj update matrix if isinstance matrix WeldObject matrix_var matrix obj_id weld_obj dependencies matrix_var matrix vector_var weld_obj update vector loopsize_annotation if isinstance vector WeldObject vector_var vector obj_id weld_obj dependencies vector_var vector if isinstance vector np ndarray loopsize_annotation loopsize dL len vector weld_template map matrix s row vec matrix_ty s result loopsize_annotation s for result loopsize_annotation s for zip row vector s appender b2 i2 e2 matrix_ty s vector_ty s merge b2 f64 e2 0 matrix_ty s e2 1 merger f64 b i e merge b e weld_obj weld_code weld_template matrix matrix_var vector vector_var matrix_ty matrix_ty vector_ty vector_ty loopsize_annotation loopsize_annotation return weld_obj
tests accepting a user submitted exercise as a regular user,def test_accept_user self self user_login test self accept fail True
sets up test server and database and loops over handling http requests .,def run self try handler basehttp AdminMediaHandler WSGIHandler httpd None while httpd is None try server_address self address self port httpd StoppableWSGIServer server_address basehttp WSGIRequestHandler except basehttp WSGIServerException as e if Address already in use in str e self port 1 else raise e httpd set_app handler self started set except basehttp WSGIServerException as e self error e self started set return from django conf import settings create_db False if hasattr settings DATABASES and settings DATABASES if settings DATABASES default ENGINE django db backends sqlite3 or settings DATABASES default TEST_NAME create_db True elif settings DATABASE_ENGINE if settings DATABASE_ENGINE sqlite3 and not settings TEST_DATABASE_NAME or settings TEST_DATABASE_NAME memory create_db True if create_db from django db import connection db_name connection creation create_test_db 0 if hasattr self fixtures call_command loaddata self fixtures verbosity 1 while not self _stopevent isSet httpd handle_request httpd server_close
store a file in a given location,def store self filepointer location raise NotImplementedError
"sends input to the remote terminal , but does n't check for a return code",def sendInput self input realOutput self __runCmd input return output realOutput return 0
parses the header_plus block of text ( the headers plus the first line of the request ) .,def parse_header self header_plus index header_plus find n if index 0 first_line header_plus index rstrip header header_plus index 1 else first_line header_plus rstrip header self first_line first_line lines get_header_lines header headers self headers for line in lines index line find if index 0 key line index value line index 1 strip key1 tostr key upper replace _ try headers key1 tostr value except KeyError headers key1 tostr value command uri version crack_first_line first_line version tostr version command tostr command self command command self version version self proxy_scheme self proxy_netloc self path self query self fragment split_uri uri self url_scheme self adj url_scheme connection headers get CONNECTION if version 1 0 if connection lower keep alive self connection_close True if version 1 1 te headers pop TRANSFER_ENCODING if te lower chunked self chunked True buf OverflowableBuffer self adj inbuf_overflow self body_rcv ChunkedReceiver buf expect headers get EXPECT lower self expect_continue expect 100 continue if connection lower close self connection_close True if not self chunked try cl int headers get CONTENT_LENGTH 0 except ValueError cl 0 self content_length cl if cl 0 buf OverflowableBuffer self adj inbuf_overflow self body_rcv FixedStreamReceiver cl buf
"method can be one of [ ' max ' , ' mean ' , ' max_pca ' , ' mean_pca ' ]",def shape_map self pred method if method max shape vectorize get_index pred shape shape 4 elif method mean shape vectorize get_index_mean pred shape shape 4 elif method max_pca shape vectorize get_index pred shape shape 4 shape self pca_noise_reduction shape elif method mean_pca shape vectorize get_index_mean pred shape shape 4 shape_pca self pca_noise_reduction shape if p debug show_predict self img shape show_predict self img shape_pca else print Unknown method method exit 0 return shape
returns a collector populated with metrics from the services found at the given root device url .,def probe target_url device probe_device target_url return Collector device
test that reviewers can only do one review per proposal,def test_only_one_review_per_reviewer_per_proposal self app db_session p1 PersonFactory roles RoleFactory name reviewer p2 PersonFactory prop ProposalFactory people p2 ProposalStatusFactory name Withdrawn db_session commit do_login app p1 resp app get proposal d review prop id f resp form f review comment first_review_comment resp f submit f review comment second_review_comment resp f submit resp resp follow db_session expunge_all revs Review find_all assert len revs 1 assert revs 0 comment second_review_comment
wsgi application level functional testing .,fixture scope session def app app_settings from encoded import main return main app_settings
generates all matches of regex in string s.,def _FindAllMatches regex s r re compile regex return r finditer s
a function which takes a dictionary with structure of the plos results and transform it to a standardized format .,def to_dataframe self raw_article raw_article author raw_article get author_display None try raw_article abstract raw_article get abstract None 0 except IndexError raw_article abstract None raw_article date int raw_article get publication_date 0 split 0 raw_article journal raw_article get journal None raw_article provenance PLOS raw_article score raw_article get score None raw_article title raw_article get title_display None raw_article key raw_article unique_key self create_keys raw_article return self dict_to_dataframe raw_article
attempts to find the nltk tree reader for various versions of nltk . returns false if it fails or a function which takes a string and returns an nltk tree object otherwise .,def get_nltk_tree_reader_maybe try import nltk tree import nltk draw tree return nltk tree Tree parse except ImportError return False except AttributeError try return nltk tree Tree fromstring except AttributeError return False
remove all items from multidict .,def clear self self _impl _items clear self _impl incr_version
sql query for queen neighbors . @param params dict : information to fill query,def queen params attr_select query_attr_select params attr_where query_attr_where params replacements attr_select attr_select attr_where_i attr_where replace idx_replace i attr_where_j attr_where replace idx_replace j query SELECT i id_col As id attr_select s SELECT ARRAY SELECT j id_col FROM subquery As j WHERE i id_col j id_col AND ST_Touches i geom_col j geom_col AND attr_where_j s As neighbors FROM subquery As i WHERE attr_where_i s ORDER BY i id_col ASC replacements return query format params
"returns the ( x , y ) projection constants for the current projection . : return : x , y tuple projection constants",property def projection_constants self return self far self far self near self far self near self near self far
return the numerical value of token.value if it is a number,def numval token if token type INTEGER return int token value elif token type FLOAT return float token value else return token value
used to stop the motorcontrol program . all this actually does is stop the currently running rxe .,def stop self self brick stop_program
provide access to the gui data widows,property def data_windows self return self _data_windows
creates a sound file name for the specified clip .,def get_file_name self clip station_name clip station name mic_output_name _get_mic_output_name clip detector_name _get_detector_name clip start_time _format_start_time clip return _ _ _ wav format station_name mic_output_name detector_name start_time
execute the search and return results .,def execute self options options content_type application json uri resources search return api call_json_api post uri self as_dict options
create a graphic circle on the board,def add_circle self center radius layer F SilkS width 0 15 return self add drawing Circle center radius layer width board self
set the renderer 's current section .,def _set_section self section if self section section if self section section raise dns_exception FormError self section section
set of tags that have been applied to the test,def tags node try value node get tags if isinstance value str unicode return value return set value except KeyError return set
initialization for the stats_hypergeom_isf ferret pyef,def ferret_init id return pyferret stats getinitdict DISTRIB_NAME FUNC_NAME
"two ferdsets are equal if their filenames , datasetnames , and dictionary of fervar variables are all equal . all string values are compared case - insensitive .",def __eq__ self other if not isinstance other FerDSet return NotImplemented if self _filename upper other _filename upper return False if self _dsetname upper other _dsetname upper return False if self _fervars other _fervars return False return True
override this with the screen - friendly name of your transition,def __repr__ self return Transition
constructs an object holding a datetime / timestamp value from the given unix timestamp .,def TimestampFromTicks ticks return Timestamp time localtime ticks 6
get stats from the stats table . tag is just the class selector .,def _get_num_anime_stats soup classname tag_name num_anime_ classname stats_table_tag soup find class_ stats status if not stats_table_tag raise MissingTagError tag_name table stat_tag stats_table_tag find a class_ classname if not stat_tag raise MissingTagError tag_name title num_text stat_tag next_sibling string strip replace try num int num_text except TypeError ValueError raise ParseError tag_name Unable to convert text s to int num_text return num
return a list of node objects ( by the index endpoint ) .,def getNodes browser token details False group None nodes page 1 per_page 100 done False while not done status data APICall browser token GET api v2 nodes json params page page per_page per_page new_nodes json loads data nodes new_nodes page 1 done True if len new_nodes per_page else False if details detailed_nodes for node in nodes status data APICall browser token GET api v2 nodes json format node id detailed_nodes append json loads data return detailed_nodes return nodes
check whether module is in shared list,def SAMBA3_IS_SHARED_MODULE bld module if module in bld env shared_modules return True return False
transforms the supplied instances into features .,def transform self instances features self _dataset features _ tensor_map _transform_features instances features self _dataset schema self _dataset metadata return tensor_map
returns the sha of the last completed jenkins build for this project . expects job_url in environment,def jenkins_last_build_sha job_url os getenv JOB_URL job_json_url 0 api json format job_url response urllib urlopen job_json_url job_data json loads response read last_completed_build_url job_data lastCompletedBuild url last_complete_build_json_url 0 api json format last_completed_build_url response urllib urlopen last_complete_build_json_url last_completed_build json loads response read return last_completed_build 1 lastBuiltRevision SHA1
can read ignore case from config file,def test_load_parser_data_ignore_case self p helper_load_cfg_file target True self assertEqual target p _ignore_case
port in use for this request,def request_port self raise NotImplementedError Implement in subclass
"assert that : attr:`~state ` , : attr:`~transition ` , and : attr:`~transition_event ` are set based on the most recent transition performed .",def test_transitions_sets_attrs switch u n Assert that attr state attr transition and attr transition_event are set based on the n most recent transition performed n switch on assert switch state switch on transition next_state assert switch transition switch on transition assert switch transition_event switch on transition default_transition_event switch off assert switch state switch off transition next_state assert switch transition switch off transition assert switch transition_event switch off transition default_transition_event
download table for the obj given ' object_id ' from the hsc catalog to file ( hsc_{tab_name}.csv ) and return status .,def download_table self tab_name photoz_demp columns overwrite False fp self get_fp_table tab_name tab_name object_id self xid object_id 0 sql _get_table_sql object_id object_id tab_name tab_name columns columns rerun self rerun status self _download_table_kernel sql fp overwrite overwrite return status
function to add app auth information to parameter store,def save_app_auth_info app info overwrite False auth_dict auth_key user_input info description False info format for auth_key info in app required_auth_info iteritems description Required authentication information for the service for use in the app format info type info app_name param_name _ format info function_name AppConfig AUTH_CONFIG_SUFFIX saved save_parameter info region param_name auth_dict description overwrite if saved LOGGER_CLI info App authentication info successfully saved to parameter store else LOGGER_CLI error App authentication info was not saved to parameter store return saved
send alert to a lambda function,def _dispatch self alert descriptor alert_string json dumps alert record separators function_name self config self __service__ descriptor parts function_name split if len parts 2 or len parts 8 function parts 2 qualifier parts 1 else function parts 1 qualifier None LOGGER debug Sending alert to Lambda function s function_name client boto3 client lambda region_name self region invoke_params FunctionName function InvocationType Event Payload alert_string if qualifier invoke_params Qualifier qualifier client invoke invoke_params return True
"return the running configuration which almost always matches the configuration in the config file . during a reconfiguration , it may be transitioning to the new state , in which case it will be different to the pending config . neither the running or pending configurations necessarily match the operational state , either because a task has exited and not yet restarted , or because a task control has been changed via the management interface .",def config self path postmap None params q httpd merge_query path postmap ans self _legion _config_running if not ans ans return self _format ans q
mock sending to a maildir queue .,def send_to_queue self message self queue append message
return all endpoints of a particular service in the vpc .,def filters self service return Name vpc id Values self vpc_id Name service name Values self service_name service
add / update the account to s3,def add_account self account_name config config_type self _config_account_type config key_name accounts 0 s 1 format config_type account_name key self bucket bucket new_key key_name self bucket save_config key config
close any existing connection to the database .,app teardown_appcontext def close_connection exception database getattr g _database None if database is not None database close return None
add a project to a team .,requires_auth def add_project self team_id project if isinstance project Repository project project project return self get_values str team_id repositories method POST post_data name project filter repositories datatype Repository
ami bridge leave event callback .,def bridge_leave_handler self ami event channel event get channel if bob in channel self bob_in_bridge False elif alice in channel self alice_in_bridge False
check if this driver support a particular oob type .,classmethod def oob_type_support cls type_string if type_string in cls oob_types_supported return True return False
return a new attr instance and set properties from dargs,def new_attr self dargs new_one self Attr virsh_instance self virsh for key value in dargs items setattr new_one key value return new_one
: return : true if command is async else false,def is_async self return self _async
tests the unicode method executes .,def test_unicode self logs self create_logs user self user1 for log in logs log __unicode__
"is this element horizontal ? if rotation is none , use this element 's rotation .",def is_horizontal self rotation None rotation rotation or self get_rotation return rotation in 0 180
"handle a page change . when the user clicks on a new tab , reload the flow graph to update the vars window and call handle states ( select nothing ) to update the buttons .",def _handle_page_change self notebook page page_num self current_page self notebook get_nth_page page_num Messages send_page_switch self current_page get_file_path Actions PAGE_CHANGE
create an instance based on the configuration .,def __init__ self config self blockchain self __get_blockchain config blockchain if neo4j in config nc config neo4j self graph_db GraphController nc host nc port nc user nc pass
generates compatible problem critical in the last two versions,def testFinderCompatibleTest self last_block self _biigraph get_num_blocks 1 self _biigraph make_independent last_block last_block 1 t self _biigraph _get_range_block last_block 2 self _biigraph make_dependent last_block t 0 self _biigraph make_dependent last_block 1 t 0 self _publish_graph request self _unresolvedDependencyRequest self lbcn result self service find request BiiResponse self assertEqual len self lbcn len result resolved
"walk s3 path to get detailed information , cache the result .",def _s3walk self if self data is None conn S3Connection S3Handler S3_KEYS s3url S3URL self path bucket conn lookup s3url bucket self data for key in bucket list s3url path PATH_SEP self data append key conn close return self data
disconnect a single callback when it is no longer used . called when the last signal for this callback is disconnected .,def disconnectCallback self signal if signal sceneNewRequested self _fbapp OnFileNew Remove self _mobCallback elif signal sceneNewFinished self _fbapp OnFileNewCompleted Remove self _mobCallback elif signal sceneMergeRequested self _fbapp OnFileMerge Remove self _mobCallback elif signal sceneOpenRequested self _fbapp OnFileOpen Remove self _mobCallback elif signal sceneOpenFinished self _fbapp OnFileOpenCompleted Remove self _mobCallback elif signal sceneSaveRequested self _fbapp OnFileSave Remove self _mobCallback elif signal sceneSaveFinished self _fbapp OnFileSaveCompleted Remove self _mobCallback
"audio left changed , update macro ( 1 tick delay )",def audio_left_changed self val int self _track output_meter_left 127 if val self _last_meter_left_val self _last_meter_left_val val if IS_LIVE_9 self _parent schedule_message 1 partial self update_macros val else self _parent schedule_message 1 self update_macros val
adds the agent to the database .,def add_agent_to_db self with self app app_context if not models Agent query filter_by name self name count db_agent models Agent name self name user self user url self url password self password db session add db_agent db session commit
"lower incomplete gamma function = integral from 0 to x of t * * ( s-1 ) exp(-t ) dt divided by gamma(s ) , i.e. , the fraction of gamma that you get if you integrate only until x instead of all the way to infinity . implemented here only if s is a positive multiple of 0.5 .",def gammainc_halfint s x if s 0 raise ValueError s is not positive s if x 0 raise ValueError s 0 x if s 2 int s 2 raise NotImplementedError s is not a multiple of 0 5 s if s int s term 1 total 1 for k in range 1 int s term x k total term return 1 exp x total result 0 0 while s 1 result x s 1 exp x gamma s s s 1 result erf sqrt x return result
create a urllib opener . @return : an opener . @rtype : i{openerdirector },def u2opener self if self urlopener is None return u2 build_opener self u2handlers else return self urlopener
refinement of quadricgm._select_coords ; we want to choose the correct intersection point for a set of rays and our * sliced * quadric cone surface .,def _select_coords self coords prm select N empty prm shape 1 select fill N nan height N sum N linalg inv self _working_frame None 2 None N concatenate coords N ones 2 1 coords shape 1 axis 1 axis 1 inside self z1 height height self z2 positive prm 1e 06 hitting inside positive select N logical_and hitting True one_hitting N logical_xor hitting select one_hitting N nonzero hitting T one_hitting 1 return select
ensure the cmdclass string outputting is correct .,def test_cmdclass_string conf Config cmdclass foo MyFooClass test gets overridden cmdcls_str conf _cmdclass_string assert cmdcls_str startswith cmdclass assert foo MyFooClass in cmdcls_str assert test PyPackageTest in cmdcls_str
return a new copied version of this object .,def copy self svm SVMLeafRank self paramDict self folds self sampleSize svm setKernel self kernel self kernelParam svm setC self C svm setErrorCost self errorCost svm setPenalty self penalty svm setSvmType self type svm processes self processes svm epsilon self epsilon svm metricMethod self metricMethod svm chunkSize self chunkSize svm timeout self timeout svm normModelSelect svm normModelSelect return svm
"mass of the segment , in units of kg .",property def mass self return self _mass
"this method is called to convert the given value into the designated type , or throw an exception if this is not possible .",abc abstractmethod def constraint self obj attr value pass
adds a new resource to the vm .,def _add_virt_resource self res_setting_data vm_path vs_man_svc self _conn Msvm_VirtualSystemManagementService 0 res_xml res_setting_data GetText_ 1 job_path new_resources ret_val vs_man_svc AddResourceSettings vm_path res_xml self check_ret_val ret_val job_path return new_resources
calculates simple moving average from data list specifying window for moving average,def simple_moving_average_list data window if len data window return None return sum data window float window
tests that the : func:`networkx.from_scipy_sparse_matrix ` function interprets integer weights as the number of parallel edges when creating a multigraph .,def test_from_scipy_sparse_matrix_parallel_edges self A sparse csr_matrix 1 1 1 2 expected nx DiGraph edges 0 0 0 1 1 0 expected add_weighted_edges_from u v 1 for u v in edges expected add_edge 1 1 weight 2 actual nx from_scipy_sparse_matrix A parallel_edges True create_using nx DiGraph assert_graphs_equal actual expected actual nx from_scipy_sparse_matrix A parallel_edges False create_using nx DiGraph assert_graphs_equal actual expected edges 0 0 0 1 1 0 1 1 1 1 expected nx MultiDiGraph expected add_weighted_edges_from u v 1 for u v in edges actual nx from_scipy_sparse_matrix A parallel_edges True create_using nx MultiDiGraph assert_graphs_equal actual expected expected nx MultiDiGraph expected add_edges_from set edges weight 1 expected 1 1 0 weight 2 actual nx from_scipy_sparse_matrix A parallel_edges False create_using nx MultiDiGraph assert_graphs_equal actual expected
see the real accessor for a description .,def connect self super HybridAccessor self connect self _metadata_accessor connect self _data_accessor connect self is_connected True
performs the pixel purity index algorithm for endmember finding .,def PPI M q numSkewers ini_skewers None M M T M np matrix M dtype np float32 p N M shape u np transpose np transpose M mean axis 0 Mm M np kron np ones 1 N u if ini_skewers None skewers np random rand p numSkewers else skewers ini_skewers votes np zeros N 1 for kk in range numSkewers tmp abs skewers kk Mm idx np argmax tmp votes idx votes idx 1 max_idx np argsort votes axis None end_member_idx max_idx q 1 U M end_member_idx return np array U T end_member_idx
"iterates over triples of the form ( prediction , class , count ) of this confusion matrix .",def iteritems self for prediction in self labels for clazz in self labels yield prediction clazz self getMatrixEntry prediction clazz
test if all sets of members from supplied lists satisfy predicate p,def all p lsargs return reduce and_ map p lsargs True
return all players with specific civlization,def byCivilization self civlization players list for player in self _players if player civlization civlization players append player return players
test the code will die gracefully if input files are missing,def test_missing_files self with self assertRaises ValueError targets cuts select_targets blat foo1234 numproc 1 gaiadir self gaiadir
function to create a default mongo db configuration file,def createMongoDConfig configDir TEMP_DIR dbPath os path join TEMP_DIR mongodb logPath os path join TEMP_DIR mongodb log try log info Creating mongo db config file configfile os path join configDir mongod conf f open configfile w f write dbpath s n dbPath f write logpath s n logPath f write logappend true n f close except log exception Failed to create mongo db default configuration file raise return configfile
"returns the digest , if it has not been computed , calls compute_digest",property def digest self if self _digest is None self compute_digest return self _digest
returns json - like mock result of the servicenow rest api query : param data : append extra data to simulate expected result,def json self data None result MOCK_RESULT if data result update data return result result
er can not initialize with a list of length > 2 .,def test_ER_02 assert raises ValueError t ER 1 2 3 4
test samplers using ks - statistic for two continuous distributions and ensure that generated values correctly correlate with each one,def test_simpSample self ulim 0 1 ufun lambda x 1 0 np diff ulim n int 100000 0 nlim 10 10 nfun lambda x np exp x 2 0 2 0 np sqrt 2 0 np pi for mod in self mods print Testing uniform and normal distributions for sampler s mod __name__ usampler mod ufun ulim 0 ulim 1 usample usampler n self assertGreaterEqual usample min ulim 0 Uniform sampler does not obey lower limit for s mod __name__ self assertLessEqual usample max ulim 1 Uniform sampler does not obey upper limit for s mod __name__ nsampler mod nfun nlim 0 nlim 1 nsample nsampler n self assertGreaterEqual nsample min nlim 0 Normal sampler does not obey lower limit for s mod __name__ self assertLessEqual nsample min nlim 1 Normal sampler does not obey upper limit for s mod __name__ nu scipy stats kstest nsample uniform 1 if nu 0 01 nsample nsampler n nu scipy stats kstest nsample uniform 1 self assertLessEqual nu 0 01 Normal sample looks too uniform for s mod __name__ un scipy stats kstest usample norm 1 if un 0 01 usample usampler n un scipy stats kstest usample norm 1 self assertLessEqual un 0 01 Uniform sample looks too normal for s mod __name__ pu scipy stats kstest usample uniform 1 if pu 0 01 usample usampler n pu scipy stats kstest usample uniform 1 self assertGreaterEqual pu 0 01 Uniform sample does not look uniform for s mod __name__ pn scipy stats kstest nsample norm 1 if pn 0 01 nsample nsampler n pn scipy stats kstest nsample norm 1 self assertGreaterEqual pn 0 01 Normal sample does not look normal for s mod __name__
handles zoom in / out of the text .,def wheelEvent self event if event modifiers QtCore Qt ControlModifier delta event delta if delta 0 self zoom 1 elif delta 0 self zoom 1 return True return super TextEditor self wheelEvent event
return the resource corresponding to a single translation,base resource Translation def translation self translation_id return Translation self translation_id
"return a list of connect app resource representations , each representing a connect app you 've authorized to access this account .",base resource applications AuthorizedConnectApps def authorized_connect_apps self return applications AuthorizedConnectApps self
return the resource corresponding to the single test,base resource single Single def single self return single Single self
"uploads a file or a directory recursively ( depending on what ` localpath ` is ) an optional ` extentions ` keyword argument may be given , specifying the extensions of the files to be uploaded ( relevant to directories only ) . if no extentions are given , all files will be uploaded .",def upload conn localpath remotepath a k if os path isdir localpath upload_dir conn localpath remotepath a k elif os path isfile localpath upload_file conn localpath remotepath a k else raise UploadError can only upload files or directories
override with your own formula that calculates a new modifier value based on the current time t.,def calculate self t raise NotImplementedError
returns the comment_count and response_count for a thread,def get_comment_and_response_count self thread_id url threads format self url_prefix thread_id response self client get url verify False name GET_thread self verify_response response url response response json return response comment_count response response_count
make a pipelineloader that emits random arrays seeded with ` seed ` for the columns in `` testingdataset `` .,def make_seeded_random_loader seed dates sids return SeededRandomLoader seed TestingDataSet columns dates sids
restride ` array ` to repeat ` count ` times along the last axis .,def repeat_last_axis array count return as_strided array array shape count array strides 0
push an object onto the stack for the given type .,def push self typ obj if isinstance typ basestring for cls in self type_map if _mod_name_key cls typ self type_map cls append obj break else if typ not in self name_map self name_map typ self name_map typ append obj else if typ not in self type_map self type_map typ self type_map typ append obj
send a bug report email .,def send_bug_report self smtp_server fromaddr toaddrs ccaddrs message try import smtplib logger debug Connecting to s smtp_server server smtplib SMTP host smtp_server logger debug Connected s server server sendmail fromaddr toaddrs ccaddrs message as_string server quit except Exception as e logger exception Problem sending error report
return the user agent for this payload,def get_UA self return self payload agent
process the request arguments from the web server to see if any apply to this block,def process self request is_cancel common requestHasCancel request if is_cancel self idevice edit False if not hasattr self idevice content content_w_resourcePaths self idevice content content_w_resourcePaths if not hasattr self idevice content content_wo_resourcePaths self idevice content content_wo_resourcePaths return Block process self request if u action not in request args or request args u action 0 u delete content self contentElement process request if content self idevice content content
returns an xhtml string for editing this option element,def renderEdit self html self question_question renderEdit html _ True html common option self keyId self question isCorrect true html _ False html common option self keyId not self question isCorrect false html br br n html common elementInstruc self idevice keyInstruc html self question_feedback renderEdit html self question_hint renderEdit html common submitImage self id self idevice id images stock cancel png _ Delete question html br br n return html
run simulation loops and reschedule callbacks .,def simulate self global _simtag if _simtag is not None gobject source_remove _simtag self runUntilCurrent timeout min self timeout 0 1 if timeout is None timeout 0 1 _simtag gobject timeout_add int timeout 1010 self simulate
"grouper(3 , ' abcdefg ' , ' x ' ) -- > abc def gxx",def grouper n iterable fillvalue None args iter iterable n return it izip_longest fillvalue fillvalue args
save cart 's state into order instance .,def set_positions self cart self save for id_ position in cart self positions create order self product_id id_ name position name price position price quantity position quantity return self
libevconnection should publish a big message and consume it,unittest skipIf target PyPy PyPy is not supported unittest skipIf adapters LibevConnection is None pyev is not installed def start_test self self start
"updates both tx ( specifically the spending_info attribute of the tx.inputs ) and utxoset ( removes utxos being spent by tx , and adds tx.outputs as utxos ) .",def _track_tx_spending tx utxoset for txin in tx inputs if txin is_coinbase continue spending_info utxoset spend txin _spent_txid txin spent_output_idx txin spending_info spending_info utxoset add_from_tx tx
corrects major and minor peak intensities in presence of exchange .,def correct_intensities magz_a 1 0 magz_b 0 0 pb 0 0 kex 0 0 dw 0 0 r_ixy 0 0 dr_ixy 0 0 kab kex pb kba kex kab k2ab r_ixy kab k2ba r_ixy dr_ixy 1j dw kba k2ex k2ab k2ba fac k2ab k2ba 2 4 0 kab kba 0 5 nu1 nu2 0 5 k2ex SIGN fac magz_a_c kab nu2 k2ab magz_a kba nu1 k2ab magz_b nu1 nu2 magz_b_c kab nu1 k2ab magz_a kba nu2 k2ab magz_b nu1 nu2 magz_a_c magz_b_c magz_b_c magz_a_c if abs nu1 imag abs nu2 imag else magz_a_c magz_b_c signa 1 0 if abs np angle magz_a_c 0 5 pi else 1 0 signb 1 0 if abs np angle magz_b_c 0 5 pi else 1 0 return signa abs magz_a_c signb abs magz_b_c
get the capabilities of the given slot .,def ca_get_hsm_capability_set slot slot_id CK_SLOT_ID slot cap_ids AutoCArray cap_vals AutoCArray refresh_c_arrays 1 def _get_hsm_caps Closer for retries to work w properties return CA_GetHSMCapabilitySet slot_id cap_ids array cap_ids size cap_vals array cap_vals size ret _get_hsm_caps return ret dict list zip cap_ids cap_vals
calculate displacement field given coordinates of vertices .,def calcDisplacements self vertices return self soln displacement vertices
called when the remote tries to write to this descriptor .,def _write_value self value options logger warning Default Descriptor WriteValue called returning error raise NotSupportedException
test parsing of url with case sensitive urls,def test_parser_case_url urls http github com gogoair Test config https github com gogoair Test config http github com gogoair Test config git https github com gogoair Test config git https username testgithub com gogoair Test config git git github com gogoair Test config git git git github com gogoair Test config git file opt git gogoair Test config git ssh git github com gogoair Test config git gogoair Test config git var opt gitlab git data repositories gogoair Test config git gogoair Test config git HTTPS username Testgithub com gogoair Test config git for url in urls project repo Parser url lower False parse_url assert project gogoair assert repo Test config
print the usage and exit .,def Usage msg None usage Usage s n dry run X exclude GLOB FILE DESTDIR sys argv 0 if msg Die s n n s msg usage else Die usage
"get returns photo entity , patch modifies photo entity .",def photo self photo_id client self _get_datastore_client result flask_users authn_check flask request headers if isinstance result flask Response return result userid_hash users get_userid_hash result if not users check_if_user_exists client userid_hash return flask Response User does not exist status 404 result roles _check_if_user_has_role client userid_hash set roles ADMIN_ROLE roles REVIEWER_ROLE if isinstance result flask Response return result if result is False return flask Response Permission denied status 403 key client key Photo str photo_id if self request method GET result entity client get key for field in FIELDS if field not in entity return flask Response Invalid photo missing field s field 404 result field entity field result reviews for review in entity reviews reviewer review user_id name vote review vote result reviews append reviewer vote result user entity user name return flask jsonify result elif flask request method PATCH result util _validate_json flask request if result is not True return result json flask request get_json json util _escape_json json if vote not in json return flask Response Missing vote 400 vote json vote if vote up and vote down return flask Response Invalid vote use up or down 400 with client transaction entity client get key review datastore Entity key client key Review review user_id userid_hash review vote vote if reviews not in entity entity reviews review else for r in entity reviews reviewer_key r user_id if reviewer_key userid_hash r vote vote else entity reviews append review entity num_reviews len entity reviews try client put entity except Exception as e logging error Datastore update operation failed s str e flask Response Internal server error status 500 return flask Response OK status 200
check the buffer for a new request .,def _CheckForNewRequest self if self _blocked return if r n r n in self _buffer request new_buffer self _buffer split r n r n 1 self _buffer new_buffer response Response self try request Request request self _remote_addr except KeyError ValueError response headers add_header Content Type text plain response start_response 400 response out write Failed to parse request response end_response return if request path favicon ico logging info s s s self _remote_addr request method request path self _blocked True self _callback request response
"settiltfilter(value ) sets the rate of tilt debounce filtering when value = 0 - tilt debounce filtering is disabled . for other values , value number of samples have to match before the device updates portrait/ landscape data .",def settiltfilter self value assert 0 value 8 Tilt debounce filtering must be between 0 and 8 self i2cdev write self MMA7660_ADDR self REG_MODE self MODE_STAND_BY self i2cdev write self MMA7660_ADDR self REG_SR value self i2cdev write self MMA7660_ADDR self REG_MODE self MODE_ACTIVE
set a new runvars object .,def setRunVars self runvars self runvars runvars
"the wrapper method . based on the imageprocessing settings , applies the desired image transformations .",def process self image u The wrapper method Based on the ImageProcessing settings n applies the desired image transformations if not self do_image_processing logging info u ImageProcessing no processing requested return image if _is_binary image return image if self warp_registration try image PerspectiveRegistrationProcessor process image except Exception as e logging warn u Perspective transformation failed Are you sure the input is a photo of a light sheet of music on a dark background if self auto_invert logging info u ImageProcessing auto invert set to 0 type 1 auto inverting format self auto_invert type self auto_invert image _auto_invert image if self stretch_intensity image _stretch_intensity image if self otsu_background image _binarize_and_apply_background image return image
the registry should have some dimensions,def test_registry_contains_dimension self time registry get_dimension time self assertIsNotNone time self assertIsInstance time models TimeDimension
"constructs a dstoken object . you probably want to be using the kind - specific constructors instead of this one : create_decorator , create_number , create_word , and create_timezone . returns the dstoken object .",def __init__ self kind text option None self kind kind self text text self option option if option self score option common else self score 0
factory function for making multicontainerfshandler . uses the current project directory to retrieve all paths and info about whether certain files exist . : return : multicontainerfshandler,def make_multicontainer_fs_handler docker_proj_path fops get_project_root dockercfg_path os path join fops get_home fshandler DOCKERCFG_FILENAME dockerignore_path fops project_file_path fshandler DOCKERIGNORE_FILENAME logdir_path fops get_logs_location log HOST_LOGS_DIRNAME hostlog_path log get_host_log_path logdir_path dockerrun_path fops project_file_path fshandler DOCKERRUN_FILENAME compose_path fops get_eb_file_full_location fshandler COMPOSE_FILENAME dockerrun_dict dockerrun get_dockerrun dockerrun_path return MultiContainerFSHandler docker_proj_path docker_proj_path dockercfg_path dockercfg_path dockerignore_path dockerignore_path hostlog_path hostlog_path compose_path compose_path dockerrun dockerrun_dict
: param str|unicode fpath : file path . default : uwsgi.stats,def __init__ self fpath None separator None push_interval None value KeyValue locals aliases fpath path push_interval freq super PusherFile self __init__ value
"sensor data is contained in the 2nd and 4th byte , with sensor ids being contained in the 3rd and 5th byte respectively .",def getData self rawData self getRawData if rawData is not None sensorData rawData 3 rawData 2 rawData 5 rawData 4 else sensorData return sensorData
test the creation of a simple xlsxwriter file .,def test_create_file self filename self got_filename workbook Workbook filename worksheet workbook add_worksheet chart workbook add_chart type pie data 2 4 6 60 30 10 worksheet write_column A1 data 0 worksheet write_column B1 data 1 chart add_series categories Sheet1 A 1 A 3 values Sheet1 B 1 B 3 worksheet insert_chart E9 chart workbook close got exp _compare_xlsx_files self got_filename self exp_filename self ignore_files self ignore_elements self assertEqual got exp
test the creation of a simple xlsxwriter file with page breaks .,def test_create_file self filename self got_filename workbook Workbook filename worksheet workbook add_worksheet worksheet set_h_pagebreaks 1 5 13 8 8 8 worksheet set_v_pagebreaks 8 3 1 0 worksheet write A1 Foo workbook close got exp _compare_xlsx_files self got_filename self exp_filename self ignore_files self ignore_elements self assertEqual got exp
release an interface previously claimed with claiminterface .,def releaseInterface self util release_interface self dev self __claimed_interface self __claimed_interface 1
record the current camera settings as a named preset .,def preset_add self name settings self preset_table name settings if not name in self preset_names self preset_names name self preset_picker append_text name self preset_picker set_active self preset_names index name
return a flask `` response `` object containing a json representation of * resource*.,def jsonify resource response flask jsonify resource to_dict response add_link_headers response resource links return response
serves requests using the wsgi callable interface .,def serve environ start_response u fieldstorage cgi FieldStorage fp environ u wsgi input environ environ keep_blank_values True d dict k getfield fieldstorage k for k in fieldstorage uri environ get u PATH_INFO u if not uri uri u index html else uri re sub u u index html uri if re match u html uri try template lookup get_template uri except exceptions TopLevelLookupException start_response u 404 Not Found return str encode u Cant find template s uri start_response u 200 OK u Content type u text html try return template render d except return exceptions html_error_template render else u re sub u u uri filename os path join root u if os path isfile filename start_response u 200 OK u Content type guess_type uri return open filename u rb read else start_response u 404 Not Found return str encode u File not found s filename
migrate to the latest schema version .,def migrate self migrate_indicator self
return true if the given v has an inverse in mod m.,def has_inverse v m try return invert v m m except ValueError return False except ZeroDivisionError return False
"example : > > > print(matlab2cpp.qtree(""a.b = 4.4 ; c = [ a.b ] "" , core = true , suggest = true ) ) # doctest : + normalize_whitespace 1 1block code_block type 1 1| assign double double 1 1| | fvar struct double a 1 7| | float double double 1 12| assign struct double 1 12| | var double double c 1 16| | matrix struct double 1 17| | | vector matrix double 1 17| | | | fvar struct double a",def Fvar node declare node func 0 node name if declare backend in struct structs node backend declare backend
"create a group . one post parameter required , the group identifier ( a string ) --- # yaml omit_serializer : true parameters : - name : gid description : group identifier required : true type : string paramtype : form",def create self request telnet request telnet telnet sendline group a telnet expect Adding a new Group n INTERACTIVE_PROMPT if not gid in request data raise MissingKeyError Missing gid group identifier telnet sendline gid request data gid n telnet expect INTERACTIVE_PROMPT telnet sendline ok n matched_index telnet expect Successfully added n r STANDARD_PROMPT Error n r INTERACTIVE_PROMPT INTERACTIVE_PROMPT STANDARD_PROMPT if matched_index 0 gid telnet match group 2 strip telnet sendline persist n return JsonResponse name gid else raise ActionFailed telnet match group 1
return the current problem name .,property def problem_name self return self q css problem header text 0
updates the should_display field of the rerun state object for self.course_key and verifies its new state .,def dismiss_ui_and_verify self rerun user_who_dismisses_ui UserFactory CourseRerunState objects update_should_display entry_id rerun id user user_who_dismisses_ui should_display False self expected_rerun_state update updated_user user_who_dismisses_ui should_display False self verify_rerun_state
this clicks on the reset attempts link with an optionally specified user .,def reset_attempts self user None if user self q css input id sd_fu_ first fill user self q css section staff modal a staff debug reset click
remove any language that is not either in `` self.released_langs `` or a territory of one of those languages .,def _clean_accept_headers self request accept request META get HTTP_ACCEPT_LANGUAGE None if accept is None or accept return new_accept join self _format_accept_value lang priority for lang priority in dark_parse_accept_lang_header accept if self _is_released lang request META HTTP_ACCEPT_LANGUAGE new_accept
execute request and return result parsed as json,def run_request self request None if request is None request self request response change_email_request self request return json loads response content
gets provider ( or none ) by backend name .,classmethod def get_by_backend_name cls backend_name cls _check_configured for enabled in cls _ENABLED values if enabled BACKEND_CLASS name backend_name return enabled
returns a key derived using the scrypt key - derivarion function,def scrypt password salt N SCRYPT_N r SCRYPT_r p SCRYPT_p olen 64 check_args password salt N r p olen try return _scrypt password password salt salt N N r r p p buflen olen except raise ValueError
get : read data from targetaddress and return to client through http response,def do_GET self s self _get_socket if s to_reads to_writes in_errors select select s 5 if len to_reads 0 to_read_socket to_reads 0 try print Getting data from target address data to_read_socket recv self BUFFER print data self send_response 200 self end_headers if data self wfile write data except socket error as ex print Error getting data from target socket s ex self send_response 503 self end_headers else print No content available from socket self send_response 204 self end_headers else print Connection With ID s has not been established self _get_connection_id self send_response 400 self end_headers
make data have mean 0 and covariance matrix i.,def standardize_mvn data X data np mean data axis 0 T p n X shape Sigma np cov X W np linalg cholesky np linalg inv Sigma Y np dot W T X return Y T
fixture to get the factory used to create profiles .,pytest fixture def profile_factory db return factories ProfileFactory
learn parameters using subgradient descent .,def fit self X Y constraints None warm_start False initialize True train_scorer None test_scorer None if initialize self model initialize X Y print Training primal subgradient structural SVM self grad_old np zeros self model size_joint_feature self w getattr self w np zeros self model size_joint_feature self train_scores self test_scores self w_history w self w copy if not warm_start self objective_curve_ self timestamps_ time if self learning_rate auto self learning_rate_ self C len X else self learning_rate_ self learning_rate else self timestamps_ np array self timestamps_ time tolist try for iteration in xrange self max_iter if iteration self alpha max 1e 06 1 0 iteration if self shuffle X Y shuffle X Y if self n_jobs 1 objective positive_slacks w self _sequential_learning X Y w else objective positive_slacks w self _parallel_learning X Y w objective objective self C np sum w 2 2 0 if positive_slacks 0 print No additional constraints if self break_on_no_constraints break if self verbose 0 print iteration d iteration print positive slacks d objective f positive_slacks objective self timestamps_ append time self timestamps_ 0 self objective_curve_ append self _objective X Y if self verbose 2 print self w if iteration self check_every 0 if train_scorer is not None self train_scores append train_scorer self w print Train SCORE format self train_scores 1 if test_scorer is not None self test_scores append test_scorer self w print Test SCORE format self test_scores 1 self w_history append self w copy self _compute_training_loss X Y iteration if self logger is not None self logger self iteration except KeyboardInterrupt pass self w_history np vstack self w_history self timestamps_ append time self timestamps_ 0 return self
"handler for drop action : opens the dropped file , if it is exactly one",def OnDropFiles self arr if len arr 1 fn arr 0 if os path isfile fn and self AskSaveModified self document fn self Open self UpdateRecentFileList fn self modified False self UpdateTitle
extract data from facebook opengraph tags .,def extract self html extracted soup BeautifulSoup html for meta_tag in soup find_all meta if self key_attr in meta_tag attrs and content in meta_tag attrs property meta_tag self key_attr if property in self property_map property_dest self property_map property if property_dest not in extracted extracted property_dest extracted property_dest append meta_tag attrs content return extracted
create destructive sorted iterator of prioritydictionary .,def __iter__ self def iterfn while len self 0 x self smallest yield x del self x return iterfn
test the flask blueprint subdomain configuration,def test_bower_subdomain self self app config BOWER_SUBDOMAIN static Bower self app with self app app_context self assertEqual bower_url_for jquery dist jquery js http static unit test bower jquery dist jquery min js version 2 1 3
the ppf must be defined between 0 and 1 ( where is equal to the xmin and xmax values of the original spline ) .,def test_ppf self ppf self s3 build_ppf _delta abs ppf xmin self assertTrue _delta 0 001 ppf xmin 9f _delta _delta abs ppf xmax 1 0 self assertTrue _delta 0 001 ppf xmax 1 9f _delta _delta abs ppf 0 self s3 xmin self assertTrue _delta 0 001 ppf 0 xmin 9f _delta _delta abs ppf 1 self s3 xmax self assertTrue _delta 0 001 ppf 1 xmax 9f _delta
visits the players city and prints out buildings we are interested in ... good for sabotaging,def visit self data self request visitPlayer self player_id city Request service data OtherPlayerService buildings city city_map entities for building in buildings if building type not in residential street decoration pprint pprint building return data
convert snake_case string to title case,def _to_title_case snake_case_str components snake_case_str split _ return join x title for x in components
list of available operation modes .,property def operation_list self return STATE_AUTO STATE_MANUAL
computes the connected sets of c.,staticmethod def _compute_connected_sets C mincount_connectivity strong True import msmtools estimation as msmest import scipy sparse as scs if scs issparse C Cconn C tocsr copy True Cconn data Cconn data mincount_connectivity 0 Cconn eliminate_zeros else Cconn C copy Cconn np where Cconn mincount_connectivity 0 S msmest connected_sets Cconn directed strong return S
"a ~ normal(mu , tau )",stoch def A value A_init mu 1 0 ones K_max dtype float tau ones K_max dtype float return normal_like value mu tau
returns true if two sets are the same,def same self other return self root other root
bake a ` rubocop ` command so it 's ready to execute and returns none .,def bake self self _rubocop_command sh rubocop bake self options self _tests _env self env _out LOG out _err LOG error
reads the registry to find the installed path of the phar lap ets development kit .,def getPharLapPath if not SCons Util can_read_reg raise SCons Errors InternalError No Windows registry module was found try k SCons Util RegOpenKeyEx SCons Util HKEY_LOCAL_MACHINE SOFTWARE Pharlap ETS val type SCons Util RegQueryValueEx k BaseDir idx val find x00 if idx 0 val val idx return os path normpath val except SCons Util RegError raise SCons Errors UserError Cannot find Phar Lap ETS path in the registry Is it installed properly
add builders and construction variables for pdftex to an environment .,def generate env global PDFTeXAction if PDFTeXAction is None PDFTeXAction SCons Action Action PDFTEXCOM PDFTEXCOMSTR global PDFLaTeXAction if PDFLaTeXAction is None PDFLaTeXAction SCons Action Action PDFLATEXCOM PDFLATEXCOMSTR global PDFTeXLaTeXAction if PDFTeXLaTeXAction is None PDFTeXLaTeXAction SCons Action Action PDFTeXLaTeXFunction strfunction SCons Tool tex TeXLaTeXStrFunction env AppendUnique LATEXSUFFIXES SCons Tool LaTeXSuffixes import pdf pdf generate env bld env BUILDERS PDF bld add_action tex PDFTeXLaTeXAction bld add_emitter tex SCons Tool tex tex_pdf_emitter pdf generate2 env SCons Tool tex generate_common env
"test get_create_transform(""unknowntransform "" ) throws an error . @param self object reference .",def test_create_transform_unknown self with self assertRaisesRegexp ValueError No such transform UnknownTransform WorkerUtilities create_transform UnknownTransform
add builders and construction variables for ar to an environment .,def generate env SCons Tool createSharedLibBuilder env SCons Tool createProgBuilder env env SHLINK LINK env SHLINKFLAGS SCons Util CLVar LINKFLAGS dll env _SHLINK_TARGETS windowsShlinkTargets env _SHLINK_SOURCES windowsShlinkSources env SHLINKCOM compositeShLinkAction env Append SHLIBEMITTER windowsLibEmitter env LINK link env LINKFLAGS SCons Util CLVar nologo env _PDB pdbGenerator env LINKCOM TEMPFILE LINK LINKFLAGS OUT TARGET windows _LIBDIRFLAGS _LIBFLAGS _PDB SOURCES windows env Append PROGEMITTER prog_emitter env LIBDIRPREFIX LIBPATH env LIBDIRSUFFIX env LIBLINKPREFIX env LIBLINKSUFFIX LIBSUFFIX env WIN32DEFPREFIX env WIN32DEFSUFFIX def env WIN32_INSERT_DEF 0 env WINDOWSDEFPREFIX WIN32DEFPREFIX env WINDOWSDEFSUFFIX WIN32DEFSUFFIX env WINDOWS_INSERT_DEF WIN32_INSERT_DEF env WIN32EXPPREFIX env WIN32EXPSUFFIX exp env WINDOWSEXPPREFIX WIN32EXPPREFIX env WINDOWSEXPSUFFIX WIN32EXPSUFFIX env WINDOWSSHLIBMANIFESTPREFIX env WINDOWSSHLIBMANIFESTSUFFIX SHLIBSUFFIX manifest env WINDOWSPROGMANIFESTPREFIX env WINDOWSPROGMANIFESTSUFFIX PROGSUFFIX manifest env REGSVRACTION regServerCheck env REGSVR os path join SCons Platform win32 get_system_root System32 regsvr32 env REGSVRFLAGS s env REGSVRCOM REGSVR REGSVRFLAGS TARGET windows msvc_setup_env_once env SCons Tool createLoadableModuleBuilder env env LDMODULE SHLINK env LDMODULEPREFIX SHLIBPREFIX env LDMODULESUFFIX SHLIBSUFFIX env LDMODULEFLAGS SHLINKFLAGS env _LDMODULE_TARGETS _windowsLdmodTargets env _LDMODULE_SOURCES _windowsLdmodSources env LDMODULEEMITTER ldmodEmitter env LDMODULECOM compositeLdmodAction
switch out environment variable into _ elmscom.txt,def _substitute_elmscom Common substitute geometry source icool _elmscom txt elmscom txt ICOOL_ELMSDB os path expandvars ICOOL_ELMSDB
process a cuckoo dropped file obtained from analysis .,def extract_file_cuckoo dropped_file custom_labels None u n Process a Cuckoo dropped file obtained from analysis n n Args n dropped_file A dict from the dropped list from the Cuckoo Sandbox n portion of the report n custom_labels A list of labels to attach into generated Indicators n n Returns n stix2 Indicator with a pattern that matches the file by name or n a variety of hashes n n labels u file hash watchlist dropped_pattern if custom_labels labels extend custom_labels file_name dropped_file get u filepath u sha1_value dropped_file get u sha1 u sha256_value dropped_file get u sha256 u md5_value dropped_file get u md5 u if file_name file_name file_name split u 1 dropped_pattern append create_stix2_comparison_expression u file name u file_name if sha1_value dropped_pattern append create_stix2_comparison_expression u file hashes SHA 1 u sha1_value if sha256_value dropped_pattern append create_stix2_comparison_expression u file hashes SHA 256 u sha256_value if md5_value dropped_pattern append create_stix2_comparison_expression u file hashes MD5 u md5_value if dropped_pattern return stix2 Indicator u labels labels u pattern create_stix2_observation_expression dropped_pattern u OR else return None
load and return mnist dataset .,def load_mnist mode train path if mode train fname_data os path join path train images idx3 ubyte fname_target os path join path train labels idx1 ubyte elif mode test fname_data os path join path t10k images idx3 ubyte fname_target os path join path t10k labels idx1 ubyte else raise ValueError mode must be test or train with open fname_data rb as fdata magic n_samples n_rows n_cols struct unpack IIII fdata read 16 data np fromfile fdata dtype np uint8 data data reshape n_samples n_rows n_cols with open fname_target rb as ftarget magic n_samples struct unpack II ftarget read 8 target np fromfile ftarget dtype np int8 return data astype float target
return profiles with at least one public field .,def public self return self filter self public_q
gets a set of performance signatures associated with a project and time range,def get_performance_signatures self project params results self _get_json self PERFORMANCE_SIGNATURES_ENDPOINT project params return PerformanceSignatureCollection results
"fail the test if : py : data:`first ` is not : py : data:`second ` . this is an obect - identity - equality test , not an object equality ( i.e. : py : func:`__eq _ _ ` ) test .",def failUnlessIdentical self first second msg None if first is not second raise self failureException msg or r is not r first second return first
merge all the applications logging configurations,def configure log_conf app_name None app_default_conf configobj ConfigObj indent_type interpolation False if app_name app_default logger_app_ app_name qualname nagare application app_name level INFO handlers app_ app_name propagate 1 handler_app_ app_name class StreamHandler formatter app_ app_name args sys stderr formatter_app_ app_name format asctime s name s levelname s message s app_default_conf merge configobj ConfigObj app_default indent_type interpolation False loggers append app_ app_name handlers append app_ app_name formatters append app_ app_name handler log_conf get logger pop handlers None if handler app_default_conf logger_app_ app_name handlers handler logger_sections values for section values in log_conf iteritems if section startswith logger_ for logger_section in logger_sections if qualname in logger_section and logger_section qualname startswith logger_section qualname nagare application app_name logger_section qualname rstrip for section in logger handler formatter log_conf section _app_ app_name log_conf pop section keys log_conf get loggers get keys if keys if isinstance keys basestring keys keys loggers extend keys keys log_conf get handlers get keys if keys if isinstance keys basestring keys keys handlers extend keys keys log_conf get formatters get keys if keys if isinstance keys basestring keys keys formatters extend keys log_conf configobj ConfigObj log_conf interpolation False app_default_conf merge log_conf apps_log_conf merge app_default_conf
test support . just prints docco on the module to standard output .,def dumpDoc modulename directory None docco getObjectsDefinedIn modulename directory print codegrab py ReportLab Documentation Utility print documenting modulename py print print if docco functions print No functions found else print Functions for f in docco functions print f proto print f doc if docco classes print No classes found else print Classes for c in docco classes print c name print c doc for m in c methods print m proto print m doc print
testarraycreation ( ) creation of a numpy array,def testArrayCreation self self assertTrue type rec 0 0 asarray type np empty 0
returns git service as per requested .,def get_git_service git if git github return GithubService elif git gitlab return GitlabService elif git pagure return PagureService elif git gerrit return GerritService else raise ValueError requested git service s is not valid git
! test subclass @param self this object @return none,def testSubclass self class MyNode ns network Node def __init__ self Initializer param self this object return none super MyNode self __init__ node MyNode
checks if chain has existing rules or not,staticmethod def hasExistingRules rules chain for rule in rules if A chain in rule return True return False
adjust the centre frequency of the signal .,def adjust_frequency self frequency_shift correction numpy exp 2j numpy pi frequency_shift self time_axis return self inherit numpy multiply self correction
check if algorithm and bit_length combination is supported .,def _is_algorithm_supported self algorithm None bit_length None if algorithm is None or bit_length is None return False if algorithm lower in c PluginSupportTypes SYMMETRIC_ALGORITHMS and bit_length in c PluginSupportTypes SYMMETRIC_KEY_LENGTHS return True elif algorithm lower in c PluginSupportTypes ASYMMETRIC_ALGORITHMS and bit_length in c PluginSupportTypes ASYMMETRIC_KEY_LENGTHS return True else return False
get action_log entry by set of attributes values .,classmethod def get_by_kwargs cls kwargs instance db query models ActionLog filter_by kwargs first return instance
attempt to encode json and xml automatically .,def _to_content_type self body headers content_type None content_type content_type or self content_type if content_type json headers Accept application json if body headers Content Type application json return jsonutils dump_as_bytes body
detach and flush the volume .,utils trace lockutils synchronized aoe_control aoe def disconnect_volume self connection_properties device_info force False ignore_errors False aoe_device aoe_path self _get_aoe_info connection_properties if os path exists aoe_path self _aoe_flush aoe_device
"check if a servicegroup , contactgroup or hostgroups exist with shortname = = group_name",def group_exists group_name servicegroups Model Servicegroup objects filter shortname group_name contactgroups Model Contactgroup objects filter shortname group_name hostgroups Model Hostgroup objects filter shortname group_name result servicegroups contactgroups hostgroups if result return False return result
create directories necessary for deployment .,def setup_directories sudo mkdir p path s env
initialize the object with values from a dtd array .,def init self sarray harray int x 16 for x in sarray for name desc in dtd_descriptor iteritems attr_value 0 total_width 0 for tup in desc if isinstance tup tuple offset shift width tup else offset shift width tup 0 8 mask 1 width 1 attr_value attr_value width harray offset shift mask total_width width setattr self PREFIX name attr_value setattr self max_ PREFIX name 1 total_width 1
constructor : param botengine : : param device_id : : param device_type : : param device_description : : param precache_measurements :,def __init__ self botengine device_id device_type device_description precache_measurements True SirenDevice __init__ self botengine device_id device_type device_description precache_measurements precache_measurements self last_sound None
"make the camera beep : param times : 1 , 2 , or 3",def beep self botengine times if not self is_connected or not self can_control return False botengine send_command self device_id ppc alarm times 1 return True
test ` foamlist ` class .,def test_foamlist print nTesting FoamList flist FoamList 1 2 3 4 print flist for i in flist print i flist2 FoamList flist flist dtype FoamList print flist2 flist FoamList 0 0 0 0 dtype int assert flist 0 4
saves recorded audio to a file .,def save file_path overwrite False global _temp_file_path if _thread_running is False if _temp_file_path and path exists _temp_file_path if path exists file_path is False or overwrite is True if path exists file_path remove file_path rename _temp_file_path file_path _temp_file_path else PTLogger info File already exists else PTLogger info No recorded audio data found else PTLogger info Microphone is still recording
check & set data to ` data `,def set_data self data for param in PARAMS if param not in data raise ValueError Missing parameter d in data param for path_key in PATHS path data path_key if not os path exists path raise ValueError Path does not exist s path self data data
"wallets must be list of two item lists . first item is crypto , second item is the address . example :",def fetch_wallet_balances wallets fiat modes price_fetch set x 0 for x in wallets balances prices fetch_length len wallets len price_fetch helpers fiat lower if not modes get async False for crypto in price_fetch try p get_current_price crypto fiat helper_prices helpers report_services True modes prices crypto price p if crypto in btc ltc doge uno helpers fiat lower crypto p except NoService as exc prices crypto error str exc for crypto address in wallets if address replace isdigit balances address balance float address continue try balances address balance get_address_balance crypto address strip modes except NoService as exc balances address error str exc else if modes get verbose False print Need to make fetch_length external calls with futures ThreadPoolExecutor max_workers int fetch_length 2 as executor future_to_key dict executor submit get_current_price crypto fiat report_services True modes crypto for crypto in price_fetch future_to_key update dict executor submit get_address_balance crypto address strip modes address for crypto address in wallets done not_done futures wait future_to_key return_when futures ALL_COMPLETED if len not_done 0 print not_done import debug raise Exception Broke for future in done key future_to_key future if len key 5 which balances else which prices res future result which key res ret for crypto address in wallets error None if balance in balances address crypto_value balances address balance else crypto_value 0 error balances address error if price in prices crypto sources fiat_price prices crypto price else sources fiat_price 0 error prices crypto error ret append crypto crypto address address crypto_value crypto_value fiat_value crypto_value or 0 fiat_price or 0 conversion_price fiat_price price_source sources 0 name if sources else None error error return ret
provider0 - > provider1 - > provider2,def test_u0D2r self app with app test_client as client rv client get provider0 dest provider2 assert rv status 200
tidal dissipation for a given tidal harmonic,def test_dissipation self test_dissipation 0 0400390625 res_dissipation dissipation self rho self U test assert_equal res_dissipation test_dissipation
return the `` attrs `` attribute values of * inst * as a dict .,def asdict inst recurse True filter None dict_factory dict retain_collection_types False attrs fields inst __class__ rv dict_factory for a in attrs v getattr inst a name if filter is not None and not filter a v continue if recurse is True if has v __class__ rv a name asdict v True filter dict_factory retain_collection_types elif isinstance v tuple list set cf v __class__ if retain_collection_types is True else list rv a name cf _asdict_anything i filter dict_factory retain_collection_types for i in v elif isinstance v dict df dict_factory rv a name df _asdict_anything kk filter df retain_collection_types _asdict_anything vv filter df retain_collection_types for kk vv in iteritems v else rv a name v else rv a name v return rv
get the first intersection on * b _ _ * with * boundaries*.,def get_first_intersection b__ boundaries intersections bounds get_intersections b__ boundaries del bounds dists np array b__ start distance p__ for p__ in intersections indices dists argsort if len intersections 0 return intersections indices 0 return None
handle a file being dropped from file manager,def OnDropFiles self msg hDropInfo msg 2 self frame SetActiveWindow nFiles win32api DragQueryFile hDropInfo try for iFile in range 0 nFiles fileName win32api DragQueryFile hDropInfo iFile win32ui GetApp OpenDocumentFile fileName finally win32api DragFinish hDropInfo return 0
split requested columns into columns that should load the next known value and columns that should load the previous known value .,def split_next_and_previous_event_columns self requested_columns def next_or_previous c if c in self next_value_columns return next elif c in self previous_value_columns return previous raise ValueError c not found in next_value_columns or previous_value_columns format c c groups groupby next_or_previous requested_columns return groups get next groups get previous
"returns texparserbase derived object on success , none on failure .",def process_article filename filename file_obj tarfile_obj get_tex_file filename if file_obj is None return None kind detect_file_kind file_obj parser None if kind PS print skipping postscript file elif kind auto ignore print asked to ignore file most likely it was withdrawn parser WithdrawnPaper if kind tex print parsing as TeX parser TexParser filename file_obj tarfile_obj elif kind latex print parsing as LaTeX parser LatexParser filename file_obj tarfile_obj else print cannot determine kind of file try if parser is not None parser parse except Exception as e print exception while trying to parse file print str e parser None file_obj close if tarfile_obj is not None tarfile_obj close return parser
create an http request to url and return the data in case of a problem return none,def _getXmlData self url try return ET fromstring urllib2 urlopen url timeout self timeout read except urllib2 URLError return None
"adds an artist to the known list of artists tagged with this tag ( if necessary ) , and sets the count of times that that artist has been known to be tagged with this tag .",def set_artist_count self artist count self artist_counts artist count
: param rev_str : : return : list of rev chars,def get_single_chars rev_str double_letter_code H F W Y i 0 rev_str_list while i len rev_str ch rev_str i dict_key ch if ch in double_letter_code ch_next rev_str i 1 dict_key ch ch_next i i 1 i i 1 rev_str_list append dict_key return rev_str_list
get information about mounted devices from /proc / mounts and /proc / self / mountinfo,def _get_active_mounts self self mountpoints defaultdict list mountinfo _MountinfoCache with open proc mounts as mounts for line in mounts try devspec mountpoint fstype _rest line split None 3 except ValueError log error failed to parse proc mounts line s line continue if devspec startswith dev devspec resolve_devspec devspec sysname True or devspec if fstype btrfs root mountinfo get_root devspec mountpoint if root is not None subvolspec root 1 or str btrfs MAIN_VOLUME_ID self mountpoints devspec subvolspec append mountpoint else log error failed to obtain subvolspec for btrfs device s at mountpoint s devspec mountpoint else self mountpoints devspec None append mountpoint
serialize a queryset ( or any iterator that returns database objects ) using a certain serializer .,def serialize self format queryset options s get_serializer format s serialize queryset options return s getvalue
add the impact severity for the most severe consequence,def _add_impact_severity self variant_obj gemini_variant gemini_impact gemini_variant impact_severity if gemini_impact MED gemini_impact MEDIUM variant_obj impact_severity gemini_impact
function calculates logarithm 2 of a kind of multinom .,def multinomLog2 selectors ln2 0 6931471805599453 noAll sum selectors lgNf math lgamma noAll 1 0 ln2 lgnFac for selector in selectors if selector 0 or selector 1 lgnFac append 0 0 elif selector 2 lgnFac append 1 0 elif selector noAll lgnFac append lgNf else lgnFac append math lgamma selector 1 0 ln2 return lgNf sum lgnFac
outputs a ` last - modified ` header for ` datetime ` .,def lastmodified date_obj web header Last Modified net httpdate date_obj
constructor : add description to argparser .,def __init__ self LogFileTool __init__ self multiple_logfiles True stdin_allowed False self argparser description Extracts general information from logfile and prints it to stdout self argparser add_argument verbose action store_true help show more verbose output depends on info section inf info sections cmds Below commands activate additional info sections for the log file self argparser_sectiongroup self argparser add_argument_group inf cmds self sections c 1 self for c in inspect getmembers sections inspect isclass
shows the login screen to the user,def login self return render default base login screen mako
"show regression coefficients x100 . note : run self.train ( ) first , or these will be meaningless .",def coefs self Target Cats Predictors self _unpack Coefs self model coef_ if len Cats 2 index Cats else index True Coefs st pd DataFrame Coefs index index columns Predictors columns Coefs 100 Coefs round return Coefs
view to create statistics endpoint .,def calculate_statistics satellites Satellite objects all transmitters Transmitter objects all modes Mode objects all total_satellites satellites count total_transmitters transmitters count total_data DemodData objects all count alive_transmitters transmitters filter alive True count alive_transmitters_percentage 0 format round float alive_transmitters float total_transmitters 100 2 mode_label mode_data for mode in modes tr transmitters filter mode mode count mode_label append mode name mode_data append tr band_label band_data filtered transmitters filter downlink_low__lt 30000000 count band_label append HF band_data append filtered filtered transmitters filter downlink_low__gte 30000000 downlink_low__lt 300000000 count band_label append VHF band_data append filtered filtered transmitters filter downlink_low__gte 300000000 downlink_low__lt 1000000000 count band_label append UHF band_data append filtered filtered transmitters filter downlink_low__gte 1000000000 downlink_low__lt 2000000000 count band_label append L band_data append filtered filtered transmitters filter downlink_low__gte 2000000000 downlink_low__lt 4000000000 count band_label append S band_data append filtered filtered transmitters filter downlink_low__gte 4000000000 downlink_low__lt 8000000000 count band_label append C band_data append filtered filtered transmitters filter downlink_low__gte 8000000000 downlink_low__lt 12000000000 count band_label append X band_data append filtered filtered transmitters filter downlink_low__gte 12000000000 downlink_low__lt 18000000000 count band_label append Ku band_data append filtered filtered transmitters filter downlink_low__gte 18000000000 downlink_low__lt 27000000000 count band_label append K band_data append filtered filtered transmitters filter downlink_low__gte 27000000000 downlink_low__lt 40000000000 count band_label append Ka band_data append filtered mode_data_sorted mode_label_sorted zip sorted zip mode_data mode_label reverse True band_data_sorted band_label_sorted zip sorted zip band_data band_label reverse True statistics total_satellites total_satellites total_data total_data transmitters total_transmitters transmitters_alive alive_transmitters_percentage mode_label mode_label_sorted mode_data mode_data_sorted band_label band_label_sorted band_data band_data_sorted return statistics
"execute a callable over the objects in the given iterable , in parallel , using no more than `` count `` concurrent calls .",def parallel iterable count callable args named coop task Cooperator work callable elem args named for elem in iterable return defer DeferredList coop coiterate work for i in xrange count
"this routine reads the data from the ascii file a , b , c = readcol('dat.txt',delimiter='| ' ) you can skip a certain number of rows in the top of the file by specifying skiprows = x option . the format option is needed if you have datatypes different from float in your table in that case format string should be comma delimted set of i ( int ) f(float ) d ( double ) s ( string ) characters . e.g. a , b , c = readcol('dat.txt',format='i , s , d ' )",def readcol filename delimiter format None skiprows 0 kw if format None res numpy loadtxt filename delimiter delimiter skiprows skiprows kw nrows res shape 0 if res ndim 2 ncols res shape 1 elif res ndim 1 ncols 1 res shape nrows 1 else raise Exception wrong array dimensions stor for i in range ncols stor append res i return tuple stor else types i 0 formats format split convs retnull lambda s numpy float s or 0 for i a in enumerate formats if a I curtype numpy int32 convs i retnull elif a L curtype numpy int64 convs i retnull elif a F curtype numpy float32 convs i retnull elif a D curtype numpy float64 convs i retnull elif a S curtype S100 else raise Exception Sorry Unknown type in the format string The allowed types are S I F D string int float double types append a d i curtype rec numpy loadtxt filename dtype types delimiter delimiter skiprows skiprows converters convs ncols len rec 0 nrows len rec buf stor for a in formats if a I tmp numpy zeros nrows dtype numpy int32 if a L tmp numpy zeros nrows dtype numpy int64 elif a F tmp numpy zeros nrows dtype numpy float32 elif a D tmp numpy zeros nrows dtype numpy float64 elif a S tmp numpy zeros nrows dtype S100 stor append tmp for i in range ncols for j in range nrows stor i j rec j i return tuple stor
initialise the map using an image the image grid .,classmethod def from_imagegrid cls im cells file None origin None texture_sequence im texture_sequence l cw ch texture_sequence item_width texture_sequence item_height inst cls for y row in enumerate cells m l append m for x num in enumerate row m append spryte Sprite texture_sequence num x cw y ch map inst batch inst inst set_cells cw ch l origin return inst
moves down the block 1 square,def block_down self sound True self block backup self block pos y 1 if not self is_valid_block self block restore self next_block elif sound self dispatch_event on_move_block
creates one or more spirent testcenter automation objects .,def create self obj_type parent attributes return self ls create obj_type under parent obj_ref attributes
return total file size of extracted files in bytes .,def extracted_size self raise NotImplementedError
return card popularity count by snapshot i d .,def get_cardpop_count self card None snapshot_id None out 0 snapshot_id str snapshot_id if card is not None and snapshot_id is not None if snapshot_id in self cardpop cardpop self cardpop snapshot_id cardpop cpid self get_card_cpid card if cpid in cardpop out cardpop cpid count return out
": return : total amount of points , scored by the party or none if not initialized : rtype : float",property def points self return self _points
build huffman code table from symbol sequence,classmethod def from_data cls data frequencies collections Counter data return cls from_frequencies frequencies concat _guess_concat data
"sets up the file to export the data as csv . if filename is not specified , a default name based on time will be used . : param filename : name of the file where data will be exported . : type filename : str . : param path : path where data file will be saved . : type path : str . : param timeout : time to wait after emptying the internal buffer before next write . : type timeout : float .",def __init__ self filename None path None timeout 0 5 multiprocessing Process __init__ self self _exit multiprocessing Event self _store_queue multiprocessing Queue self _csv None self _file None self _timeout timeout if filename is None filename strftime Constants csv_default_filename gmtime self _file self _create_file filename path path Log i TAG Process ready
returns true if the provided path is an existing directory,error_msg The provided path must be an existing folder def validate_isfolder value return os path isdir value
uploading package sets metadata and sends to s3,def test_upload self package make_package datastr foobar data BytesIO datastr self storage upload package data key list self bucket objects all 0 Object contents BytesIO key download_fileobj contents self assertEqual contents getvalue datastr self assertEqual key metadata name package name self assertEqual key metadata version package version self assertEqual key metadata summary package summary
runner to use for the ' test_suite ' entry of your setup.py .,def setup_py_test nose main addplugins NoseSQLAlchemy argv runner
"a different user than the object 's owner should not be able to access the view , a permissiondenied should be raised",def test_author_required_not_allow_not_object_user self request self factory get some random place request user AnonymousUser user get_user_model objects create_user username test_user password top_secret question Question objects create title Another Question description A not so long random text to fill this field pub_date timezone datetime 2016 1 6 0 0 0 reward 0 user user closed False with self assertRaises PermissionDenied SomeAuthorRequiredView as_view request pk question pk
returns the actual repository root for a path . default implmentation passes through the path,def getRoot self path return path
sets the output directory for all the analyzers,def setDirectory self d self oDir d for nm in self analyzers self analyzers nm setDirectory self oDir
halt computation until a key is pressed .,def std_pause message_in None message_out None if not message_in is None print message_in getch if not message_out is None print message_out
"null declaration , is used when a token appears at the beginning of a language construct .",def nud self raise SyntaxError Syntax error r self ident
return the element wise multiplicative of the inputs .,def mul_or_none a b if a is None or b is None return None return a b
"builds graph , loads checkpoint , and returns wrapped model .",def load_checkpoint path instantiate_sess True tf logging info Loading checkpoint from s path hparams lib_hparams load_hparams path model build_graph is_training False hparams hparams wmodel lib_tfutil WrappedModel model model loss graph hparams if not instantiate_sess return wmodel with wmodel graph as_default wmodel sess tf Session saver tf train Saver tf logging info loading checkpoint s path chkpt_path os path join path best_model ckpt saver restore wmodel sess chkpt_path return wmodel
validation only succeeds if all passed in validators return no errors,def all validators def validate_all fields for validator in validators errors validator fields if errors return errors validate_all __doc__ and join validator __doc__ for validator in validators return validate_all
should fetch from twitter and save to db when profile not found in db,def test_profile_not_cached self p Profile username twitter network F description Cached in DB p save profile self client get_profile twitter expected_description u Your official source for news updates and tips from Twitter Inc self assertEqual profile description expected_description p Profile objects get username twitter network T self assertEqual p name Twitter self assertEqual p network T self assertEqual p description expected_description
searches for the base address used in a phrase[+displacement ] ex : dword [ eax * 4 + 0x08040000 ] - > 0x08040000 dword [ ebp + 0x8 ] - > 0x8,def search_displ_base il res _search_phrase_op il LowLevelILOperation LLIL_CONST if res is not None return int res tokens 0 text 16
"set the number of openmp threads used , typically equals the number of numa domains",cached_property def omp_threads self return str self attributes omp_threads
set the contents of the text box .,def set self value if isinstance value NSAttributedString self _nsObject setAttributedStringValue_ value else self _nsObject setStringValue_ value
"from matrix_world and desired real size length in meters , calculate relative length without matrix applied . apply matrix , and you will get desired length .",def real_length_to_relative matrix length l r s matrix decompose ms Matrix Scale s x 4 l Vector length 0 0 v ms inverted l return v x
cleans up a folder by removing all files in it .,def clean_folder directory ignore tmp c if not os path isdir directory return False ignore_list ignore split for file_path in os listdir directory if os path basename file_path not in ignore_list if os path isfile file_path os unlink file_path elif os path isdir file_path shutil rmtree file_path return True
a view that returns a serialized list of all resources registers to the `` api `` . useful for discovery .,def top_level self request api_name None serializer Serializer available_resources if api_name is None api_name self api_name for name in sorted self _registry keys available_resources name list_endpoint self _build_reverse_url api_dispatch_list kwargs api_name api_name resource_name name schema self _build_reverse_url api_get_schema kwargs api_name api_name resource_name name desired_format determine_format request serializer options if text javascript in desired_format callback request GET get callback callback if not is_valid_jsonp_callback_value callback raise BadRequest JSONP callback name is invalid options callback callback serialized serializer serialize available_resources desired_format options return HttpResponse content serialized content_type build_content_type desired_format
startd adb server daemon on host : return : result of _ exec_command ( ) execution,def start_server adb_full_cmd v ADB_COMMAND_PREFIX v ADB_COMMAND_START_SERVER return _exec_command adb_full_cmd
return a lydocinfo instance for the document .,def docinfo document return info document lydocinfo
ask the user a color .,def getColor parent None title color None alpha False global _savedColor if color is None color _savedColor dlg QColorDialog color parent options QColorDialog ColorDialogOptions if alpha options QColorDialog ShowAlphaChannel if not QSettings value native_dialogs colordialog True bool options QColorDialog DontUseNativeDialog dlg setOptions options dlg setWindowTitle title or app caption _ Select Color if dlg exec_ _savedColor dlg selectedColor return _savedColor
"yields two - tuples ( headername , entered text ) for the headers that are non - empty .",def headers self for name desc in headers text self edits name text strip if text yield name text
return the text of the specified block .,def text self block return block text
returns the current main widget ( an empty qwidget by default ) .,def mainWidget self return self _mainWidget
sends a json encodable object over the specified socket ( zlib - compressed ) .,def Send obj sock obj json dumps obj compression_level 2 compressed zlib compress obj compression_level payload struct pack i len compressed compressed sock sendall payload
searches |text| for instances of properties requiring the -webkit- prefix and adds the prefix to them .,def add_webkit_prefix_to_unprefixed_properties self text converted_properties set text_chunks cur_pos 0 for m in self prop_re finditer text text_chunks extend text cur_pos m start m group 1 property m group 2 oldProperty self renamed_properties get property if oldProperty text_chunks append oldProperty elif property in self prefixed_properties text_chunks extend webkit property else text_chunks append property text_chunks append self add_webkit_prefix_to_unprefixed_value property m group 3 converted_properties add property cur_pos m end text_chunks append text cur_pos for prop in converted_properties _log info converting s prop return converted_properties join text_chunks
scans a given ro version directory for files that have been modified since last synchronization and pushes them to rosrs . modification is detected by checking modification times and checksums .,def pushResearchObject localRo remoteRo force False push PushResearchObject localRo remoteRo force for action uri in push push yield action uri return
"extract the images into a 4d uint8 numpy array [ index , y , x , depth ] .",def extract_images filename print Extracting filename with gzip open filename as bytestream magic _read32 bytestream if magic 2051 raise ValueError Invalid magic number d in MNIST image file s magic filename num_images _read32 bytestream rows _read32 bytestream cols _read32 bytestream buf bytestream read rows cols num_images data numpy frombuffer buf dtype numpy uint8 data data reshape num_images rows cols 1 return data
process elements that make blocks of text in the final thread,def processBlock self text wrap code p class code p quote p class quote p pre pre pre output text for block in YABB_BLOCK pattern re compile block s w S s block s S block re IGNORECASE matchsets re findall pattern text for m in matchsets html wrap block 0 m 2 wrap block 1 output re sub pattern html output 1 return output
create a path and set up owner uid .,def mkdir path uid mode 448 exist_ok True os makedirs path mode exist_ok exist_ok os chown path uid 1
"downloads the required pre - trained embedding : param emb_type : one of the supported embedding classes ( word2vec , glove etc .. ) : param directory : the directory where the file will be downloaded default dir : ~/.embeddings : return : the full path of the downloaded file",def download emb_type directory embeddings if directory 1 SEP directory SEP if not os path exists directory and os path isdir directory print directory does not exist create one os makedirs directory f_emb directory emb_type file if not os path exists f_emb print downloading the required file emb_type name emb_type download directory else print file already exist return f_emb
change values of keypoint according to paramters for resizing an image .,def resize_keypoint keypoint in_size out_size keypoint keypoint copy y_scale float out_size 0 in_size 0 x_scale float out_size 1 in_size 1 keypoint 0 y_scale keypoint 0 keypoint 1 x_scale keypoint 1 return keypoint
return an iterator that recursively traverses anonymous fields .,def deep_items type_ for k v in type_ iteritems if k yield k v else for i in deep_items v type yield i
release grib message handle and inform file of release .,def __exit__ self exc_type exc_val exc_tb super self __class__ self __exit__ exc_type exc_val exc_tb if self grib_index self grib_index open_messages remove self
test that printing the thermal params does n't bomb,def test_print_thermal_params self trappy wa SysfsExtractor pretty_print_in_ipython
"parse a sourcedid value from an lti 1.1 outcomes service request . return a tuple ( exercise , user_profile ) . either value may be none if the instance is not found in the database .",def parse_sourced_id sourced_id_str exercise_id _ user_token sourced_id_str partition if not exercise_id or not user_token return None None try exercise LTIExercise objects get pk exercise_id except LTIExercise DoesNotExist exercise None token_type token user_token 0 user_token 1 if token_type i try user_profile User objects get pk token userprofile except User DoesNotExist user_profile None elif token_type a try user_profile Enrollment objects get anon_id token user_profile except Enrollment DoesNotExist user_profile None else user_profile None return exercise user_profile
"inserts squirt command for given tool @param tool : integer , tool to squirt @param squirt_initial_inactve_tool : boolean , if this is the squirt of the initial significant toolchange",def squirt_tool self tool squirt_initial_inactive_tool False if not squirt_initial_inactive_tool self buffer append M135 T i n tool self buffer append G92 s0 n self TOOLHEADS tool self buffer append G1 F f s f n self squirt_feedrate self TOOLHEADS tool self retract_distance_mm self buffer append G92 s0 n self TOOLHEADS tool
: param src_text : source text to be minified : return : minified text,def minify_js_proc src_text return jsmin src_text
helper for admins to generate random 24 character string . used as the secret key for sessions . must be consistent ( and secret ) per environment . output : b'cd8c2471 ................. 2416c0e030d09 ' copy the value in between the quotation marks to the settings file,manager command def generate_session_key return binascii hexlify os urandom 24
callback trigger for every module loaded .,def load_module params global cm global pyrebox_print global entry_point_bp global target_pgd global target_procname import pefile import api from api import BP pid params pid pgd params pgd base params base size params size name params name fullname params fullname if pgd target_pgd and target_procname lower startswith name lower ep None try pe_data api r_va pgd base 4096 pe pefile PE data pe_data ep base pe OPTIONAL_HEADER AddressOfEntryPoint except Exception as e print e pyrebox_print Could not read EP from module s on load name if ep is not None pyrebox_print The entry point for s is 0x x n target_procname ep cm rm_callback load_module pyrebox_print Setting BP on entrypoint entry_point_bp BP ep pgd new_style True func module_entry_point entry_point_bp enable
create a script file to feed into bitgen .,def create_script config create_bitgen_dir config bgs_fn get_bitgen_script_filename config True flags get_flags config bgs open bgs_fn w for flag in flags if flag configuration continue if flags flag _true bgs write s n flag continue bgs write s s n flag flags flag bgs write n for c in flags configuration bgs write s n c bgs close return bgs_fn
the observed object can pass itself as first argument .,def test_callerIdentification self a Foo a self buf observable_function def f self buf append f def g caller self buf append g s caller __name__ f add_observer g identify_observed True f add_observer a milton identify_observed True f self buf sort self assertEqual self buf amiltonf f gf
verify deadline is set to course end date by signal .,def test_deadline self deadline datetime now tz UTC timedelta days 7 VerificationDeadline set_deadline self course id deadline _listen_for_course_publish store self course id self assertEqual VerificationDeadline deadline_for_course self course id self course end
"returns a dict containing the filenames for a complete set of profile images , keyed by pixel size .",def get_profile_image_names username name _make_profile_image_name username return size _get_profile_image_filename name size for size in _PROFILE_IMAGE_SIZES
test render_to_string ( ) when makomiddleware has not initialized the threadlocal request_context.context . this is meant to run in lms .,unittest skipUnless settings ROOT_URLCONF lms urls Test only valid in lms patch edxmako middleware REQUEST_CONTEXT def test_render_to_string_when_no_global_context_lms self context_mock del context_mock context self assertIn this module is temporarily unavailable render_to_string courseware error message html None
"given a course key , return the course if it exists , the given user has access to it , and it is properly configured for video uploads",def _get_and_validate_course course_key_string user course_key CourseKey from_string course_key_string course get_course_and_check_access course_key user if settings FEATURES ENABLE_VIDEO_UPLOAD_PIPELINE and getattr settings VIDEO_UPLOAD_PIPELINE None and course and course video_pipeline_configured return course else return None
client api operation adapter / wrapper,def add_user_milestone user milestone if not settings FEATURES get MILESTONES_APP False return None from milestones import api as milestones_api return milestones_api add_user_milestone user milestone
"add dest to the graph , possibly updating the shortest paths object",def add_dest_to_graph dest graph edges_src None spt None node_data_gen None kw added None if dest in graph and not _is_fake_dest graph dest log debug s is already in the graph dest in_dag True else in_dag False if not edges_src added sinks find_sink graph if not sinks log info No sinks found in the graph for node in sinks if node dest continue log info Connected s to s in the graph node dest _add_fake_route graph node dest kw added append node else added edges_src dest log info Connecting edges sources s to the graph to s dest added for s in added _add_fake_route graph s dest kw graph add_edges_from s dest for s in added kw ndata if not node_data_gen else node_data_gen if node_data_gen or not in_dag graph add_node dest prefix True ndata if added and spt log info Updating SPT _update_paths_towards spt graph dest added
vimeo < url > -- returns information on the vimeo video at < url >,hook regex vimeo com 0 9 def vimeo_url match info http get_json http vimeo com api v2 video s json match group 1 if info info 0 duration timeformat format_time info 0 duration info 0 stats_number_of_likes format info 0 stats_number_of_likes d info 0 stats_number_of_plays format info 0 stats_number_of_plays d return x02 title s x02 length x02 duration s x02 x02 stats_number_of_likes s x02 likes x02 stats_number_of_plays s x02 plays x02 user_name s x02 on x02 upload_date s x02 info 0
restart [ reason ] -- restarts the bot with [ reason ] as its quit message .,hook command autohelp False permissions botcontrol adminonly True def restart inp nick None conn None bot None for botcon in bot conns if inp bot conns botcon cmd QUIT Restarted by format nick inp else bot conns botcon cmd QUIT Restarted by format nick time sleep 5 args sys argv args insert 0 sys executable os execv sys executable args
create an example set of data that can be used in testing,pytest fixture scope function def example_dataset_one request inventory Inventory gold 1000 skulls 100 cave Lair name Cave inventory inventory cave insert burt ComplexDragon name Burt dob datetime 1979 6 11 breed Cold drake lair cave traits irritable narcissistic burt insert
return the content type ( django model ) for this model .,property def content_type self return ContentType objects get app_label calls model call
create object instance and perform a single optimization run using lus .,def __init__ self problem parameters parameters_default parallel False args kwargs self problem problem gamma parameters 0 self decrease_factor 0 5 1 0 gamma problem dim SingleRun __init__ self args kwargs
"finds position on line closest to a given point , using projection",def closest_point_on_seg seg pt seg_v seg b seg a pt_v pt seg a seg_len math sqrt seg_v dot seg_v seg_v_unit seg_v copy seg_len proj pt_v dot seg_v_unit if proj 0 return seg a copy if proj seg_len return seg b copy return seg_v_unit proj seg a
this function is called to reset the clock before running a set of tests .,bacpypes_debugging def reset_time_machine start_time 0 0 if _debug reset_time_machine _debug reset_time_machine r start_time global time_machine if not time_machine raise RuntimeError no time machine if isinstance start_time str start_time xdatetime start_time if _debug reset_time_machine _debug start_time r start_time time_machine tasks time_machine current_time start_time time_machine time_limit None
it returns a mapping function from multiprocessing or itertools,def _get_func_tools processes if isinstance processes bool and not processes map_ imap else import multiprocessing if not isinstance processes int processes None pool multiprocessing Pool processes map_ pool imap_unordered raise RuntimeError Multiprocessing not supported yet filter_ ifilter return map map_ filter filter_
get an executable instance for one of problemtools ' external tools .,def get_tool name path get_tool_path name return Executable path if path is not None else None
returns the array of the next decision period .,def get_next_period_array self period if self is_real_decision_period period index self decision_times np where self decision_times period 0 1 0 return self tree index copy raise IndexError Given period is not in real decision times
test app i d : return : void,def test_app_id self app_id self create_application app_id self assert_is_not_none app_id self assert_in testbed app_id self testbed deactivate with self assert_raises_regexp RuntimeError Not running in Google App Engine environment while fetching app_id self create_application app_id self testbed activate app_id self create_application app_id self assert_is_not_none app_id self assert_in testbed app_id
get the setup arguments : return : the setup arguments,def _load_arguments self setup_arguments dict self _process_argument setup_arguments name general name str self _process_argument setup_arguments version general version str if scm in setup_arguments version from setuptools_scm import get_version setup_arguments version get_version root self base_path self _process_argument setup_arguments description general description str self _process_argument setup_arguments long_description general long_description str self _process_argument setup_arguments url general url str self _process_argument setup_arguments license general license str self _process_argument setup_arguments install_requires general requirements list self _process_argument setup_arguments author author name str self _process_argument setup_arguments author_email author email str classifiers self _process_classifier classifiers classifiers status list Development Status 0 w d 0 self _process_classifier classifiers classifiers programming_languages list Programming Language 0 self _process_classifier classifiers classifiers audiences list Intended Audience 0 self _process_classifier classifiers classifiers topics list Topic 0 self _process_classifier classifiers classifiers license list License 0 if classifiers setup_arguments classifiers list set classifiers self _process_argument setup_arguments setup_requires setup requirements list self _process_argument setup_arguments tests_require tests requirements list self _process_argument setup_arguments test_suite tests suite str packages_arguments dict self _process_argument packages_arguments exclude packages exclude list self _process_argument packages_arguments include packages include list if packages_arguments setup_arguments packages setuptools find_packages packages_arguments self _process_argument setup_arguments include_package_data package data include bool commands dict if commands in self config for command_name in self config commands if command_name endswith description continue description_name s description command_name given_command self _process_value commands command_name str if description_name in self config commands given_description self config commands description_name else given_description given_command class CustomCommand distutils cmd Command command given_command description given_description user_options def initialize_options self Set default values for options pass def finalize_options self Post process options pass def run self Run command process Popen self command shell True return_code process wait if return_code 0 exit return_code commands command_name CustomCommand if commands setup_arguments cmdclass commands return setup_arguments
computes git - style hash of a string .,def hashString strr hasher hashlib sha1 hasher update blob str len strr x00 hasher update strr return hasher hexdigest
schema for data in collectorupdate .,staticmethod def schema_complete return Schema stage And str len timestamp int status And str lambda s s in started succeeded failed Optional matrix default default And str len Optional information default Optional Regex a z _a z object
"for each backends , calls f with its tensors , and assert the results to be all close .",def funcs_allclose f backends backend_tensors rtol 0 atol 1e 07 results for backend tensors in zip backends backend_tensors results append call_func f backend tensors return tensors_allclose results rtol rtol atol atol
start the execution of tasks by the processes .,def processTasks self for i in self tasks self dispatcher putTask i
"solves a constrained optimization problem basic solve : getmin(x , y , z , msg , fns , state ) solve with a state manipulator : getmin(x , y , z , msg , smanip , fns , state )",def getMin X Y Z msg fns state smanip None if smanip is None smanip StateManipulator checkVectorSpace X X checkVectorSpace Y Y checkVectorSpace Z Z checkMessaging msg msg Optizelle Constrained Functions checkT fns fns Optizelle Constrained State checkT state state checkStateManipulator smanip smanip ConstrainedAlgorithmsGetMin X Y Z msg fns state smanip
"set the default initializer , the initializer should be constant , uniform , normal , xavier , msra .",def _set_default_initializer self initializer if initializer is None if self initializer is None raise ValueError ParamAttr initializer is not set return if self initializer is not None return self initializer initializer
initializes a new : py : class:`mahjong.models . table ` .,def create return Table stones mahjong services stone get_all_shuffled
steady state photon number from drive strenghth eps_d and kappa,def photon_number eps kappa n_bar 2 eps kappa 2 return n_bar
return a titlecased version of the string .,def title self return apply_text self lambda s s title
sample the posterior of a component,def sample self Xnew gp 0 size 10 full_cov True mu va self predict Xnew gp samples for i in range mu shape 1 if full_cov smp np random multivariate_normal mean mu i cov va size size else smp np random multivariate_normal mean mu i cov np diag np diag va size size samples append smp return np stack samples 1
return a prototype scanner instance for scanning executable files for static - lib dependencies,def ProgramScanner kw kw path_function SCons Scanner FindPathDirs LIBPATH ps SCons Scanner Base scan ProgramScanner kw return ps
generate . : param str size_mb : size in mb : return str : bytes,hammock get response_content_type hammock TYPE_OCTET_STREAM def generate self size_mb return io BytesIO bytearray int size_mb 20
sets option < name > to value < value > if possible . can be overwritten and expanded by modules .,def setoption self name value if not name or not isinstance name str print_error Option name not understood return False if not value or not isinstance value str print_error Option value not understood return False if name and isinstance name str and name upper in self options values self options name upper if Options in values and values Options and not value upper in values Options print_error str name upper must be one of join values Options return True elif Options in values and values Options value value upper self options name upper Value value return True else return False
return a list of all defined types,def getTypes self assert False abstract method called
set the upper boundary for the value of this parameter .,def set_kbx_param_max_value self value pass
clear the box / coordinate / velocity / force data .,def clear self self _box None self _x None self _v None self _f None
delete a project from the db completely . warning : this will delete all the project 's networks and cannot be reversed !,rpc Integer _returns Unicode def purge_project ctx project_id project_lib delete_project project_id ctx in_header __dict__ return OK
set location based on ' by ' column .,def set_location self place_item None if self has_non_empty_attribute by place self by if utils count_wikilinks place 1 place utils get_wikilinks place 0 title if utils wp_page_exists da place place_item utils q_from_wikipedia da place if place_item place_item_ids utils get_P31 place_item self repo for p31_value in place_item_ids if p31_value in self data_files settlement self add_statement location place_item return
webviewcellwidget(parent : qwidget ) - > webviewcellwidget create a rich text cell without a toolbar,def __init__ self parent None QCellWidget __init__ self parent self setLayout QtGui QVBoxLayout self self toolBarType WebViewCellToolBar QtWebKit QWebSettings globalSettings setAttribute QtWebKit QWebSettings DeveloperExtrasEnabled True self browser QtWebKit QWebView self layout addWidget self browser self browser setMouseTracking True self urlSrc None
parse_string(text : str ) - > dom parses an xml string and returns the dom object,def create_document_from_string self text try dom minidom parseString text except xml parsers expat ExpatError as e raise self XMLParseError e lineno e offset e code return dom
uses csvfile and extractcolumn with mismatching columns .,def test_csv_mismatch self self assertTrue execute read CSVFile identifier file File self _test_dir test csv ExtractColumn identifier column_index Integer 0 column_name String col 2 0 value 1 table
"dump the grammar tables to standard output , for debugging .",def report self from pprint import pprint print s2n pprint self symbol2number print n2s pprint self number2symbol print states pprint self states print dfas pprint self dfas print labels pprint self labels print start self start
returns the dn for this entry .,def dn self if self attributes 0 startswith dn return self attributes 0 4 else return None
first setup aikif logging then initialise pyaixi,def __init__ self name fldr mod_agt Agent __init__ self name fldr self lg mod_log Log fldr options copied from https github com gkassel pyaixi blob release 1 1 0 aixi py self default_options self default_options agent mc_aixi_ctw self default_options agent horizon 5 self default_options ct depth 30 self default_options compare self default_options environment coin_flip self default_options exploration 0 0 Do not explore self default_options explore decay 1 0 Exploration rate does not decay self default_options learning period 0 Learn forever self default_options mc simulations 300 self default_options non learning only False Whether to record statistics gathered in the non learning period only self default_options profile False Whether to profile code self default_options terminate age 0 Never die self default_options verbose False self start
replace singletons by the unknown word with a probability p.,def insert_singletons words singletons p 0 5 new_words for word in words if word in singletons and np random uniform p new_words append 0 else new_words append word return new_words
log and ignore all signals .,def signal_handler_ignore signum frame u n Log and ignore all signals n logging warning u Received signal d ignoring it signum
get the tab separated representation of this filenamepath .,def __repr__ self return s t s self fileName self path
"find a socket , which is connected to the specified port leaves socket in r6 reg .",def generate sc findpeer generate sc dupsh generate sock r6 return sc
transform with estimator using formula .,if_delegate_has_method delegate estimator def transform self data if self return_type dataframe X dmatrix self design_X_ data return_type dataframe else X np array dmatrix self design_X_ data return self estimator_ transform X
adds a server to the serverlist .,def addServer self server needpw self not_locked_pixbuf if server needsPassword None if server needsPassword needpw self lock_pixbuf else needpw self not_locked_pixbuf flagmanager FlagManager flag flagmanager get_flag server get_location self liststore append needpw flag server getName server getVersionString server getaddress server getPing server getPlayerString server getMap server getGameTypeName server server getConnections server getLastConnect self liststore set_sort_column_id 10 gtk SORT_DESCENDING
handle from x.y import z as a,def test_import_package_as self self obfuscate_and_write testfiles package tobeimported py generated package tobeimported py self obfuscate_and_write testfiles package __init__ py generated package __init__ py self obfuscate_and_write testfiles importpackage_as py generated importpackage_as py assert 42 subprocess call sys executable generated importpackage_as py env PYTHONPATH generated Incorrect value returned after obfuscation
action function for ` poupdate ` builder,def _update_or_init_po_files target source env import SCons Action from SCons Tool GettextCommon import _init_po_files for tgt in target if tgt rexists action SCons Action Action MSGMERGECOM MSGMERGECOMSTR else action _init_po_files status action tgt source env if status return status return 0
concatenate url and argument dictionary regardless of whether url has existing query parameters .,def url_concat url args if not args return url if url 1 not in url if in url else return url urllib urlencode args
calculate the current false positive rate based on elements added,def current_false_positive_rate self u Calculate the current false positive rate based on elements added n n Return n float The current false positive rate num self number_hashes 1 self elements_added dbl num float self number_bits exp math exp dbl return math pow 1 exp self number_hashes
the filename where the task writes its description .,def description_fn self fn os path join self directory description txt return fn
deletes an access token from the store using its token string to identify it . this invalidates both the access token and the token .,def delete_token self token raise NotImplementedError
"writes the statistical information as rows formatted as : title , mu , sigma to the specified file .",def write_statistics filename statistics save_to_file titles list values list for title value sigma in statistics titles append title titles append sig_ title values append value values append sigma titles map str titles values map str values title_line join titles value_line join values if save_to_file outfile open filename w outfile write title_line n outfile write value_line outfile close else print title_line print value_line
random classify the training data .,def train self x_train y_train n_rounds random_state min_inf 1 0 n_features x_train shape 1 test_funcs threshold1 threshold2 threshold3 threshold4 for _ in xrange n_rounds i random_state randint 0 len test_funcs 1 func test_funcs i if i 0 col random_state randint 0 n_features thresh random_state uniform x_train col min x_train col max args col thresh z x_train col thresh else selected random_state randint 0 n_features 2 col1 col2 selected 0 selected 1 if i 1 diff x_train col1 x_train col2 elif i 2 diff x_train col1 x_train col2 elif i 3 diff np abs x_train col1 x_train col2 thresh random_state uniform diff min diff max args col1 col2 thresh z diff thresh inf information_gain y_train z y_train z if inf min_inf min_inf inf self func func self args args return self
"delete a bunch of values in the cache at once . for certain backends ( memcached ) , this is much more efficient than calling delete ( ) multiple times .",def delete_many self keys version None u n Delete a bunch of values in the cache at once For certain backends n memcached this is much more efficient than calling delete multiple n times n for key in keys self delete key version version
run migrations in ' online ' mode .,def run_migrations_online bot_config ConfigParser default_section bot bot_config read Path __file__ resolve parent parent config ini connectable engine_from_config config get_section config config_ini_section prefix sqlalchemy poolclass pool NullPool url bot_config get bot db_url with connectable connect as connection context configure connection connection target_metadata target_metadata with context begin_transaction context run_migrations
tests the gprmc message parsing .,def test_handle_gprmc self sup800f Sup800fTelemetry None sup800f _handle_gprmc GPRMC 123456 789 A 4005 429 N 10511 105 W 9 719 180 0 030415 003 9 W A hh r n dummy_telemetry sup800f _telemetry self assertAlmostEqual dummy_telemetry message lat 40 090483 6 self assertAlmostEqual dummy_telemetry message long 105 185083 6 self assertAlmostEqual dummy_telemetry message bearing 180 0 self assertAlmostEqual dummy_telemetry message speed 5 0 3 self assertAlmostEqual dummy_telemetry message timestamp 1428064496 789 3
removes the option from configparser as well as the secure storage backend,def remove_option self section option u Removes the option from ConfigParser as well as n the secure storage backend n if self is_secure_option section option and self keyring_available s_option u s s section option self _unsaved s_option u delete None ConfigParser remove_option self section option
test pre - cleaning packages in a workspace .,def test_preclean pass
get named configuration option from git repository .,def git_config_get option default None u n Get named configuration option from git repository n try return subprocess check_output GIT u config u get option rstrip decode u utf 8 except subprocess CalledProcessError as e return default
run kvm - ok as root to check that kvm is properly enabled after installation of the required packages .,def RunKvmOk try return not cmd_helper RunCmd sudo kvm ok except OSError logging info kvm ok not installed return False
get the transaction object given a transaction hash .,def get_tx self txhash txhex self get_raw_transaction txhash tx CTransaction deserialize to_binary txhex return blockchain CTransaction from_bitcoincore txhash tx self
add code to execute when a node is destroyed,def addOnDestroy call args kwargs nodeClass pass
"test scan_for_tests with tox.ini in the files list , should add several build requirements",def test_scan_for_tests_tox_requires self listdir_backup os listdir test os listdir mock_generator tox ini test scan_for_tests pkgdir test os listdir listdir_backup self assertEqual test buildreq buildreqs set tox pytest virtualenv pluggy py python
sets the semantic role @param srole : the semantic role @type srole : string,def set_sem_role self sRole self node set semRole sRole
returns the sentiment_product_feature for the expression @rtype : string @return : the sentiment_product_feature for the expression,def get_sentiment_product_feature self return self node get sentiment_product_feature
set the checked state after all children have been populated .,def init_layout self super AndroidRadioGroup self init_layout d self declaration w self widget if d checked self set_checked d checked else for c in d children if c checked d checked c w setOnCheckedChangeListener w getId w onCheckedChanged connect self on_checked_changed
calculate the truncated singular value decomposition : math:`a = u * sigma * v^t ` using svdlibc .,def svd matrix k 50 assert matrix ndim 2 if isinstance matrix DenseMatrix Ut S Vt svd_ndarray matrix k elif isinstance matrix SparseMatrix if matrix nnz 0 U DenseMatrix matrix shape 0 k S np zeros k V DenseMatrix matrix shape 1 k return U S V if matrix shape 1 matrix shape 0 1 2 V S U matrix T svd k return U S V Ut S Vt svd_llmat matrix llmatrix k else raise TypeError Don t know how to SVD a r type matrix U DenseMatrix Ut T matrix row_labels None V DenseMatrix Vt T matrix col_labels None return U S V
tests that updates on static only column work as intended,skipUnless PROTOCOL_VERSION 2 only runs against the cql3 protocol v2 0 def test_static_only_updates self instance TestStaticModel create instance static it s shared instance text some text instance save u TestStaticModel get partition instance partition u static it s still shared u update actual TestStaticModel get partition u partition assert actual static it s still shared
gets the guild(s ) for the given guild id(s ) .,def get_guilds self gid members False sort username page 1 if isinstance gid list tuple gid join str i for i in gid if sort not in self guild_sorts raise InvalidInputError Guild sort types must be one of format join self guild_sorts d id gid members int members sort sort page int page return self call guild d
test the cflux convolution model calculation .,def _test_cflux_calc mdl slope ampl d setup_data kern XScflux cflux mdl_unconvolved mdl mdl_convolved kern mdl pterm 1 0 slope emin d xlo 0 emax d xhi 1 counts_expected ampl emax pterm emin pterm pterm y_unconvolved d eval_model mdl_unconvolved nbins_unconvolved y_unconvolved size assert nbins_unconvolved d xlo size unconvolved model has correct bins counts_unconvolved y_unconvolved sum assert np abs counts_expected counts_unconvolved 1e 15 can integrate a power law kern emin 0 5 kern emax 7 0 desired_flux 3 2e 14 kern lg10flux np log10 desired_flux y_convolved d eval_model mdl_convolved nbins_convolved y_convolved size assert nbins_convolved d xlo size convolved model has correct bins econv 1 60218e 09 emid econv d xlo d xhi 2 0 y_signal emid y_convolved idx np where d xlo kern emin val d xhi kern emax val flux y_signal idx sum assert np abs flux desired_flux 2e 16 flux is not as expected rescale 1000 0 mdl pars 1 val rescale y_unconvolved_rescaled d eval_model mdl_unconvolved y_convolved_rescaled d eval_model mdl_convolved assert_allclose y_unconvolved y_unconvolved_rescaled rescale atol 0 rtol 1e 07 assert_allclose y_convolved y_convolved_rescaled atol 0 rtol 1e 07
run the actual command using fabric,def run self return fab run cd format self directory self cmd
set default values for options relating to ` build_mjbindings ` .,def _initialize_mjbindings_options cmd_instance cmd_instance inplace 0 cmd_instance headers_dir os path expanduser DEFAULT_HEADERS_DIR
sets the joints to a random collision - free state .,def _set_random_joint_angles physics random max_attempts 1000 for _ in xrange max_attempts randomizers randomize_limited_and_rotational_joints physics random physics after_reset if physics data ncon 0 break else raise RuntimeError Could not find a collision free state after attempts format max_attempts
log a message which is not associated with a particular object .,def log self message u n Log a message which is not associated with a particular object n self _log None message level LOG_DEFAULT
"call noteon(note , velocity ) for each note in chord .",def chordon chord velocity
expects an iso-3166 two - letter country - code .,def country self value return self set_string_parameter country value
encode bbox coordinates in a format used for computing the loss,def encode_bboxes_tf proposals gt config prop_x proposals 0 prop_y proposals 1 prop_w proposals 2 prop_h proposals 3 gt_x gt 0 gt_y gt 1 gt_w gt 2 gt_h gt 3 diff_x gt_x 0 5 gt_w prop_x 0 5 prop_w prop_w diff_y gt_y 0 5 gt_h prop_y 0 5 prop_h prop_h diff_w tf log gt_w prop_w diff_h tf log gt_h prop_h var_x var_y var_w var_h config prior_variance x tf stack diff_x var_x diff_y var_y diff_w var_w diff_h var_h 1 return x
write a soundfile to disk .,def write filename data samplerate data data np power 2 15 astype np int16 if not filename endswith wav fid tmpfile tempfile mkstemp suffix wav WF write tmpfile samplerate data convert tmpfile filename os remove tmpfile else WF write filename samplerate data
checks for updates to the sdk .,def check_for_updates application_configuration update_server appengine_rpc HttpRpcServer _UPDATE_SERVER lambda unused_email unused_password _get_user_agent _get_source_name update_server authenticated True if application_configuration servers update_check sdk_update_checker SDKUpdateChecker update_server application_configuration servers update_check CheckSupportedVersion if update_check AllowedToCheckForUpdates update_check CheckForUpdates
"test page with login : admin , and a non - admin cookie .",def test_admin_no_admin self url_map appinfo URLMap url login admin h url_handler UserConfiguredURLHandler url_map self environ HTTP_COOKIE COOKIE expected_status 401 Not authorized expected_headers Content Type text html Cache Control no cache expected_content Current logged in user johnny example com is not authorized to view this page self assertResponse expected_status expected_headers expected_content h handle_authorization self environ
add an adapter to the ' top ' of the adapter stack .,def push_adapter self adapter return self _adapters append adapter
get a tuple key if not set .,def _get key existing tple if existing return existing if tple 0 key return tple 1
take one step through the data set . a step contains a sequences of batches where the sequence is of size num_unrollings . the batches are size batch_size . args : sess : current tf session the model is being run in batch : batch of data of type batch returns : predictions : the model predictions for each data point in batch,def step self sess batch feed_dict self _get_feed_dict batch predictions sess run self _predictions feed_dict return predictions
assert calling get loads the default config .,def test_lazy_load_get self conf fedmsg config FedmsgConfig self assertEqual conf conf get stomp_ssl_key self assertEqual self defaults conf
"duplicate the underlying fd ( to fd ` newfd ` , if provided )",def dup self newfd None if newfd is not None os dup2 self fd get_fileno newfd return FD newfd else return FD os dup self fd
h encodes the n'bors info .,def create_verts_and_H self dim_range valid_outside if self type I return self create_verts_and_H_type_I dim_range valid_outside elif self type II return self create_verts_and_H_type_II dim_range else raise NotImplementedError self type
tests that the manifiest watch validates manifest filenames .,mock patch os chmod mock Mock mock patch treadmill fs mkdir_safe mock Mock mock patch os path exists mock Mock def test_check_path self watch manifest_watch ManifestWatch does not exist 2 os path exists return_value False self assertFalse watch _check_path test yml os path exists return_value True self assertFalse watch _check_path test yml self assertFalse watch _check_path test self assertTrue watch _check_path test yml
reads per - proc memory details stats .,def read_psmem_stats appname allpids cgrp os path join treadmill apps appname group_pids set cgutils pids_in_cgroup memory cgrp meminfo psmem get_memory_usage allpids group_pids use_pss True return meminfo
callback invoked on connection lost .,def connectionLost self reason protocol connectionDone _LOGGER info connection lost
the boundaries and boundary conditions are defined here .,def create_bcs Lx Ly mesh enable_NS enable_EC namespace boundaries dict bcs dict bcs_pointwise dict if enable_NS bcs_pointwise p 0 0 DOLFIN_PI 4 DOLFIN_EPS x 0 DOLFIN_PI 4 DOLFIN_EPS x 1 x 0 DOLFIN_PI 4 DOLFIN_EPS x 1 DOLFIN_PI 4 DOLFIN_EPS if enable_EC bcs_pointwise V 0 0 DOLFIN_PI 2 DOLFIN_EPS x 0 DOLFIN_PI 2 DOLFIN_EPS x 1 x 0 DOLFIN_PI 2 DOLFIN_EPS x 1 DOLFIN_PI 2 DOLFIN_EPS return boundaries bcs bcs_pointwise
return an appropriate zip file entry,def getFileEntry self contents filename self mktemp z zipfile ZipFile filename w self compression z writestr content contents z close z zipstream ChunkingZipFile filename r return z readfile content
l{_sourcefragmentelement } renders source lines at and around the line number indicated by a frame object .,def test_sourceFragmentElement self element _SourceFragmentElement TagLoader tags div tags span render lineNumber tags span render sourceLine render sourceLines self frame source u xa0 xa0message This is a problem u xa0 xa0raise Exception message u Figure out the line number from which the exception will be raised d flattenString None element d addCallback self assertEqual join div class snippet sLine span d span span s span div Highlight lineNumber 1 self base lineNumber u xa0 4 sourceLine encode utf 8 for lineNumber sourceLine in enumerate source return d
test references search through an object attribute .,def test_instance self class Dummy pass o object d Dummy d o o self assertIn o reflect objgrep d o reflect isSame
"returns heat capacity at constant pressure at the pressure , temperature , and volume [ j / k / mol ]",def molar_heat_capacity_p self pressure temperature volume params return 0
finds successor of the specified chunk . uses fragment inheritance hierarchy to pick an edge from the outward edges of the specified chunk .,def next_chunk self chunk if chunk out_edges count 0 return None else if chunk out_edges count 1 pp self predecessor_priorities def sorter_f e return pp e fragment_id if e fragment_id in pp else len pp out_edges sorted list chunk out_edges all key sorter_f else out_edges chunk out_edges all return out_edges 0 to_chunk
replaces union all select with union select,def tamper payload kwargs return payload replace UNION ALL SELECT UNION SELECT if payload else payload
"get a : class:`connectionpool ` based on the host , port , and scheme .",def connection_from_host self host port None scheme http scheme scheme or http port port or port_by_scheme get scheme 80 pool_key scheme host port with self pools lock pool self pools get pool_key if pool return pool pool self _new_pool scheme host port self pools pool_key pool return pool
"from an association measure function , produces a new function which accepts contingency table values as its arguments .",staticmethod def _make_contingency_fn measures old_fn def res contingency return old_fn measures _marginals contingency res __doc__ old_fn __doc__ res __name__ old_fn __name__ return res
"deletes a repo and associated person , note , authorization , subscription ( but not counter , apiactionlog , or useragentlog ) entities .",def delete_repo repo for person in Person all_in_repo repo filter_expired False delete_person person entities Repo get_by_key_name repo for cls in Person Note Authorization Subscription entities list cls all filter repo repo min_key db Key from_path ConfigEntry repo max_key db Key from_path ConfigEntry repo entities list config ConfigEntry all filter __key__ min_key filter __key__ max_key db delete entities
this method takes input from the given squadron_dir and configures a temporary directory according to that information,def apply squadron_dir node_name tempdir resources previous_run dry_run False log debug entering commit apply s squadron_dir node_name tempdir resources dry_run node_info get_node_info os path join squadron_dir nodes node_name if not check_node_info node_info log debug leaving commit apply check_node_info returned error return False None log debug node_info env str node_info env conf_dir os path join squadron_dir config node_info env result library_dir os path join squadron_dir libraries state StateHandler library_dir for service in node_info services configdata _get_config conf_dir service version configdata version base_dir configdata base_dir get_service_file functools partial _get_service_file squadron_dir service version cfg get_service_file defaults cfg update node_name node_name cfg update configdata config schema get_service_file schema if schema jsonschema validate cfg schema stateinfo get_service_file state config cfg for state_item in stateinfo library state_item name items state_item parameters if isinstance items 0 str or isinstance items 0 unicode print_items join items else print_items items log info s s through s Would process if dry_run else Processing print_items library state apply library items dry_run service_dir os path join squadron_dir services service version root render DirectoryRender service_dir tmp_serv_dir os path join tempdir service makedirsp tmp_serv_dir atomic render render tmp_serv_dir cfg resources dry_run copy_config get_service_file copy config cfg _apply_copy copy_config previous_run service tmp_serv_dir result service atomic atomic base_dir base_dir config cfg dir tmp_serv_dir version version log debug leaving commit apply str result return result
"e.g. a = advogato(date = ' 2007 - 12 - 21 ' ) date = the date of the dot file , if you would to use a old dataset base_path = the path in wich is located the datasets folder weights = if no value is assigned to this parameter , the class choose automatically between _ color_map and _ obs_app_jour_mas_map comp_threshold = if this parameter is set , the class evaluate the ditch component",def __init__ self date None weights _obs_app_jour_mas_map comp_threshold 0 download False base_path prefix None cond_on_edge None from_dot False silent False self silent silent self url http www trustlet org datasets self _name_lowered self _name_lowered self cond_on_edge cond_on_edge if not date date datetime datetime now strftime Y m d self url graph latest dot else self url graph date dot if date 2006 05 20 weights _color_map self key_on_edge level else self key_on_edge color self level_map weights trustlet Dataset Network WeightedNetwork __init__ self weights self level_map base_path base_path prefix prefix date date self name Robots_netNetwork self path os path join self path date if not os path exists self path os mkdir self path self dotpath os path join self path self dotfile self filepath self dotpath 3 c2 self download only_if_needed download from_dot from_dot self get_graph from_dot from_dot if comp_threshold self ditch_components comp_threshold
converts the a user - type object into a sql datum .,def serialize self obj if isinstance obj PolyLine return obj else raise TypeError cannot serialize r of type r obj type obj
test simultaneous delta and sig generation,def test_dirdelta_write_sig self deltadir1 Path testfiles output dir deltatar1 deltadir2 Path testfiles output dir deltatar2 cur_full_sigs Path testfiles output fullsig dir1 cur_dir Path testfiles dir1 get_sel lambda cur_dir selection Select cur_dir set_iter diffdir write_block_iter diffdir SigTarBlockIter get_sel cur_dir cur_full_sigs sigstack cur_full_sigs for dirname in dir2 dir3 dir4 old_dir cur_dir cur_dir Path testfiles dirname old_full_sigs cur_full_sigs cur_full_sigs Path testfiles output fullsig dirname delta1 Path testfiles output delta1 dirname delta2 Path testfiles output delta2 dirname incsig Path testfiles output incsig dirname diffdir write_block_iter diffdir DirDelta get_sel cur_dir old_full_sigs open rb delta1 block_iter diffdir DirDelta_WriteSig get_sel cur_dir p open rb for p in sigstack incsig open wb sigstack append incsig diffdir write_block_iter block_iter delta2 compare_tar delta1 open rb delta2 open rb assert not os system cmp s s delta1 name delta2 name diffdir write_block_iter diffdir SigTarBlockIter get_sel cur_dir cur_full_sigs
list news items for that brand .,blueprint route brands brand_id defaults page 1 blueprint route brands brand_id pages int page permission_required NewsItemPermission view templated def index_for_brand brand_id page brand get_brand_or_404 brand_id per_page request args get per_page type int default 15 items news_service get_items_paginated brand id page per_page return brand brand items items
this elegant function comes courtesy of geoffrey irving https://stackoverflow.com/questions/8151300/ignore-case-in-glob-on-linux,def insensitive_glob pattern def either c return s s c lower c upper if c isalpha else c return glob glob join map either pattern
: return : - > returns the current list of saved models,def getModelList onlyfiles f for f in listdir modelDir if isfile join modelDir f return onlyfiles
train your model . do n't forget to create folders for checkpoints and outputs .,def train model generated_image initial_image skip_step 1 with tf Session as sess saver tf train Saver sess run generated_image assign initial_image ckpt tf train get_checkpoint_state os path dirname checkpoints checkpoint if ckpt and ckpt model_checkpoint_path saver restore sess ckpt model_checkpoint_path initial_step model global_step eval start_time time time for index in range initial_step ITERS if index 5 and index 20 skip_step 10 elif index 20 skip_step 20 sess run model optimizer if index 1 skip_step 0 gen_image gen_image MEAN_PIXELS writer add_summary summary global_step index print Step n Sum 5 1f format index 1 np sum gen_image print Loss 5 1f format total_loss print Time format time time start_time start_time time time filename outputs d png index utils save_image filename gen_image if index 1 20 0 saver save sess checkpoints style_transfer index
remove a user from a list,api_error_handle def remove_list_member self list_id user_id return List tweepy_list_to_json self _client remove_list_member list_id list_id user_id user_id
used by the web application .,endpoints method PairwiseJobRequest PairwiseResults name run http_method POST def run_job self request features count len request feature 1 while count 0 features append str request feature count count 1 prepped_features Pairwise prepare_features request cohort_id features outputs Pairwise run_pairwise prepped_features results PairwiseResults result_vectors filter_messages logging info results for row_label row in outputs items if type row is dict results result_vectors append PairwiseResultVector feature_1 row feature_A feature_2 row feature_B comparison_type row comparison_type correlation_coefficient row correlation_coefficient n int row n _logp float row _logp n_A int row n_A p_A float row p_A n_B int row n_B p_B float row p_B exclusion_rules row exclusion_rules elif type row is unicode results filter_messages append PairwiseFilterMessage filter_message row 0 return results
adds a number of founder individuals to the population,def add_founders self n for _ in range n self founder_individual register True
writes the specified string to the output target of the report .,def output self msg newline True click echo text_type msg nl newline file self output_file
estimate the motion parameters for the current volume .,def estimateMotion self niiVol volIdx if volIdx self refVolIdx return None elif volIdx self refVolIdx self refVol niiVol return None elif volIdx self refVolIdx reg HistogramRegistration niiVol self refVol interp tri T reg optimize self prevVol_T copy ftol 0 1 maxfun 30 rms_abs self computeRMS self refVol_T T rms_rel self computeRMS self prevVol_T T self prevVol_T T motionParams rms_abs rms_abs rms_rel rms_rel return motionParams
"testing geoqueryset.update ( ) , see # 10411 .",def test01_update self pnt City objects get name Pueblo point bak pnt clone pnt y 0 005 pnt x 0 005 City objects filter name Pueblo update point pnt self assertEqual pnt City objects get name Pueblo point City objects filter name Pueblo update point bak self assertEqual bak City objects get name Pueblo point
returns the number of forms that are required in this formset .,def initial_form_count self if self is_bound return self management_form cleaned_data INITIAL_FORM_COUNT else initial_forms self initial and len self initial or 0 if initial_forms self max_num 0 initial_forms self max_num return initial_forms
loads the session data and returns a dictionary .,def load self raise NotImplementedError
listens for new speed set point messages on a subscriber socket .,def listen_speed_set_points my_serial robot_id robot_speed speed_calc_times wait_times xbee_times logger debug Initializing subscriber socket listener zmq Context instance socket zmq SUB listener setsockopt_string zmq SUBSCRIBE u listener setsockopt zmq CONFLATE True listener connect tcp localhost format int os environ get UVISPACE_BASE_PORT_SPEED robot_id logger debug Listening for speed set points try while True data listener recv_json logger debug Received new speed set point format data move_robot data my_serial wait_times speed_calc_times xbee_times robot_speed except KeyboardInterrupt pass return
tests the control 's ` visible ` initial value is false .,def test_visible_initial_value self self assertEqual self control getVisible False
fill our surface and render our buttons,def render self self surface fill 255 255 255 self components draw self surface for component in self components component render_text
interface to criterion.target_class for attacks .,def target_class self try target_class self __criterion target_class except AttributeError target_class None return target_class
closes the output packet capture ; wrapper for pcap_close ( ) . @rtype : none,def close self self pcap_close
test that config properly handles multiple instance types syntax ( within node_instance_type setting ),def test_multiple_instance_types self invalid_cases c1_node_type c1 xlarge ami asdffdas c1_node_type c1 xlarge 3 c1_node_type c1 xlarge ami asdffdas 3 c1_node_type c1 xlarge asdf asdf asdf m1 small c1_node_type c1 asdf 4 m1 small c1_node_type c1 xlarge 0 m1 small c1_node_type c1 xlarge 1 m1 small for case in invalid_cases try self get_custom_config case except exception ConfigError pass else raise Exception config allows invalid multiple instance type syntax s case valid_cases c1_node_type c1 xlarge 3 m1 small c1_node_type c1 xlarge ami asdfasdf 3 m1 small c1_node_type c1 xlarge ami asdfasdf 3 m1 large m1 small c1_node_type m1 large c1 xlarge ami asdfasdf 3 m1 large m1 small c1_node_type c1 xlarge ami asdfasdf 2 m1 large 2 m1 small for case in valid_cases try self get_custom_config case except exception ConfigError raise Exception config rejects valid multiple instance type syntax s case
"remove hook if hook exists . if function is specified , remove function from hook . if priority is not same as functions priority , it will not remove the function .",def remove_action hook func None priority 10 if func is None if hook in hooks del hooks hook return True else if hook not in hooks raise LookupError Hook s was not found hook for i plugin in enumerate hooks hook plugins if plugin 1 is func and plugin 0 priority del hooks hook plugins i return True return False
"returns the index to the following non - metadata element after the given index , or -infinity .",def _find_following_non_metadata self index return self __find_following_element index predicates non_metadata
return string containing encoded `` value `` .,def encodeValue self value return struct pack q round value 10000
add a label to an instance .,def _labels_post request instance form TagForm request data if form is_valid tags form cleaned_data get tags None if tags for tag in tags instance tags add tag if isinstance instance XForm xform_tags_add send sender XForm xform instance tags tags return status HTTP_201_CREATED
tests that peaks are separated by minimum peak distance .,def test_min_peak_distance self y np array 0 1 0 2 0 3 0 2 0 1 0 mpd 2 peaks detect_peaks y mpd mpd show False for idx ind in enumerate peaks start max 0 ind mpd end min len y 1 ind mpd peaks_before np array i for i in range start ind if y i y ind peaks_after np array i for i in range ind 1 end 1 if y i y ind if idx 0 ind_prev peaks idx 1 idel np zeros peaks_before size dtype bool for i in range peaks_before size if peaks_before i ind_prev mpd and y ind_prev y peaks_before i idel i 1 peaks_before peaks_before idel if idx len peaks 1 ind_next peaks idx 1 idel np zeros peaks_after size dtype bool for i in range peaks_after size if ind_next peaks_after i mpd and y ind_next y peaks_after i idel i 1 peaks_after peaks_after idel assert peaks_before size 0 and peaks_after size 0
check stats.rankdata with an array of length 1 .,def test_one self data 100 a np array data dtype np int r rankdata a assert_array_equal r np array 1 0 dtype np float64 r rankdata data assert_array_equal r np array 1 0 dtype np float64
starts the server tcp connection on the given host : port .,def connect self timeout 600 if self socket raise TensorForceError Already connected to Only one connection allowed at a time Close first by calling close format self host self port self socket socket socket socket AF_INET socket SOCK_STREAM if timeout 5 or timeout is None timeout 5 err 0 start_time time time while time time start_time timeout self socket settimeout 5 err self socket connect_ex self host self port if err 0 break time sleep 1 if err 0 raise TensorForceError Error when trying to connect to errno errcode format self host self port err errno errorcode err os strerror err
create common test assets prior to each individual unit test run .,def setUp self self tzinfo timezone get_current_timezone self inventory Inventory objects create name foo weight Weight g 1 0 address Address objects create street_address 123 Test St locality Test country US warehouse Warehouse objects create name foo address address self purchase_order PurchaseOrder objects create warehouse warehouse product Product objects create name foo sku 123 self variant Variant objects create product product name bar sub_sku 456 component Component objects create variant self variant inventory self inventory quantity Decimal 1 shipping_address Address objects create street_address 123 Test St locality Test country US self order Order objects create shipping_address shipping_address transaction Transaction objects create order self order transaction_id bar
args : app(flask ) : the flask appliation instance . db(mongoengine ) : the mongoengine object - database mapper instance .,def __init__ self app db super MongoDbAdapter self __init__ app db
"decorator that automatically transfers the user from http sessions to channel - based sessions , and returns the user as message.user as well . useful for things that consume e.g. websocket.connect",def channel_session_user_from_http func http_session_user channel_session functools wraps func def inner message args kwargs if message http_session is not None transfer_user message http_session message channel_session return func message args kwargs return inner
add the whole sequence - to - sequence model to the graph .,def _build_model self hps self _hps vsize self _vocab size with tf variable_scope discriminator self rand_unif_init tf random_uniform_initializer hps rand_unif_init_mag hps rand_unif_init_mag seed 123 self trunc_norm_init tf truncated_normal_initializer stddev hps trunc_norm_init_std with tf variable_scope embedding embedding tf get_variable embedding vsize hps emb_dim dtype tf float32 initializer self trunc_norm_init emb_dec_inputs tf nn embedding_lookup embedding self _dec_batch self emb_enc_inputs emb_dec_inputs with tf variable_scope output_projection w tf get_variable w_output hps hidden_dim vsize dtype tf float32 initializer self trunc_norm_init v tf get_variable v_output vsize dtype tf float32 initializer self trunc_norm_init with tf variable_scope decoder loop_function None cell tf contrib rnn LSTMCell hps hidden_dim initializer tf random_uniform_initializer 0 1 0 1 seed 113 state_is_tuple False emb_dec_inputs tf unstack emb_dec_inputs axis 1 self _dec_in_state cell zero_state FLAGS batch_size hps max_enc_sen_num tf float32 decoder_outputs self _dec_out_state tf contrib legacy_seq2seq rnn_decoder emb_dec_inputs self _dec_in_state cell loop_function None decoder_outputs tf transpose decoder_outputs 1 0 2 decoder_outputs tf reshape decoder_outputs 1 hps hidden_dim decoder_outputs tf nn xw_plus_b decoder_outputs w v decoder_outputs tf reshape decoder_outputs hps batch_size hps max_enc_sen_num hps max_enc_seq_len FLAGS vocab_size crossent tf nn sparse_softmax_cross_entropy_with_logits labels self _target_batch logits decoder_outputs self out_put tf argmax crossent 1 self out_put tf reshape self out_put hps batch_size hps max_enc_sen_num weights self _target_mask self label self train_loss tf contrib seq2seq sequence_loss decoder_outputs self _target_batch weights average_across_timesteps True average_across_batch True weights self _target_mask self label self train_loss tf contrib seq2seq sequence_loss decoder_outputs self _target_batch weights average_across_timesteps True average_across_batch True self out_loss tf contrib seq2seq sequence_loss decoder_outputs self _target_batch self _target_mask average_across_timesteps False average_across_batch False self out_loss tf reshape self out_loss 1 self out_loss tf reshape self out_loss hps batch_size hps max_enc_sen_num hps max_enc_seq_len self out_loss_sentence tf reduce_mean self out_loss axis 1
"create a queue logger for a specific class , which * must * have a "" logging_queue "" property redirecting to a queue - like object . if the instance possesses a "" log_level "" attribute , the log level will be set to its value ; otherwise , the logger will be configured with a default level of "" warning "" .",def create_queue_logger instance prefix if not hasattr instance logging_queue raise AttributeError A queue logger can be built only using a class with the logging_queue property instance _log_handler logging handlers QueueHandler instance logging_queue if hasattr instance log_level instance _log_handler setLevel instance log_level else instance _log_handler setLevel WARNING if prefix instance logger logging getLogger 0 1 format prefix instance name if hasattr instance name else default else instance logger logging getLogger instance name instance logger addHandler instance _log_handler instance logger setLevel instance _log_handler level instance logger propagate False return
modified from the energy module in simulate package # # @note to zhl : is this ok ?,def calc other_self itheta theta parm beta nonbondflag seed_object log other_self log pgui other_self run_utils print_gui search True vdi 10000000000 0 vdf 10000000000 0 pi numpy pi angle_to_radians pi 180 0 thetarad theta angle_to_radians ithetarad itheta angle_to_radians number_of_parm len parm 3 iv 0 0 v 0 0 for i in xrange number_of_parm offset i 3 k_ang float parm 0 offset n_ang float parm 1 offset delta_ang float parm 2 offset angle_to_radians iv k_ang 1 0 math cos n_ang ithetarad delta_ang v k_ang 1 0 math cos n_ang thetarad delta_ang if nonbondflag 0 if v iv search False vdi iv vdf v else kcal2kj 4 184 vkjmol v kcal2kj ivkjmol iv kcal2kj kjmol2j 1 66054e 21 vj vkjmol kjmol2j ivj ivkjmol kjmol2j earg beta vj ivj if seed_object 1 r seed_object rand else r random random arg numpy exp earg if r arg search False vdi iv vdf v else pass return search vdi vdf else vdi iv vdf v return vdi vdf
saves the pixels to a file ( .png or .jpg ) .,def write self filename filename fixWorkingDirForJEM filename suffix filename 3 suffix suffix lower if suffix jpg or suffix png ImageIO write self image suffix File filename self filename filename self display setTitle self filename else print Filename must end in jpg or png
benchmark cpu vs gpu time wise .,def benchmark_cpu_vs_gpu input_raw_file nb_iterations 20 cpu1 f1 interpolate input_raw_file cpu_nn_lena dat cpu nb_iterations nn 4000 2000 gpu1 f2 interpolate input_raw_file gpu_nn_lena dat gpu nb_iterations nn 4000 2000 cpu2 f3 interpolate input_raw_file cpu_bl_lena dat cpu nb_iterations bl 4000 2000 gpu2 f4 interpolate input_raw_file gpu_bl_lena dat gpu nb_iterations bl 4000 2000 return cpu1 cpu2 gpu1 gpu2
download the entire youtube - bb data set into ` dl_dir ` .,def parse_and_sched dl_dir videos num_threads 4 check_call mkdir p dl_dir for d_set in youtube_bb d_sets annotations clips vids youtube_bb parse_annotations d_set dl_dir youtube_bb sched_downloads d_set dl_dir num_threads vids
: returns : process status : rtype : int,def _set name value if name core dcos_url return _cluster_setup value toml msg config set_val name value emitter publish DefaultError msg return 0
partition a node from all network traffic except for ssh and loopback,def partition_agent hostname shakedown copy_file_to_agent hostname net services agent sh format scripts scripts_dir print partitioning format hostname shakedown run_command_on_agent hostname sh net services agent sh fail
test if a permission is in the given set .,def is_permission_in_set perm perm_set if isinstance perm_set basestring return perm perm_set elif isinstance perm_set Container return perm in perm_set elif isinstance perm_set Callable return perm_set perm else raise TypeError permission set must be a string container or callable
read a websocket frame sent by a server or client,classmethod def from_file cls fp header FrameHeader from_file fp payload fp safe_read header payload_length if header mask 1 and header masking_key payload Masker header masking_key payload frame cls payload frame header header return frame
it deletes the cache because it will not be valid after the 0006 migration is applied,def forwards_func apps schema_editor CachedEnrollment apps get_model dashboard CachedEnrollment CachedCertificate apps get_model dashboard CachedCertificate CachedCurrentGrade apps get_model dashboard CachedCurrentGrade db_alias schema_editor connection alias CachedEnrollment objects using db_alias delete CachedCertificate objects using db_alias delete CachedCurrentGrade objects using db_alias delete
tests that courserunfinder will return a desired course run,def test_course_run_finder_success self course_run CourseRunFactory create title courserun1 edx_course_key coursekey1 CourseRunFactory create title courserun2 edx_course_key coursekey2 found_course_runs CourseRunFinder find course_run_title courserun1 CourseRunFinder find course_run_title run1 CourseRunFinder find course_run_key coursekey1 CourseRunFinder find course_run_key key1 assert all course_run found_course_run for found_course_run in found_course_runs
tests that reviewfinancialaidview returns the expected results with search,def test_view_with_search self staff_client program_data fin_aid_status FinancialAidStatus AUTO_APPROVED profiles ProfileFactory create_batch 4 first_name factory Iterator match_name x y z last_name factory Iterator x y z match_name FinancialAidFactory create_batch 4 tier_program program_data tier_programs 0k status fin_aid_status user factory Iterator p user for p in profiles name_query match_name url self review_url program_data program id status fin_aid_status search_param name_query resp staff_client get url assert resp status_code status HTTP_200_OK financial_aid_objects resp context_data financial_aid_objects assert len financial_aid_objects 2 assert all fin_aid user profile first_name name_query or fin_aid user profile last_name name_query for fin_aid in financial_aid_objects
test email backend pulling from settings and db .,pytest mark django_db def test_apostello_mail_backend mail_backend ApostelloEmailBackend assert mail_backend host smtp test apostello s SiteConfiguration get_solo s get_solo s email_host smtp test2 apostello s save mail_backend ApostelloEmailBackend assert mail_backend host smtp test2 apostello
"returns list of connected resources of contact "" jid "" .",def getResources self jid return self _data jid jid find resources keys
return boolean indicating whether this extension is available,def glInitDebugMarkerEXT from OpenGL import extensions return extensions hasGLExtension _EXTENSION_NAME
return boolean indicating whether this extension is available,def glInitD3DShareHandleClientBufferANGLE from OpenGL import extensions return extensions hasGLExtension _EXTENSION_NAME
return boolean indicating whether this extension is available,def glInitShadowARB from OpenGL import extensions return extensions hasGLExtension _EXTENSION_NAME
return boolean indicating whether this extension is available,def glInitVertexProgram2OptionNV from OpenGL import extensions return extensions hasGLExtension _EXTENSION_NAME
correctly pick random points on the surface of a unit sphere,def sample_surface_sphere count u v np random random 2 count theta np pi 2 u phi np arccos 2 v 1 points util spherical_to_vector np column_stack theta phi return points
get the value of l_loopb_txpad_trf<1:0 >,property def L_LOOPB_TXPAD_TRF self return self _readReg TXPAD L_LOOPB_TXPAD_TRF 1 0
set the state of the shutter ( to open or closed ),def set_state self value if isinstance value str self _open value lower open elif isinstance value bool self _open value
make a directory if none exists already,def makeDirIfNone dirname if os path exists dirname return else os makedirs dirname
iterates breadth - first up to root,def __iter__ self curAttr self while isinstance curAttr AdHocTree yield curAttr curAttr curAttr parent
find the specified protocol layer based on the class name,def find self proto if self __class__ __name__ proto and self parsed return self elif self next and isinstance self next packet_base return self next find proto else return None
show image for path using html,def hshow path return display HTML img src format path
returns a list of oslo.config options available in the library .,def list_opts key_manager_opts key_manager_opts extend km key_manager_opts key_manager_opts extend utils credential_opts opts key_manager key_manager_opts if bkm is not None opts append bkm BARBICAN_OPT_GROUP bkm barbican_opts if vkm is not None opts append vkm VAULT_OPT_GROUP vkm vault_opts return opts
check network connectivity from instance via floating ip target component : nova,def test_008_check_public_instance_connectivity_from_instance self self check_image_exists if not self security_groups self security_groups self tenant_id self verify 25 self _create_security_group 1 Security group can not be created security group creation self compute_client name rand_name ost1_test server smoke security_groups self security_groups self tenant_id name server self verify 250 self _create_server 2 Server can not be created server creation self compute_client name security_groups floating_ip self verify 20 self _create_floating_ip 3 Floating IP can not be created floating IP creation self verify 20 self _assign_floating_ip_to_instance 4 Floating IP can not be assigned floating IP assignment self compute_client server floating_ip self floating_ips append floating_ip ip_address floating_ip ip LOG info is address is 0 format ip_address LOG debug ip_address self verify 600 self _check_vm_connectivity 5 VM connectivity doesn t function properly VM connectivity checking ip_address 30 9 60 self verify 600 self _check_connectivity_from_vm 6 Connectivity to 8 8 8 8 from the VM doesn t function properly public connectivity checking from VM ip_address 30 9 60 self verify 20 self compute_client servers remove_floating_ip 7 Floating IP cannot be removed removing floating IP server floating_ip self verify 20 self compute_client floating_ips delete 8 Floating IP cannot be deleted floating IP deletion floating_ip if self floating_ips self floating_ips remove floating_ip self verify 60 self _delete_server 9 Server can not be deleted server deletion server
sends an email to this user .,def email_user self subject message from_email None u n Sends an email to this User n send_mail subject message from_email self email
call `` sklearn.cross_validation.cross_val_score `` using automatic mapping .,def cross_val_score self estimator args kwargs func self _module cross_val_score return func estimator X self _data values y self _target values args kwargs
for geos unary topology functions .,def topology func args argtypes GEOM_PTR if args argtypes args func argtypes argtypes func restype GEOM_PTR func errcheck check_geom return func
testing initialization on invalid wkt .,def test02_bad_wkt self for bad in bad_srlist try srs SpatialReference bad srs validate except SRSException OGRException pass else self fail Should not have initialized on bad WKT s
init this serializer given a stream or a string,def __init__ self stream_or_string options self options options if isinstance stream_or_string basestring self stream StringIO stream_or_string else self stream stream_or_string models get_apps
"returns a string of html for representing this as an < input type=""hidden"">.",def as_hidden self attrs None return self as_widget self field hidden_widget attrs
establish an ssh tunnel and start a thread that forwards tcp requests on the local host to the server running on the remote host .,def startLocalForwarder self pyroPort pyroListenAddr localhost pyroPort localListenAddr localhost 0 forwardServer FlowBuilderTransportForwardingServer localListenAddr FlowBuilderTransportForwardingHandler forwardServer setTransport self ssh get_transport pyroListenAddr forwardThread threading Thread target forwardServer serve_forever forwardThread daemon True forwardThread start host port forwardServer server_address return forwardServer forwardThread port
compute i_min(inputs : output ) = \sum_{s \in output } p(s ) min_{input _ \in inputs } i(input _ : output = s ),def i_min d inputs output Compute I_min inputs output sum_ s in output p s min_ input_ in inputs I input_ output s Parameters d Distribution The distribution to compute i_min for inputs iterable of iterables The input variables output iterable The output variable Returns imin float The value of I_min p_s d marginal output return sum p_s s min s_i d input_ output s for input_ in inputs for s in p_s outcomes
test product_distribution ( ) with overlapping rvs specification .,def test_product_with_badrvs d dit example_dists Xor with pytest raises Exception dit product_distribution d 0 1 0
reassemble the - possibly edited - export data from the tree - entries .,def _getExportData self assetList for item in self assetItemList path item text 1 if not path endswith and len path 0 path path path path item text 0 entry AssetListEntry path for i in range 0 item childCount child item child i entry append child obj_name child obj_ref assetList append entry return assetList
: return : the description of this rolling stock type : rtype : str,property def description self return self _description
"the superclass constructor does not really need to be called , but it enables a few useful features ( like unified logging ) . if not called by the child , it just makes sure that bugtracker class is not instantiated directly .",def __init__ self args kwargs if self __class__ __name__ BugTracker raise FafError You need to subclass the BugTracker class in order to implement a bugtracker plugin super BugTracker self __init__
"calculates the perplexity given the training and testing files in trainf_list and testf_list , respectively @param trainf_list : list of paths of the training corpora @param testf_list : list of paths of the corresponding testing corpora ( must be same length as trainf_list so that each training corpus has a testing corpus ) @param test_wc : the total number of words in each test corpus @return the perplexity for each fold",def kf_perplexity self trainf_list testf_list test_wc param ntopics start 1 stop 1 step 5 train_params algorithm train test_params algorithm testlike def _handle_ppt self test_wci lhood float open os path join self params outdir test loglike dat readline strip return round 1 lhood test_wci 3 return self general_kf_ppt trainf_list testf_list test_wc param start stop step train_params test_params _handle_ppt
return a filtered version of a repository,def filtered self name if name self filtername return self return self unfiltered filtered name
verify that unused unspents do not increase fee .,def test_no_combine_with_fee self unspents_single Unspent 5000 0 0 unspents_original Unspent 5000 0 0 Unspent 5000 0 0 outputs_original RETURN_ADDRESS 1000 satoshi unspents outputs sanitize_tx_data unspents_original outputs_original fee 1 leftover RETURN_ADDRESS combine False message None unspents_single outputs_single sanitize_tx_data unspents_single outputs_original fee 1 leftover RETURN_ADDRESS combine False message None assert unspents Unspent 5000 0 0 assert unspents_single Unspent 5000 0 0 assert len outputs 2 assert len outputs_single 2 assert outputs 1 0 RETURN_ADDRESS assert outputs_single 1 0 RETURN_ADDRESS assert outputs 1 1 outputs_single 1 1
retrieve the metadata of the report .,def parse_metadata self re_result self re_metadata findall self metadata_stream metadata dict el 0 el 1 for el in re_result if self check_version metadata key sf_version return metadata raise NotSupportedVersionError PTP does NOT support this version of Skipfish
getter method to remove any trailing dots that indicate the hostname is an fqdn .,property def host self return self _dns_host rstrip
installs the include_markdown template tag . see includemarkdownextension for details .,def install_markdown_template_tag app markdown_path app jinja_env extend markdown_base_dir markdown_path app jinja_env add_extension imageserver flask_ext IncludeMarkdownExtension
log end execute tcl code .,def tcl self cmd self class_logger debug Run tcl command s cmd return self tcl_interpret eval cmd
"set test preconditions , e.g. flows .",def set_ovs_complex_test_preconditions ports test_preconditions switch controller dpid None if isinstance test_preconditions tuple for i v in enumerate test_preconditions name flow d i 1 if output in test_preconditions i 1 action test_preconditions i 1 split for j k in enumerate action if output in action j action j output d int ports action j split 1 action j split 2 int action j split 3 action_string join action test_preconditions i 1 action_string if enqueue in test_preconditions i 1 action test_preconditions i 1 split for j l in enumerate action if enqueue in action j action j enqueue d s int ports action j split 1 action j split 2 int action j split 3 action j split 4 action_string join action test_preconditions i 1 action_string if in_port in test_preconditions i 0 qualifiers test_preconditions i 0 split for j g in enumerate qualifiers if in_port in qualifiers j port_string qualifiers j split 1 qualifiers j in_port d int ports port_string split 0 port_string split 1 int port_string split 2 qualifiers_string join qualifiers test_preconditions i 0 qualifiers_string add_flow_via_controller test_preconditions i 0 test_preconditions i 1 controller name name dpid dpid else add_flow_via_controller test_preconditions i 0 test_preconditions i 1 controller name name dpid dpid time sleep 5
add supported type to supported type list @param type_name : supported type name string @param type_desc : type description,def addSuportedType self type_name type_desc try if type_desc is None type_desc type_name self typeName_norm_cb type_name type_tuple type_name type_desc if not type_tuple in self supported_types self supported_types append type_tuple except Exception as ex self logger exception Failed to add supported type s ex
add a connector between wire1 and wire2 in the network .,def addConnector self wire1 wire2 if wire1 wire2 return if wire1 wire2 wire1 wire2 wire2 wire1 try last_level self 1 except IndexError self append wire1 wire2 return for wires in last_level iteritems if wires 1 wire1 and wires 0 wire2 self append wire1 wire2 return last_level wire1 wire2
cluster and walletmgr shutdown and cleanup .,staticmethod def shutdown cluster walletMgr testSuccessful True killEosInstances True killWallet True keepLogs False cleanRun True dumpErrorDetails False assert cluster assert isinstance cluster Cluster if walletMgr assert isinstance walletMgr WalletMgr assert isinstance testSuccessful bool assert isinstance killEosInstances bool assert isinstance killWallet bool assert isinstance cleanRun bool assert isinstance dumpErrorDetails bool if testSuccessful Utils Print Test succeeded else Utils Print Test failed if not testSuccessful and dumpErrorDetails cluster dumpErrorDetails if walletMgr walletMgr dumpErrorDetails Utils Print Errors see above if killEosInstances Utils Print Shut down the cluster cluster killall allInstances cleanRun if testSuccessful and not keepLogs Utils Print Cleanup cluster data cluster cleanup if walletMgr and killWallet Utils Print Shut down the wallet walletMgr killall allInstances cleanRun if testSuccessful and not keepLogs Utils Print Cleanup wallet data walletMgr cleanup
returns a list of instruments that this artist performs on this release .,def instruments_for_artist self artist return Instrument objects filter instrumentperformance__artist artist instrumentperformance__recording self distinct
add ldap entries and add teardown for removing them,def create_ldap_fixture request ldap_conn ent_list None create_ldap_entries ldap_conn ent_list create_ldap_cleanup request ldap_conn ent_list
only messages with record level info and warning can pass for messages with another level an extra handler is used,def filter self record if record levelno logging INFO return True
test if telegram payload may be parsed .,def payload_valid self payload return isinstance payload DPTArray and len payload value 3
serialize to knx / ip raw data .,def to_knx self data data append len self data data append self dtc value data extend self data 2 return data
"return a list of rectangles ( each a list of 4 points , in self.parentitem coordinates ) for quadrilaterals to be mapped into .",def getNormalizedRects self quads self getQuadrilaterals widths for i q in enumerate quads w abs Point q 0 q 3 q 0 2 0 q 1 q 2 q 1 2 0 length widths append w if QtGui QPolygonF q containsPoint QtCore QPointF 0 0 0 0002 QtCore Qt OddEvenFill ind i mids quads ind 0 quads ind 3 quads ind 0 2 0 quads ind 1 quads ind 2 quads ind 1 2 0 xPos Point mids 0 length math sin Point mids 0 angle Point 0 1 math pi 180 0 rects for i q in enumerate quads rect if i ind rect append sum widths i ind xPos 0 0 elif i ind rect append xPos 0 0 elif i ind rect append sum widths ind i xPos 0 0 rect append rect 0 0 widths i 0 0 rect append rect 0 0 widths i 0 001 rect append rect 0 0 0 001 rects append rect return rects
returns a set of tmps that this irexpr depends on,def tmp_deps self if len self actions 0 or o ACTION_DEPS not in self state options return _nonset else return frozenset union r tmp_deps for r in self actions if type r in SimActionData SimActionOperation
get tuples with contents in the correct order to go into the stored procedure with the same values as in the messages in _ get_record_txt ( ) .,def _get_record_tuples self tuples tuple1 RAL LCG2 3 2010 C whatever D someDN atlas atlas Role production some host org grid Si2k 1000 0 None None datetime utcfromtimestamp 1267405200 datetime utcfromtimestamp 1269046800 234256 244435 100 tuple2 RAL LCG2 4 2010 C whatever D someDN atlas atlas Role production some host org local Si2k 1000 0 None None datetime utcfromtimestamp 1270083600 datetime utcfromtimestamp 1271725200 234256 244435 100 tuple3 RAL LCG2 5 2010 C whatever D someDN atlas atlas Role production some host org local Si2k 1000 0 1 1 datetime utcfromtimestamp 1272672000 datetime utcfromtimestamp 1272672500 234256 244435 100 tuples append tuple1 tuples append tuple2 tuples append tuple3 return tuples
tell the feedback to load variable values from given file .,def load_configuration self filename signal bcixml BciSignal None bcixml CMD_LOAD_VARIABLES filename filename bcixml INTERACTION_SIGNAL self send_signal signal
compute the distance in kilometres between this position and another .,def distance self another r 6371 dlat math radians another lat self lat dlon math radians another lon self lon lat1 math radians self lat lat2 math radians another lat a math sin dlat 2 math sin dlat 2 math sin dlon 2 math sin dlon 2 math cos lat1 math cos lat2 c 2 math atan2 math sqrt a math sqrt 1 a return r c
assigns the commit sha of the current git head to env.head_commit .,def make_head_commit revision local git rev list default_revision s n 1 abbrev commit abbrev 7 env capture True env head_commit revision rstrip n
"returns a new array of given shape and dtype , filled with zeros .",def zeros shape dtype float order C a cupy ndarray shape dtype order order a data memset_async 0 a nbytes return a
return all not - completed output messages .,def get_not_completed self ret for value in self get_all if not value _IS_COMPLETED ret append value _MESSAGE return ret
copy a directory of files from a known directory to another known file path whose directory does not exist . postcondition : should have recursively created the directories and files for the entire tree,def test_copy_directory_pass test_src_dir tempfile gettempdir PathSeparator test_src test_dst_dir tempfile gettempdir PathSeparator test_dst pkgpanda util remove_directory test_src_dir pkgpanda util remove_directory test_dst_dir assert not os path isdir test_src_dir assert not os path isdir test_dst_dir pkgpanda util make_directory test_src_dir fno src_path tempfile mkstemp dir test_src_dir os close fno dst_path test_dst_dir PathSeparator os path basename src_path test_data Test Data n with open src_path w as f f write test_data pkgpanda util copy_directory test_src_dir test_dst_dir with open dst_path r as f lines f readlines assert lines 0 test_data
"allocate evenly the evaluation budget to all the individuals . the winners will be determined by the averaged objective values . ( note : only applicable to single objective , non - constrained problems )",def brute_force_average_f pop_noisy num_winner eval_budget pop_n len pop_noisy f_mean 0 0 pop_n cnt 0 pop_n eval_total 0 f_prev 999 0 pop_n pop_noisy_local copy deepcopy pop_noisy while eval_total eval_budget cur_seed random randint 0 100000000 pop_noisy_local _problem_reference seed cur_seed for i p in enumerate pop_noisy_local newest_f pop_noisy_local problem objfun p cur_x 0 f_mean i f_mean i newest_f cnt i cnt i 1 eval_total eval_total 1 if eval_total eval_budget break f_mean f_mean i cnt i for i in range 0 pop_n winners np argsort f_mean num_winner return winners
: return : icon depicting the graph type . : rtype : qicon,def icon self return None
slot raised when an enumeration table is selected . : param index : index of currently selected item . : type index : int,def _on_enum_table_changed self index enum_table self cbo_enum_table currentText self cbo_primary_col clear self cbo_other_col clear self _enum_col_names if enum_table self _enum_col_names table_column_names enum_table id_col id id_idx getIndex self _enum_col_names id_col if id_idx 1 self _enum_col_names remove id_col self cbo_primary_col addItem self cbo_primary_col addItems self _enum_col_names
"drops an fk constraint in the database . : param entity_relation : entityrelation object : type entity_relation : entityrelation : return : true if the foreign key was successfully dropped , else false . : rtype : bool",def drop_foreign_key_constraint entity_relation fk_cons fk_constraint_from_er entity_relation if fk_cons is None LOGGER debug Foreign key constraint object could not be created return False Catch and log exception if the constraint does not exist mostly due to related cascades s having removed the constraint try fk_cons drop cascade True return True except ProgrammingError as pe LOGGER debug Drop of foreign key constraint failed s unicode pe return False
"run a setup method , framing the operation with a base class that will catch new subclasses to be established within the "" classes "" registry .",classmethod def _with_register_classes cls fn cls_registry cls classes class FindFixture type def __init__ cls classname bases dict_ cls_registry classname cls return type __init__ cls classname bases dict_ class _Base util with_metaclass FindFixture object pass class Basic BasicEntity _Base pass class Comparable ComparableEntity _Base pass cls Basic Basic cls Comparable Comparable fn
add a new included pattern .,def add_included self raw_pattern self _included append re compile raw_pattern
"calculate the tile bounding box based on position , map size and resolution .",def get_print_bbox x y zoom width height dpi tiles_h width dpi_to_dpmm dpi TILE_SIZE tiles_v height dpi_to_dpmm dpi TILE_SIZE mercator_coords MercatorCoordinate x y tile_coords mercator_coords to_tile zoom tile_bb GridBB zoom min_x tile_coords x math ceil tiles_h 2 max_x tile_coords x math ceil tiles_h 2 min_y tile_coords y math ceil tiles_v 2 max_y tile_coords y math ceil tiles_v 2 return tile_bb
test conversion of hyexpressions with embedded non - hyobjects .,def test_wrap_nested_expr wrapped wrap_value HyExpression long_type 0 assert type wrapped HyExpression assert type wrapped 0 HyInteger assert wrapped HyExpression HyInteger 0
get the specifications of a given instance type .,def get_instance_spec instance_type return t2 micro mem 1G cpu power 10 cores 1 instance_type
"query relation with nrpe subordinate , return the nagios_host_context",def get_nagios_hostcontext relation_name nrpe external master for rel in relations_of_type relation_name if nagios_hostname in rel return rel nagios_host_context
"permutations(range(3 ) , 2 ) -- > ( 0,1 ) ( 0,2 ) ( 1,0 ) ( 1,2 ) ( 2,0 ) ( 2,1 )",def permutations iterable r None pool tuple iterable n len pool if r is None r n indices range n cycles range n r 1 n 1 1 yield tuple pool i for i in indices r while n for i in reversed range r cycles i 1 if cycles i 0 indices i indices i 1 indices i i 1 cycles i n i else j cycles i indices i indices j indices j indices i yield tuple pool i for i in indices r break else return
i extend cls according to the design rationale of the ktbs abstract api .,def extend_api cls methods pair for pair in cls __dict__ items if _INTERESTING_METHOD match pair 0 methods sort for methodname raw_function in methods if hasattr raw_function _extend_api_ignore continue if isinstance raw_function classmethod continue nrequired raw_function func_code co_argcount len raw_function func_defaults or if methodname startswith get_ if nrequired 1 continue stripped_name methodname 4 prop property raw_function doc raw_function __doc__ setattr cls stripped_name prop elif methodname startswith set_ if nrequired 2 continue stripped_name methodname 4 prop getattr cls stripped_name None if prop is None prop property doc raw_function __doc__ setattr cls stripped_name prop setter raw_function else stripped_name methodname 5 new_name list_ s stripped_name repo exec def new_name s self args kw Make a list from methodname s return list self methodname s args kw locals in globals repo func repo new_name setattr cls new_name func if nrequired 1 continue prop property func doc func __doc__ setattr cls stripped_name prop return cls
python destructor for when no more refs to this face object,def __del__ self self release return
gets the purpose of each boot image .,def get_boot_image_purposes self arch subarch release label return BOOT_IMAGE_PURPOSE EPHEMERAL
list all bcache cache sets belonging to a machine .,def read self request system_id machine Machine objects get_node_or_404 system_id request user NODE_PERMISSION VIEW return CacheSet objects get_cache_sets_for_node machine
is this the default zone ?,def is_default self return self name DEFAULT_ZONE_NAME
"return sources , list of releases , and list of architectures that exists for the given operating system from the ` bootsource ` 's .",def get_os_info_from_boot_sources os os_sources releases set arches set for source in BootSource objects all for cache_item in BootSourceCache objects filter boot_source source os os if source not in os_sources os_sources append source releases add cache_item release arches add cache_item arch return os_sources releases arches
spawn the bind server process .,def _spawn self env dict os environ HOME self config homedir with open self config log_file wb as log_file with open os devnull rb as devnull self process subprocess Popen self config named_file f c self config conf_file stdin devnull stdout log_file stderr log_file close_fds True cwd self config homedir env env preexec_fn preexec_fn self addCleanup self _stop open_log_file open self config log_file rb self addDetail os path basename self config log_file Content UTF8_TEXT lambda open_log_file
display categories if they are available : cat : list : returns : bool,def display_categories cat print cats for e in cat print colorize msg e ty cats return True
this method implements progress reporting for package installation by apt and may be extended to dpkg at a later time . this method takes two parameters : the parameter percent is a float value describing the overall progress and the parameter status is a string describing the current status in an human - readable manner .,def status_change self pkg percent status diff t now self pulse_time if diff total_seconds 10 12 return True self pulse_time t now call_parent progress_bar percent int percent heading self parent heading message status
terminates the process that fills this buffers : class:`~alot.walker . pipewalker ` .,def kill_filler_process self if self proc if self proc is_alive self proc terminate
validations a list of oeprop computations . throws if not found,def oeprop_validator prop_list oeprop_methods core OEProp valid_methods if not len prop_list raise ValidationnError OEProp No properties specified for prop in prop_list prop prop upper if MULTIPOLE in prop continue if prop not in oeprop_methods alt_method_name p4util text find_approximate_string_matches prop oeprop_methods 2 alternatives if len alt_method_name 0 alternatives Did you mean s join alt_method_name raise ValidationError OEProp Feature s is not recognized s prop alternatives
@param list_or_dict : a list or a dictonary,def toJS self list_or_dict def toArray self list array Array for obj in list obj self toJS obj array push obj return array def toObject self dict object Object for key obj in dict iteritems obj self toJS obj setattr object key obj return object obj list_or_dict if hasattr obj keys obj toObject self obj elif hasattr obj append obj toArray self obj return obj
handles a request by calling the appropriete method the service exposes,def handleRequest self req name req method params req params id req id obj None try obj getMethodByName self service name except MethodNameNotAllowed as e self sendResponse id None e except self sendResponse id None MethodNotFound if obj try rslt obj params self sendResponse id rslt None except TypeError s getTracebackStr self sendResponse id None InvalidMethodParameters except s getTracebackStr self sendResponse id None s
"check that ' self.compiler ' really is a ccompiler object ; if not , make it one .",def _check_compiler self from distutils ccompiler import CCompiler new_compiler if not isinstance self compiler CCompiler self compiler new_compiler compiler self compiler dry_run self dry_run force 1 customize_compiler self compiler if self include_dirs self compiler set_include_dirs self include_dirs if self libraries self compiler set_libraries self libraries if self library_dirs self compiler set_library_dirs self library_dirs
pygame.surfarray.array_colorkey ( surface ) : return array,def array_colorkey surface if __arraytype numeric return numericsf array_colorkey surface elif __arraytype numpy return numpysf array_colorkey surface raise NotImplementedError surface arrays are not supported
minimize a function using simulated annealing .,def anneal func x0 args schedule fast full_output 0 T0 None Tf 1e 12 maxeval None maxaccept None maxiter 400 boltzmann 1 0 learn_rate 0 5 feps 1e 06 quench 1 0 m 1 0 n 1 0 lower 100 upper 100 dwell 50 cvar 0 05 x0 asarray x0 lower asarray lower upper asarray upper schedule eval schedule _sa schedule init dims shape x0 func func args args boltzmann boltzmann T0 T0 learn_rate learn_rate lower lower upper upper m m n n quench quench dwell dwell cvar cvar current_state last_state best_state _state _state _state if T0 is None best_state x x0 x0 schedule getstart_temp best_state else best_state x None best_state cost 30000000000 0 last_state x asarray x0 copy fval func x0 args schedule feval 1 last_state cost fval if last_state cost best_state cost best_state cost fval best_state x asarray x0 copy schedule T schedule T0 fqueue 100 300 500 700 iters 0 while 1 for n in range dwell current_state x schedule update_guess last_state x current_state cost func current_state x args schedule feval 1 dE current_state cost last_state cost if schedule accept_test dE last_state x current_state x copy last_state cost current_state cost if last_state cost best_state cost best_state x last_state x copy best_state cost last_state cost schedule update_temp iters 1 fqueue append squeeze last_state cost fqueue pop 0 af asarray fqueue 1 0 if all abs af af 0 af 0 feps retval 0 if abs af 1 best_state cost feps 10 retval 5 print Warning Cooled to f at s but this is not the smallest point found squeeze last_state cost squeeze last_state x break if Tf is not None and schedule T Tf retval 1 break if maxeval is not None and schedule feval maxeval retval 2 break if iters maxiter print Warning Maximum number of iterations exceeded retval 3 break if maxaccept is not None and schedule accepted maxaccept retval 4 break if full_output return best_state x best_state cost schedule T schedule feval iters schedule accepted retval else return best_state x retval
test representation on domain with some binary dimensions,def test_compact_binary u mapDir os path join __rlpy_location__ u Domains u SystemAdministratorMaps mapname os path join mapDir u 20MachTutorial txt domain SystemAdministrator networkmapname mapname rep IndependentDiscretizationCompactBinary domain assert rep features_num 21 stateVec np zeros 20 stateVec 0 1 phiVec rep phi stateVec terminal False assert sum phiVec 1 assert phiVec 0 1
initialises a new ' dynamicsmetablockconnectivity ' instance .,def __init__ self BlockConnectivity None MetaBlockConnection None args kw_args self _BlockConnectivity self BlockConnectivity if BlockConnectivity is None else BlockConnectivity self _MetaBlockConnection self MetaBlockConnection if MetaBlockConnection is None else MetaBlockConnection super DynamicsMetaBlockConnectivity self __init__ args kw_args
initialises a new ' operationallimittype ' instance .,def __init__ self direction high acceptableDuration 0 0 OperationalLimit None args kw_args self direction direction self acceptableDuration acceptableDuration self _OperationalLimit self OperationalLimit if OperationalLimit is None else OperationalLimit super OperationalLimitType self __init__ args kw_args
initialises a new ' bay ' instance .,def __init__ self VoltageLevel None Substation None args kw_args self _VoltageLevel None self VoltageLevel VoltageLevel self _Substation None self Substation Substation super Bay self __init__ args kw_args
initialises a new ' discretevalue ' instance .,def __init__ self value 0 Discrete None args kw_args self value value self _Discrete None self Discrete Discrete super DiscreteValue self __init__ args kw_args
initialises a new ' conformload ' instance .,def __init__ self LoadGroup None args kw_args self _LoadGroup None self LoadGroup LoadGroup super ConformLoad self __init__ args kw_args
a line can be contained by a subgeographical region .,def getRegion self return self _Region
the point or polygon location of a given hazard .,def getLocations self return self _Locations
conducting equipment may have multiple clearance tags for authorized field work,def getClearanceTags self return self _ClearanceTags
receipt that recorded this receiving of a payment in the form of tenders .,def getReceipt self return self _Receipt
a thermal generating unit may have one or more fossil fuels,def getThermalGeneratingUnit self return self _ThermalGeneratingUnit
test adding nodes to a graph .,def test_add_node self g Graph g nodes append Node ID node1 g add_node node2 g add_node Node node3 self assertEqual len g 3
: param rng : : param l : : return : gt - 0 = 1|0 1 = 0|1 2 = 1|1,def genotype p_het rng l r1 rng rand l r2 rng rand l gt np zeros l dtype int gt r1 p_het 2 gt r1 p_het r2 0 5 1 return gt
get the currently selected radiobutton .,def get_selected self for button in self get_group if button get_active return button
"function is called each frame while switching screens and responsible for drawing transition state . t will go from -1.0 ( previous screen ) , to 0 ( rigth in middle ) , until 1.0 ( last time called before giving new screen full controll )",def draw_transition self t set_color self style bg color drawRectangle pos self container pos size self container size r g b self style bg color 0 3 if t 0 if self previous_screen is not None self previous_screen dispatch_event on_draw set_color r g b 1 t drawRectangle pos self container pos size self container size else if self previous_screen is not None self screen dispatch_event on_draw set_color r g b 1 t drawRectangle pos self container pos size self container size
allow setting of the keycmd externally .,def set_keycmd self keycmd self keylet set_keycmd keycmd self update_event set self keylet False
pretty - print a python object to a stream [ default is sys.stdout ] .,def pprint object stream None indent 1 width 80 depth None printer PrettyPrinter stream stream indent indent width width depth depth printer pprint object
"copy an entire directory tree ' src ' to a new location ' dst ' . both ' src ' and ' dst ' must be directory names . if ' src ' is not a directory , raise distutilsfileerror . if ' dst ' does not exist , it is created with ' mkpath ( ) ' . the end result of the copy is that every file in ' src ' is copied to ' dst ' , and directories under ' src ' are recursively copied to ' dst ' . return the list of files that were copied or might have been copied , using their output name . the return value is unaffected by ' update ' or ' dry_run ' : it is simply the list of all files under ' src ' , with the names changed to be under ' dst ' .",def copy_tree src dst preserve_mode 1 preserve_times 1 preserve_symlinks 0 update 0 verbose 0 dry_run 0 from distutils file_util import copy_file if not dry_run and not os path isdir src raise DistutilsFileError cannot copy tree s not a directory src try names os listdir src except os error as errno errstr if dry_run names else raise DistutilsFileError error listing files in s s src errstr if not dry_run mkpath dst outputs for n in names src_name os path join src n dst_name os path join dst n if preserve_symlinks and os path islink src_name link_dest os readlink src_name log info linking s s dst_name link_dest if not dry_run os symlink link_dest dst_name outputs append dst_name elif os path isdir src_name outputs extend copy_tree src_name dst_name preserve_mode preserve_times preserve_symlinks update dry_run dry_run else copy_file src_name dst_name preserve_mode preserve_times update dry_run dry_run outputs append dst_name return outputs
handles the http get request .,def do_GET self response self server generate_html_documentation self send_response 200 self send_header Content type text html self send_header Content length str len response self end_headers self wfile write response self wfile flush self connection shutdown 1
test that we get [ ] if the peer did not exist .,def test_nonexistant_peer_status self status self pybird get_peer_status HAMSTER assert status
append a rule that stops traversal at a branch node .,def prune self rule self pruneRules append rule
"add "" missing "" in fields which we will require for the known_changes table",def mark_missing_fields self for key in urgency maintainer fingerprint changed by if key not in self changes or not self changes key self changes key missing
remove all tasks from the scheduler,def remove_all_tasks self self tasks
callback for object : state - changed : busy accessibility events .,def onBusyChanged self event pass
extract interesting events from a log file as a list of logevent .,def parse_log_events stream context 6 jobs None profile False if parse_log_events ctest_parser is None parse_log_events ctest_parser CTestLogParser profile profile result parse_log_events ctest_parser parse stream context jobs if profile parse_log_events ctest_parser print_timings return result
"given an observation array , a label vector , and the location of the centers plot the clusters",def plot_2d_clusters X labels centers clabels set labels K len clabels if len centers K raise ValueError Expecting the number of unique labels and centres to be the same figure figsize 10 10 ax gca vor Voronoi centers voronoi_plot_2d vor ax colors cm hsv np arange K float K for k col in enumerate colors my_members labels k scatter X my_members 0 X my_members 1 c col marker o s 20 for k col in enumerate colors cluster_center centers k scatter cluster_center 0 cluster_center 1 c col marker o s 200 axis tight axis equal title Clusters
quaternion from ( body 3(psi)-2(theta)-1(phi ) euler angles,def euler_to_quat phi theta psi s1 sin psi 2 c1 cos psi 2 s2 sin theta 2 c2 cos theta 2 s3 sin phi 2 c3 cos phi 2 return array s1 s2 s3 c1 c2 c3 s1 s2 c3 s3 c1 c2 s1 s3 c2 s2 c1 c3 s1 c2 c3 s2 s3 c1
pre exec func . for starting the logger process for a service .,def logger_preexec log_path u Pre exec func for starting the logger process for a service n n Before execing the logger service s6 log connect stdin to the logging n FIFO so that it reads log lines from the service and connect stdout stderr n to the void since we ignore the logger s console output n The logger writes actual log output to files in SERVICE_DIR logs n n param log_path path to the logging FIFO n log_fifo_reader os open log_path os O_RDWR devnull os open os devnull os O_WRONLY os dup2 log_fifo_reader StreamFileDescriptor STDIN os dup2 devnull StreamFileDescriptor STDOUT os dup2 devnull StreamFileDescriptor STDERR os close log_fifo_reader os close devnull
create a dom from a stream,def fromStream self stream ownerDoc None raise NOT OVERIDDEN
bind a queue to an exchange .,def queue_bind self args kwargs pass
"load the qdr with values within the fpga loadchoice can be 0 for loading all zeros 1 for loading all ones 2 for loading all twos 3 for loading a sequence that matches the row number 4 to set 32 bits to 1 5 to load 36 bits to 1 6 to set every other bit in 32 bits to 1 , starting with a 1 7 to set every other bit in 36 bits to 1 ,",def loadQdrInFirmware roach loadChoice 0 roach write_int load_qdr 0 roach write_int read_qdr 0 roach write_int load_data_choice loadChoice time sleep 0 2 roach write_int load_qdr 1 time sleep 2 roach write_int load_qdr 0 time sleep 1
converts a dictionary to and from the specified class .,def __init__ self class_type attribute_conversions super SimpleClassConversion self __init__ self _class_type class_type self _attribute_conversions attribute_conversions
get for each estimable parameter a scaling factor that is to be used for scaling this parameter to unitary .,def numdiff_get_scaling_factors self raise NotImplementedError
register access and refresh tokens to auth token store . that way they can be used like a session .,def register_tokens app access_token refresh_token None access_jti get_jti encoded_token access_token auth_tokens_store add access_jti false app config JWT_ACCESS_TOKEN_EXPIRES if refresh_token is not None refresh_jti get_jti encoded_token refresh_token auth_tokens_store add refresh_jti false app config JWT_REFRESH_TOKEN_EXPIRES
retags the tagged instances in the given list using lowest entropy . uses only the instances that give an anchor .,def lowest_entropy instances lowest None anchor None for i instance in enumerate instances if not instance predicted startswith n entropy instance entropy if lowest is None lowest entropy if entropy lowest anchor i lowest entropy instance change_prediction n instance predicted instances anchor change_prediction instances anchor predicted 2 return instances
this method attempts to percieve bonds,def percieveBonds self for iat atom1 in enumerate self getAtoms for jat atom2 in enumerate self getAtoms if iat jat continue dr atom2 getCoordinate atom1 getCoordinate R2 dr dot dr dr_cov atom1 getCovalentRadius atom2 getCovalentRadius self _bond_threshold R2_cov dr_cov 2 if R2 R2_cov yield bond Bond id1 iat id2 jat
| make a grid of dust grain radius values | | * * inputs * * | amin : scalar [ micron ] : minimum grain size to use | amax : scalar [ micron ] : maximum grain size to use | na : integer : number of points in grid | | * * returns * * | a numpy array of length na,def make_rad amin amax na log False if log return np logspace np log10 amin np log10 amax na else return np linspace amin amax na
: param value : value to pack . : type value : object : returns : packed object . : rtype : str,staticmethod def pack value return value encode
create spatial extent with a geofeature instance or list of tiles,def __init__ self dataclass feature None tiles None pcov 0 0 ptile 0 0 self repo dataclass Asset Repository self site feature if tiles is None and feature is None tiles self repo find_tiles if feature is not None tiles self repo vector2tiles feature pcov ptile tiles self feature feature Filename feature LayerName feature FID self sitename feature Basename else tiles t 1 1 for t in tiles self sitename tiles self coverage tiles
merge multiple hyperloglog values into an unique value that will approximate the cardinality of the union of the observed sets of the source hyperloglog structures .,def pfmerge self dest_key keys return self _execute PFMERGE dest_key list keys OK
linux uses a normal path .,def CanonicalPathToLocalPath path return utils SmartStr utils NormalizePath path
runs parsers over the raw data and maps it to artifact_data types .,def _ProcessData self processor responses artifact_name source artifact_data self state host_data get artifact_name result_iterator artifact ApplyParserToResponses processor responses source self self token for rdf in result_iterator if isinstance rdf rdf_anomaly Anomaly artifact_data ANOMALY append rdf else artifact_data PARSER append rdf
check we can download files references in a collection .,def testDownloadCollectionWithFlattenOption self fd sequential_collection GeneralIndexedCollection self collection_urn with data_store DB GetMutationPool as pool fd Add rdfvalue RDFURN self out Add testfile1 mutation_pool pool fd Add rdf_client StatEntry pathspec rdf_paths PathSpec path testfile2 pathtype OS mutation_pool pool fd Add rdf_file_finder FileFinderResult stat_entry rdf_client StatEntry pathspec rdf_paths PathSpec path testfile5 pathtype OS mutation_pool pool with utils TempDirectory as tmpdir export_utils DownloadCollection self collection_urn tmpdir overwrite True dump_client_info True flatten True token self token max_threads 2 symlinks os listdir os path join tmpdir files self assertEqual len symlinks 3 self assertListEqual sorted symlinks C 1000000000000000_fs_os_testfile1 C 1000000000000000_fs_os_testfile2 C 1000000000000000_fs_os_testfile5 self assertEqual os readlink os path join tmpdir files C 1000000000000000_fs_os_testfile1 os path join tmpdir C 1000000000000000 fs os testfile1
creates new output stream with a given name .,def _CreateOutputStream self name if name in self stream_objects return self stream_objects name urn self state output_base_urn Add name self state output_streams name urn logging info Creating new output stream s urn output_stream aff4 FACTORY Create urn aff4_type aff4 AFF4UnversionedImage mode rw token self token output_stream Seek 0 2 self stream_objects name output_stream return output_stream
strips regular expression notation syntax characters from the given string expression .,def strip_regex expr return expr replace 3 1 if isregex_expr expr else expr
serialize nnop or list of nnop and all necessary variables to a folder .,def serialize nnops path None save_variables True variables binary_output False override False if path is None and not binary_output raise ValueError path cannot be None if binary_output False is_path_given False if path is None else True if path is None path tmp tmp path_folder path uuid length 25 if binary_output else path vars if save_variables for op in as_tuple nnops if hasattr op variables for v in as_tuple op variables if K is_variable v vars append v vars list set vars as_list variables if os path exists path_folder if os path isfile path_folder raise ValueError path s is NOT a folder path_folder elif override shutil rmtree path_folder os mkdir path_folder else os mkdir path_folder nnops_path os path join path_folder nnops ai vars_path os path join path_folder variables with open nnops_path wb as f cPickle dump nnops f protocol cPickle HIGHEST_PROTOCOL if len vars 0 K save_variables vars vars_path if binary_output data folder2bin path_folder if not is_path_given shutil rmtree path_folder return data if os path exists path if override if os path isfile path os remove path else shutil rmtree path else raise RuntimeError File at path s exists cannot override path with open path wb as f cPickle dump data f protocol cPickle HIGHEST_PROTOCOL shutil rmtree path_folder return path
the address my employer sends email to for me,def employee_address return employer_email employee_username
return the default job timeout threshold in seconds .,property def timeout self return self _timeout
return a dict with all the meta of the file,def get_meta self with open self filename r as f decoded bencode bdecode f read return self __get_meta_recursively decoded
"like pytree . node.__repr _ _ , but names instead of numbers for tokens .",def _PytreeNodeRepr node if isinstance node pytree Node return s s r node __class__ __name__ NodeName node _PytreeNodeRepr c for c in node children if isinstance node pytree Leaf return s s r node __class__ __name__ NodeName node node value
creates and returns the argparse parser object .,def getParser parser argparse ArgumentParser description __description__ formatter_class RawTextHelpFormatter parser add_argument output help Target volume parser add_argument inputs nargs help Source volumes of same shape and dtype parser add_argument s dest spacing type float default 1 help The voxel spacing of the newly created dimension Default is 1 parser add_argument p dest position type int default 0 help The position where to put the new dimension starting from 0 Standard behaviour is to place it in the first position parser add_argument i dest ignore action store_true help Ignore if the images datatypes differ parser add_argument v dest verbose action store_true help Display more information parser add_argument d dest debug action store_true help Display debug information parser add_argument f dest force action store_true help Silently override existing output images return parser
send http message code 500 back to the client,def returnHTTPversionServerError pass
save a job page to smw,moa args forceable moa args needsJob moa args command def smw_save_job job args _saveJobToSmw job
"return true if command exited normally , false otherwise .",def command_successful args return_code _ run_command args return return_code 0
tokenizer that maps all numeric tokens to a placeholder .,def number_aware_tokenizer doc token_pattern re compile u u b w w b tokens token_pattern findall doc tokens NUMBER if token 0 in 0123456789_ else token for token in tokens return tokens
used to test that private errors defined within a class can not be properly pickled . this means that the exception should come out on the client side as a jobfailederror instead . : raise myprivateexception : a private exception class,def raise_private_error self raise TestClass MyPrivateError ___Failure3
checks the genomes returned by the create_population function are of the correct type .,def test_returns_valid_genomes self result create_population 1 TARGET_WORD self assertEqual Genome type result 0
this function creates a select.poll object that can be used in the same manner as signal.pause ( ) . the poll object returns each time a signal was received by the process .,def register global _signal_poller global _signal_read_fd if _signal_poller is not None raise RuntimeError register was already called read_fd write_fd os pipe filecontrol set_non_blocking write_fd filecontrol set_non_blocking read_fd filecontrol set_close_on_exec write_fd filecontrol set_close_on_exec read_fd signal set_wakeup_fd write_fd poller select poll poller register read_fd select POLLIN _signal_poller poller _signal_read_fd read_fd
"replace the xml snippet of all disk devices with fresh configuration obtained from vdsm . vdsm initializes its disk device objects from the xml . vdsm also needs to do some per - host adjustments on the disk devices ( e.g. prepare the paths ) , so we ca n't avoid this replacement .",def replace_disks_xml dom disk_devices devs vmxml find_first dom devices to_remove dev_elem for dev_elem in vmxml children devs if dev_elem tag vmdevices hwclass DISK for dev_elem in to_remove vmxml remove_child devs dev_elem for dev in disk_devices vmxml append_child devs child dev getXML return dom
override to use our private target .,def setTarget self target self _target target
"read configurations from the config file . if the section exists , then create the config module as of right now , it is still in doubt whether to error out on bad configuration , or to just exclude module",def read_configs config_file config ConfigParser SafeConfigParser cfg_success config read config_file if not cfg_success syslog syslog syslog LOG_ERR Could not read nyx conf exit 1 configs source False if config has_section crits configs crits if config has_option crits username configs crits username config get crits username else syslog syslog syslog LOG_ERR nyx Please make sure that the crits section of the nyx conf file has a username section exit 1 if config has_option crits api_key configs crits api_key config get crits api_key else syslog syslog syslog LOG_ERR nyx Please make sure that the crits section of the nyx conf file has a api_key section exit 1 if config has_option crits url configs crits url config get crits url else syslog syslog syslog LOG_ERR nyx Please make sure that the crits section of the nyx conf file has a url section exit 1 if config has_option crits offset configs crits offset int config get crits offset else crits_config offset 20 source crits if config has_section soltra configs soltra if config has_option soltra username configs soltra username config get soltra username else syslog syslog syslog LOG_ERR nyx Please make sure that the soltra section of the nyx conf file has a username section exit 1 if config has_option soltra password configs soltra password config get soltra password decode base64 decode rot13 else syslog syslog syslog LOG_ERR nyx Please make sure that the soltra section of the nyx conf file has a password section exit 1 if config has_option soltra server configs soltra server config get soltra server else syslog syslog syslog LOG_ERR nyx Please make sure that the soltra section of the nyx conf file has a server section exit 1 if config has_option soltra subscriptions configs soltra subscriptions json loads config get soltra subscriptions else syslog syslog syslog LOG_ERR nyx Unable to get the Soltra subscriptions from the configuation file exit 1 if config has_option soltra supported_objects configs soltra supported_objects json loads config get soltra supported_objects else syslog syslog syslog LOG_ERR nyx Unable to get the Soltra supported_objects from the configuation file exit 1 source soltra if not source syslog syslog syslog LOG_ERR nyx minimum sections required for nyx to run a threat intel source please populate either the soltra or the CRITs sections exit 1 if config has_section qradar configs qradar map ip medium nyx_default_IP_medium high nyx_default_IP_high sample medium nyx_default_sample_medium high nyx_default_sample_high email medium nyx_default_email_medium high nyx_default_email_high domain medium nyx_default_domain_medium high nyx_default_domain_high if config has_option qradar console configs qradar base_url config get qradar console api else syslog syslog syslog LOG_ERR nyx Unable to get the QRadar console address from the configuation file exit 1 if config has_option qradar api_key configs qradar SEC config get qradar api_key else syslog syslog syslog LOG_ERR nyx Unable to get the QRadar api key from the configuration file exit 1 if config has_option qradar sets_to_validate configs qradar sets_to_validate json loads config get qradar sets_to_validate else syslog syslog syslog LOG_ERR nyx Unable to get the QRadar intel reference sets from the configuation file exit 1 set_test if config has_option qradar high_reference_sets configs qradar high_reference_sets json loads config get qradar high_reference_sets set_test configs qradar high_reference_sets values configs qradar map ip high configs qradar high_reference_sets Address ipv4 addr configs qradar map domain high configs qradar high_reference_sets A configs qradar map sample high configs qradar high_reference_sets md5 configs qradar map email high configs qradar high_reference_sets email else syslog syslog syslog LOG_ERR nyx Unable to get the QRadar intel reference sets from the configuation file exit 1 if config has_option qradar medium_reference_sets configs qradar medium_reference_sets json loads config get qradar medium_reference_sets set_test configs qradar medium_reference_sets values configs qradar map ip medium configs qradar medium_reference_sets Address ipv4 addr configs qradar map domain medium configs qradar medium_reference_sets A configs qradar map sample medium configs qradar medium_reference_sets md5 configs qradar map email medium configs qradar medium_reference_sets email else syslog syslog syslog LOG_ERR nyx Unable to get the QRadar intel reference sets from the configuation file exit 1 for qset in set_test if not qset in configs qradar sets_to_validate keys configs qradar sets_to_validate qset ALNIC syslog syslog syslog LOG_ERR nyx Unable to find metadata about the s set in the configuation file Defaulting to ALNIC qset if config has_section bro configs bro if config has_option bro filename configs bro filename config get bro filename for ftype in _file txt _addr txt _dom txt _mail txt with open configs bro filename w as bro_file bro_file write fields indicator indicator_type meta source meta do_notice else syslog syslog syslog LOG_ERR Unable to get the BRO intel file location from the configuation file exit 1 if config has_option bro indicator_map configs bro indicator_map json loads config get bro indicator_map set_test configs bro indicator_map keys else syslog syslog syslog LOG_ERR nyx Unable to load the BRO indicator map from the configuation file exit 1 if config has_section palo_alto configs palo_alto map ip medium nyx_default_IP_medium high nyx_default_IP_high domain medium nyx_default_domain_medium high nyx_default_domain_high if config has_option palo_alto api_key configs palo_alto api_key config get palo_alto api_key else syslog syslog syslog LOG_ERR nyx Unable to get the Palo Alto api key from the configuation file exit 1 if config has_option palo_alto url configs palo_alto url config get palo_alto url else syslog syslog syslog LOG_ERR nyx Unable to get the Palo Alto base URL from the configuation file exit 1 if config has_option palo_alto url_alert_list configs palo_alto map domain medium config get palo_alto url_alert_list else syslog syslog syslog LOG_ERR nyx Unable to get the Palo Alto BlockList from the configuation file exit 1 if config has_option palo_alto url_block_list configs palo_alto map domain high config get palo_alto url_block_list else syslog syslog syslog LOG_ERR nyx Unable to get the Palo Alto Alert List from the configuation file exit 1 if config has_option palo_alto ip_alert_list configs palo_alto map ip medium config get palo_alto ip_alert_list else syslog syslog syslog LOG_ERR nyx Unable to get the Palo Alto BlockList from the configuation file exit 1 if config has_option palo_alto ip_block_list configs palo_alto map ip high config get palo_alto ip_block_list else syslog syslog syslog LOG_ERR nyx Unable to get the Palo Alto Alert List from the configuation file exit 1 if config has_section web_proxy configs web_proxy if config has_option web_proxy filename configs web_proxy filename config get web_proxy filename with open configs web_proxy filename w as wp_file wp_file write else syslog syslog syslog LOG_ERR nyx Unable to get the BRO intel file location from the configuation file exit 1 if config has_section wise configs wise if config has_option wise filename configs wise filename config get wise filename else syslog syslog syslog LOG_ERR Unable to get the wise intel file location from the configuation file exit 1 if config has_option wise indicator_map configs wise indicator_map json loads config get wise indicator_map set_test configs wise indicator_map keys else syslog syslog syslog LOG_ERR nyx Unable to load the wise indicator map from the configuation file exit 1 for ftype in config wise indicator_map values with open configs wise filename ftype w as wise_file wise_file write return configs
send an email to a user with a given address .,def notify_role role subject template kwargs if role email is None log info Role r not have email skip notify role return try sender s s settings APP_TITLE settings MAIL_FROM subject s s settings APP_TITLE subject html render_template template role role ui_url settings APP_UI_URL app_title settings APP_TITLE kwargs msg Message subject subject sender sender recipients role email msg html html mail send msg except Exception log exception Error sending email to user
: param ds : string datasource i d : type ds : basestring : return : none,def set_datasource_name self ds_name self ds_name ds_name
return start and end frames ; end is exclusive .,def view self start cell2frame self _view_start self density end start cell2frame self _width self density n self numframes if end n end n return start end
"this runs when a miner submits a blob with a valid nonce . it returns true only if blockheader says the nonce position is okay , and the powvalidator says the nonce is valid . : param m_gettime : : param m_logger : : return :",def test_submit_mined_block self m_getTime m_logger m_mining_block Mock autospec Block name mock _mining_block m_mining_block verify_blob return_value False self miner _mining_block m_mining_block blob this is a blob12345that was the nonce encode result self miner submit_mined_block blob self assertFalse result m_mining_block verify_blob return_value True self chain_manager validate_mining_nonce MagicMock return_value False result self miner submit_mined_block blob self assertFalse result m_mining_block verify_blob return_value True self chain_manager validate_mining_nonce MagicMock return_value True self m_pre_block_logic return_value True result self miner submit_mined_block blob self assertTrue result
internal method to update the slider knob,def _update_knob self self _knob left self current_val self _knob width 2 self _side_margin if self _filled self _fill_mid width self current_val self _fill_left width self _side_margin
utility function to find cuda path,def find_cuda_path if CUDA_PATH in os environ return os environ CUDA_PATH cmd which nvcc proc subprocess Popen cmd stdout subprocess PIPE stderr subprocess STDOUT out _ proc communicate out py_str out if proc returncode 0 return os path abspath os path join str out strip cuda_path usr local cuda if os path exists os path join cuda_path bin nvcc return cuda_path raise RuntimeError Cannot find cuda path
sets up a subparser to download the svhn dataset files .,def fill_subparser subparser subparser add_argument which_format help which dataset format type int choices 1 2 return svhn_downloader
return duration metadata extracted by taglib,def get_duration self return self __info duration
test distributing a sub - expr from right over single - operands .,def test_distributing_sub_expr_over_single_operands_from_right self self assert_distribute_ors_tranformation A and B and C and D or E or F A or E or F and B or E or F and C or E or F and D or E or F
generate a list of python decimals with * none_prob * probability of an entry being none ( or nan if * use_nan * is true ) .,def generate_decimal_list self n none_prob DEFAULT_NONE_PROB use_nan False data decimal Decimal 9f f for f in self rnd uniform 0 0 1 0 n assert len data n self sprinkle data none_prob value decimal Decimal nan if use_nan else None return data
create a tmva reader and predict data .,def tmva_process info data import ROOT reader ROOT TMVA Reader for feature in data columns reader AddVariable feature array array f 0 0 model_type sigmoid_function info model_type reader BookMVA info method_name info xml_file signal_efficiency None if model_type classification and sigmoid_function is not None and sig_eff in sigmoid_function signal_efficiency float sigmoid_function strip split 1 assert 0 0 signal_efficiency 1 0 signal efficiency must be in 0 1 not format signal_efficiency if signal_efficiency is not None predictions evaluate_reader reader info method_name data aux signal_efficiency else predictions evaluate_reader reader info method_name data return predictions
install or upgrade setuptools and easyinstall .,def main options _parse_args archive download_setuptools _download_args options return _install archive _build_install_args options
send a custom metric report .,def custom self name metric value tags None id_ None self _report name metric value tags id_
initialize chord with pitch tokens .,def test_Chord___init___03 chord abjad Chord ds 4 ef 4 1 4 assert format chord ds ef 4
chord coipes articulations and markup .,def test_Chord___copy___05 chord_1 abjad Chord ef cs f 4 articulation_1 abjad Articulation staccato abjad attach articulation_1 chord_1 markup_1 abjad Markup foo direction abjad Up abjad attach markup_1 chord_1 chord_2 copy copy chord_1 assert format chord_1 format chord_2 assert chord_1 is not chord_2 articulation_2 abjad inspect chord_2 get_indicators abjad Articulation 0 assert articulation_1 articulation_2 assert articulation_1 is not articulation_2 markup_2 abjad inspect chord_2 get_markup 0 assert markup_1 markup_2 assert markup_1 is not markup_2
make 200-note voice with durated complex beam spanner on every 4 notes .,def make_spanner_score_01 self import abjad voice abjad Voice 200 abjad Note c 16 for part in abjad sequence voice partition_by_counts 4 cyclic True beam abjad Beam abjad attach beam part return voice
this writes the byte string to a destination file,def encrypt_file src dest key decrypt bt write_bytes dest encryptor src key decrypt
convert an integer to a string .,def long2str l if type l not in types IntType types LongType raise ValueError the input must be an integer if l 0 raise ValueError the input must be greater than 0 s while l s s chr l 255L l 8 return s
code run before each unit test .,def setUp self self system1 seapy system System self system1 frequency center 500 0 1000 0 2000 0 4000 0 8000 0 self steel self system1 addMaterial steel MaterialSolid loss_factor np ones len self system1 frequency center 0 2
build the sources in srcdir in builddir / prefix using options for qmake,def Build Status SrcDir BuildDir LogDir BuildPath BuildDir Status prefix os system mkdir p BuildPath rc os system cd BuildPath qmake Status options SrcDir Status projectFile LogDir qmake Status prefix log 2 1 if rc 0 Status configureStatus 1 else Status configureStatus 2 rc os system cd BuildPath make all LogDir make all Status prefix log 2 1 if rc 0 Status compileStatus 1 else Status compileStatus 3 return Status
whether flake8 should consider a file as a core file or a package .,def is_package f return f startswith var spack repos or docs tutorial examples in f
fit phenos ntimes with different random initialization and returns the minima order with respect to gp . lml,def fit_ntimes self ntimes 10 grad_threshold 0 01 dist_mins 0 01
returns a string representation of the specified kmer .,def decode_kmer binary_kmer kmer_size assert kmer_size 31 binary_kmer_int struct unpack Q binary_kmer 0 b 0 064b format binary_kmer_int 1 ret for j in range kmer_size nuc BASES b j 2 j 1 2 ret append nuc ret join ret return ret 1
translate fractional coordinates into real - space coordinates,def _get_scaled_elements self scaled_elements for key in self elements keys scaled_elements key copy copy self elements key scaled_elements key 3 self cellSize return scaled_elements
"retrieve a random socket address from the local os by binding to an ip , acquiring a random port and then closing the socket and returning that address .",def getsockaddr host family socket AF_INET port 0 sockmod socket for fam stype proto _ sa in socket getaddrinfo host port family socket SOCK_DGRAM 0 socket AI_PASSIVE s socket socket family stype proto s bind sa sockaddr s getsockname 2 s close return sockaddr raise socket error getaddrinfo returned empty sequence
evaluate a type cast and return the result .,def eval self context target_type context find ty self target if target_type is not None value self children 0 eval context return target_type cast value raise Exception Type not found
attempts to import the plugin aliased to alias in config .,def import_plugin config alias full_class_name config get plugins alias if full_class_name module_name join full_class_name split 1 class_name full_class_name split 1 else module_name nav ipdevpoll plugins s alias class_name None _logger debug Importing plugin s s alias full_class_name try module_ __import__ module_name globals locals module_name if class_name class_ getattr module_ class_name else class_ get_plugin_from_module module_ except ImportError AttributeError as error _logger exception Failed to import plugin s full_class_name raise PluginImportError error class_ alias alias plugin_registry alias class_ class_ on_plugin_load
store the set of enabled vlans for each trunk port .,def _store_trunk_ports self native_vlans enabled_vlans for ifindex vector in enabled_vlans items if ifindex not in self _valid_ifindexes self _logger debug ignoring info for invalid ifindex s ifindex continue interface self containers factory ifindex shadows Interface interface trunk True if ifindex in native_vlans interface vlan native_vlans ifindex self _logger debug Trunk port r enabled VLAN count s interface ifname len vector get_set_bits allowed self containers factory ifindex shadows SwPortAllowedVlan allowed interface interface allowed hex_string vector to_hex
get ifin / outoctets for an interface using a single request,def get_interface_data interface in_bps out_bps None targets metric_path_for_interface interface netbox sysname interface ifname counter for counter in INOCTETS OUTOCTETS targets get_metric_meta t target for t in targets data get_metric_average targets start TRAFFIC_TIMEPERIOD for key value in iteritems data if ifInOctets in key in_bps value elif ifOutOctets in key out_bps value return in_bps out_bps
find contacts for the vlans on the downlinks on the netboxes,def find_vlan_organizations netboxes vlans for netbox in netboxes interfaces netbox interface_set filter to_netbox__isnull False swportvlan__direction SwPortVlan DIRECTION_DOWN swportvlan__vlan__organization__isnull False for interface in interfaces vlans extend v vlan for v in interface swportvlan_set exclude vlan__in vlans return v organization for v in set vlans if v organization
turn off a single rgbled .,def off self rgb_mask 7 self index RGBLEDS_START_INDEX 3 new_val RGBLED _rgbleds_val rgb_mask self _set_rgbleds_value new_val
"checks whether given object is a 5-element tuple . : return : `` true `` if argument is a 5-element tuple , `` false `` otherwise",def is_quintuple obj return is_tuple obj len_ 5
verifies the response code is http 200 and parses the json response . @returns a dictionary of the response contents .,def parseResponse self response self assertEqual response status_code 200 return json loads response content
convert the cgi pil value into something we can query,def pil_logic s if s return s s upper pils if s find 1 pils append s else pils s split res for pil in pils if pil 3 WAR for q in FLS FFS AWW TOR SVR FFW SVS LSR SPS WSW FFA WCN res append s s q pil 3 6 else res append 6 6s pil strip return res
query for outlook based on some timestamp,def dotime time lon lat day cat if time in current now ts datetime datetime utcnow replace tzinfo pytz utc if day 1 ts datetime timedelta days day 1 else ts datetime datetime strptime time Y m dT H MZ ts ts replace tzinfo pytz utc pgconn get_dbconn postgis df read_sql SELECT issue at time zone UTC as i expire at time zone UTC as e valid at time zone UTC as v threshold category from spc_outlooks where valid select valid from spc_outlooks where issue s and expire s and day s and outlook_type C ORDER by valid DESC LIMIT 1 and ST_Contains geom ST_GeomFromEWKT SRID 4326 POINT s s and day s and outlook_type C and category s pgconn params ts ts day lon lat day cat index_col None res generation_time datetime datetime utcnow strftime ISO9660 query_params time ts strftime ISO9660 lon lon lat lat cat cat day day outlook if df empty return json dumps res df threshold_rank df threshold apply get_order df sort_values threshold_rank ascending False inplace True res outlook threshold df iloc 0 threshold utc_valid df iloc 0 v strftime ISO9660 utc_issue df iloc 0 i strftime ISO9660 utc_expire df iloc 0 e strftime ISO9660 return json dumps res
perform any needed postprocessing on the table and return it,def filter_table self table return table
properly encode input text to make it satisfy named url convention .,def _encode_uri text for c in URL_PATH_RESERVED_CHARSET if c in text text text replace c URL_PATH_RESERVED_CHARSET c text text replace NAMED_URL_RES_INNER_DILIMITER s NAMED_URL_RES_INNER_DILIMITER return text
converts a unix timestamp into a formatted string .,def timestamp2str t fmt Y m d H M S 000 return datetime fromtimestamp t strftime fmt
parse the command line for options,def _parse_args parser optparse OptionParser parser add_option user dest user_install action store_true default False help install in user site package requires Python 2 6 or later parser add_option download base dest download_base metavar URL default DEFAULT_URL help alternative URL from where to download the setuptools package parser add_option insecure dest downloader_factory action store_const const lambda download_file_insecure default get_best_downloader help Use internal non validating downloader parser add_option version help Specify which version to download default DEFAULT_VERSION options args parser parse_args return options
returns the best observed point and its function value,def get_incumbent self if self normalize_input X zero_mean_unit_var_unnormalization self X self x_mean self x_std m self predict X 0 else m self predict self X 0 best_idx np argmin self y inc self X best_idx inc_value m best_idx if self normalize_input inc zero_mean_unit_var_unnormalization inc self x_mean self x_std if self normalize_output inc_value zero_mean_unit_var_unnormalization inc_value self y_mean self y_std return inc inc_value
"returns true if there are tabs in the leading whitespace of a line , including the whitespace of docstring code samples .",def tab_in_leading s n len s len s lstrip if not s n n 3 in check s n else smore s n 3 check s n smore len smore len smore lstrip return check expandtabs check
whether two parameters match values .,def matches self new old if isinstance new np ndarray or isinstance old np ndarray return np array_equal new old if pd if isinstance new pd Series or isinstance old pd Series return np array_equal new old if isinstance new pd Index or isinstance old pd Index return np array_equal new old try if isinstance new dict and isinstance old dict if set new keys set old keys return False return all self matches new k old k for k in new return new old except ValueError return False
"sets the state of the object to "" error "" after a failure .",def set_error self self _set_state ERROR
sets the width and height of the plot uses an aspect ratio of 4:3 if only one of width and height are specified if neither width or height are specified it defaults to 8 by 6 inches .,def set_width_and_height self width height if height is not None if width is None width height 4 0 3 0 elif width is not None height width 3 0 4 0 else height 6 width 8 self fig set_figheight height self fig set_figwidth width
return whether the document is likely to be a sitemap .,classmethod def is_request cls request return cls is_url request url_info
iterates all filesystem paths that get matched by the glob pattern . syntax is equal to that of fnmatch .,def glob pattern return list iglob pattern
register a link structure for the plugin .,abc abstractmethod def register_link_structure self app
number of ( per default unrelated ) children,def getChildrenLength self filter True u count 0 for child in self if not filter or not hasattr child u rel count 1 return count
"input_filename_replacements apply to filename , before --name = seriesname takes effect",attr functional def test_replacements_applied_before_force_name conf always_rename true select_first true force_name Scrubs input_filename_replacements is_regex true match S01E02 replacement out_data run_tvnamer with_files S01E02 Some File avi with_config conf expected_files S01E02 Some File avi verify_out_data out_data expected_files expected_returncode 2
the number of parameters that parameterise the component .,property def n_params self return self _n_params
the current set of d - values associated with this component .,property def d_values self return self _d_values
"updates a database table with values defined in dict iterator , finds rows using unique column other fields are assumed to have the same name as their dict key : param unique_column : the column name for unique column , probably the i d field",def mysql_update db_eng db_table dict_iterator unique_column id log_every 10000 first_row next dict_iterator update_columns list first_row keys del update_columns update_columns index unique_column update_statements join s format col for col in update_columns update_sql UPDATE SET WHERE s format db_table update_statements unique_column _mysql_update_row db_eng update_sql first_row unique_column update_columns count 0 starttime time time for row in dict_iterator count 1 if count log_every 0 time_elapsed time time starttime print rows updated in s format count time_elapsed _mysql_update_row db_eng update_sql row unique_column update_columns
creates an instance of a link object,def __init__ self name None super Link self __init__ name name
update the set with the union of itself and other iterables .,def update self args for arg in args for item in arg self add item
"block until some callback sets the event and clearing the event subsequently . returns true if event was set , false on timeout",def wait self self _event wait IDLEMOCK_TIMEOUT if self _event isSet self _event clear return True else return False
warp real image into an existing image,def test_warp_into self geoimg gpt get_test_image select 1 ext geoimg extent bbox np array ext x0 ext y0 ext width ext height imgout gp GeoImage create geoimg xsize geoimg ysize 1 geoimg srs bbox geoimg type string geoimg warp_into imgout self assertEqual imgout read sum geoimg read sum
"do resource release exercise at low memory threshold , blow up over max",def do_garbage_collect self error_str try rss_mem_usage float self proc_monitor memory_info rss 1024 1024 except AttributeError rss_mem_usage float self proc_monitor get_memory_info rss 1024 1024 except Exception as exc error_str str exc if error_str log_error Error obtaining resource usage s error_str systemd_exit os EX_SOFTWARE SDEX_NOTRUNNING memory_exec_threshold get_numeric_setting memory_exec_threshold float if rss_mem_usage memory_exec_threshold log_warning Memory exec threshold s MB reached actual s MB execve to reclaim memory_exec_threshold rss_mem_usage file_path os path join sys path 0 sys argv 0 file_path os path normpath file_path os execve file_path sys argv os environ else gc collect return
"pubdev-3624 top or bottom n test h2o.frame.h2oframe.topn ( ) and h2o.frame.h2oframe.bottomn ( ) functions . given a h2o frame , a column index or column name , a double denoting percentages of top / bottom rows to return , the topn will return a h2oframe containing two columns , one will be the topn ( or bottomn ) values of the specified column . the other column will record the row indices into the original frame of where the topn ( bottomn ) values come from . this will let the users to grab those corresponding rows to do whatever they want with it .",def h2o_H2OFrame_top_bottomN dataFrame h2o import_file pyunit_utils locate bigdata laptop jira TopBottomNRep4 csv zip topAnswer h2o import_file pyunit_utils locate smalldata jira Top20Per csv zip bottomAnswer h2o import_file pyunit_utils locate smalldata jira Bottom20Per csv zip nPercentages 1 2 3 4 frameNames dataFrame names tolerance 1e 12 nsample 100 nP nPercentages randint 0 len nPercentages 1 colIndex randint 0 len frameNames 1 if randint 0 2 0 print For topN Percentage chosen is 0 Column index chosen is 1 format nP colIndex newTopFrame dataFrame topN frameNames colIndex nP newTopFrameC dataFrame topN colIndex nP pyunit_utils compare_frames newTopFrame newTopFrameC nsample tol_numeric tolerance compare_rep_frames topAnswer newTopFrame tolerance colIndex 1 else print For bottomN Percentage chosen is 0 Column index chosen is 1 format nP colIndex newBottomFrame dataFrame bottomN frameNames colIndex nP newBottomFrameC dataFrame bottomN colIndex nP pyunit_utils compare_frames newBottomFrame newBottomFrameC nsample tol_numeric tolerance compare_rep_frames bottomAnswer newBottomFrame tolerance colIndex 1
make sure the directory ' path ' exists in a thread - safe way .,def ensure_dir_exists path try os makedirs path except OSError as e if e errno errno EEXIST or not os path isdir path raise e
confirm iref nodes are created correctly,def test_net_object_Iref_attributes_present self program MainProgram routine TestFunctionBlockRoutine sheet 1 iref self prj programs program routines routine sheets sheet blocks 0 self assertEqual iref x 160 self assertEqual iref y 120 self assertEqual iref operand boolean1 self assertEqual iref hide_desc false
"formats a datetime , using `` ' today ' `` or `` ' yesterday ' `` instead of the given date format when appropriate .",def format_datetime dt user date_format time_format separator if user dt user_timezone dt user today user_timezone datetime datetime now user date else today datetime date today date_part dt date delta date_part today if delta days 0 date u Today elif delta days 1 date u Yesterday else date dateformat format dt date_format return u s s s date separator dateformat time_format dt time time_format
a list of all items in that path,def directory_list path if not os path isdir path return return os listdir path
"copy file on local filesystem in an atomic way , so partial copies never exist . preserves timestamps .",def copyfile_atomic source_path dest_path make_parents False backup_suffix None with atomic_output_file dest_path make_parents make_parents backup_suffix backup_suffix as tmp_path shutil copyfile source_path tmp_path set_file_mtime tmp_path os path getmtime source_path
"cleanly shutdown the connection to rabbitmq by stopping the consumer with rabbitmq . when rabbitmq confirms the cancellation , on_cancelok will be invoked by pika , which will then closing the channel and connection . the ioloop is started again because this method is invoked when ctrl - c is pressed raising a keyboardinterrupt exception . this exception stops the ioloop which needs to be running for pika to communicate with rabbitmq . all of the commands issued prior to starting the ioloop will be buffered but not processed .",def stop self LOGGER info Stopping self _closing True self stop_consuming self _connection ioloop start LOGGER info Stopped
just call the cmdloop method in cmd module,def _main self return self cmdloop
"errors when we 're fairly sure that the server did not receive the request , so it should be safe to retry .",def _is_connection_error self err return isinstance err ConnectTimeoutError
create the glsl copy_program for copying the rendered texture,def setup_copy_program vertex_shader attribute vec2 position attribute vec2 texcoord varying vec2 var_texcoord void main gl_Position vec4 position 0 0 1 0 var_texcoord texcoord fragment_shader uniform sampler2D texture varying vec2 var_texcoord void main gl_FragColor texture2D texture var_texcoord return ShaderProgram vertex_shader fragment_shader position gl GL_FLOAT 2 texcoord gl GL_FLOAT 2
find link matched the given regular expression in response body .,deprecated def find_link_rex self rex make_absolute True if make_absolute self tree make_links_absolute self doc url for elem _ link _ in self tree iterlinks if elem tag a match rex search link if match return link return None
"complex morlet wavelet function compatible with scipy.signal.cwt parameters : points : int number of points in ` vector ` . width : scalar width parameter of wavelet . equals ( sample rate / fundamental frequency of wavelet ) returns : ` vector ` : complex - valued ndarray of shape ( points , )",def cwtmorlet points width omega 5 0 s points 2 0 omega width return wavelets morlet points omega s complete True
import course from an olx directory .,def import_course_from_path path repo_id user_id u n Import course from an OLX directory n n Args n path unicode Path to extracted OLX tree n repo_id int Primary key of repository course belongs to n user_id int Primary key of Django user doing the import n Returns n course learningresources Course n bundle XBundle keep_urls True keep_studio_urls True preserve_url_name True bundle import_from_directory path static_dir join path u static with transaction atomic course import_course bundle repo_id user_id static_dir return course
get bins of overlapping rectangles . all rectangles which overlap by a certain percentage will be put into the same bin .,def get_bins rectangles bins r for r in rectangles for i rect1 in enumerate rectangles for rect2 in rectangles r1 p1 rect1 r2 p2 rect2 if not numpy array_equal r1 r2 and rectangle intersect_percentage r1 r2 0 5 bins i append rect2 return bins
generator with _ _ vhdl _ _ is not permitted,def incGen count enable clock reset n instance def logic incGen vhdl_code Template string while 1 yield clock posedge reset negedge if reset ACTIVE_LOW count next 0 elif enable count next count 1 n return logic
"pop a value from collection[uid][key ] ( which is assumed to be a list ) value=-1 pops the last element of the list ( default ) value=0 pops the first element of the list other values for "" value "" will throw error and return a none ( not supported in mongo )",timed op_type get def pop self uid key None value 1 exp None uid self uid_prefix uid format exp_uid self exp_uid if exp None else exp return self db pop_list self collection uid key value
test the check for nonzero bits of a masked entry,def test_nxm_ip self def try_bad e nx NXM_OF_IP_SRC IPAddr 192 168 56 1 IPAddr 255 255 255 0 e pack self assertRaisesRegexp AssertionError nonzero masked bits try_bad
find tests in ' dir ' .,def load_testsuite loader dir suite unittest TestSuite files for f in os listdir dir path join dir f if isfile path and fnmatch f test_ py files append f elif isfile join path __init__ py suite addTests loader discover path for f in files f relpath join dir f loader _top_level_dir f splitext normpath f replace os path sep 0 suite addTests loader loadTestsFromName f return suite
the llvm - registered name for a cpython - compatible wrapper of the raw function ( i.e. a pycfunctionwithkeywords ) .,property def llvm_cpython_wrapper_name self return itanium_mangler prepend_namespace self mangled_name ns cpython
test that forbid_codegen ( ) prevents code generation using the @jit decorator .,def test_forbid_codegen self def f return 1 with forbid_codegen with self assertRaises RuntimeError as raises cfunc jit nopython True f cfunc self assertIn codegen forbidden by test case str raises exception
generate a unique filename that maintains the extension,def uniqify_filename filename filelist filename rsplit 1 filelist 0 uuid4 hex return join filelist
get the number of items to paginate by,def get_paginate_by self queryset paginate_by self request GET get self paginate_key None if paginate_by and paginate_by isdigit return int paginate_by return super PaginateByMixin self get_paginate_by queryset
checks that the user is on the expected branch .,def verify_current_branch_name expected_branch_name if get_current_branch_name expected_branch_name raise Exception ERROR This script can only be run from the s branch expected_branch_name
on ' self / other ' .,def __div__ self other return self data other
gives the continuousfactor operation ( product or divide ) with the other factor .,def _operate self other operation inplace True if not isinstance other ContinuousFactor raise TypeError ContinuousFactor objects can only be multiplied or divided with another ContinuousFactor object Got other_type expected ContinuousFactor format other_type type other phi self if inplace else self copy phi distribution phi distribution _operate other other distribution operation operation inplace False if not inplace return phi
remove saved data successful runs from db,def _execute self forget_sub if not self sel_tasks self dep_manager remove_all self outstream write forgetting all tasks n else tasks dict t name t for t in self task_list check_tasks_exist tasks self sel_tasks forget_list self sel_tasks if forget_sub to_forget list tasks_and_deps_iter tasks forget_list True else to_forget for name in forget_list task tasks name to_forget append task to_forget extend subtasks_iter tasks task for task in to_forget self dep_manager remove task name self outstream write forgetting s n task name self dep_manager close
overloading of iterator from model . we iterate only on the variables defined in the assignment .,def __iter__ self return iter self assignment items
add the wf with given kpoint and spin to the ldos,def add_wf_to_ldos self n u weight None kpt self calc wfs kpt_u u psi kpt psit_nG n w weight if w is None w kpt weight self ldos w psi np conj psi real
"returns the batch having highest priority , or `` none `` , if there are no batches .",def _select_batch_to_flush self best_batch None best_priority None batches_to_remove None for batch in self _batches if not batch items or batch is_flushed if batches_to_remove is None batches_to_remove batch else batches_to_remove append batch continue priority batch get_priority if best_batch is None or best_priority priority best_batch batch best_priority priority if batches_to_remove for batch in batches_to_remove self _batches remove batch return best_batch
converts an interger into the binary string .,def statenum_to_binstate statenum base bstate bin statenum 2 bstate join 0 for n in xrange base len bstate bstate return bstate
wpa2-enterprise negative test - domain suffix mismatch,def test_ap_wpa2_eap_tls_neg_suffix_match dev apdev params hostapd wpa2_eap_params ssid test wpa2 eap hostapd add_ap apdev 0 ifname params dev 0 connect test wpa2 eap key_mgmt WPA EAP eap TTLS identity DOMAIN mschapv2 user anonymous_identity ttls password password phase2 auth MSCHAPV2 ca_cert auth_serv ca pem domain_suffix_match incorrect example com wait_connect False scan_freq 2412 ev dev 0 wait_event CTRL EVENT EAP STARTED timeout 10 if ev is None raise Exception Association and EAP start timed out ev dev 0 wait_event CTRL EVENT EAP METHOD timeout 10 if ev is None raise Exception EAP method selection timed out if TTLS not in ev raise Exception Unexpected EAP method ev dev 0 wait_event CTRL EVENT EAP TLS CERT ERROR CTRL EVENT EAP SUCCESS CTRL EVENT EAP FAILURE CTRL EVENT CONNECTED CTRL EVENT DISCONNECTED timeout 10 if ev is None raise Exception EAP result timed out if CTRL EVENT EAP TLS CERT ERROR not in ev raise Exception TLS certificate error not reported if Domain suffix mismatch not in ev raise Exception Domain suffix mismatch not reported ev dev 0 wait_event CTRL EVENT EAP SUCCESS CTRL EVENT EAP FAILURE CTRL EVENT CONNECTED CTRL EVENT DISCONNECTED timeout 10 if ev is None raise Exception EAP result 2 timed out if CTRL EVENT EAP FAILURE not in ev raise Exception EAP failure not reported ev dev 0 wait_event CTRL EVENT CONNECTED CTRL EVENT DISCONNECTED timeout 10 if ev is None raise Exception EAP result 3 timed out if CTRL EVENT DISCONNECTED not in ev raise Exception Disconnection not reported ev dev 0 wait_event CTRL EVENT SSID TEMP DISABLED timeout 10 if ev is None raise Exception Network block disabling not reported
@param caption : the caption of the audio component @param source : the audio file to play .,def __init__ self caption source None super Audio self __init__ self setCaption caption self setSource source self setShowControls True
"selects all text in the rich text area . as a side effect , focuses the rich text area .",def selectAll self self _selectAll True self focus self requestRepaint
gets the value formatter of textfield .,def getFormat self warn replaced by PropertyFormatter DeprecationWarning return self _format
called if no specific method for processing a trace event has been found .,def catchall self event rec pass
run any post - connection steps . this happens after the protocolparts are initalized so can depend on a fully - populated object .,abstractmethod def after_connect self pass
read and return a bytestring from reading the path .,def read self mode r with self open mode as f return f read
convert a nurbs object into a nd - linear tensor product fe mesh .,def create_linear_fe_mesh nurbs pars None knots nurbs knots shape nurbs weights shape if pars is None pars for ii kv in enumerate knots par nm linspace kv 0 kv 1 shape ii pars append par coors nurbs pars coors shape 1 coors shape 1 conn desc get_tensor_product_conn len ii for ii in pars if coors 1 0 0 all coors coors 1 return coors conn desc
check the source file 's time stamp and notify the self.notify_obj in case it changed . subclasses should implement the file_changed ( ) method .,def poll_file self if not self notify_obj return s os stat self filename if s 2 self last_stat 2 setattr self notify_obj self notify_attr False else self file_changed setattr self notify_obj self notify_attr True self last_stat s
override this method with a custom base graph .,def prototype_adjacency self n_block_features alpha pass
test parsing of arguments from main method,patch pyqs main _main patch pyqs main ArgumentParser mock_sqs def test_real_main_method ArgumentParser _main ArgumentParser return_value parse_args return_value Mock concurrency 3 queues email1 interval 1 batchsize 10 logging_level WARN region us east 1 prefetch_multiplier 2 access_key_id None secret_access_key None main _main assert_called_once_with queue_prefixes email1 concurrency 3 interval 1 batchsize 10 logging_level WARN region us east 1 prefetch_multiplier 2 access_key_id None secret_access_key None
"spherical bessel functions computes a table of j_l(x ) for fixed xx , eq . ( 39 ) args : xx : float lc : integer angular momentum result : xj[0:lc ] : float",def xjl xx lc assert lc 1 xj np zeros lc 1 dtype float64 if abs xx 1e 10 xj 0 1 0 return xj sin_xx_div_xx np sin xx xx if xx 0 75 lc aam aa bbm bb sa qqm 1 0 2 lc 1 xx 0 0 1 0 1 0 10000000000 0 for k in range 1 51 sb 2 lc k 1 xx aap bbp sb aa sa aam sb bb sa bbm aam bbm aa bb aa bb aap bbp qq aa bb if abs qq qqm 1e 15 break qqm qq xj lc 1 0 if lc 0 xj lc 1 qq if lc 1 for l in range lc 1 0 1 xj l 1 2 l 1 xj l xx xj l 1 cc sin_xx_div_xx xj 0 for l in range lc 1 xj l cc xj l else xj 0 sin_xx_div_xx if lc 0 xj 1 xj 0 xx np cos xx xx if lc 1 for l in range 1 lc xj l 1 2 l 1 xj l xx xj l 1 return xj
apply the mm charges in the qm gradients ' method . it affects both the electronic and nuclear parts of the qm fragment .,def mm_charge_grad scf_grad coords charges unit None if unit is None unit scf_grad mol unit if unit startswith B b au AU coords numpy asarray coords order C elif unit startswith A a coords numpy asarray coords order C lib parameters BOHR else coords numpy asarray coords order C unit charges numpy asarray charges class QMMM scf_grad __class__ _QMMMGrad def __init__ self self __dict__ update scf_grad __dict__ def get_hcore self mol None QM 1e grad d dX i q_mm r_mm j if mol is None mol self mol g_qm scf_grad get_hcore mol nao g_qm shape 1 if pyscf DEBUG v 0 for i q in enumerate charges mol set_rinv_origin coords i v mol intor int1e_iprinv comp 3 q else if mol cart intor int3c2e_ip1_cart else intor int3c2e_ip1_sph nao mol nao max_memory self max_memory lib current_memory 0 blksize int max max_memory 1000000 0 8 nao 2 400 v 0 for i0 i1 in lib prange 0 charges size blksize fakemol gto fakemol_for_charges coords i0 i1 j3c df incore aux_e2 mol fakemol intor aosym s1 comp 3 v numpy einsum ipqk k ipq j3c charges i0 i1 return scf_grad get_hcore mol v def grad_nuc self mol None atmlst None if mol is None mol scf_grad mol g_qm scf_grad grad_nuc mol atmlst g_mm numpy empty mol natm 3 for i in range mol natm q1 mol atom_charge i r1 mol atom_coord i r lib norm r1 coords axis 1 g_mm i q1 numpy einsum i ix i x charges r1 coords 1 r 3 if atmlst is not None g_mm g_mm atmlst return g_qm g_mm return QMMM
prepend object new_child to the list of parent_object 's children .,def insert_object self parent_object new_child p s c self _get_parent_sibling_child new_child original_child self get_child parent_object self set_sibling new_child original_child self set_parent new_child parent_object self set_child parent_object new_child if p 0 return item self get_child p if item 0 raise ZObjectMalformedTree elif item new_child self set_child p s else prev item current self get_sibling item while current 0 if current new_child self set_sibling prev s break else raise ZObjectMalformedTree
perform install dependencies action for this venv .,hookspec firstresult True def tox_testenv_install_deps venv action
generates parent dictionary . this is necessary because elementtree nodes do not have parent pointers .,def generate_parent_dictionary root parent_dic for i in root getiterator for j in i getchildren parent_dic j i return parent_dic
insert child alphabetically using data d.,def insertChildSorted self newchild cdata c data for c in self childnodes idx bisect bisect_left cdata newchild data newchild parent self self childnodes insert idx newchild
write the settings using qsettings .,def writeSettings self s qt4 QSettings self domain self product cleankeys for key in self database cleankey key replace self sepchars cleankeys append cleankey s setValue cleankey repr self database key for key in list s childKeys if key not in cleankeys s remove key
check if vpp died before executing a cli,def before_cli self cli super PollHook self before_cli cli self poll_vpp
returns a list of tables in the database .,guard def tables self table_list list cursor self connection cursor try cursor execute SHOW TABLES while True row cursor fetchone if row is None break table_list append str row 0 finally cursor close return table_list
verifies the behavior of filter ( ) method .,def testFilter self collection ee Collection ee Function self assertRaises Exception collection filter filtered collection filter ee Filter eq foo 1 self assertEquals ee ApiFunction lookup Collection filter filtered func self assertEquals collection collection filter ee Filter eq foo 1 filtered args self assertTrue isinstance filtered ee Collection
a blocking fetch function similar to urlfetch.fetch .,def _retry_fetch url retry_params kwds n 1 start_time time time delay retry_params delay n start_time if delay 0 return logging info Will retry request to s url while delay 0 resp None try logging info Retry in s seconds delay time sleep delay resp urlfetch fetch url kwds except runtime DeadlineExceededError logging info Urlfetch retry s will exceed request deadline after s seconds total n time time start_time raise except _RETRIABLE_EXCEPTIONS as e pass n 1 delay retry_params delay n start_time if resp and not _should_retry resp break elif resp logging info Got status s from GCS resp status_code else logging info Got exception r while contacting GCS e if resp return resp logging info Urlfetch failed after s retries and s seconds in total n 1 time time start_time raise
adds relation in this document .,def add_relation self relation self relations append relation
"this forks the current process into a daemon . the stdin , stdout , and stderr arguments are file names that will be opened and be used to replace the standard file descriptors in sys.stdin , sys.stdout , and sys.stderr . these arguments are optional and default to /dev / null . note that stderr is opened unbuffered , so if it shares a file with stdout then interleaved output may not appear in the order that you expect .",def daemonize stdin dev null stdout dev null stderr dev null try pid os fork if pid 0 sys exit 0 except OSError as e sys stderr write fork 1 failed d s n e errno e strerror sys exit 1 os chdir os umask 0 os setsid try pid os fork if pid 0 sys exit 0 except OSError as e sys stderr write fork 2 failed d s n e errno e strerror sys exit 1 si open stdin r so open stdout a se open stderr ab 0 os dup2 si fileno sys stdin fileno os dup2 so fileno sys stdout fileno os dup2 se fileno sys stderr fileno
set the filename permissions according to umask .,def umask_permissions self filename current_umask os umask 0 os umask current_umask new_mode 438 current_umask os chmod filename new_mode
places the model 430 programmer in the manual up ramping mode . ramping continues at the ramp rate until the current limit is achieved .,def ramp_up self self interface write INCR
generate shell code to reset environment variables by unrolling modifications based on all workspaces in cmake_prefix_path . this does not cover modifications performed by environment hooks .,def rollback_env_variables environ env_var_subfolders lines unmodified_environ copy copy environ for key in sorted env_var_subfolders keys subfolder env_var_subfolders key value _rollback_env_variable unmodified_environ key subfolder if value is not None environ key value lines append assignment key value if lines lines insert 0 comment reset environment variables by unrolling modifications based on all workspaces in CMAKE_PREFIX_PATH return lines
creates a ipyvolume mesh of the edge lines to be displayed in jupyter notebooks,def edge_mesh sheet coords edge_specs ipv style use dark minimal spec sheet_spec edge spec update edge_specs if isinstance spec color str color spec color elif hasattr spec color __len__ color _wire_color_from_sequence spec sheet 3 u v w coords mesh ipv Mesh x sheet vert_df u y sheet vert_df v z sheet vert_df w lines sheet edge_df srce trgt astype dtype np uint32 color color return mesh
state transition map is honoured .,def test_state_transition self for method in self context poweron self context resume self context pause self context poweroff self context shutdown self context restart for state in STATES self context domain state return_value state if method __name__ not in context context STATES_MAP state with self assertRaises RuntimeError method
return path for @exename in $ path or none,def lookup_exec_path exename PATH os environ get PATH or os defpath for execdir in PATH split os pathsep exepath os path join execdir exename if os access exepath os R_OK os X_OK and os path isfile exepath return exepath
"if you install one single package and do n't specify a name , the name of the installed package is used .",def test_install_default_name self self run_cli i foo self assertEqual self installed self locator for_name foo foo set
"returns a list of plugin names where the plugins implement at least one of the * features*. * features * must a list of plugin methods , e.g. [ plugin.postprocess_testrun , plugin.postprocess_testjob ]",def get_plugins_by_feature features if not features return get_all_plugins plugins PluginLoader load_all items names set f __name__ for f in features return e for e plugin in plugins if names set plugin __dict__ keys
> > > get_file_name_without_extension('yuv / src01_hrc01.yuv ' ) ' src01_hrc01 ' > > > get_file_name_without_extension('yuv / src01_hrc01 ' ) ' src01_hrc01 ' > > > get_file_name_without_extension('abc / xyz / src01_hrc01.yuv ' ) ' src01_hrc01 ' > > > get_file_name_without_extension('abc / xyz / src01_hrc01.sdr.yuv ' ) ' src01_hrc01.sdr ' > > > get_file_name_without_extension('abc / xyz / src01_hrc01.sdr.dvi.yuv ' ) ' src01_hrc01.sdr.dvi ',def get_file_name_without_extension path return os path splitext path split 1 0
else + return is not accetable .,def test_return_while while True return 1 else print math is broken return None
extract extern functions from a header,def extract_C_functions c d f open c prevline for line in f line line rstrip line line replace t line line replace m cmatch match line if m and not prevline startswith static and line find INTERRUPT 1 d m group 1 prevline line prevline line
this function is called at every time the status attribute value matches start_at_status config option .,def start self m pass
import the bundled version of a package .,def import_bundled_package modulename location source_tree_container namespace if in_source_tree extra_path os path join source_tree_topdir source_tree_container location if not extra_path in sys path sys path insert 0 extra_path sys modules modulename __import__ modulename else sys modules modulename __import__ s s namespace modulename fromlist namespace
retrives the information from a user,def get_user self identifier group False shaid sha1 str identifier hexdigest cur self conn cursor cursor_factory DictCursor if group sql SELECT FROM groups WHERE shaid s LIMIT 1 cur execute sql shaid else sql SELECT FROM users WHERE shaid s LIMIT 1 cur execute sql shaid d cur fetchone cur close data dict if d is None return self get_defaultconfig else data update d if lang not in d data lang en data lang_set False else data lang_set True if data lang is None data lang en data lang_set False return data
apply field move action to ca class .,staticmethod def apply_move bsca args for i in range len args delta args i bsca pos i bsca pos i delta bsca size i
"fixture that yields a : class:`~bytes ` that is 128 bits and is ordered "" less than "" the result of the : func:`~valid_bytes_128_after ` fixture .",pytest fixture scope session def valid_bytes_128_before valid_bytes_48_before return valid_bytes_48_before x00 10
: return : return ( and create if necessary ) the verifiable client implementation object .,property def impl self if not hasattr self _impl setattr self _impl create_verifiable_client_implementation self context self if hasattr self context logger and self context logger is not None self context logger debug Using client implementation s for s self _impl __class__ __name__ self __class__ __name__ return self _impl
pencapstyle : the cap style .,property def cap_style self return self _cap_style
optional . set the preferred polarity for variables in the fallback heuristic ( required fallback method ) . : return : list of literals,def signFallback pass
returns true if this request supports http/1.1 semantics,def supports_http_1_1 self return self version HTTP 1 1
end the scope of a prefix - uri mapping .,def endPrefixMapping self prefix
go through the cron directory in the root of the project and link cron files from there to the relevant directory in the /etc / cron * on the server,def link_cron_files cron_dirs cron d cron daily cron hourly cron weekly cron monthly for cron_dir in cron_dirs vcs_cron_dir path join env vcs_root_dir cron cron_dir etc_cron_dir path join etc cron_dir if path isdir vcs_cron_dir for cron_file in os listdir vcs_cron_dir vcs_cron_file path join vcs_cron_dir cron_file etc_cron_file path join etc_cron_dir _make_cron_name_safe cron_file if path islink etc_cron_file os unlink etc_cron_file _create_link vcs_cron_file etc_cron_file
the enum type that can only return `` true `` when compared to types of own type .,def Enum values kwargs type_name kwargs get type_name None docstr kwargs get doc if type_name is None raise Exception Please specify type_name as a keyword argument assert len values 0 Empty enums are meaningless maximum len values class EnumValue object __slots__ __value def __init__ self value self __value value def __hash__ self return hash self __value def __cmp__ self other if isinstance self type other return cmp self __value other __value else return cmp id self id other def __invert__ self return values maximum self __value def __nonzero__ self return bool self __value def __bool__ self return bool self __value def __repr__ self return str values self __value class EnumType EnumBase __doc__ docstr __type_name__ type_name __values__ values def __iter__ self return iter values def __len__ self return len values def __getitem__ self i return values i def __repr__ self return Enum str enumerate values def __str__ self return enum str values for i v in enumerate values setattr EnumType v EnumValue i return EnumType
adds the name of the type to the language,def add_type self type if type name in self type_dict raise AlreadyDef type name else self type_dict type name type
stores log entries and sends them to clients upon request .,def state_manager ctx pipe port maxlen store deque maxlen maxlen snapshot ctx socket zmq ROUTER snapshot bind tcp format port poller zmq Poller poller register pipe zmq POLLIN poller register snapshot zmq POLLIN while True try items dict poller poll except zmq ZMQError KeyboardInterrupt break if pipe in items sequence entry int pipe recv pipe recv_string store append sequence entry if snapshot in items client request snapshot recv_multipart assert request ICANHAZ for k v in store snapshot send client zmq SNDMORE snapshot send str k encode zmq SNDMORE snapshot send_string v snapshot send_multipart client 1
try to match a single stored value ( dv ) with a supplied value ( v ) .,def match_value self k dv v if not isinstance v type dv result False elif not isinstance dv str or k not in self _partial_matches result v dv else result dv find v 0 return result
reads project into an ast and transforms imports into nodes : param root_path : string : return : node,def read_project root_path verbose False ignore None encoding None nodes root_node None errors False ignore_files set hg svn git tox __pycache__ env venv if ignore for ignored_file in ignore ignore_files add os path basename os path realpath ignored_file for root dirs files in os walk root_path dirs d for d in dirs if d not in ignore_files files fn for fn in files if os path splitext fn 1 py and fn not in ignore_files for file_name in files full_path os path join root file_name with open_func full_path r encoding encoding as f try file_data f read lines file_data splitlines tree ast parse file_data if verbose click echo crayons yellow Trying to parse file format full_path if full_path in nodes node nodes full_path else node Node file_name 3 full_path full_path nodes full_path node if not root_node root_node node for ast_node in ast walk tree if isinstance ast_node ast Import and ast_node names for subnode in ast_node names if not subnode name continue path_to_module get_path_from_package_name root_path subnode name if path_to_module in nodes new_node nodes path_to_module else new_node Node subnode name full_path path_to_module nodes path_to_module new_node new_node is_imported_from full_path append ast_node lineno node add new_node elif isinstance ast_node ast ImportFrom and ast_node module current_path root_path if 0 ast_node lineno 1 len lines and REGEX_RELATIVE_PATTERN findall lines ast_node lineno 1 current_path root path_to_module get_path_from_package_name current_path ast_node module if path_to_module in nodes new_node nodes path_to_module else new_node Node ast_node module full_path path_to_module nodes path_to_module new_node for obj_import in ast_node names if ast_node lineno not in node func_imports node func_imports ast_node lineno obj_import name else node func_imports ast_node lineno append obj_import name new_node is_imported_from full_path append ast_node lineno node add new_node elif isinstance ast_node ast ClassDef ast FunctionDef node func_defs ast_node name ast_node lineno except Exception as e errors True click echo crayons yellow Parsing of file failed format full_path if verbose click echo crayons red traceback format_exc e if errors click echo crayons red There were errors during the operation perhaps you are trying to parse python 3 project with python 2 version of the script or vice versa return root_node
"strips any .aux or .log files from the input source list . these are created by the tex builder that in all likelihood was used to generate the .dvi file we 're using as input , and we only care about the .dvi file .",def PDFEmitter target source env def strip_suffixes n return not SCons Util splitext str n 1 in aux log source list filter strip_suffixes source return target source
return a bool indicating whether the error between z1 and z2 is < = tol .,def comp z1 z2 tol if not z1 z1 z2 z2 z1 if not z1 return True diff abs z1 z2 az1 abs z1 if z2 and az1 1 return diff az1 tol else return diff tol
verify the correctness of a base and strong generating set .,def _verify_bsgs group base gens from sympy combinatorics perm_groups import PermutationGroup strong_gens_distr _distribute_gens_by_base base gens current_stabilizer group for i in range len base candidate PermutationGroup strong_gens_distr i if current_stabilizer order candidate order return False current_stabilizer current_stabilizer stabilizer base i if current_stabilizer order 1 return False return True
for internal use by the modules class .,def _vector_to_sdm self v order raise NotImplementedError
evaluates the inverse cos of an interval,def acos x np import_module numpy if isinstance x int float if abs x 1 return interval np inf np inf is_valid False else return interval np arccos x np arccos x elif isinstance x interval if x is_valid is False or x start 1 or x end 1 return interval np inf np inf is_valid False elif x start 1 or x end 1 return interval np inf np inf is_valid None else start np arccos x start end np arccos x end return interval start end is_valid x is_valid
return a list of valid platform names .,def platform_names return _platform_classes keys _platform_aliases keys
get cycle class by name .,def cycle_by_name name u return symbol_by_name name CYCLE_ALIASES
test executing a statement without any arguments,def testExecuteNoArgs self result self cursor execute begin null end self failUnlessEqual result None
"ensure headers sent by the default middleware do n't inadvertently change . for example , we never want "" vary : cookie "" to appear in the list since it prevents the caching of responses .",def test_middleware_headers self from django conf project_template project_name settings import MIDDLEWARE with self settings MIDDLEWARE MIDDLEWARE ROOT_URLCONF project_template urls response self client get empty headers sorted response serialize_headers split r n self assertEqual headers Content Length 0 Content Type text html charset utf 8 X Frame Options SAMEORIGIN
compare two version strings in the form of 1.2.34,def cmp_version ver1 ver2 return cmp int v for v in ver1 split int v for v in ver2 split
test binding in / out with set input sizes defined,def testBindInOutSetInputSizes self vars self cursor setinputsizes value cx_Oracle TIMESTAMP self cursor execute begin value value 5 25 end value cx_Oracle Timestamp 2002 12 12 10 0 0 self failUnlessEqual vars value getvalue cx_Oracle Timestamp 2002 12 17 16 0 0
get_conf ( ) - > confparse object for hive-site.xml,def get_conf if _HIVE_SITE_DICT is None _parse_hive_site return _HIVE_SITE_DICT
test array size too large generates an exception,def testArraySizeTooLarge self self cursor arraysize 65536 self failUnlessRaises ValueError self cursor execute select from TestLongRaws
the prefix for the flatpage template tag can be a template variable,def test_get_flatpages_with_variable_prefix self out Template load flatpages get_flatpages location_prefix as location_flatpages for page in location_flatpages page title endfor render Context location_prefix location self assertEqual out A Nested Flatpage
write the core workbook xml .,def write_workbook workbook root Element workbook xmlns http schemas openxmlformats org spreadsheetml 2006 main xml space preserve xmlns r http schemas openxmlformats org officeDocument 2006 relationships SubElement root fileVersion appName xl lastEdited 4 lowestEdited 4 rupBuild 4505 SubElement root workbookPr defaultThemeVersion 124226 codeName ThisWorkbook book_views SubElement root bookViews SubElement book_views workbookView activeTab d workbook get_index workbook get_active_sheet autoFilterDateGrouping 1 firstSheet 0 minimized 0 showHorizontalScroll 1 showSheetTabs 1 showVerticalScroll 1 tabRatio 600 visibility visible sheets SubElement root sheets for i sheet in enumerate workbook worksheets sheet_node SubElement sheets sheet name sheet title sheetId d i 1 r id rId d i 1 if not sheet sheet_state sheet SHEETSTATE_VISIBLE sheet_node set state sheet sheet_state defined_names SubElement root definedNames for named_range in workbook get_named_ranges name SubElement defined_names definedName name named_range name dest_cells cell_ids for worksheet range_name in named_range destinations cell_ids append workbook get_index worksheet dest_cells append s s worksheet title replace absolute_coordinate range_name base_id cell_ids 0 if named_range local_only and all x base_id for x in cell_ids name set localSheetId s base_id name text join dest_cells SubElement root calcPr calcId 124519 calcMode auto fullCalcOnLoad 1 return get_document_content root
test binding out a number array ( with arrayvar ),def testBindOutNumberArrayByVar self array self cursor arrayvar cx_Oracle NUMBER 6 expectedData i 100 for i in range 1 7 self cursor execute begin pkg_TestNumberArrays TestOutArrays numElems array end numElems 6 array array self failUnlessEqual array getvalue expectedData
"run doctest on the given module . return ( # failures , # tests ) .",def run_doctest module verbosity None import doctest if verbosity is None verbosity verbose else verbosity None save_stdout sys stdout sys stdout get_original_stdout try f t doctest testmod module verbose verbosity if f raise TestFailed d of d doctests failed f t return f t finally sys stdout save_stdout
syncs ( creates ) document2permissions based on the documentpermissions found for a given document .,def _sync_permissions self document document2 doc_permissions DocumentPermission objects filter doc document for perm in doc_permissions doc2_permission created Document2Permission objects get_or_create doc document2 perms perm perms if perm users doc2_permission users add perm users all if perm groups doc2_permission groups add perm groups all
"if the cloud was successfully segmented , then function returns colored cloud ( with only rgb fields ) . otherwise it returns none .",def get_colored_cloud self if len self _clusters 0 return None colors randint 0 256 size len self _clusters 3 colors colors astype u1 colordata np tile np array 255 24 dtype u4 len self _clusters colordata colors 0 16 colors 1 8 colors 2 colordata dtype f4 colored_cloud PointCloud width self _input width height self _input height fields rgb f4 self _input copy_metadata colored_cloud for coloridx cluster in enumerate self _clusters for index in cluster colored_cloud index colordata coloridx return colored_cloud
turns a function into a bound method and adds it to the given object .,def _bind fn obj wraps fn def method self args kwargs return fn args kwargs bound_method types MethodType method obj obj __class__ setattr obj bound_method __name__ bound_method
add the ` dyld_library_path ` environment variable for dakota .,def add_dyld_library_path try dakota_exe which_dakota dakota_dir os path dirname os path dirname dakota_exe os environ DYLD_LIBRARY_PATH os path join dakota_dir bin os path pathsep os path join dakota_dir lib except AttributeError TypeError return None
test default object run method fails with no input file .,def test_default_run_without_input_file if is_dakota_installed if os path exists input_file os remove input_file try k Dakota k run except CalledProcessError pass
"function decorator for caching pickleable return values on disk . uses a hash computed from the function arguments for invalidation . if ' method ' , skip the first argument , usually being self or cls . the cache filepath is ' directory / basename - hash.pickle ' .",def disk_cache basename directory method False directory os path expanduser directory ensure_directory directory def wrapper func functools wraps func def wrapped args kwargs key tuple args tuple kwargs items if method and key key key 1 filename pickle format basename hash key filepath os path join directory filename if os path isfile filepath with open filepath rb as handle return pickle load handle result func args kwargs with open filepath wb as handle pickle dump result handle return result return wrapped return wrapper
"each private envfile resource gets a k8s service , deployment and internalrequiresconfigmap .",def test_envfile_to_k8s_private_resource system SIMPLE_SYSTEM transform application services myservice requires myresource RequiredResource name myresource template database system system transform local templates database DockerResource name myresource image postgres 9 3 config dict port 3535 another value expected_resource_deployment k8s Deployment name myservice myresource docker_image postgres 9 3 port 3535 expected_resource_service k8s InternalService deployment expected_resource_deployment expected_addrconfigmap k8s InternalRequiresConfigMap backend_service expected_resource_service resource_name myresource data another value expected_deployment SIMPLE_K8S_DEPLOYMENT transform address_configmaps expected_addrconfigmap expected_service k8s InternalService deployment expected_deployment assert envfile_to_k8s system pset expected_deployment expected_service k8s Ingress exposed_path abc backend_service expected_service expected_resource_service expected_resource_deployment expected_addrconfigmap
this source can be shuffled .,def can_shuffle self return True
get the terminal width as number of characters,def width self return self _width
create a new ewma with a specific smoothing constant .,def __init__ self period interval None self initialized False self _period period self _interval interval or EWMA INTERVAL self _uncounted 0 0 self _rate 0 0 self _last_tick time
to decrypt the password from the cipher text . written to test the functionality of pycrypto : return :,def decrypt_password config_file open CONFIG_FILE_PATH contents yaml load config_file cipher_key contents encryption cipher_key cipher_IV456 contents encryption cipher_IV456 cipher_text contents github password s AES new cipher_key AES MODE_CBC cipher_IV456 decrypt cipher_text return s old_div len s 16
yield any modified versions of `` line `` needed to address the errors in `` errors `` .,def fix_pylint line errors if not errors yield line return current PYLINT_EXCEPTION_REGEX search line if current original_errors disable strip for disable in current group disables split else original_errors set disabled_errors set original_errors for error in errors if error error_name useless suppression parsed re search Useless suppression of P error_name error error_msg disabled_errors discard parsed group error_name elif error error_name missing docstring and error error_msg Missing module docstring yield format_pylint_disables error error_name strip n else disabled_errors add error error_name disable_string format_pylint_disables disabled_errors not disabled_errors original_errors if current yield PYLINT_EXCEPTION_REGEX sub disable_string line else yield re sub s disable_string 1 line
"we build the topic chain : if the event 's topic is empty , the chain is [ '' ] if the event 's topic was a , the chain is [ '' , a ] if the event 's topic was a.b , the chain is [ '' , a , b ] and so on",def build_topic_chain topic subtopics topic split topic_chain for i in range len subtopics topic_chain append join subtopics i 1 topic_chain reverse return topic_chain
convenience method that sends request messages to the client .,def send self path batch params self messages return Neo4jRequest post self path params
type : : = sum i d ( fields ),def p_type_2 self sum id _0 attributes _1 if id value attributes raise ASDLSyntaxError id lineno msg expected attributes found s id return Sum sum attributes
handle parameter substitution and execute command as child process .,def worker data json_file with open json_file as fp d json load fp json_directory os path dirname json_file def p parts return os path join json_directory parts log_file data log_file savecmd_file data savecmd_file template_file data template_file if template_file output_template p os path basename template_file with open output_template w as out_fobj template_subs_file template_file out_fobj d try shutil copymode template_file output_template except OSError as e if e errno errno EPERM logging warn Couldn t set permissions on s Continuing with existing permissions output_template else raise work data template format d if savecmd_file with open p savecmd_file w as command_file command_file write work n if data dry_run logging info s Dry run of s n p work else try with open p log_file w as log cmd shlex split work while True try pr subprocess Popen cmd stdout log stderr log cwd p except OSError as e if e errno errno EINTR raise continue else break logging info d Started s in s pr pid work p nestproc NestlyProcess cmd p pr yield nestproc except Exception as e logging error s Error executing s s p work e raise e
"returns the list of ontology ids scorresponding to the specified term name . if the term name is not found , return the empty list .",def getTermIds self termName u n Returns the list of ontology IDs scorresponding to the specified term n name If the term name is not found return the empty list n return self _nameIdMap termName
return evenly spaced intervals of a given colormap ` cmap ` .,def cmap_intervals length 50 cmap YlOrBr start None stop None cm getattr plt cm cmap if cmap in Accent Dark2 Paired Pastel1 Pastel2 Set1 Set2 Set3 Vega10 Vega20 Vega20b Vega20c base_n_colors cm N cmap_list cm range base_n_colors if base_n_colors length factor int np floor_divide length base_n_colors cmap_list np tile cmap_list factor 1 return cmap_list crange CMAP_RANGE get cmap dict start 0 stop 255 if cmap in REVERSE_CMAP crange dict start crange stop stop crange start if start is not None crange start start if stop is not None crange stop stop idx np linspace crange start crange stop length astype np int return cm idx
add a new object to this container .,def add self args for obj in args if obj not in self _objects self _objects append obj
"creates a new instance of a mock consumer class . to perform initialization tasks , extend consumer._initialize : param dict configuration : the configuration from rejected",def __init__ self configuration process self _configuration configuration self _process process
return cache image path @param uri as str @param suffix as str @return str / none,def get_path self uri suffix if uri is None return None parsed urlparse uri cached_uri remove_www parsed netloc cached_path parsed path rstrip if cached_path cached_uri cached_path encoded sha256 cached_uri encode utf 8 hexdigest filepath s s_ s png EOLIE_CACHE_PATH encoded suffix return filepath
return an instance of a registered class .,staticmethod def getInstance name if not name in PluginRegistry modules raise ValueError no module s available name if isclass PluginRegistry modules name return None return PluginRegistry modules name
this function waits for a capture to terminate and guarantees that the capture is saved to the capture file configured during the start_capture ( ) method . depending on the type of the sniffer the file may previously contain partial results ( e.g. for a local sniffer ) or may not exist until the stop_capture ( ) method is executed ( e.g. for a remote sniffer ) .,def wait_for_capture self timeout None raise NotImplementedError Base class should not be called directly
"return an iterator over the items ( `` ( key , value ) `` pairs ) .",def iteritems self for key in self value self key yield key value
get a complexlist that contains only a single version of each complex .,def toComplexList self version 1 return ComplexList c version for c in self
"concatenate this with the given profilemirror(s ) . : : p0.concat ( p1 [ , p2 , .. ] ) - > single profilemirror with the same number of profiles as p0 but with the length of p0+p1+p2 ..",def concat self profiles if len profiles 0 return self next profiles 0 assert isinstance next self __class__ can only concat with other ProfileMirrors rmap N concatenate self map next map r self __class__ rmap self pc return r concat profiles 1
generate a string command that import object variables to locals ( ) in the class methods,def IN val_list return join s self s v v for v in val_list
"join paths , collating multiple arguments .",def pathjoin args return os sep join args
cast some values in c++ via custom type casters and count the number of moves / copies .,def test_move_and_copy_casts cstats m move_and_copy_cstats c_m c_mc c_c cstats MoveOnlyInt cstats MoveOrCopyInt cstats CopyOnlyInt assert m move_and_copy_casts 3 18 assert c_m copy_assignments c_m copy_constructions 0 assert c_m move_assignments 2 assert c_m move_constructions 2 assert c_mc alive 0 assert c_mc copy_assignments c_mc copy_constructions 0 assert c_mc move_assignments 2 assert c_mc move_constructions 2 assert c_c alive 0 assert c_c copy_assignments 2 assert c_c copy_constructions 2 assert c_m alive c_mc alive c_c alive 0
send correlation on one processor for a list of healpix,def corr_func pixels xcf fill_neighs pixels cor xcf xcf pixels return cor
updates the current selection in each list .,def _update_selection self event selected event owner is self _lists True self _selected selected v for v in event new if v
return the point group operations of a systems .,def get_point_group atoms tol 1e 08 rotations translations get_symmetry atoms tol tol point_group spglib get_pointgroup rotations 0 strip laue 1 2 m mmm 4 m 4 mmm 3 3m 6 m 6 mmm m 3 m 3m is_laue point_group in laue return point_group is_laue
get free memory of current system .,def get_free_memory self if self instance_type in AWS_INSTANCE_INFO return AWS_INSTANCE_INFO self instance_type mem 1024 else return 1024
check if any of the switches have been asked to forward packets out ports that do n't exist,def check_for_invalid_ports simulation violations for sw in simulation topology switches if sw port_violations violations str v for v in sw port_violations return violations
open a connection to the broker .,retry CONNECTION_EXCEPTIONS def open self if self is_open return connector Connector find self url host join connector host str connector port virtual_host connector virtual_host or VIRTUAL_HOST domain self ssl_domain connector userid connector userid or USERID password connector password or PASSWORD log info open s connector self _impl RealConnection host host virtual_host virtual_host ssl domain userid userid password password confirm_publish True self _impl connect log info opened s self url
test active_workers workers when some workers are inactive,mock patch object threading Thread is_alive def test_active_workers_some_inactive self mock_thread self set_active_workers mock_thread side_effect False True active self fake_manager active_workers self assertEqual 1 len active
"will copy the selected ( upper or lower ) triangle of a square matrix to the opposite side , so that the matrix is symmetrical . alters in place .",def symmetrise matrix tri upper if tri upper tri_fn np triu_indices else tri_fn np tril_indices size matrix shape 0 matrix tri_fn size 1 matrix tri_fn size return matrix
returns login credentials . this method is also in charge of expiring them .,def get_login self remote_url try statement self connection cursor statement execute select user token from s where remote_url s REMOTES_USER_TABLE remote_url rs statement fetchone if not rs return None None name rs 0 token rs 1 return name token except Exception raise ConanException Couldn t read login n Try removing s file self dbfile
executes the given query against all the given param sequences .,def executemany_rowcount self query parameters cursor self _cursor try cursor executemany query parameters return cursor rowcount finally cursor close
"process each line of gerald output and return fastq str . cut seq @ first ' . ' position . also , check for quality if qualityth defined . return none if length of the seq < minlen or an error occured during line processing .",def getFastQ file minLen qualityTh ASCII_offset_33 True pair sep N name file next 1 seq file next 1 sepli file next 1 quals file next 1 if len name split 1 name s s name split 0 pair if minLen and sep in seq pos seq index sep if pos minLen return seq quals seq pos quals pos if not ASCII_offset_33 quals join chr ord q 31 for q in quals if qualityTh pos 0 for q in quals phredQ ord q 33 if phredQ qualityTh seq quals seq pos quals pos break pos 1 if len seq minLen or not seq return return s n s n n s n name seq quals
"return s if s < size/2 , otherwise return e.",def get_name_abbrev size s e if s e s 2 0 size 2 0 return s return e
returns the name to use when creating an instance template .,def get_name instance_template_revision return s s instance_template_revision key parent id instance_template_revision key id
"interesting non - guassian distribution , to get a few very large files .",def gen_size mid_size return int random gammavariate 3 2 mid_size 4
adds the metric to the list of metrics sent by flush ( ) .,def register metric for m in state metrics values if metric m state metrics metric name metric return if metric name in state metrics raise errors MonitoringDuplicateRegistrationError metric name state metrics metric name metric
"decodes a token , checks mac tag and unwraps embedded data .",def decode_token algo token possible_secrets message assert algo in MAC_ALGOS algo assert isinstance token str assert possible_secrets assert isinstance message list _ digest_size MAC_ALGOS algo try binary base64_decode token if len binary digest_size 2 raise ValueError version ord binary 0 public binary 1 digest_size token_mac binary digest_size except ValueError TypeError raise InvalidTokenError Bad token format r token for secret in possible_secrets good_mac compute_mac algo secret chr version public message assert len good_mac len token_mac accum 0 for x y in zip token_mac good_mac accum ord x ord y if not accum public k encode ascii v encode ascii for k v in json loads public iteritems return version public try public k encode ascii replace v encode ascii replace for k v in json loads public iteritems except AttributeError ValueError pass raise InvalidTokenError Bad token MAC now d data s time time public
make sure that _ getprofiledir returns its argument when that argument is not none .,def test__getprofiledir self profiledir x self assertEqual profiledir makerbot_driver profile _getprofiledir profiledir
stuns a player for a specified duration of time .,command admin def stun script name milliseconds 1000 milliseconds abs milliseconds if milliseconds MAX_STUN_TIME err Stun time is too long Please specify a value lower than d return err MAX_STUN_TIME player script get_player name player entity damage stun_duration int milliseconds message s was stunned player name print message script server send_chat message
usage : zcat < remote file >,def do_zcat self path try path self _fix_path path required zcat if self hdfs stat path is_dir raise WebHDFSError s cannot cat directory path sys stdout write zlib decompress self hdfs get path 16 zlib MAX_WBITS except WebHDFSError OSError as e print e
"vals is list of int , each val either 0 or 1 returns the decimal value from concatenating vals",def bin_strs_to_decimal self vals return int join str x for x in vals 2
make sure accessible 's text is expected,def assertText self accessible expected_text procedurelogger action check s s text accessible procedurelogger expectedResult s s text is s accessible expected_text assert accessible text expected_text actual text is s expected text is s accessible text expected_text
"a successful response from this endpoint simply proves that django is up and running . it does n't mean that its supporting services ( like mysql , memcached , celery ) can be successfully used from within this service .",never_cache require_safe def liveness request return HttpResponse status 204
mock a login to github and return the response .,def github_login self token_data None profile_data None email_data None process login login_url reverse github_login callback_url reverse github_callback self ensure_github_app login_response self client get login_url process process assert login_response status_code 302 location urlparse login_response location query parse_qs location query assert callback_url in query redirect_uri 0 state query state 0 with requests_mock Mocker as mock_requests mock_requests post GitHubOAuth2Adapter access_token_url json token_data or self github_token_data headers content type application json mock_requests get GitHubOAuth2Adapter profile_url json profile_data or self github_profile_data if email_data is None email_data self github_email_data mock_requests get GitHubOAuth2Adapter emails_url json email_data data code github_code state state response self client get callback_url data follow True return response
return datetime obj iso formatted .,library filter def format_datetime_iso obj return obj strftime Y m dT H M S
"return a dictionary representation of the raw settings information generated by this dialog . such settings will need to be processed / checked in the "" logic "" layer of mu .",def settings self return envars self envar_widget text_area toPlainText minify self microbit_widget minify isChecked microbit_runtime self microbit_widget runtime_path text
low - level function to get json datasets from the who database .,def who_get string filter_ None force False expire EXPIRE raw False filter_ filter format filter_ if filter_ is not None else url http apps who int gho athena api format json format string filter_ mn mnc expire EXPIRE raw True key WHO format string filter_ if not force and mn exists key t mn get key if raw return t else return json loads t else req requests get url t req text replace Radio band Radio band mn key t if expire is not None mn expire key expire if raw return t j json loads t return j
returns dict with keys that need to be applied to the settings object,def process_options options args res DynObject if options exec_with_args if not exists options exec_with_args 0 print s is not a file Cannot continue options exec_with_args 0 return None res ExecLaunch options exec_with_args elif len args 1 if re match d args 0 pid int args 0 res ExecAttach pid elif exists args 0 res ExecLaunch args 0 else print s is not a file nor a pid Cannot continue args 0 return None elif len args 2 if not exists args 0 print s is not a file Cannot continue args 0 return if not re match d args 1 print Second argument should be a pid args 1 return res ExecAttach int args 1 else log1 No arguments return res
slot for ' valuechanged ' signal of : py : class:`vgrid < artview.core.core.variable > ` .,def NewGrid self variable strong self CreateLevelWidget self SetLevelRadioButtonsGrid
fixes previous command . used when ` thefuck ` called without arguments .,def fix_command known_args settings init known_args with logs debug_time Total logs debug u Run with settings format pformat settings raw_command _get_raw_command known_args try command types Command from_raw_script raw_command except EmptyCommand logs debug Empty command nothing to do return corrected_commands get_corrected_commands command selected_command select_command corrected_commands if selected_command selected_command run command else sys exit 1
turn a connection info object into a dict or return it if it was a dict already . supports both the traditional libpq format and the new url format,def get_connection_info info if isinstance info dict return info copy elif info startswith postgres or info startswith postgresql return parse_connection_string_url info else return parse_connection_string_libpq info
"look ahead for a non - space token , using the given lexer mode .",def LookAhead self lex_mode pos self line_pos while True if pos len self line t ast token Id Unknown_Tok const NO_INTEGER return t tok_type end_pos self match_func lex_mode self line pos tok_val self line pos end_pos if tok_type Id WS_Space break pos end_pos return ast token tok_type tok_val const NO_INTEGER
use cases : id . op_rparen - > id . right_subshell -- disambiguate id . op_rparen - > id . eof_rparen,def PushHint self old_id new_id self translation_stack append old_id new_id
initialize a project dir but the dir already exists,def test_dirExists self prj_dir os path join self tmpdir testprj os mkdir prj_dir prj osc core Project init_project http localhost prj_dir testprj getPackageList False self assertTrue isinstance prj osc core Project storedir os path join prj_dir osc core store self _check_list os path join storedir _project testprj n self _check_list os path join storedir _apiurl http localhost n self _check_list os path join storedir _packages project name testprj
"make sure a parameter can be made into an int , and enforce limits if required",def CheckParamInt self section param min_value 1 max_value None is_multiple_of 1 try self parameters section param int self parameters section param except ValueError self parameter_errors section param Must be a valid integer return if min_value is not None and self parameters section param min_value self parameter_errors section param Must be greater than or equal to d min_value return if max_value is not None and self parameters section param max_value self parameter_errors section param Must be less than or equal to d max_value return if is_multiple_of 1 and self parameters section param is_multiple_of 0 self parameter_errors section param Must be a multiple of d is_multiple_of return return
update information for this list . returns a new list object .,def update_list self query_params None list_json self fetch_json uri_path self base_uri http_method PUT query_params query_params or return self create_list list_json
"base is the as we will be stacking on top of , opts are options which we may use .",def __init__ self base opts self base base self opts opts
return a single ( most recently set attribute ),def resolve self uri attribute follow_inheritence True for x in self resolve_list uri attribute follow_inheritence return x return NoneObject No attribute s found on s attribute uri
fit class - dependent multivariate gaussians on the training set .,def fit self X Y X_boxcox self _fit_boxcox X pos_idx np where Y 1 0 mu_pos np mean X_boxcox pos_idx axis 0 cov_pos np cov X_boxcox pos_idx rowvar 0 neg_idx np where Y 0 0 mu_neg np mean X_boxcox neg_idx axis 0 cov_neg np cov X_boxcox neg_idx rowvar 0 rv_pos multivariate_normal mean mu_pos cov cov_pos allow_singular True rv_neg multivariate_normal mean mu_neg cov cov_neg allow_singular True self rv_pos rv_pos self rv_neg rv_neg
encode this event into a linux input event structure .,def encode self tint long self time tfrac long self time tint 1000000 return struct pack Format Event tsec tfrac self eventType self eventCode self eventValue
checks that x is smaller than y elementwise .,def assert_array_less x y err_msg verbose True assert_array_compare operator __lt__ x y err_msg err_msg verbose verbose header Arrays are not less ordered
"returns an interpolator between the two numbers * a * and * b * ; the interpolator is similar to number , except it will round the resulting value to the nearest integer .",def interpolate_round a b b b a def _interpolate t return int py_round a b t return _interpolate
ensure bug # 32 does not regress .,def test_max_complexity_is_always_an_int self class _options object max_complexity None options _options options max_complexity 16 self assertEqual 0 mccabe McCabeChecker max_complexity mccabe McCabeChecker parse_options options self assertEqual 16 mccabe McCabeChecker max_complexity
sax parse xml text . @param file : parse a python i{file - like } object . @type file : i{file - like } object . @param string : parse string xml . @type string : str,def parse self file None string None timer metrics Timer timer start sax handler self saxparser if file is not None sax parse file timer stop metrics log debug sax s duration s file timer return handler nodes 0 if string is not None source InputSource None source setByteStream StringIO string sax parse source timer stop metrics log debug s nsax duration s string timer return handler nodes 0
return the number of jobs by state .,def get_stats raise NotImplementedError
execute the wrapped func registered with key passing the input_data .,def __call__ self key input_data decision extra_args try wrapped_func self registry key except KeyError logger error Colud not find implementation for key r key return try serialized_result wrapped_func input_data extra_args except SuspendTask decision flush except TaskError as e logger exception Unhandled task error in task decision fail e except Restart as e decision restart e input_data except Exception as e logger exception Unhandled exception in task decision fail e else decision finish serialized_result
"pysal does n't really support empty shapes . like , the following errors out :",def test_is_empty self for df in self dframes self compare is_empty df
this will set the light color based on a hex value,def set_color self light_id hex_value brightness None light self get_light light_id xy get_xy_from_hex hex_value data xy xy x xy y if brightness is not None data bri brightness return self set_state light light_id data
"get , or create , a project from an address .",staticmethod def get_or_create_from_address address creator return Project get_or_create type None address address creator creator
compare the result of a custom objective with the symbolic result . : return :,def test_custom_objective self xdata np linspace 0 100 25 a_vec np random normal 15 0 scale 2 0 size xdata shape b_vec np random normal 100 scale 2 0 size xdata shape ydata a_vec xdata b_vec a Parameter a value 0 min 0 0 max 1000 b Parameter b value 0 min 0 0 max 1000 x Variable model a x b fit Fit model xdata ydata minimizer BFGS fit_result fit execute def f x a b return a x b def chi_squared a b return np sum ydata f xdata a b 2 fit_custom BFGS chi_squared a b fit_custom_result fit_custom execute self assertIsInstance fit_custom_result FitResults self assertAlmostEqual fit_custom_result value a fit_result value a 1 0 5 self assertAlmostEqual fit_custom_result value b fit_result value b 1 0 4
return an ellipticcurveprivatekey provider using the given numbers .,abc abstractmethod def load_elliptic_curve_private_numbers self numbers
call all handlers . any decayed references will be purged .,def _fire self args kwargs delenda for handler in self _handlers try maya utils executeDeferred partial handler args self metadata kwargs except DeadReferenceError delenda append handler self _handlers self _handlers difference set delenda
"args : direct : a series of direct horizontal irradiance with a datetime index diffuse : a series of diffuse horizontal irradiance with the same datetime index as for direct coords : ( lat , lon ) tuple of location coordinates tilt : angle of panel relative to the horizontal plane , 0 = flat azimuth : deviation of the tilt direction from the meridian , 0 = towards pole , going clockwise , 3.14 = towards equator tracking : 0 ( none , default ) , 1 ( tilt ) , or 2 ( tilt and azimuth ) . if 1 , azimuth is the orientation of the tilt axis , which can be horizontal ( tilt=0 ) or tilted . albedo : reflectance of the surrounding surface dni_only : only calculate and directly return a dni time series ( ignores tilt , azimuth , tracking and albedo arguments ) angles : solar angles , if default ( none ) , is computed here",def aperture_irradiance direct diffuse coords tilt 0 azimuth 0 tracking 0 albedo 0 06 dni_only False angles None config if coords 0 0 azimuth azimuth np pi if angles is None sunrise_set_times sun_rise_set_times direct index coords angles sun_angles direct index coords sunrise_set_times dni direct angles duration 60 np cos angles sun_zenith if dni_only return dni if tracking 0 incidence _incidence_fixed angles sun_alt tilt azimuth angles sun_azimuth panel_tilt tilt elif tracking 1 incidence _incidence_single_tracking angles sun_alt tilt azimuth angles sun_azimuth panel_tilt _tilt_single_tracking angles sun_alt tilt azimuth angles sun_azimuth elif tracking 2 incidence 0 panel_tilt angles sun_zenith azimuth angles sun_azimuth else raise ValueError Invalid setting for tracking format tracking if config and config transducer solar stationary False pitch config transducer solar pitch roll config transducer solar roll incidence incidence np sin pitch np sin roll pitch roll plane_direct dni np cos incidence fillna 0 plane_diffuse diffuse 1 np cos panel_tilt 2 albedo direct diffuse 1 np cos panel_tilt 2 fillna 0 else plane_direct dni np cos incidence fillna 0 plane_diffuse diffuse 1 np cos panel_tilt 2 albedo direct diffuse 1 np cos panel_tilt 2 fillna 0 return pd DataFrame direct plane_direct diffuse plane_diffuse
args : : param verbose : ( boolean ) print elapsed time without prompting,def __init__ self verbose False self verbose verbose
set the filter . @param filter : a filter to set . @type filter : l{tnsfilter },def setfilter self filter self filter filter
create and run an instance or instances,def schedule_run_instance self context request_spec admin_password injected_files requested_networks is_first_time filter_properties instance_uuids request_spec get instance_uuids for num instance_uuid in enumerate instance_uuids request_spec instance_properties launch_index num try host self _schedule context compute request_spec filter_properties updated_instance driver instance_update_db context instance_uuid host self compute_rpcapi run_instance context instance updated_instance host host requested_networks requested_networks injected_files injected_files admin_password admin_password is_first_time is_first_time request_spec request_spec filter_properties filter_properties except Exception as ex driver handle_schedule_error context ex instance_uuid request_spec
makes sure that the host exists .,def check_host fn def wrapped self req id service None args kwargs listed_hosts _list_hosts req service hosts h host_name for h in listed_hosts if id in hosts return fn self req id args kwargs else message _ Host s could not be found id raise webob exc HTTPNotFound explanation message return wrapped
create compute - manager(computenode and service record ) .,def _create_compute_service self ctxt context get_admin_context dic host dummy binary nova compute topic compute report_count 0 availability_zone dummyzone s_ref db service_create ctxt dic dic service_id s_ref id vcpus 16 memory_mb 32 local_gb 100 vcpus_used 16 memory_mb_used 32 local_gb_used 10 hypervisor_type qemu hypervisor_version 12003 cpu_info stats db compute_node_create ctxt dic return db service_get ctxt s_ref id
evidence is updated . : param join_tree : join tree .,def evidence_updated self join_tree Propagator propagate join_tree
raise an error when newsamples is not positive or none .,def test_segment_dat_with_negative_newsamples self with self assertRaises AssertionError segment_dat self dat self mrk_def 400 400 newsamples 1
add path to search paths for display setups,def add_search_path path global _search_path _search_path append path
return the dict of default format classes to test with .,def default_format_classes u return RptkAPI default_format_classes
: returns : old port if learned . ( this may be = port ) none otherwise,def port_add self dpid port mac old_port self mac_to_port dpid get mac None self mac_to_port dpid mac port if old_port is not None and old_port port LOG debug port_add 0x 016x 0x 04x s dpid port haddr_to_str mac return old_port
"plot option prices , deltas and vegas for a set of different initial values of the underlying .",def plot_option_stats s_list pv de ve plt figure figsize 9 7 sub1 plt subplot 311 plt plot s_list pv ro label Present Value plt plot s_list pv b plt grid True plt legend loc 0 plt setp sub1 get_xticklabels visible False sub2 plt subplot 312 plt plot s_list de go label Delta plt plot s_list de b plt grid True plt legend loc 0 plt setp sub2 get_xticklabels visible False sub3 plt subplot 313 plt plot s_list ve yo label Vega plt plot s_list ve b plt xlabel Strike plt grid True plt legend loc 0
return the parents process i d .,def getppid patch ct threading current_thread if isinstance ct _stash runtime ShThread pt ct parent else return 1 if hasattr pt job_id return pt job_id else return 0
create an ellipsoid which is surely encompassing the * full * shape,def toEllipsoid self return self toSphere toEllipsoid
process the given file - like object .,def process self fh replacer self _make_replacer self _macros pp cStringIO StringIO for line in fh match re match self _pat_inc line if match is not None incfile match group 1 included False for p in self paths incpath p os path sep incfile if os path isfile incpath with open incpath r as ifh processed self process ifh pp write processed read included True break if included False raise RuntimeError Unable to include file format incfile continue match re match self _pat_set line if match is not None self _macros match group 1 match group 2 continue line re sub self _pat_sub replacer line pp write line pp seek 0 os SEEK_SET return pp
plot multiple maps in a single figure with common colourbar .,def plotmultimap m nrowcol filename title None vmin None vmax None units cbar True mask None ctab parchment width 18 0 nside hp npix2nside len m 0 if ctab parchment cmap planck_parchment_cmap elif ctab grey cmap planck_grey_cmap else cmap cm binary xsize 2000 ysize xsize 2 0 theta np linspace np pi 0 ysize phi np linspace np pi np pi xsize longitude np radians np linspace 180 180 xsize latitude np radians np linspace 90 90 ysize PHI THETA np meshgrid phi theta grid_pix hp ang2pix nside THETA PHI from matplotlib projections geo import GeoAxes class ThetaFormatterShiftPi GeoAxes ThetaFormatter Shifts labelling by pi Shifts labelling from 180 180 to 0 360 def __call__ self x pos None if x 0 x 1 if x 0 x 2 np pi return GeoAxes ThetaFormatter __call__ self x pos nrow ncol nrowcol rat float nrow float ncol height 0 6 width rat fig plt figure figsize cm2inch width cm2inch height for i s in enumerate m if mask None s np ma masked_array s np logical_not mask grid_mask s mask grid_pix grid_map np ma MaskedArray s grid_pix grid_mask else grid_map s grid_pix ax plt subplot nrow ncol i 1 projection mollweide image plt pcolormesh longitude 1 latitude grid_map vmin vmin vmax vmax rasterized True cmap cmap if title None plt title title i fontsize small ax xaxis set_ticklabels ax yaxis set_ticklabels ax xaxis set_ticks ax yaxis set_ticks if cbar cax fig add_axes 0 35 0 08 0 3 0 04 0 5 rat cb fig colorbar image cax cax orientation horizontal ticks vmin vmax cb ax xaxis set_label_text units cb ax xaxis labelpad 8 cb solids set_edgecolor face plt subplots_adjust left 0 0 right 1 0 bottom 0 1 top 1 0 wspace 0 02 hspace 0 01 plt savefig filename bbox_inches tight pad_inches cm2inch 0 1
"configure plugin , this function should be called before plugin execute ( ) method is used .",def setup self args kwargs return True
outputs the results to html for viewing in the gui or reports . override for custom reporting / display functionality,def toHTML self statsoutput resultsoutput for key value in list self stats items statsoutput em s em s key value resultcounter 1 for result in self results resultsoutput hr h5 Result s h5 br resultcounter resultcounter 1 resultsoutput result toHTML return h3 s s h3 h4 Analysis Stats h4 s h4 Results h4 s s self pageid if self pageid is not None else self context statsoutput resultsoutput
set the wordpress api key for all transactions .,def setAPIKey self key None blog_url None if key is None and isfile apikey txt the_file l strip for l in open apikey txt readlines if l strip and not l strip startswith try self key the_file 0 self blog_url the_file 1 except IndexError raise APIKeyError Your apikey txt is invalid else self key key self blog_url blog_url
fills out the parameters dictionary with the optional arguments,def fill_out_dictionary params_input params copy deepcopy params_input if isinstance params Arrival_distributions list arr_dists params Arrival_distributions params Arrival_distributions Class 0 arr_dists if isinstance params Service_distributions list srv_dists params Service_distributions params Service_distributions Class 0 srv_dists if Transition_matrices in params if isinstance params Transition_matrices list trns_mat params Transition_matrices params Transition_matrices Class 0 trns_mat if Baulking_functions in params if isinstance params Baulking_functions list blk_fncs params Baulking_functions params Baulking_functions Class 0 blk_fncs if Batching_distributions in params if isinstance params Batching_distributions list btch_dists params Batching_distributions params Batching_distributions Class 0 btch_dists default_dict Name Simulation Transition_matrices Class str i 0 0 for i in range len params Arrival_distributions Number_of_nodes len params Number_of_servers Number_of_classes len params Arrival_distributions Queue_capacities Inf for _ in range len params Number_of_servers Priority_classes Class str i 0 for i in range len params Arrival_distributions Baulking_functions Class str i None for _ in range len params Number_of_servers for i in range len params Arrival_distributions Batching_distributions Class str i Deterministic 1 for _ in range len params Number_of_servers for i in range len params Arrival_distributions for a in default_dict params a params get a default_dict a return params
test do_delete with an i d of a neume,def testDoDeleteNeume self self deleter do_delete m afb0de04 7df2 4abd b0af 6b03e91b5fe8 self assertEqual None self mei getElementById m afb0de04 7df2 4abd b0af 6b03e91b5fe8
read graph matrix from file : param file_name : name of file with graph info : return : matrix - adjacency matrix : g_matrix[v1][v2]==v1_v2_cost,def read_graph_matrix file_name inp file file_name r n int inp readline matrix for i in range n matrix append map lambda x float x inp readline split return matrix
called when the name is valid .,def valid self self ok_button setEnabled True palette self param_name palette palette setColor self param_name backgroundRole self validColor self param_name setToolTip self param_name setPalette palette
checks whether a user is a mod / admin according to lobby_admin table .,classmethod def get_usergroup cls username with db connection cursor db connection cursor db pymysql cursors DictCursor cursor execute SELECT la group FROM lobby_admin la JOIN login l ON l id la user_id WHERE LOWER l login s username lower result cursor fetchone group UserGroup result group if result else UserGroup NONE return group
set photon energy in unit joule,def set_energy self energy self _energy energy
"handles svsmode , which is used for sending services metadata ( vhosts , account logins ) , and other forced usermode changes .",def handle_svsmode self numeric command args target args 0 ts args 1 modes args 2 parsedmodes self irc parseModes target modes for modepair in parsedmodes if modepair 0 d account args 1 if account account self irc callHooks target CLIENT_SERVICES_LOGIN text account parsedmodes remove modepair elif modepair 0 x host args 1 self irc users target host host self irc callHooks numeric CHGHOST target target newhost host parsedmodes remove modepair if parsedmodes self irc applyModes target parsedmodes return target target modes parsedmodes
"return a dictionary of module_utils names mapped to sets of python file paths . : type compile_targets : list[testtarget ] : rtype : dict[str , set[str ] ]",def get_python_module_utils_imports compile_targets module_utils enumerate_module_utils virtual_utils set m for m in module_utils if any m startswith s v for v in VIRTUAL_PACKAGES module_utils virtual_utils imports_by_target_path for target in compile_targets imports_by_target_path target path extract_python_module_utils_imports target path module_utils def recurse_import import_name depth 0 seen None Recursively expand module_utils imports from module_utils files type import_name str type depth int type seen set str None rtype set str display info module_utils import s s depth import_name verbosity 4 if seen is None seen set import_name results set import_name if import_name in VIRTUAL_PACKAGES for sub_import in sorted virtual_utils if sub_import startswith s import_name if sub_import in seen continue seen add sub_import matches sorted recurse_import sub_import depth 1 seen for result in matches results add result import_path os path join lib s py import_name replace if import_path not in imports_by_target_path import_path os path join lib import_name replace __init__ py if import_path not in imports_by_target_path raise ApplicationError Cannot determine path for module_utils import s import_name for name in sorted imports_by_target_path import_path reverse True if name in virtual_utils continue if name in seen continue seen add name matches sorted recurse_import name depth 1 seen for result in matches results add result return results for module_util in module_utils module_util_imports recurse_import module_util module_util_imports remove module_util for target_path in imports_by_target_path if module_util in imports_by_target_path target_path for module_util_import in sorted module_util_imports if module_util_import not in imports_by_target_path target_path display info s inherits import s via s target_path module_util_import module_util verbosity 6 imports_by_target_path target_path add module_util_import imports dict module_util set for module_util in module_utils virtual_utils for target_path in imports_by_target_path for module_util in imports_by_target_path target_path imports module_util add target_path for virtual_util in virtual_utils parent_package join virtual_util split 1 imports virtual_util imports parent_package display info s reports imports from parent package s virtual_util parent_package verbosity 6 for module_util in sorted imports if not len imports module_util display warning No imports found which use the s module_util module_util return imports
- os_server : nics : net - name = network1,def test_nics_string_net_name self args os_server _network_args self module self cloud assert args 0 net id 5678
"determines whether the instance_state is "" pending "" , meaning there is an operation under way to bring it in service .",def _is_instance_state_pending self instance_state return instance_state and pending in instance_state description
create error response for any non - error message stanza .,def make_error_response self cond if self get_type error raise ValueError Errors may not be generated in response to errors m Message stanza_type error from_jid self get_to to_jid self get_from stanza_id self get_id error_cond cond if self xmlnode children n self xmlnode children while n m xmlnode children addPrevSibling n copyNode 1 n n next return m
returns the height of the image found at the path supplied by ` image ` relative to your project 's images directory .,ns declare def image_height image u n Returns the height of the image found at the path supplied by image n relative to your project s images directory n image_size_cache _get_cache u image_size_cache if not Image raise SassMissingDependency u PIL u image manipulation filepath String unquoted image value path None try height image_size_cache filepath 1 except KeyError height 0 IMAGES_ROOT _images_root if callable IMAGES_ROOT try _file _storage list IMAGES_ROOT filepath 0 except IndexError pass else path _storage open _file else _path os path join IMAGES_ROOT filepath strip os sep if os path exists _path path open _path u rb if path image Image open path size image size height size 1 image_size_cache filepath size return Number height u px
returns date when relationship was created as a localtime time.struct_time,property def since self return time localtime self _friend_dict friend_since
chops lines ending with ' 1csa 14 ' and the like .,def _chop_end_codes line return re sub s s s s w 4 s d Z line
"pf._make_nocut_only(nc , s1 ) - > string .",def _make_nocut_only self nc s1 ls title if not nc return s1 nc sort st stringsite s1 or n Enzymes which do not cut the sequence n n Join join for key in nc st Join st str ljust str key self NameWidth if len st self linesize stringsite Join stringsite st n st stringsite Join stringsite st n return stringsite
test that the context manager activates extensions .,def testContextManager1 class Test1ExtensionNode mdp ExtensionNode extension_name __test1 def _testtest self pass class Test2ExtensionNode mdp ExtensionNode extension_name __test2 def _testtest self pass assert mdp get_active_extensions with mdp extension __test1 assert mdp get_active_extensions __test1 assert mdp get_active_extensions with mdp extension __test1 __test2 active mdp get_active_extensions assert __test1 in active assert __test2 in active assert mdp get_active_extensions mdp activate_extension __test1 with mdp extension __test1 __test2 active mdp get_active_extensions assert __test1 in active assert __test2 in active assert mdp get_active_extensions __test1
return euler angles corresponding to quaternion ` q `,def quat2euler q import nibabel quaternions as nq return mat2euler nq quat2mat q
generate a simple plot of the test and traning learning curve .,def plot_learning_curve estimator title X y ylim None cv None n_jobs 1 train_sizes np linspace 0 1 1 0 5 plt figure plt title title if ylim is not None plt ylim ylim plt xlabel Training examples plt ylabel Score train_sizes train_scores test_scores learning_curve estimator X y cv cv n_jobs n_jobs train_sizes train_sizes train_scores_mean np mean train_scores axis 1 train_scores_std np std train_scores axis 1 test_scores_mean np mean test_scores axis 1 test_scores_std np std test_scores axis 1 plt grid plt fill_between train_sizes train_scores_mean train_scores_std train_scores_mean train_scores_std alpha 0 1 color r plt fill_between train_sizes test_scores_mean test_scores_std test_scores_mean test_scores_std alpha 0 1 color g plt plot train_sizes train_scores_mean o color r label Training score plt plot train_sizes test_scores_mean o color g label Cross validation score plt legend loc best return plt
calculate angle in 2-d between points and x axis,def _angle_to_point point centre delta point centre res np arctan delta 1 delta 0 if delta 0 0 res np pi return res
det is the original detector not the mass spec fooling detector,def get_baseline_data self iso det kw self debug get baseline data format iso det return self _get_data baseline iso det
instruct cinder to manage a storage object .,wsgi response 202 def create self req body context req environ cinder context authorize_manage context self assert_valid_body body volume volume body volume self validate_name_and_description volume required_keys set ref host missing_keys list required_keys set volume keys if missing_keys msg _ The following elements are required s join missing_keys raise exc HTTPBadRequest explanation msg LOG debug Manage volume request body s body kwargs req_volume_type volume get volume_type None if req_volume_type kwargs volume_type volume_types get_by_name_or_id context req_volume_type else kwargs volume_type kwargs name volume get name None kwargs description volume get description None kwargs metadata volume get metadata None kwargs availability_zone volume get availability_zone None kwargs bootable utils get_bool_param bootable volume utils check_metadata_properties kwargs metadata new_volume self volume_api manage_existing context volume host volume ref kwargs utils add_visible_admin_metadata new_volume return self _view_builder detail req new_volume
returns an error if prerequisites are n't met .,def check_for_setup_error self self common check_for_setup_error if len self gateway_iscsi_ip_addresses 0 msg _ No iSCSI IPs configured on SAN gateway raise exception ViolinInvalidBackendConfig reason msg
restore an existing backup to a volume .,wsgi response 202 def restore self req id body LOG debug Restoring backup backup_id s body s backup_id id body body self assert_valid_body body restore context req environ cinder context restore body restore volume_id restore get volume_id None name restore get name None LOG info _LI Restoring backup backup_id s to volume volume_id s backup_id id volume_id volume_id context context try new_restore self backup_api restore context backup_id id volume_id volume_id name name except exception InvalidInput as error raise exc HTTPBadRequest explanation error msg except exception InvalidVolume as error raise exc HTTPBadRequest explanation error msg except exception InvalidBackup as error raise exc HTTPBadRequest explanation error msg except exception VolumeSizeExceedsAvailableQuota as error raise exc HTTPRequestEntityTooLarge explanation error msg headers Retry After 0 except exception VolumeLimitExceeded as error raise exc HTTPRequestEntityTooLarge explanation error msg headers Retry After 0 retval self _view_builder restore_summary req dict new_restore return retval
updates the class list and wipes the cache .,def update self class_list self cache None self class_list class_list
return : math:`$\chi^2 $ ` ( chi - squared ) of two vectors,def chiSquared vector1 vector2 Return math chi 2 chi squared of two vectors return np sum np power vector1 vector2 2
accept connections on the listening port .,def _accept self print Listening for connections while True try conn addr self _sock accept print s Connected to s self name str addr name Client str addr accept_thread threading Thread target self _handle_client args conn name accept_thread name name accept_thread daemon True print s Starting thread for client s self name accept_thread name accept_thread start except timeout continue except pass
returns true if the underlying weighted majority graph contains a comparision between every pair of candidate and returns false otherwise .,def isFullPreferenceOrder self candList for cand1 in candList if cand1 not in self wmgMap keys return False for cand2 in candList if cand1 cand2 continue if cand2 not in self wmgMap cand1 keys return False return True
required method that the nose - plugin - testing system calls to generate the list of test cases to be run inside the plugin - context . it returns a list with a single item in it that all the subclasses use .,def makeSuite self class TC unittest TestCase def runTest self import logging lg_list root infra run infra data test run test data for lg_name in lg_list lg logging getLogger lg_name lg info MATCH FMAT START s MATCH END lg_name return TC
: param dataset : todo : return :,def generate self dataset _tmp_pubtator_send temp_pubtator_file txt
allows command specialisation to include calls to the given functions .,def custom_cmd command_to_override functions help_doc class ExtendedCommand command_to_override description help_doc or command_to_override description def run self command_to_override run self dest getattr self build_lib None if dest is None print Running in place dest lib for func in functions func self dest return ExtendedCommand
convert measurement to float using energy consumption .,def __float__ self return self energy_consumption
generate a tuple of an attribute and a strategy that yields floats for that attribute .,st composite def float_attrs draw defaults None default NOTHING if defaults is True or defaults is None and draw st booleans default draw st floats return attr ib default default st floats
return the info for all land points,def find_all basin_id source_area land_mask lons lats res lat lon np meshgrid lats lons y x np nonzero land_mask basin basin_id y x max_area source_area y x num_basins len y x_outlet np zeros num_basins y_outlet np zeros num_basins min_x np zeros num_basins max_x np zeros num_basins min_y np zeros num_basins max_y np zeros num_basins for i bi in enumerate basin inds np nonzero basin_id bi x_basin lon inds y_basin lat inds x_outlet i lon y x y_outlet i lat y x min_x i min x_basin max_x i max x_basin res min_y i min y_basin max_y i max y_basin res return basin x_outlet y_outlet max_area min_x min_y max_x max_y
return a list with a string for each true bit in the integer .,def __call__ self val if not val return None bits for n in self _names if val 1 bits append n val 1 if not val break return bits 0 if len bits 1 else bits
run migrations in ' online ' mode .,def run_migrations_online engine engine_from_config config get_section config config_ini_section prefix sqlalchemy poolclass pool NullPool connection engine connect context configure connection connection target_metadata target_metadata extra_config try with context begin_transaction context run_migrations finally connection close
returns true if datetime is naive .,def datetime_is_naive dateTime return dateTime tzinfo is None or dateTime tzinfo utcoffset dateTime is None
run ' compute ' by generating the arguments with ' function ' then compare the array ' key ' in nc_output .,def run_compare_nc self function key refdir None nc_ref None out compute function self tmpdir if nc_ref is not None pass else if refdir is None refdir self refdir nc_ref out nc_output replace self tmpdir refdir self check_reference_exists nc_ref self AssertClose out nc_output nc_ref key
append a sequence value to a prefix if non - zero,def _maybe_append_seq n prefix if not n return prefix return format prefix n
read wepp yld file with some local mods to include a year,def read_yld filename data open filename read xref for cropcode label in YLD_CROPTYPE findall data xref cropcode label rows for cropcode doy ofe yld year in YLD_DATA findall data date datetime date int year 1 1 datetime timedelta days int doy 1 rows append dict valid date year int year yield_kgm2 float yld crop xref cropcode ofe int ofe return pd DataFrame rows
"decode the given string with the given encoding , only attempts to decode if the given txt is not already unicode @param txt : string @param enc : encoding ' utf-8 ' @return : unicode",def DecodeString txt enc if IsUnicode txt txt txt decode enc return txt
mark changes made up to the last call to `` before_commit `` as committed .,def after_commit self with self _lock if self _state CellCommitState COMMITTING self _state CellCommitState CLEAN
"gets a file , returns a list of [ type , data ] chunks",def read f assert f read 8 _MAGIC chunks while True l struct unpack I f read 4 t f read 4 d f read l assert _crc32 t d struct unpack I f read 4 0 chunks t d if t IEND return chunks raise BaseException Invalid image
create a new task object based on the current context .,classmethod def post cls function args None kwargs None result_type forget priority 10 delay 0 if args is None args if kwargs is None kwargs task_name s s function __module__ function __name__ context dict project_id None app_config_id None user_id None notifications_disabled False if getattr c project None context project_id c project _id context notifications_disabled c project notifications_disabled if getattr c app None context app_config_id c app config _id if getattr c user None context user_id c user _id obj cls state ready priority priority result_type result_type task_name task_name args args kwargs kwargs process None result None context context time_queue datetime utcnow timedelta seconds delay session obj flush obj return obj
usage : host_status { --filename = filename | --hosts = hosts } cluster,app command app command_option FILENAME_OPTION app command_option HOSTS_OPTION requires exactly cluster def host_status cluster options app get_options checkable_hosts parse_hostnames options filename options hosts statuses HostMaintenance cluster CLUSTERS cluster verbosity options verbosity bypass_leader_redirect options bypass_leader_redirect check_status checkable_hosts for pair in statuses log info s is in state s pair
"process the specified node and convert the xml document into a i{suds } l{object}. @param content : the current content being unmarshalled . @type content : l{content } @return : a i{append - result } tuple as : ( l{object } , i{value } ) @rtype : i{append - result } @note : this is not the proper entry point . @see : l{process ( ) }",def append self content self start content self append_attributes content self append_children content self append_text content self end content return self postprocess content
add builders and construction variables for ar to an environment .,def generate env SCons Tool createStaticLibBuilder env env AR ar env ARFLAGS SCons Util CLVar rc env ARCOM AR ARFLAGS TARGET SOURCES env LIBPREFIX lib env LIBSUFFIX a if env Detect ranlib env RANLIB ranlib env RANLIBFLAGS SCons Util CLVar env RANLIBCOM RANLIB RANLIBFLAGS TARGET
"given a position and radius , get the data needed to plot .",def plot_sphere_data position radius u np linspace 0 2 np pi 100 v np linspace 0 np pi 100 x radius np outer np cos u np sin v position 0 y radius np outer np sin u np sin v position 1 z radius np outer np ones np size u np cos v position 2 return x y z
produce a genanki . note with the specified guid .,def to_genanki_note self deck_index None if deck_index is None deck_index random randrange 1 30 1 31 if self deckname is not None note_id simple_hash self deckname deck_index else note_id random randrange 1 30 1 31 return genanki Note model Card MODEL fields self fields guid note_id
test running mantel test on two distmats that need ids mapped .,def test_run_mantel_test_sample_id_map self exp A sample comment nDM tDM tNumber of entries tMantel r statistic p value Number of permutations Tail type foo txt tbar txt t t t t tless n obs run_mantel_test mantel self fp1 self fp2 self dm3 self dm4 self num_perms less self comment 0 5 sample_id_map self sample_id_map self assertEqual self remove_nums obs exp
returns all base information about an artifact,def artifact_get_req user_id artifact_id artifact_id int artifact_id artifact Artifact artifact_id access_error check_access artifact study id user_id if access_error return access_error can_submit_ebi artifact can_be_submitted_to_ebi ebi_run_accessions artifact ebi_run_accessions if can_submit_ebi else None can_submit_vamps artifact can_be_submitted_to_vamps is_submitted_vamps artifact is_submitted_to_vamps if can_submit_vamps else False return id artifact_id timestamp artifact timestamp processing_parameters artifact processing_parameters visibility artifact visibility type artifact artifact_type data_type artifact data_type filepaths artifact filepaths parents a id for a in artifact parents study artifact study id if artifact study else None can_submit_ebi can_submit_ebi ebi_run_accessions ebi_run_accessions can_submit_vamps can_submit_vamps is_submitted_vamps is_submitted_vamps
clear help text previously set with ` showhelp ` .,def clearHelp self self __timer stop self showHelp
return a list of recently accessed schemes .,def recent_schemes app_dir data_dir recent_filename os path join app_dir recent pck recent if os path isdir app_dir and os path isfile recent_filename with open recent_filename rb as f recent pickle load f recent title path for title path in recent if os path exists path return recent
returns this projection in wkt format .,property def wkt self return self ExportToWkt
applies the filters to the list of todo items .,def _apply_filters self p_todos result p_todos for _filter in sorted self _filters key lambda f f order result _filter filter result return result
"a ` dict ` , with region names as keys . values are ` list`s containing the start / end points ( in raw numbering , corresponding to the oriented_input ) . if raw start / end points could n't be identified , they are ` none ` . so if an entire region is n't present ( either due to deletion or query truncation ) , the value will be ` [ none , none ] ` .",property def raw_nt_positions self u n A dict with region names as keys Values are list s containing the start end points n in raw numbering corresponding to the oriented_input If raw start end points n couldn t be identified they are None So if an entire region isn t present either due n to deletion or query truncation the value will be None None n n Note that the end points are designed for slicing so the end point is actually 1 position n beyond the actual end point This allows ab oriented_input start end to work This also n means that the end point of FR1 should be identical to the start point of CDR1 n if self _raw_nt_positions is None pos for region in self region_names start self _raw_region_start_position_nt region end self _raw_region_end_position_nt region pos region start end self _raw_nt_positions pos return self _raw_nt_positions
learn bundles and calculate bundle activities .,def featurize self new_candidates self ziptie_0_cable_pool new_candidates cable_activities self filter update_activities candidate_activities self ziptie_0_cable_pool self ziptie create_new_bundles self ziptie grow_bundles ziptie_1_cable_pool self ziptie update_bundles cable_activities all_ziptie_cable_pool self ziptie_0_cable_pool ziptie_1_cable_pool self feature_pool self map_to_feature_pool all_ziptie_cable_pool return self feature_pool
square root kalman filter time update . given the following : - * x_hat_posterior * : posterior state estimate ( n ) - * p_sqrt_posterior * : posterior error covariance square root ( nxn ) - * f_i * : time update operator ( nxn ) - * q_sqrt_i * : time update noise covariance square root ( nxn ) - * z_i * : optional ) systematic time update input ( n ),def sqrt_kf_tu x_hat_posterior P_sqrt_posterior F_i Q_sqrt_i z_i None N _ F_i shape x_hat_prior NP matmul F_i x_hat_posterior if z_i is not None x_hat_prior z_i A_T NP block NP matmul F_i P_sqrt_posterior Q_sqrt_i R_T NP linalg qr A_T T mode r P_sqrt_prior R_T T N return x_hat_prior P_sqrt_prior
net : the main net operator should be added to,def recurrent_net net cell_net inputs initial_cell_inputs links timestep None scope None outputs_with_grads 0 recompute_blobs_on_backward None forward_only False u n net the main net operator should be added to n n cell_net cell_net which is executed in a recurrent fasion n n inputs sequences to be fed into the recurrent net Currently only one input n is supported It has to be in a format T x N x D1 Dk where T is lengths n of the sequence N is a batch size and D1 Dk are the rest of dimentions n n initial_cell_inputs inputs of the cell_net for the 0 timestamp n Format for each input is n cell_net_input_name external_blob_with_data n n links a dictionary from cell_net input names in moment t 1 and n output names of moment t Currently we assume that each output becomes n an input for the next timestep n n timestep name of the timestep blob to be used If not provided timestep n is used n n scope Internal blobs are going to be scoped in a format n scope_name blob_name n If not provided we generate a scope name automatically n n outputs_with_grads position indices of output blobs which will receive n error gradient from outside recurrent network during backpropagation n n recompute_blobs_on_backward specify a list of blobs that will be n recomputed for backward pass and thus need not to be n stored for each forward timestep n n forward_only if True only forward steps are executed n assert len inputs 1 u Only one input blob is supported so far input_blobs str i 0 for i in inputs initial_input_blobs str x 1 for x in initial_cell_inputs op_name net NextName u recurrent def s name scope_name op_name if scope is None else scope return u format str scope_name str name known_inputs str b for b in input_blobs initial_input_blobs known_inputs str x 0 for x in initial_cell_inputs if timestep is not None known_inputs append str timestep references core BlobReference b for b in cell_net Proto external_input if b not in known_inputs inner_outputs list cell_net Proto external_output inner_outputs_map o o u _grad for o in inner_outputs if not forward_only backward_ops backward_mapping core GradientRegistry GetBackwardPass cell_net Proto op inner_outputs_map backward_mapping str k v for k v in viewitems backward_mapping backward_cell_net core Net u RecurrentBackwardStep del backward_cell_net Proto op if recompute_blobs_on_backward is not None recompute_blobs_on_backward str b for b in recompute_blobs_on_backward for op in cell_net Proto op if not recompute_blobs_on_backward isdisjoint set op output backward_cell_net Proto op extend op assert set op output issubset recompute_blobs_on_backward backward_cell_net Proto op extend backward_ops backward_ssa backward_blob_versions core get_ssa backward_cell_net Proto undefined core get_undefined_blobs backward_ssa ssa blob_versions core get_ssa cell_net Proto scratches blob for blob ver in viewitems blob_versions if ver 0 and blob in undefined and blob not in cell_net Proto external_output backward_cell_net Proto external_input extend scratches backward_cell_net Proto type u simple else backward_cell_net None all_inputs i 1 for i in inputs x 1 for x in initial_cell_inputs references all_outputs cell_net Proto type u simple forward_links backward_links aliases recurrent_states for cell_input _ in initial_cell_inputs cell_input str cell_input state s cell_input u _states states_grad state u _grad cell_output links str cell_input forward_links append cell_input state 0 forward_links append cell_output state 1 aliases append state cell_output u _all 1 aliases append state cell_output u _last 1 all_outputs extend cell_output u _all cell_output u _last recurrent_states append state if backward_cell_net is not None backward_links append cell_output u _grad states_grad 1 backward_cell_net Proto external_input append str cell_output u _grad recurrent_input_grad cell_input u _grad if not backward_blob_versions get recurrent_input_grad 0 backward_links append backward_mapping cell_input states_grad 0 else backward_links append recurrent_input_grad states_grad 0 for input_t input_blob in inputs forward_links append str input_t str input_blob 0 if backward_cell_net is not None for input_t input_blob in inputs backward_links append backward_mapping str input_t str input_blob u _grad 0 backward_cell_net Proto external_input extend cell_net Proto external_input backward_cell_net Proto external_input extend cell_net Proto external_output def unpack_triple x if x a b c zip x return a b c return link_internal link_external link_offset unpack_triple forward_links alias_src alias_dst alias_offset unpack_triple aliases recurrent_inputs str x 1 for x in initial_cell_inputs if backward_cell_net is not None proto backward_cell_net Proto operators while len proto op 0 op proto op 1 proto op remove op operators append op for op in operators 1 proto op extend op for j output_blob in enumerate op output if output_blob in proto external_input if output_blob in op input continue output_blob core BlobReference output_blob accum_blob output_blob u _accum proto op 1 output j str accum_blob backward_cell_net Sum output_blob accum_blob output_blob def map_to_dual_list m return str x for x in list m keys str x for x in list m values backward_args if backward_cell_net is not None backward_mapping_keys set viewkeys backward_mapping backward_link_internal backward_link_external backward_link_offset unpack_triple backward_links params x for x in references if x in backward_mapping_keys param_grads str backward_mapping x for x in references if x in backward_mapping_keys if recompute_blobs_on_backward is None recompute_blobs_on_backward set backward_args u param all_inputs index p for p in params u backward_link_internal str l for l in backward_link_internal u backward_link_external str l for l in backward_link_external u backward_link_offset backward_link_offset u outputs_with_grads outputs_with_grads u recompute_blobs_on_backward str b for b in recompute_blobs_on_backward u param_grads param_grads if len backward_cell_net Proto op 0 backward_args u backward_step_net backward_cell_net Proto results net RecurrentNetwork all_inputs all_outputs s u step_workspaces alias_src alias_src alias_dst str a for a in alias_dst alias_offset alias_offset recurrent_states recurrent_states initial_recurrent_state_ids all_inputs index i for i in recurrent_inputs link_internal str l for l in link_internal link_external str l for l in link_external link_offset link_offset enable_rnn_executor 1 step_net cell_net Proto timestep u timestep if timestep is None else str timestep backward_args cell_net Proto type u simple return results 1
testing the creation of bedgraph files without window binning,def test_05_bedGraph_noBinning self write_format bedGraph bed_str data_read convert mode write_format window False bedSingle_1_food_fat bed_str 2 food_fat bedSingle_1_food_sc bed_str 1 food_sc bedSingle_1_water bed_str 3 water bedSingle_16_food_sc bed_str 16 food_sc bedSingle_1_food_fat save_track track_line True bedSingle_1_food_sc save_track track_line True bedSingle_1_water save_track track_line True bedSingle_16_food_sc save_track track_line True
send a done message which fails update due to bad property,def test_bad_object self msg shine_msg_pack evtype comp info self info status done def buggy_update self other self wrong_property other wrong_property self tgt update types MethodType buggy_update self tgt self act fakecmd echo s msg self act launch self fs _run_actions self fs _check_errors OFFLINE self fs components self assertEqual len self fs proxy_errors 1 self assertEqual str list self fs proxy_errors messages 0 Cannot read message check Shine and ClusterShell version MGT object has no attribute wrong_property self assertEqual self tgt state RUNTIME_ERROR self assertEqual self act status ACT_OK
translate an exprid @expr : exprid to translate,def from_ExprId self expr raise NotImplementedError Abstract method
"since there is no theoretical error bound for intersection , we 'd use 3-sigma rule instead .",def test_intersect self hll Cardunion hll_1 Cardunion for i in range 10000 hll add str i for i in range 5000 15000 hll_1 add str i estimate error _ Cardunion intersect hll_1 hll print estimate error self assertTrue 5000 3 error estimate 5000 3 error
get the correctly distributed parallel chunks .,def range self start stop None step 1 self _assert_active if stop is None start stop 0 start full_list range start stop step per_worker len full_list self _num_threads rem len full_list self _num_threads schedule per_worker 1 if thread_idx rem else per_worker for thread_idx in range self _num_threads start_idx functools reduce lambda x y x y schedule self thread_num 0 end_idx start_idx schedule self _thread_num return full_list start_idx end_idx
check that the given ip falls within the range managed by this manager,def ensure_type self resource number True thing None try if isinstance resource int ip self _int_to_ipy resource else ip IPy IP resource except ValueError raise ResourceTypeException s is not a valid ip resource if self baseip and ip not in self ipy raise ResourceTypeException u The ip s is out of range for this IP manager Should be in s s str ip self baseip self netmask return self _ipy_to_int ip number
returns the long id corresponding to the first city found that matches the provided city name . the lookup is case insensitive .,deprecated will_be removed on_version 3 0 0 def id_for self city_name line self _lookup_line_by_city_name city_name return int line split 1 if line is not None else None
compute the pull for a single trial,def _trial self seed self _log_header2 gammalib NORMAL Trial d seed self seed integer 1 nbins self enumbins integer onsrc self onsrc string edisp self edisp boolean statistic self statistic string emin None emax None binsz 0 0 npix 0 proj TAN coordsys CEL if gammalib toupper onsrc NONE onrad self onrad real emin self emin real emax self emax real edisp True else onrad 0 0 onsrc None if nbins 0 emin self emin real emax self emax real binsz self binsz real npix self npix integer proj self proj string coordsys self coordsys string obs obsutils sim self obs emin emin emax emax nbins nbins onsrc onsrc onrad onrad addbounds True seed seed binsz binsz npix npix proj proj coord coordsys edisp edisp nthreads 1 log False debug self _logDebug chatter self chatter integer nevents 0 0 for run in obs nevents run nobserved self _log_header3 gammalib NORMAL Simulation for run in self obs self _log_value gammalib NORMAL Input observation s run id self _obs_string run for run in obs self _log_value gammalib NORMAL Output observation s run id self _obs_string run self _log_value gammalib NORMAL Number of simulated events nevents if self profile boolean models self obs models for model in models like ctools cterror obs like srcname model name like edisp edisp like statistic statistic like debug self _logDebug like chatter self chatter integer like run else like ctools ctlike obs like edisp edisp like statistic statistic like debug self _logDebug like chatter self chatter integer like run logL like opt value npred like obs npred models like obs models self _log_header3 gammalib NORMAL Pulls colnames LogL Sim_Events Npred_Events values LogL logL Sim_Events nevents Npred_Events npred for i in range models size model models i for k in range model size par model k if par is_free name model name _ par name colnames append name colnames append Pull_ name colnames append e_ name fitted_value par value real_value self obs models i k value error par error if error 0 0 pull fitted_value real_value error else pull 99 0 values name fitted_value values Pull_ name pull values e_ name error value 4f e e pull fitted_value error self _log_value gammalib NORMAL name value result colnames colnames values values return result
probability estimates for each label .,def predict_proba self X self _check_fitted probas Parallel n_jobs self n_jobs delayed _predict_proba_label estimator estimator X X for estimator in self estimators_ probas np vstack x 1 for x in probas T return probas
"connect to a tripp lite pdu ( power distribution unit ) and power down one of the loads . host one of the pdus , one of ' pdunetwork.solar.pvt ' , ' pduanalog.solar.pvt ' , or ' pdudigital.solar.pvt ' user username , currently set to ' admin ' for all three pdus passwd password loadn integer load number to power down returns true if successful , false otherwise",def pwr_off host user passwd loadn term_str login Password response user n passwd n 1 n 1 n 2 n 2 n str loadn n 2 n X n X n X n X n tn telnetlib Telnet host time sleep 1 for i in range len term_str out tn read_until term_str i 1 if out len term_str i term_str i print Telnet connection to host timed out tn close return False break tn write response i tn close return True
args : project : a project object compiler : a compiler object time_info_accumulator : the string ' fail ' or a list of build . timeinfo records,def store self project compiler time_info_accumulator self _table append project name compiler name time_info_accumulator
"parsers are modules with a parse function dropped in the ' parsers ' folder . when attempting to parse a file , qcri will load and try all parsers , returning a list of the ones that worked . todo : load them from config",def is_parser parser return hasattr parser parse and hasattr parser ATTACH_LIST
"c_ast - > [ str ] - > ( { str : [ c_ast ] } , [ c_ast ] )",def process_ast ast wanted def get_decls_and_typedefs decls typedefs _ node nodety type node if nodety not in c_ast Decl c_ast Typedef node_fail UnwantedNodeError unwanted node n s node if nodety is c_ast Typedef typedefs append node elif node coord file in all_wanted and node try decls node coord file append node except KeyError decls node coord file node return decls_and_types decls typedefs all_wanted wanted union utils cpp_decomp_tag return reduce get_decls_and_typedefs ast children
samples the mean of a normal distribution,def sample_normal_mean s1 ndata prec m0 0 t0 0 t t0 prec ndata m t0 m0 prec s1 t return rn normal m 1 np sqrt t
returns the cookie name to use for storing a cookie basket .,def get_cookie_key self request key super BasketMiddleware self get_cookie_key request key base _ site_id format base key site_id request site id return key
record a payment event for creation once the order is placed .,def add_payment_event self event u if self _payment_events is None self _payment_events self _payment_events append event
fetch course catalog for the given catalog i d .,def fetch_course_catalog site catalog_id api_resource catalogs cache_key get_cache_key site_domain site domain resource api_resource catalog_id catalog_id cached_response TieredCache get_cached_response cache_key if cached_response is_hit return cached_response value api site siteconfiguration discovery_api_client endpoint getattr api api_resource try response endpoint catalog_id get except HttpNotFoundError logger exception Catalog s not found catalog_id raise TieredCache set_all_tiers cache_key response settings COURSES_API_CACHE_TIMEOUT return response
checks if the order line is refunded returns : boolean : true if order line is refunded else false,staticmethod def is_order_line_refunded order_line u n checks if the order line is refunded n Returns n boolean True if order line is refunded else false n return RefundLine objects filter order_line order_line status REFUND_LINE COMPLETE exists
remove task with identifier ` task_id ` from pool .,def remove_task self task_id raise NotImplementedError
fix up the html in various ways,def _fix_content book chapter chapter_n content div id chapter d s div chapter_n chapter chapter content content expand_macro chapter chapter tree html document_fromstring content base s book url_title here base chapter chapter url_title from os path import join normpath from urlparse import urlsplit urlunsplit def flatten url prefix scheme addr path query frag urlsplit url if scheme return url path normpath join here path if not path startswith base prefix logWarning got a wierd link r in s resolves to r wanted start of s url here path base prefix return url path path len base logWarning turning r into r url path return urlunsplit path query frag for e in tree iter src e get src if src is not None e set src flatten src static href e get href if href is not None e set href flatten href return etree tostring tree encoding UTF 8 method html
": param rating : the optional initial rating : type rating : int : param player : if not none , this rating widget will automatically update to reflect the rating of the current song : type player : xl.player.exaileplayer",def __init__ self rating 0 player None Gtk EventBox __init__ self self _player player self set_visible_window False self set_above_child True self add_events Gdk EventMask POINTER_MOTION_MASK self set_can_focus True self _image Gtk Image self add self _image self _rating 1 self props rating rating if self _player is not None event add_ui_callback self on_rating_update playback_track_start self _player event add_ui_callback self on_rating_update playback_track_end self _player event add_ui_callback self on_rating_update rating_changed self on_rating_update rating_changed None None
called when a category has something happen to it,def on_category_change self view action category categories get_group_categories if action gt_widgets category_change added categories setdefault category True elif action gt_widgets category_change deleted del categories category elif action gt_widgets category_change collapsed categories category 0 False elif action gt_widgets category_change expanded categories category 0 True elif action gt_widgets category_change updated v categories setdefault category True v 1 view get_model get_category_groups category set_group_categories categories
get the entire player status needed for the front end .,def _get_status mpd player_status mpd status current_song mpd currentsong status for key in title artist album date file time id status key current_song get key 0 if key time else for key in state volume elapsed consume random repeat single status key player_status get key 0 if key elapsed else status pqe_id getattr PlayQueueEntry query filter PlayQueueEntry mpd_id status id first id None status response_time time time return status
build templates for docs models and python api,def build self docs_version u self docs_path frappe get_app_path self target_app u www u docs self path os path join self docs_path docs_version self app_context u app u docs_version docs_version self app_title self hooks get u app_title 0 self app_path frappe get_app_path self app print u Deleting current shutil rmtree self path ignore_errors True os makedirs self path self make_home_pages for basepath folders files in os walk self app_path if u doctype not in basepath and u doctype in folders module os path basename basepath module_folder os path join self models_base_path module self make_folder module_folder template u templates autodoc module_home html context u name module self update_index_txt module_folder if u doctype in basepath parts basepath split u module doctype parts 3 parts 1 if doctype u boilerplate self write_model_file basepath module doctype if self is_py_module basepath folders files self write_modules basepath folders files self copy_user_assets self add_sidebars self add_breadcrumbs_for_user_pages
"search for given text in _ _ global_search : param text : phrase to be searched : param start : start results at , default 0 : param limit : number of results to return , default 20 : return : array of result objects",frappe whitelist def search text start 0 limit 20 doctype u u n tSearch for given text in __global_search n t param text phrase to be searched n t param start start results at default 0 n t param limit number of results to return default 20 n t return Array of result objects n t text u text u if not doctype results frappe db sql u n t t tselect n t t t tdoctype name content n t t tfrom n t t t t__global_search n t t twhere n t t t tmatch content against s IN BOOLEAN MODE n t t tlimit start limit format start start limit limit text u as_dict True else results frappe db sql u n t t tselect n t t t tdoctype name content n t t tfrom n t t t t__global_search n t t twhere n t t t tdoctype s AND n t t t tmatch content against s IN BOOLEAN MODE n t t tlimit start limit format start start limit limit doctype text as_dict True for r in results try if frappe get_meta r doctype image_field r image frappe db get_value r doctype r name frappe get_meta r doctype image_field except Exception frappe clear_messages return results
at startup we build a classinfo [ ] dictionary that holds all the information needed to construct the possible inferiors,def pull_classinfo db classinfo res db search base schema_base expression objectclass classSchema attrs ldapDisplayName systemOnly objectClassCategory possSuperiors systemPossSuperiors auxiliaryClass systemAuxiliaryClass subClassOf for r in res name str r ldapDisplayName 0 classinfo name if str r systemOnly TRUE classinfo name systemOnly True else classinfo name systemOnly False if r get objectClassCategory classinfo name objectClassCategory int r objectClassCategory 0 else classinfo name objectClassCategory 0 for a in possSuperiors systemPossSuperiors auxiliaryClass systemAuxiliaryClass subClassOf classinfo name a if r get a for i in r a classinfo name a append str i def subclasses_recurse subclasses oc list subclasses oc for c in list list extend subclasses_recurse subclasses c return list subclasses for oc in classinfo subclasses oc for oc in classinfo for c in classinfo oc subClassOf if not c oc subclasses c append oc for oc in classinfo classinfo oc SUBCLASSES uniq_list subclasses_recurse subclasses oc return classinfo
close the file and release the lock .,def Close self if hasattr self fd and self fd self fd close self fd None
retries calling a function up to the specified number of times .,def RetryByNumberOfTimes max_retries backoff exception_class fn args kwargs if backoff 0 raise exception_class Backoff must be a non negative integer last_exception None delay backoff for i in range max_retries try fn args kwargs break except errors OpExecError as e logging error Error after retry no s s i e last_exception e time sleep delay delay 2 else if last_exception raise exception_class Error after s retries Last exception s max_retries last_exception
returns the minumun and maximum magnitudes,def get_min_max_mag self return min self magnitudes max self magnitudes
wait for systemd style notification on the socket .,def onready notify_socket timeout sock socket socket socket AF_UNIX socket SOCK_DGRAM sock settimeout timeout sock bind _abstractify notify_socket try try msg sock recv 512 except socket timeout return 2 finally sock close if READY 1 in msg return 0 else return 1
frequency representation of derivative of gaussian .,def frequency self w s 1 0 m self m x s w gamma scipy special gamma const 1j m gamma m 0 5 0 5 function x m np exp x 2 2 return const function
implements unittest . testcase setupclass to fork our server .,staticmethod def setUpClass SynchronousKeystoreTest __get_scenario
verifies that the vdso includes no relocations .,def CheckRelocs vdso_path output subprocess check_output readelf r vdso_path decode if output strip There are no relocations in this file Fatal VDSO contains relocations s output
move a chrome device into a new organizational unit .,def move_chrome_device_org_unit self device_id org_unit_path logging info Moving device s to OU s device_id org_unit_path self get_chrome_device device_id try self _client chromeosdevices moveDevicesToOu customerId constants MY_CUSTOMER orgUnitPath org_unit_path body deviceIds device_id execute except errors HttpError as err logging error Directory API move Chrome device Org Unit failed with a s exception because s str type err err resp reason raise DirectoryRPCError err resp reason
check for a valid mach - o file .,def check_file self self as_assert self base Must stack on another address space self as_assert self base read 0 4 xcf xfa xed xfe Header signature invalid
determine if the proc is wow64 .,def is_wow64 proc return proc environ get PROCESSOR_ARCHITECTURE x86 and proc environ get PROCESSOR_ARCHITEW6432 AMD64
"mock a model static method , return a mock setup .",def MockModelStaticBase self model_name method_name args test_class_models self GetTestClassModule models model_class getattr test_class_models model_name if not s s model_name method_name in self _set_mock mock_model self mox CreateMock getattr model_class method_name self stubs Set model_class method_name mock_model self _set_mock s s model_name method_name mock_model model self mox CreateMockAnything return getattr model_class method_name args
runs the send_mail module as a command line script .,def main options ParseArgs SendMail options server options sender options recipients options subject options message options attachments options password options ignore_missing
"runs all tasks in the given queue , even those created by prior tasks .",def DrainTaskQueue self queue_name limit None keep_running True tasks_run 0 while keep_running tasks self GetTasks queue_name keep_running bool tasks for task in tasks self _RunDeferredTask queue_name task True tasks_run 1 if limit and tasks_run limit keep_running False break
calculates the complex relative permittivity of the material at a specific frequency .,def calculate_er self freq er self er if self poles 0 w 2 np pi freq er self se w e0 if debye in self type for pole in range self poles er self deltaer pole 1 1j w self tau pole elif lorentz in self type for pole in range self poles er self deltaer pole self tau pole 2 self tau pole 2 2j w self alpha pole w 2 elif drude in self type ersum 0 for pole in range self poles ersum self tau pole 2 w 2 1j w self alpha pole er ersum return er
common teardown method for this test suite .,def tearDown self AstakosUser objects all delete
test listing only flavors accesed by a specific project,def test_flavor_list_filter_project self response self myget flavors detail data SNF flavor access self project1 self assertSuccess response api_flavors json loads response content flavors self assertEqual len api_flavors 3 for api_flavor in api_flavors self assertTrue len api_flavor SNF flavor access 0 self assertTrue self project1 in api_flavor SNF flavor access for access in api_flavor SNF flavor access self assertTrue access in self projects
unset a value in the configuration .,def unset_value self key self _ensure_have_load_only if key not in self _config self load_only raise ConfigurationError No such key format key fname parser self _get_parser_to_modify if parser is not None section name _disassemble_key key modified_something False if parser has_section section modified_something parser remove_option section name if modified_something section_iter iter parser items section try val six next section_iter except StopIteration val None if val is None parser remove_section section self _mark_as_modified fname parser else raise ConfigurationError Fatal Internal error id 1 Please report as a bug del self _config self load_only key
update parameter stdev for fit . param_stdevs is a dictionary with with some number of parameter names .,def update_stdevs self param_stdevs for p in param_stdevs keys self _params p stdev param_stdevs p
remove an ip address from the given network interface .,def del_ipaddr self ifname ipaddr cmd ip addr del str ipaddr dev ifname return self cmd cmd
get a list of models matching the provided arguments . also adds pagination capabilities . returns empty array when no models match . todo-3 also filter by kind .,def list_follows_by_entity db_conn params query SELECT FROM follows WHERE entity_id entity_id s AND entity_kind entity_kind s ORDER BY created DESC TODO OFFSET LIMIT params entity_id convert_slug_to_uuid params entity_id entity_kind params entity_kind return list_rows db_conn query params
expect update post to change body for general post .,def test_update_post_body db_conn session create_topic_in_db db_conn create_post_in_db db_conn request cookies session_id session params body Update db_conn db_conn code response routes post update_post_route request topic_a_uuid post_a_uuid assert not response get errors assert code 200 assert Update in response post body
get astng for the given class,def astng_from_class self klass modname None if modname is None try modname klass __module__ except AttributeError raise ASTNGBuildingException Unable to get module for class s safe_repr klass modastng self astng_from_module_name modname return modastng getattr klass __name__ 0
collect mapping of given nfs on the global view(dov ) .,staticmethod def __collect_binding dov nfs mappings for nf_id in nfs mapping if nf_id not in dov log warning NF s is not found in the global topology DoV nf_id continue bisbis n id for n in dov infra_neighbors nf_id log log VERBOSE Detected mapped BiSBiS node bisbis if len bisbis 1 log warning Detected unexpected number of BiSBiS node s bisbis continue bisbis bisbis pop nf id nf_id ports for dyn_link in dov network nf_id bisbis itervalues port OrderedDict id dyn_link src id if dyn_link src l4 is not None try port management ast literal_eval dyn_link src l4 except SyntaxError log warning L4 address entry s is not valid Python expression Add the original string dyn_link src l4 port management dyn_link src l4 nf ports append port mapping nf nf bisbis bisbis split bb_mapping id bisbis 0 domain bisbis 1 if len bisbis 1 else None mapping bisbis bb_mapping mappings append mapping return mappings
read ascii file with parameter names,def readNames inf names for line in inf cols line split for n in cols names append n return names
convert one provenance item from its json string version to the native python dictionary format .,def deserialize self jsonRecord provenance json loads jsonRecord cls DateTimeAwareJSONDecoder return self file fromProvenance provenance
"draw a badge for a given registration , at position pos_x , pos_y ( top - left corner ) .",def _draw_badge self canvas registration template tpl_data pos_x pos_y u config self config badge_rect pos_x self height pos_y tpl_data height_cm cm tpl_data width_cm cm tpl_data height_cm cm if config dashed_border canvas saveState canvas setDash 1 5 canvas rect badge_rect canvas restoreState if template background_image with template background_image open as f self _draw_background canvas ImageReader self _remove_transparency f tpl_data badge_rect placeholders get_placeholders u designer fields for item in tpl_data items placeholder placeholders get item u type if placeholder if placeholder group u registrant text placeholder render registration else text placeholder render registration event elif item u text text item u text else continue self _draw_item canvas item tpl_data text pos_x pos_y
checks if a user has management rights on this vc system,def can_manage_vc self user u if user is_admin return True return self settings acls contains_user u managers user
build packet for connect command .,def connect_build self nyamuk keepalive clean_session retain 0 dup 0 version 3 will 0 will_topic None byte 0 client_id utf8encode nyamuk client_id username utf8encode nyamuk username if nyamuk username is not None else None password utf8encode nyamuk password if nyamuk password is not None else None payload_len 2 len client_id if nyamuk will is not None will 1 will_topic utf8encode nyamuk will topic payload_len payload_len 2 len will_topic 2 nyamuk will payloadlen if username is not None payload_len payload_len 2 len username if password None payload_len payload_len 2 len password self command NC CMD_CONNECT self remaining_length 12 payload_len rc self alloc if rc NC ERR_SUCCESS return rc self write_string getattr NC PROTOCOL_NAME_ 0 format version self write_byte getattr NC PROTOCOL_VERSION_ 0 format version byte clean_session 1 1 if will byte byte nyamuk will retain 1 5 nyamuk will qos 3 3 will 1 2 if nyamuk username is not None byte byte 1 7 if nyamuk password is not None byte byte 1 6 self write_byte byte self write_uint16 keepalive self write_string client_id if will self write_string will_topic self write_string nyamuk will payload if username is not None self write_string username if password is not None self write_string password nyamuk keep_alive keepalive return NC ERR_SUCCESS
"given a python object o , return the corresponding type hint .",def instance_to_type o t type o if o is None return type None elif t not in typehints DISALLOWED_PRIMITIVE_TYPES if sys version_info 0 2 and t types InstanceType return o __class__ if t BoundMethod return types MethodType return t elif t tuple return typehints Tuple instance_to_type item for item in o elif t list return typehints List typehints Union instance_to_type item for item in o elif t set return typehints Set typehints Union instance_to_type item for item in o elif t dict return typehints Dict typehints Union instance_to_type k for k v in o items typehints Union instance_to_type v for k v in o items else raise TypeInferenceError Unknown forbidden type s t
checks if soup_obj is really a soup object or just a string if it has a name it is a soup object,def _has_name soup_obj try name soup_obj name if name None return False return True except AttributeError return False
return summary of a vasp directory,def jaspsum request path format vasppath os path join DATAROOT path if not os path isdir vasppath content No data found for s in jaspsum format s vasppath format content_type text html else with jasp vasppath as calc if format xml content calc xml content_type text xml elif format json content calc json content_type application json elif format python content repr calc content_type application x python elif format html calc_content str calc content pre calc_content pre p a href file INCAR INCAR a p p a href file POSCAR POSCAR a p p a href file KPOINTS KPOINTS a p p a href file OUTCAR OUTCAR a p format locals content_type text html else content str calc content_type text plain return HttpResponse content content content_type content_type
"name : read_sfd_ebv purpose : read an e(b - v ) value from the schlegel , finkbeiner , & davis ( 1998 ) maps input : glon - galactic longitude ( deg ) , can be an array glat - galactic latitude ( deg ) , can be an array interp= ( true ) if true , interpolate using the nearest pixels noloop= ( false ) if true , do n't loop through the glons verbose= ( false ) if true , be verbose output : array of e(b - v ) from schlegel , finkbeiner , & davis ( 1998 ) history : 2013 - 11 - 23 - written - bovy ( ias )",def read_SFD_EBV glon glat interp True noloop False verbose False if isinstance glon int float numpy float32 numpy float64 glon numpy array glon if isinstance glat int float numpy float32 numpy float64 glat numpy array glat ndarrayFlags C_CONTIGUOUS WRITEABLE evalFunc _lib lambert_getval evalFunc argtypes ctypes c_char_p ctypes c_char_p ctypes c_long ndpointer dtype numpy float32 flags ndarrayFlags ndpointer dtype numpy float32 flags ndarrayFlags ctypes c_int ctypes c_int ctypes c_int evalFunc restype ctypes POINTER ctypes c_float f_cont glon flags F_CONTIGUOUS glat flags F_CONTIGUOUS glon numpy require glon dtype numpy float64 requirements C W glat numpy require glat dtype numpy float64 requirements C W res evalFunc ctypes c_char_p ebvFileN encode ascii ctypes c_char_p ebvFileS encode ascii ctypes c_long len glon glon astype numpy float32 order C copy False glat astype numpy float32 order C copy False ctypes c_int interp ctypes c_int noloop ctypes c_int verbose result numpy fromiter res dtype float count len glon if f_cont 0 glon numpy asfortranarray glon if f_cont 1 glat numpy asfortranarray glat return result
receives alerts from signals that this object has chosen to listen . these signals are declared in ' self.watchlist ' .,def watch_alerted self obj signal field_name value if signal forest_changed self prepare_lexicon if signal ui_font_changed f qt_prefs get_font CONSOLE_FONT self setStyleSheet stylesheet f family f pointSize
op : open / close / fsync,def addUniOp self op pid dirid fileid path self getFilepath dir dirid pid pid file_id fileid entry str pid path op lower n self workload entry
fetch & return the domain resource that the record belongs to,def fetch_domain self return self domain fetch
get an existing suite from a module .,def get_TestSuite_from_module mod config for methname in get_suite GetSuite try meth getattr mod methname return meth config except AttributeError continue raise module ObjectImportError Module r does not have a get_suite function module
anything added to this function is executed before launching the instances,def pre_process pass
return true if the given filename is binary . @raise environmenterror : if the file does not exist or can not be accessed . @attention : found @ http://bytes.com/topic/python/answers/21222-determine-file-type-binary-text on 6/08/2010 @author : trent mick < trentm@activestate.com > @author : jorge orpinel < jorge@orpinel.com >,def is_binary pathname try with open pathname r as f CHUNKSIZE 1024 while 1 chunk f read CHUNKSIZE if x00 in chunk return True if len chunk CHUNKSIZE break except return True return False
abstract method used for retrieving a document from the search engine 's document index . the parameter document_id may be used to uniquely identify a document ( e.g. an id ) within the engine 's index .,abc abstractmethod def get_document self document_id pass
tests the open and close functions .,def test_open_close self if not unittest source return bde_volume pybde volume if unittest password bde_volume set_password unittest password if unittest recovery_password bde_volume set_recovery_password unittest recovery_password bde_volume open unittest source bde_volume close bde_volume open unittest source bde_volume close file_object open unittest source rb bde_volume open_file_object file_object bde_volume close bde_volume open_file_object file_object bde_volume close bde_volume open_file_object file_object del file_object bde_volume close
initialise with box size list .,def __init__ self size if len size 2 and len size 3 raise ValueError Invalid dimensionality must be 2 or 3 raise SystemExit self dimension len size self box_size size self pos_min_image 0 5 x for x in size self neg_min_image 0 5 x for x in size
appends signed info element to signature .,def append_signed_info self signature queue signed_info etree SubElement signature ns_id SignedInfo dsns set_algorithm signed_info CanonicalizationMethod C14N set_algorithm signed_info SignatureMethod self keytype queue insert_references signed_info
collect params related to grid lines .,def _GetGridParams self chart x 0 y 0 if chart bottom grid_spacing assert chart bottom min is not None assert chart bottom max is not None total float chart bottom max chart bottom min x 100 chart bottom grid_spacing total if chart left grid_spacing assert chart left min is not None assert chart left max is not None total float chart left max chart left min y 100 chart left grid_spacing total if x or y return dict grid 3g 3g 1 0 x y return
pull facts is kind of callback method which is called by funclogicquery when does the logic query operation in its recursive traversing ... that way we do nt put all the pulling operations in funclogicquery but making it pluggable by calling from outside . that is the place where we actually call the ' fact ' modules . if you need change in calling fact methods that is the place to go .,def pull_facts self overlord_tuple keyword_tuple overlord_tuple 0 split __ overlord_value overlord_tuple 1 if len keyword_tuple 1 keyword keyword_tuple 1 else keyword fact_name keyword_tuple 0 if not self method_fact_list has_key fact_name raise MinionQueryError None existing Fact method or tag required s fact_name fact_value self method_fact_list fact_name logic_fact self keyword_query resolve keyword overlord_value fact_value return logic_fact fact_name fact_value
"equivalent to numpy.split(array_2d , slices ) , but avoids fancy indexing",def _split_arrs array_2d slices if len array_2d 0 return np empty 0 dtype np object rtn np empty len slices 1 dtype np object start 0 for i s in enumerate slices rtn i array_2d start s start s rtn 1 array_2d start return rtn
"strips the install builder action from the source list and stores the final installation location as the "" packaging_install_location "" of the source of the source file . this effectively removes the final installed files from the source list while remembering the installation location .",def stripinstallbuilder target source env def has_no_install_location file return not file has_builder and hasattr file builder name and file builder name InstallBuilder or file builder name InstallAsBuilder if len src for src in source if has_no_install_location src warn Warning there are files to package which have no InstallBuilder attached this might lead to irreproducible packages n_source for s in source if has_no_install_location s n_source append s else for ss in s sources n_source append ss copy_attr s ss ss Tag PACKAGING_INSTALL_LOCATION s get_path return target n_source
like : func:`~asciitree.drawing . style.child_tail ` but only called for the last child .,def last_child_tail self line return line
return the correct database client object based on if we are in dev or prod,def getDatabaseClient if prod True logger info Using AWS Prod Database return boto3 resource dynamodb else logger info Using Local Dev Database return boto3 resource dynamodb endpoint_url http localhost 8000
"set types indices of corresponding properties to sites , for which the site_names are given by the user .",def set_property_acf kmc_model layer_site_name property_type for i in range kmc_model base get_volume if i 1 kmc_model lattice spuck kmc_model lattice spuck getattr kmc_model lattice layer_site_name lower kmc_model base_acf set_property_acf i 1 property_type if i 1 kmc_model lattice spuck getattr kmc_model lattice layer_site_name lower kmc_model base_acf set_property_acf i 1 property_type
message : the message string to classify . vocab : a dict of unique integers assigned to unique words .,def process_msg message vocab msg_arr tokenized join char if char isalpha else for char in message lower split for word in tokenized if word in vocab msg_arr append vocab word else msg_arr append vocab unk return np asarray msg_arr
verify we are raising properly if a get request fails .,def test_post_failure self test_base Base self CERT self URLBASE with self assertRaises requests ConnectionError test_base post make beans json dumps dict beans pinto
construct a user - agent suitable for use in client code .,def format_user_agent name None u Construct a User Agent suitable for use in client code n n This will identify use by the provided name which should be on the n format dist_name version Mopidy version and Python version n n versionadded 1 1 n parts u Mopidy s mopidy __version__ u s s platform python_implementation platform python_version if name parts insert 0 name return u join parts
retrieve the current time . this function is mocked out in unit testing .,def current_time return time time
returns a parsed value from the environment,def config envvar default NO_VALUE type_ str raise_error False types str str int int float float bool parse_bool database_url parse_database_url cache_url parse_cache_url list_of_str parse_list_of_str parser types type_ val os environ get envvar NO_VALUE if val is not NO_VALUE return parser val if default is not NO_VALUE return parser default if raise_error msg s requires a value of type s envvar type_ raise ConfigurationError msg
produce a class by name .,def instance_produce namespace class_name args kwargs mod importlib import_module namespace cls getattr mod class_name title return cls args kwargs
"called at the end of a subtest . ' err ' is none if the subtest ended successfully , otherwise it 's a tuple of values as returned by sys.exc_info ( ) .",def addSubTest self test subtest err if err is not None if getattr self failfast False self stop if issubclass err 0 test failureException errors self failures else errors self errors errors append subtest self _exc_info_to_string err test self _mirrorOutput True
"this function implements mask voting mechanism to give finer mask n is the candidate boxes ( masks ) number args : masks : all masks need to be aggregated ( n x sz x sz ) mask_weights : class score associated with each mask ( n x 1 ) boxes : tight box enclose each mask ( n x 4 ) im_width , im_height : image information",def mask_aggregation boxes masks mask_weights im_width im_height binary_thresh 0 4 assert boxes shape 0 len masks and boxes shape 0 mask_weights shape 0 im_mask np zeros im_height im_width for mask_ind in xrange len masks box np round boxes mask_ind astype int mask masks mask_ind binary_thresh astype float mask_weight mask_weights mask_ind im_mask box 1 box 3 1 box 0 box 2 1 mask mask_weight r c np where im_mask binary_thresh if len r 0 or len c 0 min_y np ceil im_height 2 astype int min_x np ceil im_width 2 astype int max_y min_y max_x min_x else min_y np min r min_x np min c max_y np max r max_x np max c clipped_mask im_mask min_y max_y 1 min_x max_x 1 clipped_box np array min_x min_y max_x max_y dtype np float32 return clipped_mask clipped_box
read the sample images and reshape to required structure,def gen_sample folder ftype jpg savepath None crop_box 200 200 res_box 50 50 clipflag False clipparam None if os path exists folder sample_list os listdir folder else return sample_mat np zeros len sample_list res_box 0 res_box 1 def read_image fpath ftype if ftype fits h fits open fpath img h 0 data else img imread name fpath flatten True return img idx 0 for fname in sample_list fpath os path join folder fname if fpath split 1 ftype img read_image fpath fpath ftype ftype rows cols img shape row_cnt int np round rows 2 col_cnt int np round cols 2 row_crop_half int np round crop_box 0 2 col_crop_half int np round crop_box 1 2 img_crop img row_cnt row_crop_half row_cnt row_crop_half col_cnt col_crop_half col_cnt col_crop_half img_rsz transform resize img_crop 255 res_box mode reflect if clipflag img_rsz get_sigma_clip img_rsz sigma clipparam 0 iters clipparam 1 img_vec img_rsz reshape res_box 0 res_box 1 sample_mat idx img_vec idx idx 1 else continue if not savepath is None stype savepath split 1 if stype mat sample_dict data sample_mat name sample_list sio savemat savepath sample_dict elif stype pkl fp open savepath wb sample_dict data sample_mat name sample_list pickle dump sample_dict fp fp close return sample_mat
gets the saved environment from a file for a given architecture .,def get_env arch pairs open arch read 2 split x00 kvs item split 1 for item in pairs return dict kvs
called when an expected failure / error occured .,def addExpectedFailure self test err self expectedFailures append test self _exc_info_to_string err test
"without arg and when use_l10n is true , the active language 's date_format is used .",override_settings USE_L10N True setup date02_l10n d date def test_date02_l10n self with translation override fr output self engine render_to_string date02_l10n d datetime 2008 1 1 self assertEqual output 1 janvier 2008
the join template filter has needs_autoescape = true,setup regroup04 regroup data by bar join as grouped for group in grouped group grouper for item in group list item foo first endfor endfor def test_regroup04 self output self engine render_to_string regroup04 data foo x bar ab c foo y bar a bc foo z bar a d self assertEqual output abc xy ad z
"child has two foreignkeys to parent , so if we do n't specify which one to use for the inline formset , we should get an exception .",def test_exception_on_unspecified_foreign_key self msg inline_formsets Child has more than one ForeignKey to inline_formsets Parent with self assertRaisesMessage ValueError msg inlineformset_factory Parent Child
the same quoted etag should be set on the header regardless of whether etag_func ( ) in condition ( ) returns a quoted or an unquoted etag .,def test_unquoted self response_quoted self client get condition etag response_unquoted self client get condition unquoted_etag self assertEqual response_quoted ETag response_unquoted ETag
detach from the shell and run in background,def go_background utils_posix daemonize pidfile var run neubot pid
pulls data through the pipeline . useful if we just want to calculate some stats .,def run self for _ in self process pass
internal function for handling right mouse button . we do want to provide a context menu where you can perform commands .,def _right_mouse_down self event node self GetSelection if node IsOk self PopupMenu ProjectTreeContextMenu event GetPosition
"convert key1=value1,key2=value2 , ... string into dictionary .",def str2dict strdict if not strdict return return dict kv split 1 for kv in strdict split
register a new set of projection(s ) .,def register self projections for projection in projections name projection name self _all_projection_types name projection
make sure the examples directory is in the correct location,def testExamplesDirExists self failMsg Path to examples does not exist s ExamplesTest examplesDir self assertTrue os path exists ExamplesTest examplesDir failMsg
: param proto : capnp twogrammodelproto message builder,def write self proto super TwoGramModel self writeBaseToProto proto modelBase proto reset self _reset proto learningEnabled self _learningEnabled proto prevValues self _prevValues self _encoder write proto encoder proto hashToValueDict hash h value v for h v in self _hashToValueDict items twoGramDicts for items in self _twoGramDicts twoGramArr for prev values in items iteritems buckets index index count count for index count in values iteritems if prev is None prev 1 twoGramArr append value prev buckets buckets twoGramDicts append twoGramArr proto twoGramDicts twoGramDicts
draw each of the widgets in this hex editor .,def _draw_file self paint start 0 for widget in self widgets start widget render start paint
query analytics and stash data in a format suitable for serializing .,def report self output OrderedDict for arg in GLOBAL_ARGUMENTS output arg getattr self args arg or self config get arg None output title getattr self args title or self config get title Untitled Report output run_date datetime now strftime Y m d output queries for analytic in self config get queries print Querying s analytic name results self query metrics analytic metrics dimensions analytic get dimensions filters analytic get filter None segment analytic get segment None sort analytic get sort start_index analytic get start index 1 max_results analytic get max results 10 dimensions_len len analytic get dimensions data OrderedDict config analytic sampled results get containsSampledData False sampleSize int results get sampleSize 0 sampleSpace int results get sampleSpace 0 data_types OrderedDict data OrderedDict for column in results columnHeaders dimensions_len data data_types column name column dataType def cast_data_type d dt if dt INTEGER return int d elif data_type in TIME FLOAT CURRENCY PERCENT return float d else raise Exception Unknown metric data type s data_type for i metric in enumerate analytic metrics data data metric OrderedDict data_type data data_types metric if dimensions_len for row in results get rows column i dimensions_len label join row dimensions_len value cast_data_type row column data_type data data metric label value data data metric total cast_data_type results totalsForAllResults metric data_type sleep 1 output queries append data return output
create a field with value 0 . to 1 . in each dimension,pytest fixture scope session def unit_box name a shape 11 11 grid Grid shape shape a Function name name grid grid dims tuple np linspace 0 0 1 0 d for d in shape a data np meshgrid dims 1 return a
parse dhcp lease : param lines : lease section as list item : return : dictionary,staticmethod def parse_lease lines lease dict lease address lines 0 split 1 for line in lines parts line split field_name parts 0 field_value None if field_name in starts ends tstp tsfp atsfp cltt and len parts 3 dt s s parts 2 parts 3 try field_value calendar timegm datetime datetime strptime dt Y m d H M S timetuple except ValueError field_value None elif field_name hardware and len parts 3 field_value hardware type parts 1 mac address parts 2 split 0 elif field_name in uid client hostname and len parts 2 and parts 1 find 1 field_value parts 1 split 1 if field_value is not None lease field_name field_value return lease
adds an ip on a given network to an instance .,wsgi action addFixedIp def _add_fixed_ip self req id body context req environ nova context authorize context if networkId not in body addFixedIp msg _ Missing networkId argument for addFixedIp raise exc HTTPBadRequest explanation msg instance common get_instance self compute_api context id want_objects True network_id body addFixedIp networkId try self compute_api add_fixed_ip context instance network_id except exception NoMoreFixedIps as e raise exc HTTPBadRequest explanation e format_message return webob Response status_int 202
helper function that returns a list of flavor dicts .,def _get_flavors self req filters sort_key req params get sort_key or flavorid sort_dir req params get sort_dir or asc limit marker common get_limit_and_marker req context req environ nova context if context is_admin filters is_public self _parse_is_public req params get is_public None else filters is_public True filters disabled False if minRam in req params try filters min_memory_mb int req params minRam except ValueError msg _ Invalid minRam filter s req params minRam raise webob exc HTTPBadRequest explanation msg if minDisk in req params try filters min_root_gb int req params minDisk except ValueError msg _ Invalid minDisk filter s req params minDisk raise webob exc HTTPBadRequest explanation msg try limited_flavors flavors get_all_flavors_sorted_list context filters filters sort_key sort_key sort_dir sort_dir limit limit marker marker except exception MarkerNotFound msg _ marker s not found marker raise webob exc HTTPBadRequest explanation msg return limited_flavors
test if this claim can be satisfied given available resources and optional oversubscription limits,def _claim_test self resources limits None if not limits limits memory_mb_limit limits get memory_mb disk_gb_limit limits get disk_gb numa_topology_limit limits get numa_topology if numa_topology_limit numa_topology_limit hardware VirtNUMALimitTopology from_json numa_topology_limit msg _ Attempting claim memory memory_mb d MB disk disk_gb d GB params memory_mb self memory_mb disk_gb self disk_gb LOG audit msg params instance self instance reasons self _test_memory resources memory_mb_limit self _test_disk resources disk_gb_limit self _test_numa_topology resources numa_topology_limit self _test_pci reasons reasons self _test_ext_resources limits reasons r for r in reasons if r is not None if len reasons 0 raise exception ComputeResourcesUnavailable reason join reasons LOG audit _ Claim successful instance self instance
load selected data from hidaq recording .,def get_data filename channel None start 0 length None detrend None if channel is None channel range _channels elif isinstance channel int channel channel if length is None length get_data_length filename start with open filename rb as f hdr _np fromfile f dtype _np dtype i4 count 1 f seek hdr 0 start _framelen _os SEEK_SET data _np fromfile f dtype _np dtype i2 count _channels length data _np reshape data length _channels data _np take data channel axis 1 astype _np float if len channel 1 data data ravel data data 2048 if detrend is not None data _sig detrend data axis 0 type detrend return data
reconfigure the open port after a property has been changed .,def _reconfigure_port self pass
get the value that is stored under symbol,def __getitem__ self symbol for d in reversed self stack v d get symbol if v is not None return v return None
dim ( ) sum ( ... ) raises type error [ 00 ] .,def testSum_00 self myObj_0 Coord Dim 71 px myObj_1 Coord Dim 72 px try sum myObj_0 myObj_1 self fail TypeError not raised except TypeError pass
estimate time complexity class of a function from execution time .,def big_o func data_generator min_n 100 max_n 100000 n_measures 10 n_repeats 1 n_timings 1 classes ALL_CLASSES verbose False ns time measure_execution_time func data_generator min_n max_n n_measures n_repeats n_timings return infer_big_o_class ns time classes verbose verbose
update a q - function and a policy .,def update Q target_Q policy target_policy opt_Q opt_policy samples gamma 0 99 xp Q xp obs xp asarray sample 0 for sample in samples dtype np float32 action xp asarray sample 1 for sample in samples dtype np float32 reward xp asarray sample 2 for sample in samples dtype np float32 done xp asarray sample 3 for sample in samples dtype np float32 obs_next xp asarray sample 4 for sample in samples dtype np float32 def update_Q y F squeeze Q obs action axis 1 with chainer no_backprop_mode next_q F squeeze target_Q obs_next target_policy obs_next axis 1 target reward gamma 1 done next_q loss F mean_squared_error y target Q cleargrads loss backward opt_Q update def update_policy q Q obs policy obs q q loss F mean q policy cleargrads loss backward opt_policy update update_Q update_policy
create new random ppi among all those possible,def random_PPI self if Complexable in self dict_types list_complexable self dict_types Complexable n len list_complexable list_possible_PPI for ip1 in range n P1 list_complexable ip1 if not self check_existing_binary P1 PPI and not self check_existing_binary P1 P1 PPI list_possible_PPI append P1 P1 for ip2 in range ip1 P2 list_complexable ip2 if not self check_existing_binary P1 P2 PPI list_possible_PPI append P1 P2 n_pPPI len list_possible_PPI if not n_pPPI self number_PPI print Potential Bug Inconsistency in Computation of number of PPI if n_pPPI 0 print In random_PPI No other posible PPIs return None else P1 P2 list_possible_PPI int self Random random n_pPPI PPI C self new_random_PPI P1 P2 return PPI C else print Error in random_PPI try to create a PPI from non existing pieces return None
mark an inbox message as collapsed .,def collapse self items while items data id join x fullname for x in items 25 self _reddit post API_PATH collapse data data items items 25
"parse ' po ' format produced by xgettext . return a list of ( msgid , msgstr ) tuples .",def parse_po text messages msgid msgstr in_msgid False in_msgstr False for line in text split n line line rstrip r if line startswith msgid if in_msgstr messages append msgid msgstr in_msgstr False in_msgid True msgid line 6 elif line startswith msgstr in_msgid False in_msgstr True msgstr line 7 elif line startswith if in_msgid msgid append line if in_msgstr msgstr append line if in_msgstr messages append msgid msgstr return messages
signs a_hash_for_sig with a_key and returns a der - encoded signature with a_sig_type appended .,def sigmake a_key a_hash_for_sig a_sig_type SIGHASH_ALL order generator_secp256k1 order r s ecdsa_sign generator_secp256k1 a_key secret_exponent a_hash_for_sig if s s order s order s return sigencode_der r s bytes_from_int a_sig_type
computes the pca of a given data .,def PCA data n_bases None scale None compute_reduced True compute_base True compute_mean False if compute_mean data_mean numpy mean data 0 data_clean data data_mean else data_clean data data_mean numpy zeros data shape 0 u s v numpy linalg svd data_clean full_matrices False if scale is not None energy numpy cumsum s numpy sum s index numpy where energy scale 0 0 1 elif n_bases is not None index n_bases else raise ValueError One of scale or n_bases must be not None if compute_reduced s_trunc s 0 index u_trunc u 0 index data_trunc numpy dot u_trunc numpy diag s_trunc else data_trunc None if compute_base base_trunc v transpose 0 index else base_trunc None return data_trunc base_trunc data_mean
compile and attach shader of given type from file,def make_shader_filename program filename type_ path os path join data shaders filename source pkgutil get_data gspyce path return make_shader_source program source type_
median combine a list of images,def MedianCombine ImgList zero_bo False zero Bias fits dark_bo False darks flat_bo False flat Flat fits n len ImgList if n 0 raise ValueError empty list provided h pyfits open ImgList 0 0 d h data d OverscanTrim d h header BIASSEC if zero_bo Master pyfits getdata zero else Master np zeros d shape 0 d shape 1 float if dark_bo and len darks 0 hd pyfits getheader ImgList 0 time hd EXPTIME Dark get_dark darks time else Dark np zeros d shape 0 d shape 1 float if flat_bo Flat pyfits getdata flat else Flat np zeros d shape 0 d shape 1 float 1 0 if flat_bo d d Master Dark Flat else d d Master Dark factor 1 25 if n 3 factor 1 ronoise factor h header ENOISE np sqrt n gain h header EGAIN if n 1 return d ronoise gain else for i in range n 1 h pyfits open ImgList i 1 0 if flat_bo d np dstack d OverscanTrim h data h header BIASSEC Master Dark Flat else d np dstack d OverscanTrim h data h header BIASSEC Master Dark return np median d axis 2 ronoise gain
sync local instance against a single remote object,def sync_from_remote org syncer remote u n Sync local instance against a single remote object n n param org the org n param syncer the local model syncer n param remote the remote object n return the outcome created updated or deleted n identity syncer identify_remote remote with syncer lock org identity existing syncer fetch_local org identity remote_as_kwargs syncer local_kwargs org remote if existing existing org org if remote_as_kwargs if syncer update_required existing remote remote_as_kwargs or not existing is_active for field value in six iteritems remote_as_kwargs setattr existing field value existing is_active True existing save return SyncOutcome updated elif existing is_active syncer delete_local existing return SyncOutcome deleted elif remote_as_kwargs syncer model objects create remote_as_kwargs return SyncOutcome created return SyncOutcome ignored
get list of installed packages and their versions .,def get_packages u n Get list of installed packages and their versions n n return installed packages and versions keyed by package name n rtype dict of str or unicode str or unicode n packages pip get_installed_distributions local_only False packages_dict for package in packages packages_dict package key package version return packages_dict
check spelling of a word .,def check self word res self _words search word return bool res
staged removal of a file .,def test_stageremoved self self stage_remove self gitrepodir a txt with self prepare as stash self assertIsNone stash
attempt to fix ipython startup to not print ( bool_t)1,def fix_ipython_startup fn BADSTR TPython Exec GOODSTR TPython Exec if sys version_info 0 3 consts fn im_func func_code co_consts else consts fn __code__ co_consts if BADSTR not in consts return idx consts index BADSTR orig_refcount sys getrefcount consts del consts PyTuple_SetItem ctypes pythonapi PyTuple_SetItem PyTuple_SetItem argtypes ctypes py_object ctypes c_size_t ctypes py_object if sys version_info 0 3 consts ctypes py_object fn im_func func_code co_consts else consts ctypes py_object fn im_func __code__ co_consts for _ in range orig_refcount 2 ctypes pythonapi Py_DecRef consts try ctypes pythonapi Py_IncRef GOODSTR PyTuple_SetItem consts idx GOODSTR finally for _ in range orig_refcount 2 ctypes pythonapi Py_IncRef consts
expects a file containing lines of the form e.g. : 226 jalesore 1122 172 26.65 85.78 275 phidim ( panchth 1419 1205 27.15 87.75 unused station name < -id < -elev < -lat < -lon 0123456789012345678901234567890123456789012345678901234567890123456789 0 1 2 3 4 5 6,def import_stations file_name for line in open file_name r readlines try place_id_text line 27 33 except IndexError continue else try station_id int place_id_text except ValueError continue else station_name line 8 25 strip elevation_metres int line 37 43 latitude Decimal line 47 53 longitude Decimal line 57 623 place_table_name climate_place _tablename existing_place db climate_station_id station_id station_id select first if existing_place is None place_id climate_place insert longitude longitude latitude latitude else print Update place_id existing_place id db climate_place id place_id update longitude longitude latitude latitude def insert_or_update table place_id attribute format value table_name table _tablename if db table id place_id count 0 value repr value formatted_value format value db executesql INSERT INTO table_name s id attribute s VALUES place_id i formatted_value s locals else db table id place_id update attribute value insert_or_update climate_station_name place_id name str station_name insert_or_update climate_elevation place_id elevation_metres float elevation_metres insert_or_update climate_station_id place_id station_id int station_id print place_id station_id station_name latitude longitude elevation_metres db commit
reutrn sequence id and quality scores in dicitonary format,def load_quals f result dict for seq_id quals seq_len in generate_phred_scores f result seq_id quals return result
clear the module state . this is mainly for testing purposes .,def reset global __module_flags __flags __stv __module_flags __flags __stv
handles the capturing the current state of processing,xworkflows on_enter_state def update_state self args kwargs self torrent self dbapi get_torrent self torrent torrent_id self torrent state self state name self torrent self dbapi save_torrent self torrent LOG debug torrent s self torrent
derivative of mccrho with respect to the model,property def MccRhoiDerivMat self u n Derivative of MccRho with respect to the model n if getattr self u _MccRhoiDerivMat None is None rho self rho vol self mesh vol drho_dlogrho Utils sdiag rho self etaDeriv self _MccRhoiDerivMat Utils sdiag vol 1 0 rho 2 drho_dlogrho return self _MccRhoiDerivMat
decorator to designate an api method applicable only to client - side instances .,def client_side func def inner args kwargs if args and hasattr args 0 is_server and voltron debugger raise ClientSideOnlyException This method can only be called on a client side instance return func args kwargs return inner
: type timeout : int | timedelta,def __init__ self timeout if isinstance timeout timedelta timeout timeout total_seconds self timeout timeout self end time time timeout self start datetime now
set or change the server certificate file used to wrap new connections .,def setCertfile self certfile if not os access certfile os R_OK raise IOError No such certfile found s certfile self certfile certfile
reconfigure the : class:`.sessionmaker ` used by this : class:`.scoped_session ` .,def configure self kwargs if self registry has warn At least one scoped session is already present configure can not affect sessions that have already been created self session_factory configure kwargs
"place a new : class:`.template ` object into this : class:`.templatelookup ` , based on the given string of `` text `` .",def put_string self uri text self _collection uri Template text lookup self uri uri self template_args
checks whether the privileges contained are equal to aggregate dav : all privilege .,def isAll self if len self privileges 1 and self privileges 0 name Constants TAG_ALL return 1 return 0
returns the argument as dictionary with given key,def as_plot_x_dict plot_x return dict plot_x plot_x
redefine the scipy.ndimage.measurements.label function to work with a wider range of data types . the default function is inconsistent about the data types it accepts on different platforms .,checks ABINARY2 def label image kw try return measurements label image kw except pass types int32 uint32 int64 uint64 int16 uint16 for t in types try return measurements label array image dtype t kw except pass return measurements label image kw
molecule - > vflib editable graph,def to_argedit molecule G vflib ARGEdit lookup for atom in molecule atoms lookup atom handle G InsertNode atom for bond in molecule bonds atom1 atom2 bond atoms index1 index2 lookup atom1 handle lookup atom2 handle G InsertEdge index1 index2 bond G InsertEdge index2 index1 bond return G
generate some random tweet text .,def mock_tweet count random randint 70 140 return join random choice string ascii_letters for _ in range count
"stir(s : string ) mix up the randomness pool . this will call add_event ( ) twice , but out of paranoia the entropy attribute will not be increased . the optional 's ' parameter is a string that will be hashed with the randomness pool .",def stir self s entropy self entropy self add_event for i in range self bytes self _hash digest_size h self _hash new self _randpool h update str self __counter str i str self _addPos s self _addBytes h digest self __counter self __counter 1 4294967295L self _addPos self _getPos 0 self _hash digest_size self add_event self entropy entropy
register a callable which can perform a schema upgrade between two particular versions .,def registerUpgrader upgrader typeName oldVersion newVersion assert isinstance typeName str read the doc string _upgradeRegistry typeName oldVersion upgrader
called when client sends stream : stream,def streamStarted self elm self xmlstream addObserver self IQ_GET_AUTH self authRequested self xmlstream addObserver self IQ_SET_AUTH self auth
verify correct encoder is attached to a file cassettelibrary .,def test_create_new_cassette_library_with_extension self filename os path join TEMPORARY_RESPONSES_ROOT tmp json lib CassetteLibrary create_new_cassette_library filename self assertTrue isinstance lib FileCassetteLibrary self assertTrue isinstance lib encoder JsonEncoder filename os path join TEMPORARY_RESPONSES_ROOT tmp yaml lib CassetteLibrary create_new_cassette_library filename self assertTrue isinstance lib FileCassetteLibrary self assertTrue isinstance lib encoder YamlEncoder
"load a ground - truth segmentation , and align times to the nearest detected beats .",def align_segmentation beat_times song try segment_times segment_labels msaf io read_references song except return None None None segment_times np asarray segment_times segment_intervals msaf utils times_to_intervals segment_times beat_intervals np asarray zip beat_times 1 beat_times 1 beat_segment_ids librosa util match_intervals beat_intervals segment_intervals segment_beats segment_times_out segment_labels_out for i in range segment_times shape 0 hits np argwhere beat_segment_ids i if len hits 0 and i len segment_intervals and i len segment_labels segment_beats extend hits 0 segment_times_out append segment_intervals i segment_labels_out append segment_labels i segment_beats list segment_beats segment_times_out segment_times return segment_beats segment_times_out segment_labels_out
search through the plugins directory and find all directories with an _ _ init__.py file . these directories will be considered plugins .,def _get_all_plugins self plugins for entry in os listdir self plugins_path entry_path os path join self plugins_path entry init_path os path join entry_path __init__ py if os path isdir entry_path and os path exists init_path module os path join self plugins_dir entry replace plugins append module return plugins
create and start up the internal workers .,def build self if not self _output_tubes self _output_tubes append self _worker_class getTubeClass self _worker_class assemble self _worker_args self _input_tube self _output_tubes self _size self _disable_result self _do_stop_task for stage in self _next_stages stage build
"prototype object based on the schema , in python code with comments .",def _to_str_impl self schema stype schema get type if stype object self emitEnd schema get description self indent if properties in schema for pname pschema in schema get properties iteritems self emitBegin s pname self _to_str_impl pschema elif additionalProperties in schema self emitBegin a_key self _to_str_impl schema additionalProperties self undent self emit elif ref in schema schemaName schema ref description schema get description s self from_cache schemaName seen self seen parts s splitlines self emitEnd parts 0 description for line in parts 1 self emit line rstrip elif stype boolean value schema get default True or False self emitEnd s str value schema get description elif stype string value schema get default A String self emitEnd s str value schema get description elif stype integer value schema get default 42 self emitEnd s str value schema get description elif stype number value schema get default 3 14 self emitEnd s str value schema get description elif stype null self emitEnd None schema get description elif stype any self emitEnd schema get description elif stype array self emitEnd schema get description self indent self emitBegin self _to_str_impl schema items self undent self emit else self emit Unknown type s stype self emitEnd self string join self value return self string
token was a part of a login url that proves email ownership .,def authenticate self site site_url token verified_email login_token load_login_token site site_url token if verified_email is None raise AuthenticationError Token invalid or expired return site users find_item_by_email verified_email
"unzip burp 's file , remove non - printable characters , cdata any html , include a valid xml header and trailer , and return a valid xml string .",def burp_to_xml self filename z zipfile ZipFile self find_file filename burp z read burp rb m TAG match burp 0 while m index m end etag m group replace m TAG match burp index if not m value length self burp_binary_field burp index if value is None break index length len etag m TAG match burp index if self params checkversion and etag version and value not in 65 67 raise FuzzExceptBadFile Unknown burp log version s value if etag https https_tag value True if etag in self request_tags raw_request self strip_cdata value if etag in self response_tags fr FuzzRequest fr update_from_raw_http raw_request http if not https_tag else https self strip_cdata value frr FuzzResult history fr raw_request https_tag yield frr update
converts a list of bytes to a list containing the corresponding mvoltages . polarity offset is included .,def numbers_to_mvoltages self numbers values x 256 y 65535 0 4000 0 x0 for x y x0 in zip numbers 2 numbers 1 2 self polmatrix return tuple values
"a recursive version of the parent 's set_rotation . changes the location part of the assembly 's transform , and updates the assembly 's children 's transform accordingly .",def set_location self location HasFrame set_location self location self transform_children
"create a ` terminalcontroller ` and initialize its attributes with appropriate values for the current terminal . ` term_stream ` is the stream that will be used for terminal output ; if this stream is not a tty , then the terminal is assumed to be a dumb terminal ( i.e. , have no capabilities ) .",def __init__ self term_stream sys stdout try import curses except return if not term_stream isatty return try curses setupterm except return self COLS curses tigetnum cols self LINES curses tigetnum lines self XN curses tigetflag xenl for capability in self _STRING_CAPABILITIES attrib cap_name capability split setattr self attrib self _tigetstr cap_name or set_fg self _tigetstr setf if set_fg for i color in zip range len self _COLORS self _COLORS setattr self color self _tparm set_fg i set_fg_ansi self _tigetstr setaf if set_fg_ansi for i color in zip range len self _ANSICOLORS self _ANSICOLORS setattr self color self _tparm set_fg_ansi i set_bg self _tigetstr setb if set_bg for i color in zip range len self _COLORS self _COLORS setattr self BG_ color self _tparm set_bg i set_bg_ansi self _tigetstr setab if set_bg_ansi for i color in zip range len self _ANSICOLORS self _ANSICOLORS setattr self BG_ color self _tparm set_bg_ansi i
this is run after each test,def teardown_method self self rp None self sim None
the `` cleanupregistration `` management command properly deletes expired accounts .,def test_management_command self new_user RegistrationProfile objects create_inactive_user site Site objects get_current self user_info expired_user RegistrationProfile objects create_inactive_user site Site objects get_current username bob password secret email bob example com expired_user date_joined datetime timedelta days settings ACCOUNT_ACTIVATION_DAYS 1 expired_user save management call_command cleanupregistration self assertEqual RegistrationProfile objects count 1 self assertRaises User DoesNotExist User objects get username bob
test that adding an existing statement causes no new commit,def testCommitNoOp self pass
return a whole red rgba array .,def red array alpha new_array_shape array shape 4 new_array _np zeros new_array_shape dtype _np uint8 new_array 0 255 array clip 0 1 new_array 1 0 new_array 2 0 new_array 3 alpha array clip 0 1 return new_array
"testing genostrutrait::locibynames(names ) , locinames ( ) , locusbyname(name ) , locusname(loc )",def testLociName self pop self getPop self assertEqual pop locusName 0 self assertEqual pop locusName 1 self assertEqual pop locusName 2 pop Population loci 1 2 lociNames la lb lc self assertEqual pop locusName 0 la self assertEqual pop locusName 1 lb self assertEqual pop locusName 2 lc self assertEqual pop locusByName la 0 self assertEqual pop locusByName lb 1 self assertEqual pop locusByName lc 2 self assertRaises IndexError pop locusName 5 self assertRaises ValueError pop locusByName somename self assertRaises ValueError pop lociByNames somename other self assertEqual pop lociByNames lb lc 1 2 self assertEqual pop lociByNames lb la 1 0
computes the three - dimensional tensor t,def compute_aotensor t theta 1 0 0 Cpa 1 atmos a 0 0 sig0 for i in range 1 natm 1 for j in range 1 natm 1 t psi i psi j 0 atmos c i 1 j 1 betp atmos a i 1 i 1 kd kdelta i 1 j 1 2 t theta i psi j 0 atmos a i 1 j 1 kd sig0 2 2 atmos a i 1 i 1 sig0 t psi i theta j 0 kd kdelta i 1 j 1 2 t theta i theta j 0 sig0 2 0 atmos c i 1 j 1 betp atmos a i 1 j 1 kd 4 0 kdp 2 0 LSBpa sc Lpa kdelta i 1 j 1 2 0 2 0 atmos a i 1 i 1 sig0 for k in range 1 natm 1 t psi i psi j psi k atmos b i 1 j 1 k 1 atmos a i 1 i 1 t psi i theta j theta k atmos b i 1 j 1 k 1 atmos a i 1 i 1 t theta i psi j theta k atmos g i 1 j 1 k 1 atmos b i 1 j 1 k 1 sig0 1 atmos a i 1 i 1 sig0 t theta i theta j psi k atmos b i 1 j 1 k 1 sig0 1 atmos a i 1 i 1 sig0 for j in range 1 noc 1 t psi i A j 0 kd atmos d i 1 j 1 2 atmos a i 1 i 1 t theta i A j 0 kd atmos d i 1 j 1 sig0 2 2 atmos a i 1 i 1 sig0 t theta i T j 0 atmos s i 1 j 1 2 LSBpo Lpa 2 2 atmos a i 1 i 1 sig0 for i in range 1 noc 1 for j in range 1 natm 1 t A i psi j 0 ocean K i 1 j 1 dp ocean M i 1 i 1 G t A i theta j 0 ocean K i 1 j 1 dp ocean M i 1 i 1 G for j in range 1 noc 1 t A i A j 0 ocean N i 1 j 1 betp ocean M i 1 i 1 rp dp kdelta i 1 j 1 ocean M i 1 i 1 G for k in range 1 noc 1 t A i A j A k ocean C i 1 j 1 k 1 ocean M i 1 i 1 G for i in range 1 noc 1 t T i 0 0 Cpo ocean W i 1 0 for j in range 1 natm 1 t T i theta j 0 ocean W i 1 j 1 2 sc Lpo sbpa for j in range 1 noc 1 t T i T j 0 Lpo sbpo kdelta i 1 j 1 for k in range 1 noc 1 t T i A j T k ocean O i 1 j 1 k 1
should erase to right of cursor .,knownBug terminal iTerm2 reason Not implemented def test_DECSEL_Default self self prepare esccmd DECSEL AssertScreenCharsInRectEqual Rect 1 1 10 1 abcd 6 NUL
returns the derivative of f w.r.t . to multidimensional vector x0 if x0 is of dimension r1 x ... x rd x rn dimension of f is assumed to be in the form s1 x ... x sf x rn . the last dimension corresponds to various observations . the value returned is of dimension : s1 x ... x sf x r1 x ... x rd x rn,def numdiff1 f x0 dv 1e 08 in_shape x0 shape nobs in_shape 1 dd in_shape 1 f0 f x0 assert f0 shape 1 nobs f_shape f0 shape 1 out_shape f_shape dd nobs ret np zeros out_shape for ind in product range i for i in dd sl ind slice None None None x x0 copy x sl dv x2 x0 copy x2 sl dv df f x f x2 dv 2 0 obj Ellipsis list ind slice None None None obj tuple obj ret obj df return ret
method to grab all the motion parameters and power parameters file from each subject for each pipeline and merge them,def grab output_dir scrubbing import glob import os import re from sets import Set pipelines glob glob os path join output_dir pipeline for p in pipelines scan_list threshold_list pattern1 re compile w scan w d w pattern2 re compile w threshold_ 0 9 0 9 0 9 scans glob glob os path join p power_params for s in scans val re search pattern1 s if val scan_list append val group 0 rstrip val re search pattern2 s if val threshold_list append val group 0 scan_list Set scan_list threshold_list Set threshold_list for scan in scan_list for threshold in threshold_list Flag 1 for sub in os listdir p sub os path join p sub motion_file os path join sub motion_params scan motion_parameters txt power_file os path join sub power_params scan threshold pow_params txt if os path exists motion_file and os path exists power_file merge p scan threshold motion_file power_file Flag Flag 0 if 0 in scrubbing for sub in os listdir p sub os path join p sub motion_file os path join sub motion_params scan motion_parameters txt power_file os path join sub power_params scan pow_params txt if os path exists motion_file and os path exists power_file threshold None merge p scan threshold motion_file power_file Flag Flag 0 return threshold
call run ( ) . @return true if a change occured .,def run self original_data list for param in self block get_params original_data append param get_value gtk Dialog run self self destroy new_data list for param in self block get_params new_data append param get_value return original_data new_data
assign ports if not already assigned .,def assign_ports self if self ports_assigned return from environment import reserve_ports import utils self zk_port_base reserve_ports 3 self hostname utils hostname self zk_ports join str self zk_port_base i for i in range 3 self addr localhost d self zk_port_base 2 self ports_assigned True
determine the path of a schema with the given name at the specified version of the standard .,def create_schema_path name version None return path_for_version os path join PATH_SCHEMAS 0 format name FILE_SCHEMA_EXTENSION version
used to recursively organize the dataverse parent / child tree into a python ordereddict,def get_child_nodes self root_node parent_child_lists depth 0 child_nodes parent_child_lists get root_node id None if not child_nodes return OrderedDict name root_node name alias root_node alias id root_node id depth depth else child_list for cn in child_nodes child_tree self get_child_nodes cn parent_child_lists depth depth 1 if child_tree and len child_tree 0 child_list append child_tree fmt_d OrderedDict fmt_d name root_node name fmt_d alias root_node alias fmt_d id root_node id fmt_d depth depth fmt_d children child_list return fmt_d
list all templates of a certain type result json,exceptions catcherrors def listTemplates self repository None kwargs cl self get_client kwargs templates dict repos if repository is not None repos cl listRepositories json else repos r name for r in repos for aysrepo in repos tmpls cl listTemplates repository aysrepo templates update aysrepo tmpls return templates
when httpresponse header has not value .,def test_assert_header_has_should_raise self with self assertRaises AssertionError self responses assert_header_has Allow PATCH
generates the policy document based on the internal lists of allowed and denied conditions . this will generate a policy with two main statements for the effect : one statement for allow and one statement for deny . methods that includes conditions will have their own statement in the policy .,def build self if self allowMethods is None or len self allowMethods 0 and self denyMethods is None or len self denyMethods 0 raise NameError No statements defined for the policy policy principalId self principalId policyDocument Version self version Statement policy policyDocument Statement extend self _getStatementForEffect Allow self allowMethods policy policyDocument Statement extend self _getStatementForEffect Deny self denyMethods return policy
returns current time in milliseconds .,def __time_now self return int time time
"for an individual string , tests whether the full string is in a valid article file . this can take two forms .",def validate_filename filename if file_regex_match search filename return True else return False
copy output file from disk to local se,def put_data self source destination fsize 0 fchecksum 0 pdict error PilotErrors pilotErrorDiag alt pdict get alt False lfn pdict get lfn guid pdict get guid token pdict get token scope pdict get scope dsname pdict get dsname analysisJob pdict get analJob False testLevel pdict get testLevel 0 extradirs pdict get extradirs experiment pdict get experiment proxycheck pdict get proxycheck False os_bucket_id pdict get os_bucket_id 1 prodSourceLabel pdict get prodSourceLabel si getSiteInformation experiment tolog put_data received prodSourceLabel s prodSourceLabel if prodSourceLabel ddm and analysisJob tolog Treating PanDA Mover job as a production job during stage out analysisJob False report self getStubTracingReport pdict report gfal copy lfn guid filename os path basename source ec pilotErrorDiag tracer_error dst_gpfn lfcdir surl si getProperPaths error analysisJob token prodSourceLabel dsname filename scope scope alt alt sitemover self if ec 0 self prepareReport tracer_error report return self put_data_retfail ec pilotErrorDiag status output adler_size adler_checksum self getLocalFileInfo source checksumType adler32 if status 0 errorLog Failed to get local file s adler32 checksum s source output tolog WARNING 1777 s errorLog status PilotErrors ERR_STAGEINFAILED state PSTAGE_FAIL output errorLog self prepareReport state report return self put_data_retfail status output surl ret_path si getCopyPrefixPathNew surl stageIn False tolog Convert destination s to new path s surl ret_path if not ret_path startswith s3 errorLog Failed to use copyprefix to convert the current path to S3 path tolog WARNING 1777 s errorLog status PilotErrors ERR_STAGEINFAILED state PSTAGE_FAIL output errorLog size None checksum None else status output size checksum self stageOut source ret_path token experiment os_bucket_id os_bucket_id if status 0 errors PilotErrors state errors getErrorName status if state None state PSTAGE_FAIL self prepareReport state report return self put_data_retfail status output surl elif size adler_size tolog The file size is not changed Will check whether adler32 changed status output new_adler_size new_adler_checksum self getLocalFileInfo source checksumType adler32 if status 0 errorLog Failed to get local file s adler32 checksum s source output tolog WARNING 1777 s errorLog status PilotErrors ERR_STAGEINFAILED state PSTAGE_FAIL output errorLog self prepareReport state report return self put_data_retfail status output surl elif adler_checksum new_adler_checksum tolog The file checksum is not changed Will use adler32 s to replace the md5 checksum s adler_checksum checksum checksum adler_checksum else errorLog The file checksum changed from s before transfer to s after transfer adler_checksum new_adler_checksum tolog WARNING 1777 s errorLog status PilotErrors ERR_STAGEINFAILED state PSTAGE_FAIL output errorLog self prepareReport state report return self put_data_retfail status output surl state DONE self prepareReport state report return 0 pilotErrorDiag surl size checksum self arch_type
"create a wav object from file ( ignore other args ) , or empty with the specified args",def __init__ self filename SampleRate 8000 BitsPerSample 8 NumChannels 1 NumSamples 0 self filename filename try file _io open filename rb header_raw file read 44 header_chunks struct unpack self __header_smask header_raw d d d d d self AudioFormat self NumChannels self SampleRate d self BlockAlign self BitsPerSample d d header_chunks self data file readall file close if header_chunks 0 self ChunkID or header_chunks 2 self Format or header_chunks 3 self SubChunk1ID or header_chunks 11 self SubChunk2ID raise TypeError is not a wav file format filename if self AudioFormat 1 raise TypeError Compressed wav files not supported except OSError if not type SampleRateBits type BitsPerSample type NumChannels int raise TypeError SampleRateBits BitsPerSample NumChannels must be integers if BitsPerSample 8 0 raise ValueError BitsPerSample must be a multiple of 8 self AudioFormat 1 self NumChannels NumChannels self SampleRate SampleRate self BlockAlign NumChannels int BitsPerSample 8 self BitsPerSample BitsPerSample self data bytes NumSamples self BlockAlign self __sample_mask 1 B 2 H 4 I 8 Q int self BitsPerSample 8 self __sample_mask self __sample_mask self NumChannels
we should not really have predictions that are constant ( should be some difference ) ... this captures bugs with the predict function not iterating forward,def test_predict_is_nonconstant model ARIMA data data ar 2 ma 2 x model fit predictions model predict_is h 10 intervals False assert not np all predictions values predictions values 0
tests prediction intervals are ordered correctly,def test_t_predict_intervals_bbvi model pf GAS data data ar 1 sc 1 family pf t x model fit BBVI iterations 100 predictions model predict h 10 intervals True assert np all predictions 99 Prediction Interval values predictions 95 Prediction Interval values assert np all predictions 95 Prediction Interval values predictions 5 Prediction Interval values assert np all predictions 5 Prediction Interval values predictions 1 Prediction Interval values
this method instantiates ` ensembler ` class .,def __init__ self return
"get device health state . when the core system detects some potential risk that may cause hardware failure in the future , the returned status value will be ' warning ' . but sensor can still work as normal . when sensor is in the protection stop state , the returned status value will be ' error ' . in case of warning or error statuses non - zero error code will be returned .",def get_health self self _send_cmd GET_HEALTH_BYTE dsize is_single dtype self _read_descriptor if dsize HEALTH_LEN raise RPLidarException Wrong get_info reply length if not is_single raise RPLidarException Not a single response mode if dtype HEALTH_TYPE raise RPLidarException Wrong response data type raw self _read_response dsize status _HEALTH_STATUSES _b2i raw 0 error_code _b2i raw 1 8 _b2i raw 2 return status error_code
purge action executions output objects .,def purge_execution_output_objects logger timestamp action_ref None if not timestamp raise ValueError Specify a valid timestamp to purge logger info Purging action execution output objects older than timestamp s timestamp strftime Y m dT H M S fZ filters filters timestamp__lt timestamp if action_ref filters action_ref action_ref try deleted_count ActionExecutionOutput delete_by_query filters except InvalidQueryError as e msg Bad query s used to delete execution output instances sPlease contact support filters str e raise InvalidQueryError msg except logger exception Deletion of execution output models failed for query with filters s filters else logger info Deleted s execution output objects deleted_count
the number of values in the surface .,def __len__ self return self getNX self getNY
appends a label with centered text to the bar : param layout : the layout to append to : param text : the text to render : param props : the properties or css values to use while rendering,def add_label layout text props txt QtWidgets QLabel set_text txt text if width in props txt setFixedWidth props width if css in props txt setStyleSheet dict_to_sheet props css if font family in props css and font size in props css family props css font family size int props css font size replace px txt setFont QtGui QFont family size txt setAlignment QtCore Qt AlignCenter if alignment in props if props alignment center txt setAlignment QtCore Qt AlignCenter elif props alignment left txt setAlignment QtCore Qt AlignCenter QtCore Qt AlignLeft elif props alignment right txt setAlignment QtCore Qt AlignCenter QtCore Qt AlignRight layout addWidget txt return txt
test that getting a bad path raises an error .,recorder use_cassette gfs metadata map bad def test_get_error self with pytest raises HTTPError self endpoint get_path
generates string matching the `` sre_parse . not_literal `` node from regexp . ast .,def _reverse_not_literal_node self node_data excluded self _chr node_data if self flags re IGNORECASE excluded excluded lower excluded upper return random choice self _negate excluded
creates a signature def for the savedmodel .,def get_signature_def model use_tf_sampling if use_tf_sampling return tf saved_model signature_def_utils predict_signature_def inputs pianorolls model inputs pianorolls outer_masks model inputs outer_masks outputs predictions model samples return tf saved_model signature_def_utils predict_signature_def inputs pianorolls model model pianorolls masks model model masks lengths model model lengths outputs predictions model model predictions
args : device : tests will run on the device of this id . shard_index : index number of the shard on which the test suite will run .,def __init__ self device shard_index self device device self adb android_commands AndroidCommands device device self adb SynchronizeDateTime self _http_server None self _forwarder None self _spawning_server None self _spawner_forwarder None self _forwarder_device_port 8000 self forwarder_base_url http localhost d self _forwarder_device_port self flags FlagChanger self adb self shard_index shard_index
fetch the pid of the plugin process with name |plugin_name| .,def _GetPluginPID self plugin_name child_processes self GetBrowserInfo child_processes plugin_type Plug in if plugin_name Shockwave Flash plugin_type self _flash_plugin_type for x in child_processes if x type plugin_type and re search plugin_name x name return x pid return None
create folders and then change into them .,def _CreateFolder self file_browser top_directory file_browser CurrentDirectory tree deep deeper deepest for directory in tree file_browser CreateDirectory directory file_browser ChangeDirectory directory self assertEqual file_browser CurrentDirectory top_directory join tree msg Ended up in wrong directory s file_browser CurrentDirectory
verify importing firefox bookmarks through preferences .,def testImportFirefoxBookmarksFromPrefs self self _ImportFromFirefox bookmarks True history False passwords False home_page False search_engines False
given a emission return the internal representation,def internal self emission return emission
pretty prints an error / exception message,def prettyPrintError ex exc_type exc_obj exc_tb sys exc_info fname os path split exc_tb tb_frame f_code co_filename 1 msg Error s encountered in s line s s exc_type fname exc_tb tb_lineno ex prettyPrint msg error
load an x.509 certificate from der encoded data .,abc abstractmethod def load_der_x509_certificate self data
adds user details to the shipping details form and redirects to pay page,def test_view_cart self self create_user self create_deal self login_user self driver execute_script window scrollTo 0 400 self driver implicitly_wait 10 self driver find_element_by_xpath xpath_first_deal_item click self driver find_element_by_xpath xpath_checkout_basket click self driver implicitly_wait 20 self driver find_element_by_xpath xpath_view_cart click self driver find_element_by_xpath xpath_checkout_button click self driver find_element_by_id street send_keys 12345 self driver find_element_by_id postal send_keys 5678 self driver find_element_by_id state send_keys states self driver find_element_by_id telephone send_keys 0794284244 self driver find_element_by_xpath xpath_proceed_to_pay click
checking since stored values are in terms of eur as base,def test_fixer_nzd_to_eur_value assert fixer NZD EUR 1 FIXER_RATES_JSON_TEST 0 5
wrapper to dataset constructor from fictitious ' foo ' data_source .,def build_dataset args kwargs origin source foo return Dataset origin origin args kwargs
download a file to the resources folder .,def _download_file self url filename compress False timeout 30 if not lineage create_dir self _resources_dir return None if compress and filename 3 gz filename gz destination os path join self _resources_dir filename if not os path exists destination try self _print_download_msg destination if compress open_func gzip open else open_func open with urllib request urlopen url timeout timeout as response with open_func destination wb as f data response read f write data except Exception as err print err return None return destination
preprocess jpeg encoded bytes to 3d float tensor .,def preprocess_image image_buffer image tf image decode_jpeg image_buffer channels 3 image tf image convert_image_dtype image dtype tf float32 image tf image central_crop image central_fraction 0 875 image tf expand_dims image 0 image tf image resize_bilinear image FLAGS image_size FLAGS image_size align_corners False image tf squeeze image 0 image tf subtract image 0 5 image tf multiply image 2 0 return image
generated source for method _ _ init _ _,overloaded def __init__ self
"check to see if there is a "" pageant "" agent we can talk to .",def can_talk_to_agent if _has_win32all or _has_ctypes and _get_pageant_window_object return True return False
"medfilter2d(data , window , null = none , numthrd=8 )",def medfilter2d data window null None numthrd 8 if len np shape data 2 raise ValueError input data must be 2d array try if len np shape window 2 winx int window 0 winy int window 1 elif len np shape window 1 winx int window 0 winy winx else raise ValueError unsupported window size d len window except TypeError winx int window winy winx if null is None nullv np finfo type data 0 0 max else nullv type data 0 0 null drows dcols np shape data data data flatten if data dtype np float32 data _medfilt_modc f_medfilt2d data copy dcols winx winy nullv numthrd elif data dtype np float64 data _medfilt_modc d_medfilt2d data copy dcols winx winy nullv numthrd else raise TypeError s is not a supported data type str data dtype return data reshape drows dcols
writes a string of text to a document stream . syntax,def write self text config VERBOSE config VERBOSE_DEBUG DEBUG in Document py Document write ln config VERBOSE config VERBOSE_DETAIL str text self __dict__ __dynamic append text content join self __dict__ __dynamic p PageParser self contentWindow self contentWindow __dict__ __sl 1 content True
! @brief get the audio resource maintained by the form representation . @return audio instance .,def get_audio self return self audio
return case - sensitive package name given any - case package name,def case_sensitive_name self package_name if len self environment package_name return self environment package_name 0 project_name
"test parsing of config with misspecified "" refit "" section",def test_parse_YATSM_config_5 YATSM_cfg YATSM_cfg YATSM refit prefix just_one_prefix with pytest raises KeyError config_parser _parse_YATSM_config YATSM_cfg
@todo : docstring for workingfol_func : returns : @todo,def workingfol_func arguments if not arguments o workingfol tempfile mkdtemp else workingfol os path dirname arguments o mkmovTEMPFOL4_ os path basename arguments o 4 if os path exists workingfol _lg error Working folder workingfol already exists has mkmov failed previously Please remove and restart sys exit Working folder workingfol already exists has mkmov failed previously Please remove and restart mkdir workingfol return workingfol
"this is what gets printed on the console . we 'll strip out the list or source files , since it tends to get very long . if you want to see the contents , the easiest way is to uncomment the line ' adding to tar file ' below .",def disttar_string target source env return DistTar s target 0
"handles an authentication message received on the connection . the authentication delimeter will be stripped prior to calling this method . if authentication fails , this method should raise l{error . dbusauthenticationfailed } with an error message describing the reason .",def handleAuthMessage self line
tallys the areas for each unique value found in values based on the amount within each pixel .,def summarize_areas_by_category values areas flat_values values ravel flat_areas areas ravel results dict for value in numpy ma unique flat_values if not isinstance value numpy ma core MaskedConstant results value numpy ma masked_array flat_areas mask flat_values value sum return results
calculates intersection between line going through p1 and p2 and sphere determined by centre sc and radius r.,def intersect_line_sphere p1 p2 sc r p_diff numpy array p2 numpy array p1 a numpy sum numpy multiply p_diff p_diff b 2 p2 0 p1 0 p1 0 sc 0 p2 1 p1 1 p1 1 sc 1 p2 2 p1 2 p1 2 sc 2 c sc 0 2 sc 1 2 sc 2 2 p1 0 2 p1 1 2 p1 2 2 2 sc 0 p1 0 sc 1 p1 1 sc 2 p1 2 r 2 i b b 4 a c if i 0 0 return if i 0 0 mu b 2 a return p1 0 mu p2 0 p1 0 p1 1 mu p2 1 p1 1 p1 2 mu p2 2 p1 2 if i 0 0 mu b math sqrt b 2 4 a c 2 a i1 p1 0 mu p2 0 p1 0 p1 1 mu p2 1 p1 1 p1 2 mu p2 2 p1 2 mu b math sqrt b 2 4 a c 2 a i2 p1 0 mu p2 0 p1 0 p1 1 mu p2 1 p1 1 p1 2 mu p2 2 p1 2 i_diff numpy array i2 numpy array i1 if numpy dot p_diff i_diff 0 return i2 i1 else return i1 i2
return nested constant sets 's name and content,property def sub_sets self return c for c in self _constants values if isinstance c ConstantSet
reconstructs the original attributes string according to the dialect .,def _reconstruct keyvals dialect keep_order False sort_attribute_values False if not dialect raise AttributeStringError if not keyvals return parts if constants ignore_url_escape_characters or dialect fmt gff3 attributes keyvals else attributes for k v in keyvals items attributes k for i in v attributes k append join quoter j for j in i if dialect repeated keys items for key val in attributes items if len val 1 for v in val items append key v else items append key val else items list attributes items def sort_key x try return dialect order index x 0 except ValueError return 1000000 0 if keep_order items sort key sort_key for key val in items if val if sort_attribute_values val sorted val val_str dialect multival separator join val if val_str if dialect quoted GFF2 values val_str s val_str part dialect keyval separator join key val_str elif dialect fmt gtf part dialect keyval separator join key else part key parts append part parts_str dialect field separator join parts if dialect trailing semicolon parts_str return parts_str
"plots the pairwise scatterplots for the ( observations * variables ) data matrix . inspired by p. 114 of tufte 's "" the visual display of quantitative information "" .",def multi_scatter data labels None framecolor None bins None label_offset 30 hist_kwargs None scatter_kwargs None data data transpose nvars data shape 0 nobs data shape 1 if labels is not None assert len labels nvars Length of labels d does not match number of variables d len labels nvars if bins is None bins min max np ceil nobs 10 3 100 if framecolor is None framecolor 0 8 0 8 0 8 if hist_kwargs is None hist_kwargs dict if scatter_kwargs is None scatter_kwargs dict k 1 for i in range nvars for j in range nvars plt subplot nvars nvars k k 1 if i j line_histogram data i bins hist_kwargs else pylab scatter data j data i scatter_kwargs axes matplotlib pylab gca colorframe axes framecolor if i 0 if j 2 0 axes xaxis tick_top axes xaxis set_label_position top else axes set_xticks elif i nvars 1 if j 2 1 axes xaxis tick_bottom axes xaxis set_label_position bottom else axes set_xticks if labels is not None offset_xlabel labels j axes label_offset else axes set_xticks if j 0 if i 2 1 axes yaxis tick_left axes yaxis set_label_position left else axes set_yticks elif j nvars 1 if i 2 0 axes yaxis tick_right axes yaxis set_label_position right else axes set_yticks else axes set_yticks plt subplots_adjust wspace 0 hspace 0
"yield list of [ [ ( name , stack ) , ... ] , [ ( name , stack ) , ... ] , ... ]",property def layered self result for layer in self _layered nxt for name in layer nxt append name self all_stacks name result append nxt return result
match a floating point number at the beginning of a string,def splitFloat s m FloatString match s if m return float m group float m group string return None
accept the data and draw according to them,def show clear dialog acceptData globals update dialog results PL createSpiralCurve turns nmod drawSpiralCurves PL nwires red blue if spread at PL atLength PL nparts X PL pointsAt at PL curve PolyLine X clear drawSpiralCurves PL nwires blue red if sweep CS createCrossSection draw CS draw CS wait structure CS sweep PL normal 1 0 0 0 0 0 upvector eval cross_upvector avgdir True clear smoothwire draw structure color red bkcolor cyan if nwires 1 structure structure toFormex rosette nwires 360 0 nwires toMesh draw structure color orange if flyalong flyAlong PL scale 1 1 trl 0 0 0 0 0 2 upvector 0 0 0 0 1 0 sleeptime 0 1 view front
returns the socket 's fileno . this allows us to select on this,def fileno self for sock in self socket if sock return sock fileno raise ConnectionClosedException
returns a copy of this bitarray .,def copy self return BitVector self size bits self bits
reads object based on given key from database,read_remove def read_simple self table_name key_name key sql_command self _put_spaces self sql_SELECT self sql_FROM table_name self sql_WHERE key_name self cur execute sql_command key object_data list self cur fetchone if not object_data return False return object_data
load all requirements from the specified requirements files . returns a list of requirement strings .,def load_requirements requirements_paths requirements set for path in requirements_paths requirements update line strip for line in open path readlines if is_requirement line return list requirements
check if list is assigned in ui panel .,def check_list_exist list_exist True try bpy data texts bpy context scene mg list_maze except KeyError list_exist False return list_exist
returns a list of duplication and speciation events in which the current node has been involved . scanned nodes are also labeled internally as dup = true|false . you can access this labels using the ' node.dup ' sintaxis .,def get_evol_events_from_leaf node sos_thr 0 0 root node get_tree_root outgroups root get_children if len outgroups 2 raise TypeError Tree is not rooted o1 set n name for n in outgroups 0 get_leaves o2 set n name for n in outgroups 1 get_leaves if len o2 len o1 smaller_outg outgroups 1 else smaller_outg outgroups 0 all_events current node ref_spcs node species sister_leaves set browsed_spcs set current species browsed_leaves set current fSize len n for n in root get_leaves if n species ref_spcs for n in root get_descendants root n del_feature evoltype while current up d 0 for s in current get_sisters for leaf in s get_leaves d current get_distance leaf sister_leaves add leaf sister_leaves sister_leaves difference browsed_leaves if len sister_leaves 0 current current up continue sister_spcs set n species for n in sister_leaves overlaped_spces browsed_spcs sister_spcs all_spcs browsed_spcs sister_spcs score float len overlaped_spces len all_spcs event EvolEvent event fam_size fSize event seed node name event sos score event outgroup smaller_outg name event in_seqs set n name for n in browsed_leaves event out_seqs set n name for n in sister_leaves event inparalogs set n name for n in browsed_leaves if n species ref_spcs if score sos_thr event node current up event etype D event outparalogs set n name for n in sister_leaves if n species ref_spcs event orthologs set current up add_feature evoltype D all_events append event elif score sos_thr event node current up event etype S event orthologs set n name for n in sister_leaves if n species ref_spcs event outparalogs set current up add_feature evoltype S all_events append event else pass browsed_spcs sister_spcs browsed_leaves sister_leaves sister_leaves set current current up return all_events
a node is slow in receiving pre - prepares and prepares . a lot of requests are sent and the slow node has started receiving commits outside of its watermarks and so stashes them . also this node is slow in receiving checkpoints . so a catch - up does not occur on it .,def test_non_primary_recvs_3phase_message_outside_watermarks chkFreqPatched reqs_for_logsize looper txnPoolNodeSet sdk_pool_handle sdk_wallet_client backupInstId 1 npr getNonPrimaryReplicas txnPoolNodeSet backupInstId slowReplica npr 0 slowNode slowReplica node slowNode nodeIbStasher delay ppDelay 300 backupInstId slowNode nodeIbStasher delay pDelay 300 backupInstId slowNode nodeIbStasher delay chk_delay 300 initialDomainLedgerSize slowNode domainLedger size oldStashCount slowReplica spylog count TestReplica stashOutsideWatermarks __name__ sdk_send_random_and_check looper txnPoolNodeSet sdk_pool_handle sdk_wallet_client reqs_for_logsize 2 newStashCount slowReplica spylog count TestReplica stashOutsideWatermarks __name__ assert newStashCount oldStashCount oldDiscardCounts discardCounts n replicas backupInstId for n in txnPoolNodeSet if n slowNode achieved stable checkpoint slowNode nodeIbStasher reset_delays_and_process_delayeds PREPREPARE PREPARE looper runFor waits expectedTransactionExecutionTime len txnPoolNodeSet checkNodeDataForInequality slowNode n for n in txnPoolNodeSet if n slowNode assert slowNode domainLedger size initialDomainLedgerSize reqs_for_logsize counts discardCounts n replicas backupInstId for n in txnPoolNodeSet if n slowNode achieved stable checkpoint for nm count in counts items assert count oldDiscardCounts nm oldCatchupTimes slowNode spylog count Node start_catchup slowNode nodeIbStasher reset_delays_and_process_delayeds CHECKPOINT waitNodeDataEquality looper slowNode n for n in txnPoolNodeSet if n slowNode assert slowNode domainLedger size initialDomainLedgerSize reqs_for_logsize 2 newCatchupTimes slowNode spylog count Node start_catchup assert newCatchupTimes oldCatchupTimes
wait for all child test processes to complete .,def wait self check_interval 3 print Waiting while children are out running and playing while True sleep check_interval waiting for cp in self tests if cp popen poll is None waiting append cp popen pid if not waiting break print Waiting on r waiting print All children have stopped
returns true if the given httprequest has permission to view * at least one * page in the admin site .,def has_permission self request return request user is_active and request user is_staff
"finish a stroke , that was created with new_unfinished_stroke ( ) and send it to the server , if connected .",def finish_stroke self stroke history register_draw_stroke stroke self stroke calculate_bounding_box network new_stroke self number stroke
add a ' fv ' keyword pointing to the flowvisor responsible fore this call .,decorator def get_fv func args kwargs fv_id kwargs fv_id fv DummyFV objects get id fv_id kwargs fv fv return func args kwargs
create a new user certificate after confirmation .,def user_cert_generate request user_id user get_object_or_404 User pk user_id must_have_permission request user user can_change_user_cert cert_fname get_user_cert_fname user key_fname get_user_key_fname user urn get_user_urn user username if request method POST create_x509_cert urn cert_fname key_fname DatedMessage objects post_message_to_user GCF Certificate for user s successfully created user username user request user msg_type DatedMessage TYPE_SUCCESS return HttpResponseRedirect reverse user_cert_manage args user id return simple direct_to_template request template user_cert_generate html extra_context curr_user user
read per - frame evaluation from file .,def db_read_eval technique None measure None sequence None raw_eval False inputdir cfg PATH EVAL_DIR def _listify arg func if isinstance arg str return arg elif arg is None return func else return arg measures _listify measure lambda db_read_benchmark measures techniques _listify technique lambda t name for t in db_read_techniques sequences _listify sequence lambda s name for s in db_read_sequences eval_func db_statistics if not raw_eval else lambda i i db for t in techniques db t OrderedDict db_h5 h5py File osp join inputdir t h5 r for m in measures db t m OrderedDict for s in sequences db t m s eval_func db_h5 m s return db
solo retorna informacion de la clase como string : return : nombre del servicio,def get_tipo_servicio self return 0 format self tipo_servicio
writes an entry to the log .,def write self timestamp data raise NotImplementedError
return current user data as a contact object .,def asContact self contact Contact contact url self url contact key self key contact name self name contact description self description contact date self date return contact
getting user - values from config_values module .,def __init__ self self user UserValues self latitude self user get_latitude self longitude self user get_longitude self altitude self user get_altitude self obs_time self user get_obs_time self dt TimeDelta 3600 0 format sec self airmass_list self time_list self step 0 self end_step 11
draw real - time debug information to the screen .,def debugDraw self program win textBuffer win textBuffer y x win top win left maxRow maxCol win rows win cols self writeLineRow 0 intent noIntent try intent win userIntent except pass color app color get debug_window self writeLine cRow 3d cCol 2d goalCol 2d s win textBuffer penRow win textBuffer penCol win textBuffer goalCol intent color self writeLine pRow 3d pCol 2d chRow 4d textBuffer penRow textBuffer penCol textBuffer debugUpperChangedRow color self writeLine mkrRow 3d mkrCol 2d sm d textBuffer markerRow textBuffer markerCol textBuffer selectionMode color self writeLine scrlRow 3d scrlCol 2d lines 3d win scrollRow win scrollCol len textBuffer lines color self writeLine y 2d x 2d maxRow d maxCol d baud d color d y x maxRow maxCol curses baudrate curses can_change_color color screenRows screenCols program cursesScreen getmaxyx self writeLine scr rows d cols d mlt f f pt f screenRows screenCols program mainLoopTime program mainLoopTimePeak textBuffer parserTime color self writeLine ch 3s s program ch app curses_util cursesKeyName program ch or UNKNOWN color self writeLine win r win color self writeLine foc r program programWindow focusedWindow color self writeLine tb r textBuffer color id mouseCol mouseRow mouseZ bState program debugMouseEvent self writeLine mouse id d mouseCol d mouseRow d mouseZ d id mouseCol mouseRow mouseZ color self writeLine bState s d app curses_util mouseButtonName bState bState color self writeLine startAndEnd r textBuffer startAndEnd color
"tag a file with the given arguments , just sets the accordingly named attribute on the file object .",def Tag env target source more_tags kw_tags if not target target source first_tag None else first_tag source if first_tag kw_tags first_tag 0 if len kw_tags 0 and len more_tags 0 raise UserError No tags given for x in more_tags kw_tags x if not SCons Util is_List target target target else target env Flatten target for t in target for k v in kw_tags items if k 10 PACKAGING_ k PACKAGING_ k setattr t k v
returns true if the strings look the same .,def match_visible self str1 str2 str1 re sub t r n n str1 n str2 re sub t r n n str2 n return str1 str2
override this to configure the angular app .,def _get_config self return
remove comments that repeat themselves .,def remove_repeated_comments node last_comment text None for _node in gast walk node if anno hasanno _node comment comment anno getanno _node comment if comment text last_comment text anno delanno _node comment last_comment comment return node
copy src_file to temp file and then rename it to dst_file .,def safe_copy src_file dst_file temp_dst_file s temp dst_file copy src_file temp_dst_file os rename temp_dst_file dst_file
return a list of all the resource requests this test makes .,classmethod def get_resource_requests cls all_requests list cls resources for field_name field in cls get_resource_requests_fields new_request request field_name field __class__ field kwargs if new_request not in all_requests all_requests append new_request return all_requests
delete node with value from the tree,def delete self value if self value value if not self right raise Exception Value not found d value else self right self right delete value if self value value if not self left raise Exception Value not found d value else self left self left delete value if self value value if self middle None and self left None and self right None return None if self middle self middle self middle delete value elif self right and self left parent succ self right find_min self if parent left succ parent left succ left else parent right succ left succ left self left succ right self right return succ elif self right return self right else return self left return self
creating a particular colormap with transparency .,def alpha_cmap color red opacity 1 0 color1 colorConverter to_rgba white color2 colorConverter to_rgba color mycmap mpl colors LinearSegmentedColormap from_list my_cmap color1 color2 256 mycmap _init alphas np zeros mycmap N 3 alphas 255 opacity mycmap _lut 1 alphas return mycmap
test iterating over empty results .,def test_empty self u def pretend_fetcher page per_page return ri BatchedResultsIterator entity model Shoe result_fetcher pretend_fetcher results list ri self assertEquals 0 len results
base function to produce exponential with defined coefficients,def _baseExponential self coefficients x num 3 if len coefficients num if num 3 return numpy exp coefficients 0 x coefficients 1 coefficients 2 else print Error else print Error
"converts the metric input files to use the new data objects @ in , tree , xml.etree.elementtree.elementtree object , the contents of a raven input file @ in , filename , the name for the raven input file @out , tree , xml.etree.elementtree.elementtree object , the modified raven input file",def convert tree fileName None simulation tree getroot models simulation find Models hasDataObjects True hasOutStreams True dataObjects simulation find DataObjects if dataObjects is None dataObjects ET Element DataObjects hasDataObjects False outStreams simulation find OutStreams if outStreams is None outStreams ET Element OutStreams hasOutStreams False steps simulation find Steps postProcess steps findall PostProcess if models is None return tree modelNames romTargets scoreDict for model in models if model tag PostProcessor and model attrib subType CrossValidation metrics model findall Metric metricNames modelNames append model attrib name for metric in metrics metricName metric text strip metricNames append metricName sklNode model find SciKitLearn score sklNode find scores if score is not None scoreDict model attrib name True else scoreDict model attrib name False if model tag ROM romTargets model attrib name var strip for var in model find Target text split for modelName in modelNames dataSetName modelName _cv printNode ET Element Print printNode attrib name dataSetName _dump typeNode ET SubElement printNode type typeNode text csv sourceNode ET SubElement printNode source sourceNode text dataSetName outStreams append printNode for pp in postProcess if modelName pp find Model text strip inputs pp findall Input for inputObj in inputs if inputObj attrib class Models romName inputObj text strip varNames for metricName in metricNames for targs in romTargets romName varName cv _ metricName _ targs varNames append varName if not scoreDict modelName varNames append RAVEN_CV_ID dataSet ET Element PointSet dataSet attrib name dataSetName outNode ET SubElement dataSet Output outNode text join varNames dataObjects append dataSet outputs pp findall Output remove False hasPrint False for output in outputs if output attrib class Files output attrib class DataObjects output attrib type PointSet output text dataSetName if remove pp remove output else remove True elif output attrib class OutStreams and output attrib type Print output text dataSetName _dump hasPrint True elif output attrib class DataObjects pp remove output if not hasPrint printNode ET SubElement pp Output printNode attrib class OutStreams printNode attrib type Print printNode text dataSetName _dump if not hasDataObjects simulation append dataObjects if not hasOutStreams simulation append outStreams return tree
"when the user hovers over the button this callback will remove the transparency from the button @ in , event , pyside . qtcore . qevent , the event that triggers this callback , namely a mouse over event . @ out , none",def enterEvent self event super OverlayButton self enterEvent event self setStyleSheet background color rgba 51 73 96 75 color rgba 236 240 241 100 opacity 0 75
"function to read the portion of the xml input that belongs to this specialized class and initialize some variables based on the inputs got . @ in , xmlnode , xml.etree.elementtree.element , xml element node that represents the portion of the input that belongs to this class @ out , none",def _readMoreXML self xmlNode u n Function to read the portion of the xml input that belongs to this specialized class n and initialize some variables based on the inputs got n In xmlNode xml etree ElementTree Element XML element node that represents the portion of the input that belongs to this class n Out None n pass
translates from torrent fields names in terms of rpc to field names in term of torrt . updates accordingly a given torrent_info .,classmethod def normalize_field_names cls torrent_info for old_name new_name in cls torrent_fields_map items if old_name in torrent_info torrent_info new_name torrent_info old_name
split given bucket into two buckets : param kbucket bucket : bucket to be split,def split_bucket self bucket logger debug Splitting bucket buck1 buck2 bucket split idx self buckets index bucket self buckets idx buck1 self buckets insert idx 1 buck2
returns a list of fluctuations with the fluctuation overrides already applied,staticmethod def get_fluctuations_with_overrides_applied fluctuations default_fluctuation_ratio fluctuation_overrides ret_fluctuations for fluc_id in fluctuations keys fluc fluctuations fluc_id ignore False ratio_to_apply default_fluctuation_ratio if fluc_id in fluctuation_overrides fluc_info fluctuation_overrides fluc_id ratio_to_apply fluc_info value ignore fluc_info ignore if ignore continue if fluc parent has_results and abs fluc parent fluctuation_ratio ratio_to_apply ret_fluctuations fluc_id fluc continue if fluc son has_results and abs fluc son fluctuation_ratio ratio_to_apply ret_fluctuations fluc_id fluc continue return len ret_fluctuations keys 0 ret_fluctuations
"returns a list of all descendants of phi , including phi itself",def descendants phi q deque phi d list while len q 0 node q popleft if not is_element_of node d d append node q extend c for c in children node if not is_element_of c d return d
recursively add linebreaks to elementtree children .,def _prettifyETree self elem i n if util isBlockLevel elem tag and elem tag not in code pre if not elem text or not elem text strip and len elem and util isBlockLevel elem 0 tag elem text i for e in elem if util isBlockLevel e tag self _prettifyETree e if not elem tail or not elem tail strip elem tail i if not elem tail or not elem tail strip elem tail i
"ask a question ; return true if the answer is yes , none if cancelled .",def askyesnocancel title None message None options s _show title message QUESTION YESNOCANCEL options s str s if s CANCEL return None return s YES
a simple 1d histogram with normal distribution .,def normal_h1 size 10000 mean 0 sigma 1 data np random normal mean sigma size return h1 data name normal axis_name x title 1D normal distribution
suppresses all warnings that are of type clazz or derived from clazz .,def suppressWarningClass clazz _enabled insert 0 clazz 0
"an iterator over the ' words ' in the given text , as defined by the regular expression given as separator .",def _wordIter text separator exp re compile separator pos 0 for occ in exp finditer text sub text pos occ start strip if sub yield sub pos occ start 1 if pos len text sub text pos strip if sub yield sub
we 'll setup the network to have 3 nodes that all mine with different parameters . but first we need to use one node to create a lot of outputs which we will use to generate our transactions .,def setup_network self self add_nodes 3 extra_args maxorphantx 1000 whitelist 127 0 0 1 blockmaxsize 17000 maxorphantx 1000 blockmaxsize 8000 maxorphantx 1000
"od.items ( ) - > list of ( key , value ) pairs in od",def items self return key self key for key in self
floor a float then turn it into an int .,def int_floor float_num return int np floor float_num
function creates temporary copies of ode and set files .,def createTmp ode_file None set_file None if ode_file None shutil copy ode_file tmp_ode if set_file None shutil copy set_file tmp_set if ode_file None and set_file None print Warning No files where created both ode and set arguments are None
"returns the name of the currently checked - out branch of the git repository at the path `` chdir `` ( default : the current directory ) , or ` none ` if the repository is in a detached head state",def get_current_branch chdir None return cmdline git symbolic ref short q HEAD cwd chdir or None
log the packages provided & depended on by this build,def dump_build_information args pkgbuild os path join args abs_dir PKGBUILD provides provides strip_version_info name for name in interpret_bash_array pkgbuild pkgname provides strip_version_info name for name in interpret_bash_array pkgbuild provides log provide_info None output provides depends depends strip_version_info name for name in interpret_bash_array pkgbuild depends depends strip_version_info name for name in interpret_bash_array pkgbuild makedepends log dep_info This build depends on the following packages output depends
read sdf file into an rdkit ` mol ` object .,def mol_from_sdf sdf_file conf_num None standardise False mol None conf_energies with smart_open sdf_file rb as f supplier rdkit Chem ForwardSDMolSupplier f i 0 while True if i conf_num break try new_mol next supplier except StopIteration logging debug Read d conformers from format i sdf_file break if new_mol HasProp CONF_ENERGY_PROPNAME conf_energies append float new_mol GetProp CONF_ENERGY_PROPNAME if mol is None mol rdkit Chem Mol new_mol mol RemoveAllConformers conf new_mol GetConformers 0 mol AddConformer conf assignId True i 1 if standardise mol mol_to_standardised_mol mol try mol GetProp _Name except KeyError name os path basename sdf_file split sdf 0 mol SetProp _Name name if len conf_energies 0 add_conformer_energies_to_mol mol conf_energies mol ClearProp CONF_ENERGY_PROPNAME return mol
verifier sent with each rpc call,def make_verf self data return self _none
test response to server returning nfs4err_badsession error on solo sequence for lease renewal,def testSessionReset2 t env cd HOME echo NFS4ERR_BADSESSION CONFIG ops sequence and wait the server leasetime so that client renews lease cd ROOT os chdir env home env set_error_wait_lease sequence NFS4ERR_BADSESSION os chdir env root env clear_two_values sequence
sets or returns the width of the widget .,property def width self return super ListBox self __class__ width fget self
write all buffers to file .,def flush self if len self __simulation_time_buffer 0 and len self __step_buffer 0 and len self __types_buffer 0 self __writeToFile self __simulation_time_buffer self __step_buffer self __types_buffer self __simulation_time_buffer self __step_buffer self __types_buffer
calculates the one - sided autocorrelation function .,def calculate_acf data delta_t 1 0 unbiased False Calculates the one sided autocorrelation function Calculates the autocorrelation function ACF and returns the one sided ACF The ACF is defined as the autocovariance divided by the variance The ACF can be estimated using math hat R k frac 1 n sigma 2 sum_ t 1 n k left X_ t mu right left X_ t k mu right Where math hat R k is the ACF math X_ t is the data series at time t math mu is the mean of math X_ t and math sigma 2 is the variance of math X_ t Parameters data TimeSeries or numpy array A TimeSeries or numpy array of data delta_t float The time step of the data series if it is not a TimeSeries instance unbiased bool If True the normalization of the autocovariance function is n k instead of n This is called the unbiased estimation of the autocovariance Note that this does not mean the ACF is unbiased Returns acf numpy array If data is a TimeSeries then acf will be a TimeSeries of the one sided ACF Else acf is a numpy array if isinstance data TimeSeries y data numpy delta_t data delta_t else y data y y y mean ny_orig len y npad 1 while npad 2 ny_orig npad npad 1 ypad numpy zeros npad ypad ny_orig y fdata TimeSeries ypad delta_t delta_t to_frequencyseries cdata FrequencySeries zeros len fdata dtype numpy complex64 delta_f fdata delta_f copy False correlate fdata fdata cdata acf cdata to_timeseries acf acf ny_orig if unbiased acf y var numpy arange len acf 0 1 else acf acf 0 if isinstance data TimeSeries return TimeSeries acf delta_t delta_t else return acf
break internal references within the document tree rooted on this element to promote garbage collection .,def unlink self ligolw Array unlink self self array None
format the date in a local aware format .,def format_date dt set_timezone True format None from pylons import tmpl_context as c if format is None format u long if set_timezone dt local_datetime dt return babel dates format_date dt format format locale c locale or babel Locale en US
files stay in the remote directory .,def test_option_keep_remote command command keep_remote True command main remote_paths set command remote_dir scan_paths memoize False assert remote_paths TEST_PATHS
"a 4-byte , big - endian crc32 checksum",def write_crc32 fo bytes data crc32 bytes 4294967295 fo write pack I data
compute the satisfiability of the stopping criteria based on stopping parameters and objective function value .,def is_satisfied self p_obj c_obj iter if self max_iter and self max_iter iter return False if self test_conv and iter self test_conv 0 return True if self min_residuals and iter 0 and p_obj c_obj self min_residuals return False if iter 0 and c_obj p_obj return False if self rel_error and self error_v_n self rel_error return False return True
add a html - page - context and a build - finished event handlers,def setup app app connect html page context change_pathto app connect build finished move_private_folders
initialize the parameters of the logistic regression,def __init__ self input n_in n_out W None b None if W is None self W theano shared value np zeros n_in n_out dtype theano config floatX name W else self W W if b is None self b theano shared value np zeros n_out dtype theano config floatX name b else self b b self p_y_given_x T nnet softmax T dot input self W self b self y_pred T argmax self p_y_given_x axis 1 self params self W self b
return the p+l for our current position ( not including past realized p+l.,def pnl self return self _realized_pnl self unrealized_pnl
load transform data from an edge list into the current scene graph .,def load self edgelist self from_edgelist edgelist strict True
constructs a thrift experimentevent object with appropriate fields .,def make_event self syncer return modeldb_types ExperimentEvent self experiment
only load if the platform is correct and we can use pyobjc libs,def __virtual__ if __grains__ get kernel Darwin return False if not HAS_LIBS return False if not _IOBluetoothPreferencesAvailable return False return __virtualname__
! convert updatebuffer object to string .,def __str__ self return format self __class__ __name__ self dataIdentifiers
handles a request . return value is a tuple where element 0 is the response object and element 1 is a dictionary of items to log .,def handle_request self query request mode request_pdu None response_pdu slave_id None function_code None func_code None slave None response None try slave_id request_pdu query parse_request request if len request_pdu 0 func_code struct unpack B request_pdu 0 logger debug Working mode s mode if mode tcp if slave_id 0 or slave_id 255 slave self get_slave slave_id response_pdu slave handle_request request_pdu response query build_response response_pdu else r struct pack BB func_code 128 defines SLAVE_DEVICE_FAILURE response query build_response r elif mode serial if slave_id 0 for key in self _slaves response_pdu self _slaves key handle_request request_pdu broadcast True return None request request_pdu encode hex slave_id slave_id function_code func_code response elif 0 slave_id 247 slave self get_slave slave_id response_pdu slave handle_request request_pdu response query build_response response_pdu else r struct pack BB func_code 128 defines SLAVE_DEVICE_FAILURE response query build_response r except MissingKeyError IOError as e logger error e r struct pack BB func_code 128 defines SLAVE_DEVICE_FAILURE response query build_response r except ModbusInvalidRequestError as e logger error e if slave function_code slave function_code return response request request_pdu encode hex slave_id slave_id function_code function_code response response_pdu encode hex
check whether two bayesian networks belong to the same equivalence class .,def are_class_equivalent x y are_equivalent True if set list x nodes set list y nodes are_equivalent False else for rv in x nodes rv_x_neighbors set x parents rv set y children rv rv_y_neighbors set y parents rv set y children rv if rv_x_neighbors rv_y_neighbors are_equivalent False break return are_equivalent
tells you if you have an old version of ndio .,def check_version import requests r requests get https pypi python org pypi ndio json json r r info version if r version print A newer version of ndio is available pip install U ndio to update return r
test that basic multi - target encryption / decryption works .,def testEncTargetsDec self pt hello encode utf 8 with self srvA with self srvB out self __encrypt pt self ca_A self srvA self srvB assert out is not None assert self __targets out self srvA hp self srvB hp with self srvA assert self __decrypt out pt with self srvB assert self __decrypt out pt assert self __decrypt out is None
register the * address * of global symbol * name*. this will make it usable ( e.g. callable ) from llvm - compiled functions .,def add_symbol name address ffi lib LLVMPY_AddSymbol _encode_string name c_void_p address
return a state of the current rulesets .,def get_state self return self rulesets copy
"adapting numpy.int64 type to sql - conform int type using psycopg extension , see [ 1 ] _ for more info .",def adapt_numpy_int64 numpy_int64 return AsIs numpy_int64
return the set of names of all resources in the template .,def all_rsrc_names self if hasattr self _template RESOURCES return set self _template get self _template RESOURCES self _resource_defns or else return self enabled_rsrc_names
"higher weights win . our multiplier is negative , so reduce our weight by number of failed builds .",def _weigh_object self host_state weight_properties return host_state failed_builds
disable an existing agent build .,def test_service_disable self subs host host1 binary nova compute response self _do_put os services disable service disable put req subs self _verify_response service disable put resp subs response 200
get the nic and vswitch info,def guest_get_nic_vswitch_info self name return self _reqh call guest_get_nic_vswitch_info name
"match a device to this pciaddress . assume this is called given pci_addr and pci_phys_addr reported by libvirt , no attempt is made to verify if pci_addr is a vf of pci_phys_addr .",def match self pci_addr pci_phys_addr if self is_physical_function and pci_phys_addr pci_phys_addr_obj PhysicalPciAddress pci_phys_addr if self pci_address_spec match pci_phys_addr_obj return True pci_addr_obj PhysicalPciAddress pci_addr return self pci_address_spec match pci_addr_obj
remove the temporal dimension from the field by only keeping the field for the first time instant .,def slice_field self field_name self fields field_name self fields field_name 0
overwrites the standard parse function so that we can specify this tag in the input without any data .,def parse self xml None text try super InputCheckpoint self parse xml text except self value 0
"return the "" extras "" tags associated with this resolvable if any .",def extras self interpreter None return
prints results from aggregate event / field dictionaries,def print_results events custom_fields source_tag print nSOURCE s source_tag print sorted_event_keys sorted events iterkeys for key in sorted_event_keys if events key 0 result hilite str events key True True else result hilite str events key False True print 40s t s key result print sorted_custom_field_keys sorted custom_fields iterkeys for key in sorted_custom_field_keys if custom_fields key 0 result hilite str custom_fields key True True else result hilite str custom_fields key False True print 40s t s key result
return value of the objective function ( sum of all energies ) .,def get_potential_energy self return sum self calc get_potential_energy image for image in self images
returns a string that once printed is colorized ( copied from putil.misc ),def pcolor text color indent 0 esc_dict black 30 red 31 green 32 yellow 33 blue 34 magenta 35 cyan 36 white 37 none 1 if not isinstance text str raise RuntimeError Argument text is not valid if not isinstance color str raise RuntimeError Argument color is not valid if not isinstance indent int raise RuntimeError Argument indent is not valid color color lower if color not in esc_dict raise ValueError Unknown color color format color color if esc_dict color 1 return x1b color_code m indent text x1b 0m format color_code esc_dict color indent indent text text return indent text format indent indent text text
return api for working with airplay .,abstractproperty def airplay self raise exceptions NotSupportedError
"index view is associated with the dashboard ( home ) view of the application . it shows the user a table of current batches , and an overall summary .",def index_view request batches Batch objects all context active dashboard batches batches title Dashboard context is_watching is_watching return render request main index html context
input : name ( string ) : name of the instrument address ( string ) : instrument ( serial port ) address,def __init__ self name address logging debug __name__ Initializing instrument Instrument __init__ self name tags physical self _address address self _visainstrument visa SerialInstrument self _address delay 0 03 self _values self _visainstrument stop_bits 1 self reset self add_parameter b_raw type types IntType flags Instrument FLAG_GET self add_parameter counts type types IntType flags Instrument FLAG_GETSET self add_function get_all self get_all
updates the parameters : tooling factor density z - ration for a selected material,def set_material self material materials Al tooling factor 82 0 Z ratio 1 08 density 2 7 AlO tooling factor 75 Z ratio 2 08 density 2 314 tooling materials material 0 1 zratio materials material 1 1 density materials material 2 1 self remote_cmd self cmds update_tooling tooling time sleep 0 1 self remote_cmd self cmds update_density density time sleep 0 1 self remote_cmd self cmds update_zratio zratio return materials material
remove the sample : raise : irmafilesystemerror if there is a problem with the filesystem,def remove_file_from_fs self try try if self path is None log debug s File already deleted self sha256 return log debug Removing s self path os remove self path except OSError log info s File already deleted self sha256 finally self path None
nx : dllcharacteristics bit 0x100 signifies nxcompat ( dep ),def check_PE_NX executable arch bits get_PE_dll_characteristics executable return bits IMAGE_DLL_CHARACTERISTICS_NX_COMPAT IMAGE_DLL_CHARACTERISTICS_NX_COMPAT
before we deal with our child object we get a chance to do some processing,def _processChildObjects cls for container in cls _getContainerControls container _processChildObject
get the index from a transaction composite key .,def get_txck_index txck return txck 1048575
advance overridden time using a datetime.timedelta .,def advance_time_delta timedelta assert not utcnow override_time is None utcnow override_time timedelta
"return a tuple ( string , af_inet ) for ' ip / cidr ' strings raise an exception if input is invalid",def validate_net cidr if not in cidr raise ValueError Invalid net Expects a CIDR IP mask format cidr ip net cidr split ip version validate_ip ip if version AF_INET count 0 for i in net split if 0 int i 256 count 1 if count 1 and int i 32 return cidr version if count 4 return cidr version raise ValueError Invalid IPv4 netmask format net elif not re match d net and int net 128 raise ValueError Invalid IPv6 netmask format net return cidr version
return the list of all multi - indices within the specified bounds .,def multi_indices n iterables range ni for ni in n return np asarray b dtype np intc for b in itertools product iterables
"returns true if there are existing iptables rules which may cause conflict with the connection redirection / forwarding , false otherwise .",staticmethod def existing_rules try stdout _ subprocess Popen iptables L split stdout subprocess PIPE stderr subprocess PIPE communicate for x in stdout splitlines if x and not x startswith Chain and not x startswith target return True except subprocess CalledProcessError OSError pass return False
returns the parser for the module command,pytest fixture scope module def parser prs argparse ArgumentParser spack cmd find setup_parser prs return prs
returns a list or set of valid components that match the requested components from `` components `` .,property def _filtered_components self if self components ALL return self components matches set for valid in _valid_components for requested in self components if valid startswith requested matches add valid return matches
this method creates a ' host - config ' file that specifies all of the options used to configure and build ascent .,def create_host_config self spec prefix py_site_pkgs_dir None c_compiler env SPACK_CC cpp_compiler env SPACK_CXX f_compiler None if self compiler fc if os path isfile env SPACK_FC f_compiler env SPACK_FC sys_type spec architecture if SYS_TYPE in env sys_type env SYS_TYPE if cmake in spec cmake_exe spec cmake command path else cmake_exe which cmake if cmake_exe is None msg failed to find CMake and cmake variant is off raise RuntimeError msg cmake_exe cmake_exe path host_cfg_fname s s s ascent cmake socket gethostname sys_type spec compiler cfg open host_cfg_fname w cfg write n cfg write spack generated host config n cfg write n cfg write 0 1 n format sys_type spec compiler cfg write n n cfg write cmake from spack n cfg write cmake executable path s n n cmake_exe cfg write n cfg write using s compiler spec n spec compiler cfg write n n cfg write c compiler used by spack n cfg write cmake_cache_entry CMAKE_C_COMPILER c_compiler cfg write cpp compiler used by spack n cfg write cmake_cache_entry CMAKE_CXX_COMPILER cpp_compiler cfg write fortran compiler used by spack n if f_compiler is not None cfg write cmake_cache_entry ENABLE_FORTRAN ON cfg write cmake_cache_entry CMAKE_Fortran_COMPILER f_compiler else cfg write no fortran compiler found n n cfg write cmake_cache_entry ENABLE_FORTRAN OFF cfg write conduit from spack n cfg write cmake_cache_entry CONDUIT_DIR spec conduit prefix cfg write Python Support n if python in spec cfg write Enable python module builds n cfg write cmake_cache_entry ENABLE_PYTHON ON cfg write python from spack n cfg write cmake_cache_entry PYTHON_EXECUTABLE spec python command path if py_site_pkgs_dir cfg write cmake_cache_entry PYTHON_MODULE_INSTALL_PREFIX py_site_pkgs_dir else cfg write cmake_cache_entry ENABLE_PYTHON OFF if doc in spec cfg write cmake_cache_entry ENABLE_DOCS ON cfg write sphinx from spack n sphinx_build_exe join_path spec py sphinx prefix bin sphinx build cfg write cmake_cache_entry SPHINX_EXECUTABLE sphinx_build_exe else cfg write cmake_cache_entry ENABLE_DOCS OFF cfg write MPI Support n if mpi in spec cfg write cmake_cache_entry ENABLE_MPI ON cfg write cmake_cache_entry MPI_C_COMPILER spec mpi mpicc cfg write cmake_cache_entry MPI_CXX_COMPILER spec mpi mpicxx cfg write cmake_cache_entry MPI_Fortran_COMPILER spec mpi mpifc mpiexe_bin join_path spec mpi prefix bin mpiexec if os path isfile mpiexe_bin if self spec cmake satisfies 3 10 cfg write cmake_cache_entry MPIEXEC_EXECUTABLE mpiexe_bin else cfg write cmake_cache_entry MPIEXEC mpiexe_bin else cfg write cmake_cache_entry ENABLE_MPI OFF cfg write CUDA Support n if cuda in spec cfg write cmake_cache_entry ENABLE_CUDA ON else cfg write cmake_cache_entry ENABLE_CUDA OFF cfg write vtk h support n if vtkh in spec cfg write tbb from spack n cfg write cmake_cache_entry TBB_DIR spec tbb prefix cfg write vtk m from spack n cfg write cmake_cache_entry VTKM_DIR spec vtkm prefix cfg write vtk h from spack n cfg write cmake_cache_entry VTKH_DIR spec vtkh prefix else cfg write vtk h not built by spack n cfg write adios support n if adios in spec cfg write cmake_cache_entry ADIOS_DIR spec adios prefix else cfg write adios not built by spack n cfg write n cfg write end spack generated host config n cfg write n cfg close host_cfg_fname os path abspath host_cfg_fname tty info spack generated conduit host config file host_cfg_fname return host_cfg_fname
called before test process is exited .,def pytest_unconfigure config
"create a scores object from a file , where each line in the file describes a score for one document .",staticmethod def from_file file scores for line in file readlines scores append Score line split return Scores scores
get linux standard base ( lsb ) information,def lsb_release data subprocess check_output lsb_release a split _os codename data 2 lower data 1 lower return _os codename
"given a username , email address and password , register a new user account , which will initially be inactive .",def register self request kwargs username email password language kwargs username kwargs email kwargs password1 kwargs language if Site _meta installed site Site objects get_current else site RequestSite request new_user RegistrationProfile objects create_inactive_user username email password language site signals user_registered send sender self __class__ user new_user request request return new_user
convert markdown source to html .,def markdown2html source no_p False if __mdx_checklist__ mkd markdown Markdown output_format html5 extensions smarty extra ChecklistExtension MathJaxExtension else mkd markdown Markdown output_format html5 extensions smarty extra MathJaxExtension markup mkd reset convert source if no_p p_start p p_end p if markup startswith p_start and markup endswith p_end markup markup len p_start len p_end return markup
method returning slide 's css .,def get_css self only_custom False css if self overtheme css self overtheme slide get_css only_custom only_custom as_list True if len css 0 return join n slide str self number c 1 for c in css else return
method for putting toc element .,staticmethod def put_toc doc style deep with doc tag div if style doc attr style style doc asis toc str deep return
"convenience wrapper to take a series of date / time elements and return a wmi time of the form ` yyyymmddhhmmss.mmmmmm+uuu ` . all elements may be int , string or omitted altogether . if omitted , they will be replaced in the output string by a series of stars of the appropriate length . : param year : the year element of the date / time : param month : the month element of the date / time : param day : the day element of the date / time : param hours : the hours element of the date / time : param minutes : the minutes element of the date / time : param seconds : the seconds element of the date / time : param microseconds : the microseconds element of the date / time : param timezone : the timeezone element of the date / time : returns : a wmi datetime string of the form : ` yyyymmddhhmmss.mmmmmm+uuu `",def from_time year None month None day None hours None minutes None seconds None microseconds None timezone None def str_or_stars i length if i is None return length else return str i rjust length 0 wmi_time wmi_time str_or_stars year 4 wmi_time str_or_stars month 2 wmi_time str_or_stars day 2 wmi_time str_or_stars hours 2 wmi_time str_or_stars minutes 2 wmi_time str_or_stars seconds 2 wmi_time wmi_time str_or_stars microseconds 6 if timezone is None wmi_time else try int timezone except ValueError wmi_time else if timezone 0 wmi_time else wmi_time timezone abs timezone wmi_time str_or_stars timezone 3 return wmi_time
residual function that handles different inputs and outputs inner dims .,def gnmt_residual_fn inputs outputs def split_input inp out out_dim out get_shape as_list 1 inp_dim inp get_shape as_list 1 return tf split inp out_dim inp_dim out_dim axis 1 actual_inputs _ nest map_structure split_input inputs outputs def assert_shape_match inp out inp get_shape assert_is_compatible_with out get_shape nest assert_same_structure actual_inputs outputs nest map_structure assert_shape_match actual_inputs outputs return nest map_structure lambda inp out inp out actual_inputs outputs
send an email to the author about a new comment,def emailComment comment obj request if not obj author frog_prefs get json emailComments return if obj author request user return html render_to_string frog comment_email html user comment user comment comment comment object obj action_type commented on image isinstance obj Image SITE_URL FROG_SITE_URL subject Comment from format getSiteConfig name comment user_name fromemail comment user_email to obj author email text_content This is an important message html_content html send_mail subject text_content fromemail to html_message html_content
"return a list of n random floats in [ 0 , 1 ) .",def randfloats n fn os path join td rr 06d n try fp open fn rb except IOError r random random result r for i in xrange n try try fp open fn wb marshal dump result fp fp close fp None finally if fp try os unlink fn except os error pass except IOError as msg print can t write fn msg else result marshal load fp fp close for i in range 10 i random randrange n temp result i del result i temp reverse result extend temp del temp assert len result n return result
"return the last modification time of a file , reported by os.stat ( ) .",def getmtime filename return os stat filename st_mtime
return the hash value of this hashing object .,def digest self h self _current return h digest
return the total time spent on the process .,def processtime user system systimes return user system
log [ rlog - options ] [ file ] ...,def do_log self opts files self cvs log files opts
returns article that matches publish_id .,property def published_article self return self history get history_id self publish_id instance
converts a single resource dict from redmine result set to resource object,def to_resource self resource return self resource_class self resource
evaluate model on dataset for a number of steps .,def evaluate dataset_path with tf Graph as_default with tf device cpu 0 train_dir Path FLAGS checkpoint_dir reference_shape mio import_pickle train_dir reference_shape pkl images gt_truth inits _ data_provider batch_inputs dataset_path reference_shape batch_size FLAGS batch_size is_training False mirrored_images _ mirrored_inits shapes data_provider batch_inputs dataset_path reference_shape batch_size FLAGS batch_size is_training False mirror_image True print Loading model with tf device FLAGS device patch_shape FLAGS patch_size FLAGS patch_size pred _ _ mdm_model model images inits patch_shape patch_shape tf get_variable_scope reuse_variables pred_mirrored _ _ mdm_model model mirrored_images mirrored_inits patch_shape patch_shape pred_images tf py_func utils batch_draw_landmarks images pred tf float32 gt_images tf py_func utils batch_draw_landmarks images gt_truth tf float32 summaries summaries append tf image_summary images tf concat 2 gt_images pred_images max_images 5 avg_pred pred tf py_func flip_predictions pred_mirrored shapes tf float32 0 avg_pred 2 0 norm_error mdm_model normalized_rmse avg_pred gt_truth variable_averages tf train ExponentialMovingAverage mdm_train MOVING_AVERAGE_DECAY variables_to_restore variable_averages variables_to_restore saver tf train Saver variables_to_restore summary_op tf merge_summary summaries graph_def tf get_default_graph as_graph_def summary_writer tf train SummaryWriter FLAGS eval_dir graph_def graph_def while True _eval_once saver summary_writer norm_error summary_op if FLAGS run_once break time sleep FLAGS eval_interval_secs
writes content to directory / name .,def write self directory with open os path join directory self name w as f f write self content
loads the dump from the root folder into the main loop .,def load_to self main_loop logger info Reloading model try logger debug loading model parameters params_all self load_parameters params_this main_loop model get_parameter_dict missing set params_this keys set params_all keys for pname in params_this keys if pname in params_all val params_all pname if params_this pname get_value shape val shape logger warning Dimension mismatch for format params_this pname get_value shape val shape pname params_this pname set_value val logger debug Loaded to CG 15 format val shape pname else logger warning Parameter does not exist format pname logger info Number of parameters loaded for computation graph format len params_this len missing except Exception as e logger error Error 0 format str e try logger info Loading iteration state iter_state self load_iteration_state if self slim_iteration_state try main_loop epoch_iterator iter_state except logger warn Stored iteration state not slim Trying to load as full state main_loop iteration_state iter_state else try main_loop iteration_state iter_state except logger warn Stored iteration state not full Trying to load as slim state main_loop epoch_iterator iter_state except Exception as e logger error Error 0 format str e try logger info Loading log main_loop log self load_log except Exception as e logger error Error 0 format str e
"returns html markup of "" from "" / "" to "" text lines",def _format_line self side flag linenum text try linenum d linenum id id s s self _prefix side linenum except TypeError id text text replace amp replace gt replace lt text text replace nbsp rstrip color if x00 in text or x00 in text or x00 in text color background color 0 if side 0 color color format ffe6e6 else color color format e3ffe3 return self TD_DIFF_HEADER format id linenum color text
returns sws notices for a given regid with myuw specific categories,def _get_notices_by_regid user_regid if user_regid is None return None notices get_notices_by_regid user_regid if notices is None return None return categorize_notices notices
initial tests data for individual testcases .,def setUp self users initial_users for user_type user_instance in users items setattr self user_type user_instance
compile the network for this test,classmethod def setUpClass self BuiltinFuncs Neuron equations r modulo t 3 pop1 Population 1 BuiltinFuncs mon Monitor pop1 r self test_net Network self test_net add pop1 mon self test_net compile silent True self test_mon self test_net get mon
prints the text with a new line before and after it . : param text : the text .,def print_spaced text print n n format text
guess whether a python source file is a part of the tensorflow library .,def guess_is_tensorflow_py_library py_file_path if not is_extension_uncompiled_python_source py_file_path and not is_extension_compiled_python_source py_file_path raise ValueError Input file path s is not a Python source file py_file_path py_file_path os path normpath os path abspath py_file_path return py_file_path startswith _TENSORFLOW_BASEDIR and not py_file_path endswith _test py and not os path dirname py_file_path endswith os path normpath python debug examples
adds the root name to a name .,def _add_prefix self name return self _prefix name if name else self _root_name
attempt to wrap a non - session - type object should cause an exception .,def testSessionInitInvalidSessionType self wrapper TestDebugWrapperSessionBadAction self _sess with self assertRaisesRegexp TypeError Expected type got type TestDebugWrapperSessionBadAction wrapper
@p parent operator @exprs list of function that take the tuple as input and outputs a scalar value @aliases name of the fields defined by the above exprs,def __init__ self c exprs aliases None super Project self __init__ c self exprs exprs self aliases list aliases or self set_default_aliases
create required number of host mac addresses and distribute them among interfaces . create host ipv4 address for every host mac address . create l2 mac packet stream with host mac addresses per interface to let the bridge domain learn these mac addresses .,classmethod def create_hosts_and_learn cls count n_int len cls pg_interfaces macs_per_if count n_int i 1 for pg_if in cls pg_interfaces i 1 start_nr macs_per_if i end_nr count if i n_int 1 else macs_per_if i 1 cls hosts_by_pg_idx pg_if sw_if_index hosts cls hosts_by_pg_idx pg_if sw_if_index packets for j in range start_nr end_nr host Host 00 00 00 ff 02x 02x pg_if sw_if_index j 172 17 1 02x u pg_if sw_if_index j packet Ether dst ff ff ff ff ff ff src host mac hosts append host if hasattr pg_if sub_if packet pg_if sub_if add_dot1_layer packet packets append packet pg_if add_stream packets cls logger info Sending broadcast eth frames for MAC learning cls pg_start
load tests from generator named on command line,def loadTestsFromName self event original_name name event name module event module try result util test_from_name name module except AttributeError ImportError as e event handled True return event loader failedLoadTests name e if result is None return parent obj name index result if not util isgenerator obj return if index is None and not isinstance parent type and not isinstance obj types FunctionType log debug Don t know how to load generator tests from s obj return if parent and isinstance parent type and issubclass parent unittest TestCase instance parent obj __name__ tests list self _testsFromGenerator event obj __name__ obj instance parent elif parent and isinstance parent type method obj instance parent tests list self _testsFromGeneratorMethod event name method instance else tests list self _testsFromGeneratorFunc event obj if index is not None try tests tests index 1 except IndexError raise exceptions TestNotFoundError original_name suite event loader suiteClass suite addTests tests event handled True return suite
"rightclick : right click the ui element , or taget coords arguments : coords : coordinate indicate where mouse click , default use ui element click point returns :",def right_click self relative_coords None if relative_coords is None coords self UIElement get_clickable_point else coords 0 0 coords 0 relative_coords 0 self UIElement coordinate 0 coords 1 relative_coords 1 self UIElement coordinate 1 LOGGER debug Mouse right click at s repr coords self UIElement set_focus SendMouseInput coords button right
initialization and set the laue class,def __init__ self laue self __laue__ None for name in self LaueDict keys if laue name __laue__ name break if __laue__ is None raise NotImplementedError LaueShiftParameter self __index__ 0 self __lauelist__ self LaueDict __laue__ return
set the value of a header .,def __setitem__ self name val del self name self _headers append name val
parses a query and performs all necessary transformations on the tree .,def ParseAndSimplify query node Parse query tree try node SimplifyNode node ValidateNode node except QueryTreeException as e msg s in query s e message query raise QueryException msg return node
simple test program to disassemble a file .,def _test if sys argv 1 if sys argv 2 sys stderr write usage python dis py file n sys exit 2 fn sys argv 1 if not fn or fn fn None else fn None if fn is None f sys stdin else f open fn source f read if fn is not None f close else fn stdin code compile source fn exec dis code
publishes a matplotlib figure to the notebook paragraph output .,def zdisplay fig kwargs width kwargs pop width auto height kwargs pop height auto fmt kwargs get format mpl_config get format supported_formats mpl_config get supported_formats if fmt not in supported_formats raise ValueError Unsupported format s fmt if fmt svg img fig canvas get_svg kwargs width px format mpl_config get width height px format mpl_config get height else src fig canvas manager angular_bind kwargs img img src src style width width height height img img format src src width width height height html div style width width height height img div print html format width width height height img img
add an aws api - compatible parameter list to a dictionary .,def _build_list_params self params items label if isinstance items basestring items items for i in range 1 len items 1 params s d label i items i 1
"most tests have time frozen , so the clock does n't drift during execution . this one purposely does not . it could flake if it takes over 2s to execute .",def test_get_chunked_time_ranges_last_1h_clock_drift kairos_timing start_relative unit hours value 1 now datetime datetime now results get_chunked_time_ranges chunking chunk_length 1800 kairos_timing assert len results 2 for i in xrange len results 1 offset datetime timedelta minutes i 30 end_diff results i 1 now offset assert end_diff datetime timedelta seconds 2 begin_diff results i 0 now offset datetime timedelta minutes 30 assert begin_diff datetime timedelta seconds 2
signals the end of the current field .,def fieldEnd self pass
test that the backing file is not updated when lock acquisition fails,def test_update_fail_acquire self self acquire return_value False self pdb add 7155 Junk permanent True assert self acquire called Lock acquire should have been called self base_db seek 0 self assertEqual self base_db read
suggest a new random brain key . randomness is provided by the operating system using `` os.urandom ( ) `` .,def suggest self word_count 16 brainkey None word_count dict_lines BrainKeyDictionary split assert len dict_lines 49744 for j in range 0 word_count num int from_bytes os urandom 2 byteorder little rndMult num 2 16 wIdx round len dict_lines rndMult brainkey j dict_lines wIdx return join brainkey upper
runs the judgement on a new thread,def run_threaded self thread threading Thread target self run thread daemon False thread start return thread
match by i{targetnamespace } excluding those that are equal to the specified namespace to prevent adding an import to itself . @param root : a schema root . @type root : l{element },def match self root ns tns root get targetNamespace if len self tns matched tns in self tns else matched 1 itself ns tns return matched and not itself
"checks if a given directory exists , if not then creates one , and finally returns it .",def ensure_dir dirpath if not os path exists dirpath os makedirs dirpath return dirpath
"widget top margin , as a fraction of the whole screen height .",property def ratio_margin_top self return self _ratio_margin_top
"can be a vector or matrix . if data are bool , sum trues .",staticmethod def reduce vector if type vector is list return array list map multiply reduce vector else return reduce operator mul vector
"get agent 's description ( metadata ) in a structure string agent_name name of the agent ( not containing "" stonith : "" prefix )",def describe_agent lib_env agent_name agent resource_agent find_valid_stonith_agent_by_name lib_env report_processor lib_env cmd_runner agent_name absent_agent_supported False return agent get_full_info
removes all permission with specified reference .,def remove_permissions_referencing tree reference xpath acl_permission reference 0 format reference for permission in tree findall xpath permission getparent remove permission
tries to connect to the server usage : connect,def do_connect self args gLogger info Trying to connect to server self connected False self prompt s colorize Not connected red acClient RPCClient Accounting DataStore retVal acClient ping if retVal OK self prompt s colorize Connected green self connected True
: param str typename : is the monitoring type registered in the types .,def export_listUniqueKeyValues self typeName setup self serviceInfoDict get clientSetup None if not setup return S_ERROR FATAL ERROR Problem with the service configuration return self __db getKeyValues typeName
deletes proxy for a vogroup for the user envoking this function . returns a list of all deleted proxies ( if any ) .,def deleteRemoteProxy userdn vogroup rpcClient RPCClient Framework ProxyManager retVal rpcClient deleteProxyBundle userdn vogroup if retVal OK gLogger notice Deleted proxy for s vogroup else gLogger error Failed to delete proxy for s vogroup
save request string to the working dir cache,def __saveRequest self requestName requestJSON try requestFile os path join self cacheDir md5 requestJSON hexdigest with open requestFile w as request request write requestJSON return S_OK requestFile except OSError as error err unable to dump s to cache file s requestName str error gLogger exception err return S_ERROR err
get all pullrequests from github .,def getGithubPRs self state open mergedOnly False perPage 100 url self _github pulls state s per_page s state perPage prs req2Json url url if not mergedOnly return prs prsToReturn for pr in prs if pr get merged_at None is not None prsToReturn append pr return prsToReturn
prepare and send dataoperation to accountingdb,staticmethod def __sendAccounting ftsJob dataOp DataOperation dataOp setStartTime fromString ftsJob submitTime dataOp setEndTime fromString ftsJob lastUpdate dataOp setValuesFromDict ftsJob accountingDict dataOp delayedCommit
"create list of filename extensions for num number of files extensions have the form : aaa , aab , aac ... aba , abb ... ,baa , bab ...",def _get_ext_list self num from string import ascii_uppercase ext ascii_uppercase idx for idx in range 0 len ascii_uppercase i1 i2 i3 0 0 0 for filenum in range num try list_ext append ext i3 ext i2 ext i1 except NameError list_ext ext i3 ext i2 ext i1 i1 1 if i1 len ascii_uppercase i1 1 i2 1 if i2 len ascii_uppercase i2 1 i3 1 if i3 len ascii_uppercase message Too many files to link raise IOError message return list_ext
"return true if ` value ` is a valid imdb id for titles ( movies , series , etc ) .",def is_valid_imdb_title_id value u n Return True if value is a valid IMDB ID for titles movies series etc n if not isinstance value basestring raise TypeError u is_valid_imdb_title_id expects a string but got 0 format type value return re match u tt d 7 value is not None
return a combined identifier for the whole pack if this has more than one episode .,property def pack_identifier self u if self id_type u ep if self episodes 1 return u S 02dE 02d E 02d self season self episode self episode self episodes 1 else return self identifier else return self identifier
display records information about a domain .,classmethod def records cls fqdn sort_by None text False meta cls get_fqdn_info fqdn url meta domain_records_href kwargs if text kwargs headers Accept text plain return cls json_get cls get_sort_url url sort_by kwargs
check if this is a null ( undefined ) instance,def is_null self return self _internal_handle 0
"determine the range in x , y and z in the ` gxdat < geosoft.gxapi.gxdat > ` source",def range_xyz self min_x min_y min_z max_x max_y max_z num_non_dummy min_x value min_y value min_z value max_x value max_y value max_z value num_non_dummy value self _range_xyz min_x value min_y value min_z value max_x value max_y value max_z value num_non_dummy value
_ _ _ test_record_creation _ _ _,def test_record_creation app with app app_context record_information create_record journal_info Phys Letts title My Journal Paper assert record_information recid assert record_information uuid assert record_information title My Journal Paper
"turn generators into objects , method can be a type , object or function",def to method def _outer f def _inner args kw return method f args kw return _inner return _outer
"whether the current os supports avx , regardless of the cpu .",def _os_supports_avx if not sys platform startswith linux or platform machine not in i386 i586 i686 x86_64 return True try f open proc cpuinfo r except OSError return True with f for line in f head _ body line partition if head strip flags and avx in body split return True else return False
restore a snapshot of the base,def base_restore self name configs None if not configs configs self base_configs for f in configs base_f Filepath base format f path name if base_f exists base_f copy f
convert a powershell script to a single base64-encoded command .,def _encode_script script as_list False script n join x strip for x in script splitlines if x strip encoded_script base64 b64encode script encode utf 16 le cmd_parts _common_args EncodedCommand encoded_script if as_list return cmd_parts return join cmd_parts
purges the queue of any tasks,def purge_queue self pass
do the wikimedia dance : replace spaces with underscores .,classmethod def transform_string cls string return string replace _
get a derived filetype and load it as json .,def get_document_as_json recordingid thetype subtype None part None version None doc file_for_document recordingid thetype subtype part version try return json loads doc except ValueError return doc
init the trie object and create root node .,def __init__ self max_edit_distance 0 match_threshold 0 0 self root TrieNode root self max_edit_distance max_edit_distance self match_threshold match_threshold
create a new table or get a reference to an existing dynamo table named ' repokid_roles ' that will store data all data for repokid . return a table with a reference to the dynamo resource,def dynamo_get_or_create_table dynamo_config if localhost in dynamo_config endpoint resource boto3 resource dynamodb region_name us east 1 endpoint_url dynamo_config endpoint else resource boto3_cached_conn dynamodb service_type resource account_number dynamo_config account_number assume_role dynamo_config get assume_role None session_name dynamo_config session_name region dynamo_config region for table in resource tables all if table name repokid_roles return table table None try table resource create_table TableName repokid_roles KeySchema AttributeName RoleId KeyType HASH AttributeDefinitions AttributeName RoleId AttributeType S AttributeName RoleName AttributeType S AttributeName Account AttributeType S ProvisionedThroughput ReadCapacityUnits 50 WriteCapacityUnits 50 GlobalSecondaryIndexes IndexName Account KeySchema AttributeName Account KeyType HASH Projection ProjectionType KEYS_ONLY ProvisionedThroughput ReadCapacityUnits 10 WriteCapacityUnits 10 IndexName RoleName KeySchema AttributeName RoleName KeyType HASH Projection ProjectionType KEYS_ONLY ProvisionedThroughput ReadCapacityUnits 10 WriteCapacityUnits 10 except BotoClientError as e LOGGER error e return table
jobs every 1 and 5 min .,def test_scheduler_2_jobs self ja jb Job 60 lambda None Job 300 lambda None s Scheduler ja jb self assertEquals s tick_duration 60 self assertEquals s _ticks 5 self assertListEqual next s ja jb for _ in range 4 self assertListEqual next s ja self assertListEqual next s ja jb
test that str can be applied to an attribute object .,def test_str self attribute objects Attribute attribute_name objects Attribute AttributeName test name attribute_index objects Attribute AttributeIndex 0 attribute_value attributes CustomAttribute test value self assertEqual str attribute_name test name attribute_index 0 attribute_value test value str attribute
write the data encoding the recover response payload to a stream .,def write self output_stream local_stream utils BytearrayStream if self _unique_identifier self _unique_identifier write local_stream self length local_stream length super RecoverResponsePayload self write output_stream output_stream write local_stream buffer
"given a list of sentences , output array of word indices that can be fed into the algorithms . : param sentences : a list of sentences : param words : a dictionary , words['str ' ] is the indices of the word ' str ' : return : x1 , m1 . x1[i , :] is the word indices in sentence i , m1[i , : ] is the mask for sentence i ( 0 means no word at the location )",def sentences2idx sentences words for i in sentences seq1 append getSeq i words x1 m1 prepare_data seq1 return x1 m1
persists the metadata of a model to a given directory .,def persist self model_dir u metadata self metadata copy metadata update u trained_at datetime datetime now strftime u Y m d H M S u rasa_nlu_version rasa_nlu __version__ filename os path join model_dir u metadata json write_json_to_file filename metadata indent 4
this method will be called when a monitor has false,def false redata jdata rdb r_server logger run True if redata trigger jdata failcount run False checktime time time float redata lastrun if checktime redata frequency run False if redata data call_on true run False if run if redata data continuous True callStathat redata jdata logger return True elif jdata check prev_status false callStathat redata jdata logger return True else line stathat Skipping stathat call as monitor s was previously false jdata cid logger info line return None else return None
break apart user@host fields into user and host .,def split_user user_at_host try user host user_at_host rsplit 1 except ValueError user host None user_at_host assert user Bad input to split_user user_at_host r format user_at_host user_at_host return user host
the manager of the panel in this case the application itself,def set_manager self manager self manager manager
flag a set of parameters as fitted parameters .,def set_fitted self param_list for k p in self _pars items p fixed k not in param_list or k in self constraints self fitted_par_names k for k in param_list if k not in self constraints self computed_par_names k for k in param_list if k in self constraints self fitted_pars self _pars k for k in self fitted_par_names self computed_pars self _pars k for k in self computed_par_names
render a single message with the given expression using l{eliotfilter._evaluate}.,def evaluateExpression self expr message u n Render a single message with the given expression using n L EliotFilter _evaluate n efilter EliotFilter expr BytesIO return efilter _evaluate message
triggers the upload to statusdb using the dependency flowcell_parser : param run run : the object run,def _upload_to_statusdb run couch fcpdb setupServer CONFIG db couch CONFIG statusdb xten_db parser run runParserObj for element in parser obj samplesheet_csv if NoIndex in element index or not element index lane element Lane try PFclusters parser obj Undetermined lane unknown except KeyError logger error While taking extra care of lane of NoIndex type I found out that not all values were available format lane continue parser obj illumina Demultiplex_Stats Lanes_stats int lane 1 PF Clusters str PFclusters updated 0 for sample in parser obj illumina Demultiplex_Stats Barcode_lane_statistics if lane in sample Lane updated 1 sample PF Clusters str PFclusters if updated 1 logger error While taking extra care of lane of NoIndex type I updated more than once the barcode_lane This is too much to continue so I will fail format lane os sys exit parser obj illumina Demultiplex_Stats NotOriginal True if not parser obj get DemultiplexConfig parser obj DemultiplexConfig Setup Software run CONFIG get bcl2fastq fcpdb update_doc db parser obj over_write_db_entry True
wrapper for lapack dpotrs function : param a : matrix a : param b : matrix b : param lower : is matrix lower ( true ) or upper ( false ) : returns :,def dpotrs A B lower 1 A force_F_ordered A return lapack dpotrs A B lower lower
returns : ( dict ) the gitiles commit log structure for a given commit .,def commit_log self url commit step_name None attempts None step_name step_name or commit log s commit commit_url s s url commit step_result self _fetch commit_url step_name attempts attempts fmt json return step_result json output
remove unnecessary information imported in bulk with necessary,def post_import_filter self
test the announce method of the dht provider,def test_announce self self dht_provider announce a 20 self assertTrue self cb_invoked
testing whether the right vod stream is returned,def test_get_vod_stream self self mock_session get_download lambda _ None self assertEqual self video_server get_vod_stream abcd None None
return the traded quantity of the order : rtype : long,property def traded_quantity self return self _traded_quantity
"return the next token , reading new text into line buffer if needed .",def next_token self while True if self line self line self file readline if self line return eof_object token self line re match InPort tokenizer self line groups if token and not token startswith return token
scraps the urls an generates text file from each url .,upload_blueprint route scrape methods GET POST def scrape num_active_docs detect_active_docs if request method GET return render_template scrape html numActiveDocs num_active_docs if request method POST import requests urls request json urls urls urls strip urls urls replace n urls re sub s n urls urls urls split n file_manager utility load_file_manager for i url in enumerate urls r requests get url file_manager add_upload_file r text url str i txt utility save_file_manager file_manager response success return json dumps response
ensure that duplicate field names are not allowed,def test_duplicate_fields self self assertPyxformXform name duplicatefields md Survey Type Name Label integer age the age integer age the age errored True error__contains There are more than one survey elements named age
"if a critical error is encountered , where it is suspected that the program is not being called with consistent parameters or data , this method will write out an error string ( str ) , then terminate execution of the program .",def do_usage_and_die self str import sys print sys stderr str self parser print_usage return 2
"setting up object so we can run 4 different ways ( live , debug , test & debug+test ) there are two different test modes : - test = true : regular test mode where the authentication and verification is done on the authorize.net staging server . for this you need to use the credentials of your test account . - test=""live_test "" : the transaction is processed on the live authorize.net server but is not submitted to financial institutions for authorization . for this you need to use the credentials of the live authorize.net account .",def __init__ self username test password testpassword debug False test False delim None super AuthorizeNet self set x_login username super AuthorizeNet self set x_tran_key password super AuthorizeNet self __init__ translations self REQUEST_FIELDS debug debug if debug self debug True if test if test self LIVE_TEST self test True test_string regular else test_string live super AuthorizeNet self set x_test_request TRUE debug_string paython gateways authorize_net __init__ You re in s test mode debug obviously test_string logger debug debug_string center 80 else self test False if delim self DELIMITER delim
this is a mirror to the store method . create a plan that bills every decade or so for a large authorized amount and charge that plan with the capture method,def authorize self money credit_card options None return self store credit_card options options
type1 fonts just scale by 1/1000 to convert from glyph space,def text_space_coords self x y return x 1000 0 y 1000 0
estimate an r_k value for the given value of k of our estimator,def estimate self num_transitions num_samples num_k 0 num_k_minus_1 0 for i in range num_samples self MC run num_transitions if self M size self k num_k 1 elif self M size self k 1 num_k_minus_1 1 return float num_k num_k_minus_1
check if file is an executable,def is_exe fpath return os path isfile fpath and os access fpath os X_OK
add parameters that are necessary for every request,def add_default_params self params params api_key self key params api_responseFormat json return params
test conversion from percent rgb triplet to color name .,def test_rgb_percent_to_name self test_pairs u 100 u 100 u 100 u white u 0 u 0 u 50 u navy u 85 49 u 64 71 u 12 5 u goldenrod for pair in test_pairs self assertEqual pair 1 webcolors rgb_percent_to_name pair 0
"given a polygon with vertices defined by ( lon , lat ) , rotate the polygon such that the north pole of the spherical coordinates is now at ( lon0 , lat0 ) . therefore , to end up with a polygon centered on ( lon0 , lat0 ) , the polygon should initially be drawn around the north pole .",def _rotate_polygon lon lat lon0 lat0 polygon UnitSphericalRepresentation lon lon lat lat m1 rotation_matrix 0 5 np pi u radian lat0 axis y m2 rotation_matrix lon0 axis z transform_matrix matrix_product m2 m1 polygon polygon to_cartesian polygon polygon transform transform_matrix polygon UnitSphericalRepresentation from_cartesian polygon return polygon lon polygon lat
compute the lomb - scargle periodogram with a given method .,def lombscargle t y dy None frequency None method auto assume_regular_frequency False normalization standard fit_mean True center_data True method_kwds None nterms 1 output_shape frequency shape frequency frequency ravel args t y dy kwds dict frequency frequency center_data center_data fit_mean fit_mean normalization normalization nterms nterms method_kwds or method validate_method method dy dy fit_mean fit_mean nterms nterms frequency frequency assume_regular_frequency assume_regular_frequency if method scipy if kwds pop fit_mean raise ValueError scipy method does not support fit_mean True if dy is not None dy np ravel np asarray dy if not np allclose dy 0 dy raise ValueError scipy method only supports uniform uncertainties dy args t y if method startswith fast f0 df Nf _get_frequency_grid kwds pop frequency assume_regular_frequency kwds update f0 f0 df df Nf Nf if not method endswith chi2 if kwds pop nterms 1 raise ValueError nterms 1 only supported with chi2 or fastchi2 methods PLS METHODS method args kwds return PLS reshape output_shape
update table columns in place if mixin columns are present .,def update_table_data self table with serialize_context_as ecsv out serialize _represent_mixins_as_columns table return out
succeed or fail an item based on the return code of a program,def done_item item code try if const FSQ_SUCCESS code success item chirp 0 succeeded format item id elif const FSQ_FAIL_TMP code fail_tmp item shout 0 failed temporarily format item id else fail_perm item shout 0 failed permanantly format item id except FSQEnqueueError as e shout e strerror encode _CHARSET return 1 except FSQError as e shout e strerror encode _CHARSET return 0
convert a click.option call into a click . option object .,def extract_option_object option option def opt pass return opt __click_params__ 0
"take a dictionary of parameters , pick out the properly named parameters according to the alias , and put them in the param state dictionary .",def update self kwargs for k in self kernel_params self params k kwargs self param_alias k
return an xml version of the current user .,def get self request format None return Response users request user request_user request user
image is a section of the texture .,classmethod def from_subtexture cls texture x y width height return cls texture get_region x y width height x y
locks btnnext if the project name does n't meet specifications,def lock_btn_title self jnk_unused btnNEXT txt self entry get_text btnNEXT set_sensitive len txt 0 and not re search a zA Z0 9_ txt return
"return true if the character is a letter , digit , underscore , dollar sign , or non - ascii character .",def isAlphanum c return c a and c z or c 0 and c 9 or c A and c Z or c _ or c or c or c is not None and ord c 126
return a unit vector orthogonal to self at point .,def get_orthogonal self point if len self 1 It might be better to selectively hit only the frame primitive of some composites But is the frame always drawn To hitted member and let user slide between members FIXME Aggregate the orthogonal of all members that intersect the point return orthogonal rect_orthogonal self bounds point elif len self 1 return self 0 get_orthogonal point else return vector downward_vector
try multiple times to run ' throw_random ',def throw_random lengths mask saved None for i in range maxtries try return throw_random_bits lengths mask except MaxtriesException as e saved e continue raise e
setup the benchmark object with the appropriate dataset .,def PrepareBenchmark self if len self nameservers 1 thread_count 1 else thread_count self options benchmark_thread_count self bmark benchmark Benchmark self nameservers query_count self options query_count run_count self options run_count thread_count thread_count status_callback self UpdateStatus
convert surrogate escapes to the unicode replacement character to avoid xml encoding errors,def _cleanse_string self value return to_text to_bytes value errors surrogateescape errors replace
read terminal status line : carrier detect,property def cd self if not self is_open raise portNotOpenError if self logger self logger info returning dummy for CD return True
should return a list of msa ids in view,def test_api_msas_endpoint self coords neLat 36 551569 neLon 78 961487 swLat 35 824494 swLon 81 828918 year 2013 url reverse msas resp self client get url coords result_list json loads resp content self assertTrue isinstance result_list list self assertContains resp 49180 self assertNotContains resp 49181
breadth first search starting from a particular vertex . returns a list of connected vertices in the order they were found .,def breadthFirstSearch self root toVisit deque root toVisitSet set root visited set searchPath while len toVisit 0 currentVertex toVisit popleft if currentVertex not in visited visited add currentVertex searchPath append currentVertex neighbours self neighbours currentVertex unvisited set neighbours difference visited unvisited unvisited difference toVisitSet toVisitSet update unvisited toVisit extend sorted unvisited return searchPath
start a new job to analyze a gene list .,def analyze_gene_list genes description None ENRICHR_URL http amp pharm mssm edu Enrichr addList genes_str n join list genes description description if description else d input genes len genes payload list None genes_str description None description print Connecting to enrichr server response requests post ENRICHR_URL files payload if response ok print ok return json loads response text else raise Exception failed
": param name : name of the model object ( default : ' randomsequencemodel ' ) : type seed : int : param seed : rng seed ( default : none ) : type callback_generator : func(from_template , to_template ) - > func(fuzzer , edge , response ) - > none : param callback_generator : a function that returns callback functions ( default : none ) : param num_mutations : number of mutations to perform ( defualt : 1000 ) : param max_sequence : maximum sequence length ( default : 10 )",def __init__ self name RandomSequenceModel seed None callback_generator None num_mutations 1000 max_sequence 10 super RandomSequenceModel self __init__ name callback_generator num_mutations self _max_sequence max_sequence self seed seed strategy 1 d max_sequence self _stage Stage name internal selection_strategy strategy seed seed self add_stage self _stage
@summary : event call when a keyboard event is catch in scan code format @param code : { integer } scan code of key @param ispressed : { boolean } true if key is down @param isextended : { boolean } true if a special key @see : rdp . rdpserverobserver.onkeyeventscancode,def onKeyEventScancode self code isPressed isExtended if self _client is None return self _client _controller sendKeyEventScancode code isPressed isExtended self _rss keyScancode code isPressed
return the running time of the job as a string in human readable format .,property def run_time_str self m s divmod self run_time 60 h m divmod m 60 return 0 02d 1 02d 2 02d format int h int m int s
"check the schedule directory for new items . if a new item is present , start a new job ( if maximum concurrency level has not been reached ) . each job gets it 's own thread .",def start_new_jobs self finished_jobs set os listdir PATH_TO_FINISHED_JOBS for job_id in os listdir PATH_TO_SCHEDULE if job_id not in self schedule_items and job_id not in finished_jobs and len self schedule_items MAX_CONCURRENCY with open os path join PATH_TO_SCHEDULE job_id r as f schedule_item pickle load f job schedule_item generate_job thread Thread target job start name job_id thread daemon True LOG info Created Job Thread 0 format job_id self schedule_items job_id thread thread start sleep SLEEP_LENGTH
set up basic auth for the client @param username : login name . @param password : login password . @param realm : the authentication realm . @return : the current object,def set_basic_auth self username password realm self _passmgr add_password realm self _base_url username password return self
performs a power operation on a system . internal method,def _power self system power_operation user None password None logger None if logger is None logger self logger power_command get_power_command system power_type if not power_command utils die logger no power type set for system meta utils blender self api False system meta power_mode power_operation if user is not None meta power_user user if password is not None meta power_pass password logger info cobbler power configuration is logger info type s system power_type logger info address s system power_address logger info user s system power_user logger info id s system power_id if meta get power_user meta power_user os environ get COBBLER_POWER_USER if meta get power_pass meta power_pass os environ get COBBLER_POWER_PASS template self get_power_template system power_type tmp templar Templar self collection_mgr template_data tmp render template meta None system logger info power command s power_command logger info power command input s template_data for x in range 0 5 output rc utils subprocess_sp logger power_command shell False input template_data if rc 0 if power_operation status match re match Status power s s on off output re IGNORECASE re MULTILINE if match power_status match groups 1 if power_status lower on return True else return False error_msg command succeeded rc s but output s was not understood rc output utils die logger error_msg raise CX error_msg return None else time sleep 2 if not rc 0 error_msg command failed rc s please validate the physical setup and cobbler config rc utils die logger error_msg raise CX error_msg
parser for ` sched_rq_nr_running ` tracepoint,register_parser def sched_rq_nr_running payratio try match re match sched_rq_nr_running_pattern payratio if match match_group_dict match groupdict return SchedRqNrRunning match_group_dict except Exception as e raise ParserError e message
test uploadprebuilts with a private location .,def testUploadPrivatePrebuilts self self testUploadPrebuilts private True
"returns whether current line is part of the current suite . this can be false when we are in a generated suite outside of cxxtest_code ( ) blocks if the suite is generated , adds the line to the list of lines",def lineBelongsToSuite suite lineNo line if not suite generated return 1 global inBlock if not inBlock inBlock lineStartsBlock line if inBlock inBlock addLineToBlock suite lineNo line return inBlock
for roles which simply wrap a given ` node_class ` around the text .,def register_generic_role canonical_name node_class role GenericRole canonical_name node_class register_canonical_role canonical_name role
construct a rgbimage from the pixel data in a buffer .,classmethod def frombytes cls mode size bytes_ return cls array np array Image frombytes mode size bytes_
proxenos - cli : consistently select nodes from service discovery .,click group click pass_context def main ctx
connects the module to some inputs .,def _build self inputs is_training input_shape tf shape inputs with tf control_dependencies tf Assert tf equal input_shape 1 self _embedding_dim input_shape flat_inputs tf reshape inputs 1 self _embedding_dim distances tf reduce_sum flat_inputs 2 1 keepdims True 2 tf matmul flat_inputs self _w tf reduce_sum self _w 2 0 keepdims True encoding_indices tf argmax distances 1 encodings tf one_hot encoding_indices self _num_embeddings quantized tf reshape tf matmul encodings self _w transpose_b True tf shape inputs e_latent_loss tf reduce_mean tf stop_gradient quantized inputs 2 q_latent_loss tf reduce_mean quantized tf stop_gradient inputs 2 loss q_latent_loss self _commitment_cost e_latent_loss quantized inputs tf stop_gradient quantized inputs avg_probs tf reduce_mean encodings 0 perplexity tf exp tf reduce_sum avg_probs tf log avg_probs 1e 10 return quantize quantized loss loss perplexity perplexity encodings encodings
"reduce arbitrary angle to [ -180,180 )",def AngNormalize2 x return Math AngNormalize math fmod x 360
returns the confusion matrix between rater 's ratings,def confusion_matrix rater_a rater_b min_rating None max_rating None assert len rater_a len rater_b if min_rating is None min_rating min rater_a rater_b if max_rating is None max_rating max rater_a rater_b num_ratings int max_rating min_rating 1 conf_mat 0 for i in range num_ratings for j in range num_ratings for a b in zip rater_a rater_b conf_mat a min_rating b min_rating 1 return conf_mat
return the duration ( in milliseconds ) that this item was in - progress .,property def duration self if self date_started and self date_finished duration self date_finished self date_started total_seconds 1000 else duration None return duration
new chainmap from maps[1 : ] .,property def parents self return self __class__ self maps 1
split a query string into a nested list of query terms .,def _split_query self query markers parens False u Split a query string into a nested list of query terms n n Returns a list of terms and or nested sublists of terms Each term and n sublist is guarenteed to be non empty n query query lstrip if not query return marker index self _scan_query query markers if not marker return query nest query index if index 0 else after query index 1 if marker u nest self _split_query after markers parens elif marker in u u close_marker close_index self _scan_query after marker if close_marker if close_index 0 nest append after close_index after after close_index 1 nest self _split_query after markers parens elif after nest append after elif marker u inner after self _split_query after markers True if inner and isinstance inner 1 tuple after self _split_query inner pop 0 markers parens if inner nest append inner if after nest after elif marker u if parens nest append after else nest self _split_query after markers return nest
verify the method refuses to create a course credential when read - only .,def test_to_internal_value_with_created_course_credential_read_only self self field_instance read_only True self assert_course_run_key_validation_error_raised create me
test that we can interact with a live clientxmpp instance .,def testClientConnection self self stream_start mode client socket live skip False jid user localhost test password user self recv_header sfrom localhost sid None self send_header sto localhost self recv_feature stream features starttls xmlns urn ietf params xml ns xmpp tls mechanisms xmlns urn ietf params xml ns xmpp sasl mechanism DIGEST MD5 mechanism mechanism PLAIN mechanism mechanisms stream features self send_feature starttls xmlns urn ietf params xml ns xmpp tls self recv_feature proceed xmlns urn ietf params xml ns xmpp tls self send_header sto localhost self recv_header sfrom localhost sid None self recv_feature stream features mechanisms xmlns urn ietf params xml ns xmpp sasl mechanism DIGEST MD5 mechanism mechanism PLAIN mechanism mechanisms stream features self send_feature auth xmlns urn ietf params xml ns xmpp sasl mechanism PLAIN AHVzZXIAdXNlcg auth self recv_feature success xmlns urn ietf params xml ns xmpp sasl self send_header sto localhost self recv_header sfrom localhost sid None self recv_feature stream features bind xmlns urn ietf params xml ns xmpp bind session xmlns urn ietf params xml ns xmpp session stream features self send_feature iq type set id 1 bind xmlns urn ietf params xml ns xmpp bind resource test resource bind iq self recv_feature iq type result id 1 bind xmlns urn ietf params xml ns xmpp bind jid user localhost test jid bind iq self stream_close
add a new transfer to the widget,def add self transfer self new_transfer_bar self ft self transfer self transfers transfer self new_transfer_bar self hbox pack_start self new_transfer_bar False False self num_transfers 1 if self num_transfers 1 self b_go_right set_sensitive True else self b_go_right set_sensitive False self set_no_show_all False self show_all
"return true if name is in cache , false otherwise this method is used to do something like if ' lolw00 t ' in cache : asd ( )",def __contains__ self name return os path isfile os path join self path name
called by user to set or show the session variables,def set self module_argument value try value ast literal_eval value except Exception as e pass action_name action_ s module_argument replace _ if hasattr self action_name action_func getattr self action_name if hasattr action_func __call__ action_func module_argument value if module_argument count 1 module_name arg_name module_argument split self module_name stored_args arg_name value log info messages sessions set_module_s_s_s module_name arg_name value else module_name module_argument if module_name not in self and module_name not in set_filters log warn messages sessions error_session_s_not_modified module_name else self module_name value log info messages sessions set_s_s module_name value
returns true if a cryptohome vault is mounted at /home / chronos / user .,def _IsCryptohomeMounted cri return cri FilesystemMountedAt home chronos user startswith home shadow
we hide debug messages from stats module when not in golo .,def testStatsDebugMsg self golo False stats StatsUploader _Upload side_effect EnvironmentError with cros_test_lib LoggingCapturer as logs upload_command_stats main self argv self AssertLogsContain logs stats StatsUploader ENVIRONMENT_ERROR inverted not golo
gets the set of divergent packages .,def GetDivergentSet version_map count divergent_set set for pkg value in version_map iteritems if len value keys count or len set value values 1 divergent_set add pkg return divergent_set
test that page navigation is successful after logging in .,def testNavigateAfterLogin self self testGoodLogin self NavigateToURL http www google com self assertEqual self GetActiveTabTitle Google msg Unable to navigate to Google and verify tab title
generates admx elements for a main - policy amd adds them to the passed parent element .,def _AddMainPolicy self parent enabled_value_elem self AddElement parent enabledValue self AddElement enabled_value_elem decimal value 1 disabled_value_elem self AddElement parent disabledValue self AddElement disabled_value_elem decimal value 0
attempt to process input from command line,def parse self line try split_results line strip split 1 except return cmd_args None cmd_class split_results 0 if len split_results 1 cmd_args query split_results 1 self process cmd_class capitalize cmd_args
"ensure comments work , see https://bugzilla.mozilla.org/show_bug.cgi?id=813674",def test_comments self comment_example os path join here comment example ini manifest TestManifest manifests comment_example self assertEqual len manifest tests 8 names i name for i in manifest tests self assertFalse test_0202_app_launch_apply_update_dirlocked js in names
command line raises an exception when the arguments are specified ambiguously,def test_commandline_over_specified self err None try processhandler ProcessHandler self proclaunch process_normal_finish ini args 1 2 3 cwd here except TypeError as e err e self assertTrue err
delegates to : py : func:`~puresnmp.api.raw.multiwalk ` but returns simple python types .,def multiwalk ip community oids port 161 timeout 2 fetcher multigetnext u n Delegates to py func puresnmp api raw multiwalk but returns simple n Python types n n See the raw equivalent for detailed documentation examples n raw_output raw multiwalk ip community oids port timeout fetcher for oid value in raw_output yield VarBind oid value pythonize
accessor for accessing a copy of registered task classes,property def task_classes self return self _registered
return the set of merged components for a particular split key,def catalog_components self catalog_name split_ver return sorted self _split_comp_info_dicts s_ s catalog_name split_ver keys
greetings timely to current date and time .,def test_greeting self testcases datetime 2015 1 8 Happy New Year 2015 datetime 2015 2 14 Happy Valentine s Day datetime 2015 2 15 10 0 Have a good weekend datetime 2016 7 10 19 30 Have a good night datetime 2015 2 16 6 0 Have a good morning datetime 2015 2 16 10 0 Have a good day datetime 2015 2 16 18 0 Have a good night datetime 2015 3 29 Happy Easter datetime 2015 10 31 Happy Halloween datetime 2015 12 15 Merry Christmas datetime 2015 12 27 Merry Christmas datetime 2016 1 1 Happy New Year 2016 for dt greetings in testcases self assertEqual greeting timely_greeting dt greetings
out of some paths it finds the common roots that need monitoring .,def _find_common_roots paths paths x split os path sep for x in paths root for chunks in sorted paths key len reverse True node root for chunk in chunks node node setdefault chunk node clear rv set def _walk node path for prefix child in iteritems node _walk child path prefix if not node rv add join path _walk root return rv
: type grid : list[list[str ] ] : rtype : int,def numIslands self grid m len grid if m 0 return 0 n len grid 0 visited False n for _ in range m res 0 for i in range m for j in range n if grid i j 1 and not visited i j self dfs i j grid visited res 1 return res
"iio : float_buffer , w , h , nch = read_buffer(filename )",def read_tiled_buffers filename from ctypes import c_int c_float c_void_p POINTER cast byref c_char memmove create_string_buffer sizeof w c_int h c_int nch c_int libiio iio_read_image_float_vec restype c_void_p tptr libiio iio_read_image_float_vec str filename encode ascii byref w byref h byref nch if tptr None raise IOError PIIO the file s cannot be read filename c_float_p POINTER c_float ptr cast tptr c_float_p w h nch w value h value nch value vmin c_float vmax c_float N w h nch libiio minmax restype c_void_p libiio minmax argtypes c_float_p c_int c_float_p c_float_p libiio minmax ptr N byref vmin byref vmax vmin vmax vmin value vmax value tiles out_nch min nch 4 if nch out_nch print piio_read the input image have d channels only the first 4 are loaded n nch for y in range 0 h 1024 for x in range 0 w 1024 ww min w x 1024 hh min h y 1024 N ww hh out_nch data ctypes ARRAY ctypes c_float N libiio copy_tile ptr w h nch data x y ww hh out_nch tiles append data x y ww hh out_nch 1 libiio freemem ptr return tiles w h out_nch vmin vmax
uri for group description data ; also view using default entity view,def recordgroup_url coll_id group_id if not valid_id group_id return None return collection_entity_view_url coll_id coll_id type_id _group entity_id group_id
returns a dict representation of the size .,property def dict self return width self width height self height
"add a radio , update url if radio already exists in db @param name as str @param duration as int @param popularity as int @param rate as int @param ltime as int @param mtime as int @param loved album as bool @param album_popularity as int @param album_rate as int @thread safe",def add self name duration popularity rate ltime mtime loved_album album_popularity album_rate with SqlCursor self as sql if self exists name duration sql execute UPDATE history SET popularity rate ltime mtime loved_album album_popularity album_rate WHERE name AND duration popularity rate ltime mtime loved_album album_popularity album_rate name duration else sql execute INSERT INTO history name duration popularity rate ltime mtime loved_album album_popularity album_rate VALUES name duration popularity rate ltime mtime loved_album album_popularity album_rate sql commit
update tracks widgets @param manager as playlistsmanager @param playlist i d as int @param track i d as int,def __on_playlist_del self manager playlist_id track_id if playlist_id in self __playlist_ids self __playlists_widget remove track_id
set some default avalible data for testing .,def __init__ self obj super TestNetgroupMap self __init__ obj self _good_entry netgroup NetgroupMapEntry self _good_entry name foo self _good_entry entries bob None othernetgroup
download the source for a package .,def DownloadSource self download_directory self PreDownload download_directory source_directory self apt_version fetch_source download_directory self PostDownload source_directory return source_directory
"on_observed_value(self , subject , time , value )",accepts 2 int float 3 int float units Quantity def on_observed_value self subject time value self _y subject append value
transform all the variables that map onto the x and y scales .,staticmethod def transform_position data trans_x None trans_y None X x xmin xmax xend xintercept Y y ymin ymax yend yintercept if trans_x xs name for name in data columns if name in X data xs data xs apply trans_x if trans_y ys name for name in data columns if name in Y data ys data ys apply trans_y return data
returns the default location of the pid file for process management,def get_pid options namespace options settings if options settings else options wsgi return s s_ s pid HENDRIX_DIR options http_port namespace replace _
generate a keyed hash value using the hmac method,wrap space str str str Optional bool def hash_hmac space algo data key raw_output False h _get_hash_algo algo res hmac algo key data raw_output return space wrap res
triggers a view : meth:`~textfieldview.refresh ` .,def refresh self self view refresh
just return data back to the client .,def echo self data return data
"given a gym name , assumes a matching model params python module exists within the model_params directory and attempts to import it . : param gymname : gym name , used to guess the model params module name . : return : opf model params dictionary",def getModelParamsFromName gymName importName model_params model_params_common print Importing model params from s importName try importedModelParams importlib import_module importName MODEL_PARAMS except ImportError raise Exception No model params exist print importedModelParams return importedModelParams
change back to initial working dir and remove temp dir .,classmethod def tearDownClass self os chdir self working_dir shutil rmtree self test_dir
backend - specific wrapper for ijson.common.items .,def items file prefix return common items parse file prefix
question 15.5 : compute the lca in a bst,def find_lca root a b smaller min a b larger max a b cur_node root while cur_node val larger or cur_node val smaller while cur_node val larger if cur_node left cur_node cur_node left else return None while cur_node val smaller if cur_node right cur_node cur_node right else return None return cur_node val
make sure the manager 's listed ( ) filter works .,def test_listed self listed_count Collection objects listed count private Collection name Hello uuid 4e2a1acc 39ae 47ec 956f 46e080ac7f69 listed False author self user private save listed Collection objects listed eq_ len listed listed_count
builds a 2-node connected graph for testing .,def build_2_node_graph directed False if directed graph DirectedGraph else graph UndirectedGraph graph new_node graph new_node graph new_edge 1 2 return graph
returns a customized file for the modeljob based on completed form fields,blueprint route customize methods POST def customize network flask request args network framework flask request args get framework if not network raise werkzeug exceptions BadRequest network not provided fw frameworks get_framework_by_id framework network_desc fw get_standard_network_desc network if network_desc return json dumps network network_desc job scheduler get_job network if job is None raise werkzeug exceptions NotFound Job not found snapshot None epoch float flask request form get snapshot_epoch 0 if epoch 0 pass elif epoch 1 snapshot job train_task pretrained_model else for filename e in job train_task snapshots if e epoch snapshot job path filename break if isinstance job PretrainedModelJob model_def open job get_model_def_path r network model_def read snapshot job get_weights_path python_layer job get_python_layer_path else network job train_task get_network_desc python_layer None return json dumps network network snapshot snapshot python_layer python_layer
copy the specified vector into the long term memory of the network . @param source : the source vector .,def copy_memory self source for i in range 0 len source self long_term_memory i source i
creates instance of class that describes free function declaration,def create_free_function self arguments keywords return free_function_t arguments keywords
reflect about the line starting from the origin at given angle from the x axis .,def reflect self angle x_axis self matrix_stack 1 np matrix 1 0 T x_angle math atan2 x_axis item 1 x_axis item 0 tt 2 x_angle angle reflection_matrix np matrix math cos tt math sin tt math sin tt 1 math cos tt self matrix_stack 1 reflection_matrix self matrix_stack 1
interpolates points so that the distance between each point is equal to ` distance ` in meters .,def interpolate_distance points distance _log info Distributing points evenly every meters format distance d 0 i 0 even_points while i len points if i 0 even_points append points 0 i 1 continue if d 0 p1 even_points 1 else p1 points i 1 p2 points i d gpxpy geo distance p1 latitude p1 longitude p1 elevation p2 latitude p2 longitude p2 elevation if d distance brng bearing p1 p2 ld gpxpy geo LocationDelta distance d distance angle brng p2_copy copy deepcopy p2 p2_copy move ld even_points append p2_copy d 0 else i 1 else even_points append points 1 return even_points
event handler for ' forward ' tool events . returns the figure to its next view .,def on_forward self evnt if self __active_figure is not None self __active_figure forward
write the txt to the file .,def text2file txt filename outputfile codecs open filename w utf 8 outputfile write txt outputfile close
it can upgrade a vcs requirement that has no distributions otherwise .,pytest mark network def test_upgrade_vcs_req_with_no_dists_found script tmpdir req s egg pip test package local_checkout git http github com pypa pip test package git tmpdir join cache script pip install req result script pip install U req assert not result returncode
add builders and construction variables for visual age c++ compilers to an environment .,def generate env import SCons Tool import SCons Tool cc static_obj shared_obj SCons Tool createObjBuilders env for suffix in CXXSuffixes static_obj add_action suffix SCons Defaults CXXAction shared_obj add_action suffix SCons Defaults ShCXXAction static_obj add_emitter suffix SCons Defaults StaticObjectEmitter shared_obj add_emitter suffix SCons Defaults SharedObjectEmitter SCons Tool cc add_common_cc_variables env if CXX not in env env CXX env Detect compilers or compilers 0 env CXXFLAGS SCons Util CLVar env CXXCOM CXX o TARGET c CXXFLAGS CCFLAGS _CCCOMCOM SOURCES env SHCXX CXX env SHCXXFLAGS SCons Util CLVar CXXFLAGS env SHCXXCOM SHCXX o TARGET c SHCXXFLAGS SHCCFLAGS _CCCOMCOM SOURCES env CPPDEFPREFIX D env CPPDEFSUFFIX env INCPREFIX I env INCSUFFIX env SHOBJSUFFIX os env OBJSUFFIX o env STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME 0 env CXXFILESUFFIX cc
you ca n't make a copy of a qubitsystem : this enforces the no - cloning theorem .,def copy self raise TypeError Cannot copy qubits violation of no cloning theorem
the main entry point of stats .,def main most_recent_match_id 0 for post in match_collection find sort _id direction 1 limit 1 most_recent_match_id post match_id most_recent_match_time post start_time total_matches match_collection count human_readable_time time strftime a d b Y H M S GMT time localtime most_recent_match_time disk_stats os statvfs mb_remaining disk_stats f_bavail disk_stats f_frsize 1024 0 1024 0 1024 0 msg Hello The database currently contains s matches The most recent match_id added to the database was s The date of that match was s There are 2f remaining GB on the hard drive 3 dotabot total_matches most_recent_match_id human_readable_time mb_remaining send_email msg subject DOTAbot Update
test admm using the l1norm in lagrange form,dec setastest True def test_admm_l1_seminorm p 1000 Y 10 np random normal 0 1 p loss R quadratic shift Y coef 0 5 sparsity R l1norm p lagrange 5 0 prob R container loss sparsity solver R admm_problem prob solver fit debug False tol 1e 12 solution solver beta npt assert_array_almost_equal solution np maximum np fabs Y sparsity lagrange 0 0 np sign Y 3
determine if the unit expects to be in ha,def expect_ha return config vip or config dns ha
sample rate in samples per second .,def get_sample_rate self u Sample rate in samples per second n n Zero if the type has no sample rate n return self __sample_rate
prepare for paramiko ssh connection .,def _build_ssh_client self u Prepare for Paramiko SSH connection n n See base_connection py file for any updates n if not self use_keys remote_conn_pre SSHClient_noauth else remote_conn_pre SSHClient if self system_host_keys remote_conn_pre load_system_host_keys if self alt_host_keys and path isfile self alt_key_file remote_conn_pre load_host_keys self alt_key_file remote_conn_pre set_missing_host_key_policy self key_policy return remote_conn_pre
returns the first buffer of the stream .,def pop self return next self
get the watershed of an outlet returned as a list of nodes .,def get_watershed_nodes grid outlet_id ws_mask get_watershed_mask grid outlet_id ws_nodes np where ws_mask 0 return ws_nodes
"get origin of grid for variable , name .",def get_grid_origin self name pass
determines rotatable bonds in a ligand molecule takes : * mol * - mol file in rdkit environment output : * bonds * - tuples of atom ids,def get_rotatable_bonds self mol RotatableBondSmarts Chem MolFromSmarts D1 D1 bonds mol GetSubstructMatches RotatableBondSmarts uniquify 1 return bonds
deploys the service to the host . this should at least perform the same actions as install and start but may perform additional tasks as needed .,def deploy self unique_id configs None self install unique_id configs self start unique_id configs
test if this is the first phase of the project .,def is_first_of_project self return self self module project phases first
returns a chrome user agent based on a user agent type . this is derived from : https://developers.google.com/chrome/mobile/docs/user-agent,def GetChromeUserAgentArgumentFromType user_agent_type if user_agent_type return user agent s UA_TYPE_MAPPING user_agent_type return
determine the file that will be generated for the given locale .,def calc_output locale if locale fake bidi return s s pak INT_DIR locale if OS mac or OS ios if locale en US locale en return s repack s lproj locale pak INT_DIR locale replace _ else return os path join INT_DIR repack locale pak
verify postal code and state labels based on selected country .,def testPostalCodeAndStateLabelsBasedOnCountry self data_file os path join self DataDir autofill functional state_zip_labels txt test_data simplejson loads open data_file read page settings AutofillEditAddressDialog FromNavigation self _driver self assertEqual State page GetStateLabel self assertEqual ZIP code page GetPostalCodeLabel for country_code in test_data page Fill country_code country_code actual_postal_label page GetPostalCodeLabel self assertEqual test_data country_code postalCodeLabel actual_postal_label msg Postal code label s does not match Country s actual_postal_label country_code actual_state_label page GetStateLabel self assertEqual test_data country_code stateLabel actual_state_label msg State label s does not match Country s actual_state_label country_code
notifies the web app that pref pane operation is done .,def NotifyWebapp self notif_center Foundation NSDistributedNotificationCenter defaultCenter notif_center postNotificationName_object_userInfo_ self _service_name update_succeeded None None
strip the dirnames and version suffixes from a list of nexe dependencies .,def StripDependencies self deps names for name in deps name os path basename name if so in name name name rsplit 1 0 names append name return names
create a route table entry for the power strip .,def _SetupRouteForPowerStrip self ipaddress iface eth try iface key for key in self default_routes keys if iface in key 0 except assert Unable to find interface of type s iface self ps_route_entry iface iface gateway self default_routes iface gateway netmask 255 255 255 255 ipaddress ipaddress os system route add net ipaddress s gateway gateway s netmask netmask s dev iface s self ps_route_entry assert os system route n egrep ipaddress s space gateway s space netmask s self ps_route_entry 0 Failed to create default route for powerstrip
stops music playback for this scene .,def stop_music self u Stops music playback for this scene n self load_music None
advances the current position to = = target_commit .,def advance_to self target_commit dist self dist_to target_commit if dist len self _commits self _cur_idx return None if dist 0 self _cur_idx dist return self current
"return a modified that returns the representation of expr , or ' ... ' if that representation is longer than ` max_len `",def _shorten_render renderer max_len def short_renderer expr res renderer expr if len res max_len return else return res return short_renderer
"returns the keys . ( message header names ) it remembers the order in which they were added , what is really important",def keys self return self _v keys
organizes multiple extensions that are separated with commas or passed by using --extension/-e multiple times .,def handle_extensions extensions html ext_list for ext in extensions ext_list extend ext replace split for i ext in enumerate ext_list if not ext startswith ext_list i s ext_list i return set x for x in ext_list if x py
error is raised if the provided email address is n't currently registered,def test_email_not_found self response self client get password_reset self assertEquals response status_code 200 response self client post password_reset email not_a_real_email email com self assertContains response That e mail address doesn t have an associated user account self assertEquals len mail outbox 0
returns a list of form in the order specified by the incoming data . raises an attributeerror is deletion is not allowed .,def _get_ordered_forms self if not self is_valid or not self can_order raise AttributeError s object has no attribute ordered_forms self __class__ __name__ if not hasattr self _ordering self _ordering for i in range 0 self _total_form_count form self forms i if i self _initial_form_count and not form has_changed continue if self can_delete and form cleaned_data DELETION_FIELD_NAME continue def compare_ordering_values x y if x 1 is None return 1 if y 1 is None return 1 return x 1 y 1 self _ordering append i form cleaned_data ORDERING_FIELD_NAME self _ordering sort compare_ordering_values return self forms i 0 for i in self _ordering
sets the client to appear as if it has successfully logged into a site .,def login self credentials user authenticate credentials if user and user is_active and django contrib sessions in settings INSTALLED_APPS engine __import__ settings SESSION_ENGINE request HttpRequest request session engine SessionStore login request user session_cookie settings SESSION_COOKIE_NAME self cookies session_cookie request session session_key cookie_data max age None path domain settings SESSION_COOKIE_DOMAIN secure settings SESSION_COOKIE_SECURE or None expires None self cookies session_cookie update cookie_data request session save return True else return False
"merge one app config ( from a dict , file , or filename ) into another .",def merge base other if isinstance other basestring cherrypy engine autoreload files add other for section value_map in reprconf as_dict other items if not isinstance value_map dict raise ValueError Application config must include section headers but the config you tried to merge doesn t have any sections Wrap your config in another dict with paths as section headers for example config base setdefault section update value_map
"branch_set : subtree "" , "" branch_set | subtree",def p_branch_set p if len p 2 p 0 p 1 else p 0 p 1 p 3
general method for printing images to the output panel,def write_image self image pass
deplete using a first - order predictor algorithm .,def predictor operator timesteps power print_out True Deplete using a first order predictor algorithm Implements the first order predictor algorithm This algorithm is mathematically defined as math y A y t y t A_p A y_n t_n y_ n 1 text expm A_p h y_n Parameters operator openmc deplete TransportOperator The operator object to simulate on timesteps iterable of float Array of timesteps in units of s Note that values are not cumulative power float or iterable of float Power of the reactor in W A single value indicates that the power is constant over all timesteps An iterable indicates potentially different power levels for each timestep For a 2D problem the power can be given in W cm as long as the volume assigned to a depletion material is actually an area in cm 2 print_out bool optional Whether or not to print out time if not isinstance power Iterable power power len timesteps with operator as vec chain operator chain if operator prev_res is None t 0 0 else t operator prev_res 1 time 1 if operator prev_res is None i_res 0 else i_res len operator prev_res 1 for i dt p in enumerate zip timesteps power if i 0 or operator prev_res is None x copy deepcopy vec op_results operator x 0 p Results save operator x op_results t t dt p i_res i else x operator prev_res 1 data 0 op_results operator prev_res 1 op_results 0 rates op_results 0 rates 0 power_res operator prev_res 1 power ratio_power p power_res op_results 0 rates 0 ratio_power 0 x_end deplete chain x 0 op_results 0 dt print_out t dt vec copy deepcopy x_end x copy deepcopy vec op_results operator x 0 power 1 Results save operator x op_results t t p i_res len timesteps
calculate the mean of ` variable ` given ` weights ` .,def mean data None variable None weights None if data is not None variable weights utils _extract_values data variable weights return _statistics mean variable utils not_empty_weights weights variable
"if a node has no siblings , attempt to cross over to the children of the parent 's sibling .",def test_next_cross self child1 PageNode template test1 html child2 PageNode template test2 html child3 PageNode template test3 html child4 PageNode template test4 html root PageRoot template root html children PageNode children PageNode children child1 PageNode children PageNode children child2 child3 PageNode children child4 PageNode eq_ root next child1 eq_ child1 next child2 eq_ child2 next child3 eq_ child3 next child4 eq_ child4 next None
store a value in the cache .,def test_1_store self cache set CACHE_KEY smoo
delete post action - post belongs to thread and thread belongs to forum .,def test_delete_post_belongs_to_thread_and_document self r get self client wiki discuss delete_post args self doc_2 slug self thread id self post id eq_ 404 r status_code r get self client wiki discuss delete_post args self doc slug self thread_2 id self post id eq_ 404 r status_code
editing a locked thread returns 403 .,def test_edit_locked_thread_403 self locked ThreadFactory is_locked True u locked creator PostFactory thread locked author u self client login username u username password testpass response get self client forums edit_thread args locked forum slug locked id eq_ 403 response status_code
"clone product , with team .",def clone self args kwargs kwargs setdefault cascade team overrides kwargs setdefault overrides overrides setdefault name Cloned 0 format self name return super Product self clone args kwargs
save envs from selected source to productversion .,def save self source self choice_map self cleaned_data source self productversion add_envs source environments all return self productversion
"with two pages , last on second page is the last .",def test_high_more_than_size_page2 self self assertEqual self pager self qs 21 20 2 high 21
return the first locale_checkout_path for locales active for the repo 's project that matches the given path .,pytest mark django_db def test_repo_url_for_path project_locale_a repo_git locale_b ProjectLocaleFactory create project repo_git project locale locale_b repo_git url https example com path to locale_code repo_git save assert repo_git url_for_path os path join repo_git locale_checkout_path project_locale_a locale foo bar po https example com path to s project_locale_a locale code
handle failures like being unable to connect to the network .,def test_get_javascript_vulnerabilities_failure self mock_popen app_config app self get_app app_config error_output pretend im a traceback mock_popen 5 error_output pretend im a traceback with pytest raises DependencySecurityCheckFailed as err app get_javascript_vulnerabilities assert err value args 0 error_output
"gives extra points to reviews of apps that are compatible with multiple platforms , to reflect the extra effort involved . only new submissions get extra points ( for now ) .",classmethod def get_extra_platform_points cls addon status if status in mkt WEBAPPS_APPROVED_STATUSES return 0 event mkt REVIEWED_WEBAPP_PLATFORM_EXTRA platform_bonus mkt REVIEWED_SCORES get event devices_count len addon device_types if devices_count 2 return 0 else return devices_count 1 platform_bonus
return an exprop standing for arg1 < s arg2,def ExprOp_inf_signed arg1 arg2 return __ExprOp_cond m2_expr TOK_INF_SIGNED arg1 arg2
check if two object are equal,def __eq__ self other return self json other
test the to_utf8 function : string to unicode,def test_str_to_utf8 s u01ff u02ff u utils to_utf8 s assert_equal type s type str assert_equal type u type u u01ff u02ff
"retrieve a list of all name , entity pairs that i store references to .",def listStaticEntities self return self entities items
render as html a listing of all known users with links to their personal resources .,def render_GET self request listing Element ul for link text in self _users linkElement Element a linkElement setAttribute href link textNode Text textNode data text linkElement appendChild textNode item Element li item appendChild linkElement listing appendChild item return self template users listing toxml
begin listening for changes to the keymap .,def start_listening self accel_map Gtk AccelMap get accel_map connect changed self _accel_map_changed_cb
"we need to copy to be sure that we are dealing with son , not a dict .",def will_copy self return True
weights by squared distance matrix normalization .,def wbysqdist X dist weighted_X X dist 2 np fill_diagonal weighted_X 0 return weighted_X
tests calling s3scanner.load_configuration ( ) successfully,def test_load_configuration self u config u type u s3 scanner S3Scanner scanner load_configuration config self assertEquals scanner _scanner_type u s3
creates and returns a trigger rule configuration from the given dict,abstractmethod def create_configuration self config_dict u Creates and returns a trigger rule configuration from the given dict n n param config_dict The configuration as a dict n type config_dict dict n returns The trigger rule configuration n rtype class trigger configuration trigger_rule TriggerRuleConfiguration n n raises class trigger configuration exceptions InvalidTriggerRule If the configuration is invalid n raise NotImplementedError
tests a valid rule does not trigger a new event when the schedule threshold has not been met .,patch u job clock _trigger_event patch u job clock _check_schedule def test_check_rule_skip self mock_check_schedule mock_trigger_event u mock_check_schedule return_value False rule job_test_utils create_clock_rule name u test name clock _check_rule rule self assertTrue mock_check_schedule called self assertFalse mock_trigger_event called
modify v4 scheduler info with a subset of fields,def patch_v4 self request u Modify v4 scheduler info with a subset of fields n n param request the HTTP PATCH request n type request class rest_framework request Request n rtype class rest_framework response Response n returns the HTTP response to send back to the user n extra filter lambda x y self update_fields x not in y request data keys if len extra 0 return Response u Unexpected fields s u join extra status status HTTP_400_BAD_REQUEST if len request data 0 return Response u No fields specified for update status status HTTP_400_BAD_REQUEST try Scheduler objects update_scheduler dict request data scheduler Scheduler objects get_master except Scheduler DoesNotExist raise Http404 serializer self get_serializer scheduler return Response serializer data
tests successfully calling the metric plot view using a minimum aggregate .,def test_aggregate_min self u url u v5 metrics job types plot data column job_time_min response self client generic u GET url self assertEqual response status_code status HTTP_200_OK response content result json loads response content self assertEqual len result u results 1 self assertEqual result u results 0 u values 0 u value 20
validates a new workspace and returns any warnings discovered,def post self request u Validates a new workspace and returns any warnings discovered n n param request the HTTP POST request n type request class rest_framework request Request n rtype class rest_framework response Response n returns the HTTP response to send back to the user n name rest_util parse_string request u name json_config rest_util parse_dict request u json_config rest_util parse_string request u title required False rest_util parse_string request u description required False rest_util parse_string request u base_url required False rest_util parse_string request u is_active required False try warnings Workspace objects validate_workspace name json_config except InvalidWorkspaceConfiguration as ex logger exception u Unable to validate new workspace s name raise BadParameter unicode ex results u id w key u details w details for w in warnings return Response u warnings results
getblockbynumber returns the data contained within a specific block in the blockchain . the genesis block is block zero .,def GetBlockByNumber self request context context code beta_interfaces StatusCode UNIMPLEMENTED
process spawn concurrent ignored sigterm signal are handled on unix .,unittest skipIf os name nt Test won t run on Windows def test_decorated_ignoring_sigterm self future sigterm_decorated with self assertRaises TimeoutError future result
get the value of a real or calculated field : param key : field name : return : calculated field value,def __getattr__ self key if key in self __dict__ _calculated cls self __dict__ _calculated key if type cls in ManyToManyLink if key not in self __dict__ _map val cls from_internal self __dict__ _doc self __dict__ _map key val self __dict__ _dif key val return self __dict__ _map key else return cls from_internal self __dict__ _doc return self __dict__ _doc get key
"convert ' xx : xx : xx : xx : xx : xx ' mac address string to a tuple of integers . example : mac_str_to_tuple('00:01:02:03:04:05 ' ) = = ( 0 , 1 , 2 , 3 , 4 , 5 )",def mac_str_to_tuple mac return tuple int d 16 for d in mac split
publish the onu device start / start status .,def _publish_device_status_event self topic OnuDeviceEntry event_bus_topic self device_id OnuDeviceEvents DeviceStatusEvent msg ACTIVE_KEY self _started self event_bus publish topic topic msg msg
clear the queue and put new queue data list in the queue .,def put_queue_data self queue_data_list raise NotImplementedError
return the i d of the resource whose name matches the pattern .,def _id_from_name resource_config resources typename id_attr id try return getattr obj_from_name resource_config resources typename id_attr except AttributeError raise exceptions RallyException There is no attribute attr in the object type format attr id_attr type typename
handle incoming request . authenticate and send downstream .,def __call__ self environ start_response req Request environ self _logger debug Calling S3Token middleware if keystone token_info not in req environ req headers update h None for h in KEYSTONE_AUTH_HEADERS try parts split_path req path 1 4 True version account container obj parts except ValueError msg Not a path query s skipping req path self _logger debug msg return self _app environ start_response s3_auth_details req environ get s3api auth_details if not s3_auth_details msg No authorization details from s3api skipping self _logger debug msg return self _app environ start_response access s3_auth_details access_key if isinstance access six binary_type access access decode utf 8 signature s3_auth_details signature if isinstance signature six binary_type signature signature decode utf 8 string_to_sign s3_auth_details string_to_sign if isinstance string_to_sign six text_type string_to_sign string_to_sign encode utf 8 token base64 urlsafe_b64encode string_to_sign encode ascii force_tenant None if in access access force_tenant access split creds credentials access access token token signature signature creds_json json dumps creds self _logger debug Connecting to Keystone sending this JSON s creds_json try resp self _json_request creds_json except HTTPException as e_resp if self _delay_auth_decision msg Received error deferring rejection based on error s self _logger debug msg e_resp status return self _app environ start_response else msg Received error rejecting request with error s self _logger debug msg e_resp status return e_resp environ start_response self _logger debug Keystone Reply Status d Output s resp status_code resp content try token resp json if access in token headers token_id tenant parse_v2_response token elif token in token headers token_id tenant parse_v3_response token else raise ValueError req headers update headers req environ keystone token_info token except ValueError KeyError TypeError if self _delay_auth_decision error Error on keystone reply d s deferring rejection downstream self _logger debug error resp status_code resp content return self _app environ start_response else error Error on keystone reply d s rejecting request self _logger debug error resp status_code resp content return self _deny_request InvalidURI environ start_response req headers X Auth Token token_id tenant_to_connect force_tenant or tenant id if six PY2 and isinstance tenant_to_connect six text_type tenant_to_connect tenant_to_connect encode utf 8 self _logger debug Connecting with tenant s tenant_to_connect new_tenant_name s s self _reseller_prefix tenant_to_connect environ PATH_INFO environ PATH_INFO replace account new_tenant_name return self _app environ start_response
wait for existing instance to be gone .,test def instance_delete_wait self self test_runner run_instance_delete_wait
create archival contents in dump dir,def run_backup self try service run_command system QUIESCE_DB2 self execute_backup_cmd system OFFLINE_BACKUP_DB service run_command system UNQUIESCE_DB2 except exception ProcessExecutionError LOG exception An exception occurred while doing an offline backup self cleanup raise
descope messages set with ' . ',def descope_message_ids_set msgset_key tokens msgset_key split return tokens 1 or None tokens 0 or None
read the status of the boolean input,def read self self last_value self interface _read_bool self params return self last_value
the main function of the program .,def get_subtitle keyword is_filename True auto_download False chiconv_type zht out_file None if is_filename filename keyword keyword get_guessed_video_name filename results DOWNLOADER search keyword if not results print No subtitle for s keyword return if not auto_download target choose_subtitle results else target results 0 datatype sub_data DOWNLOADER download target get id file_handler COMPRESSPR_HANDLER get datatype compressor file_handler sub_data subtitle subtitle name subtitle body compressor extract_bestguess subtitle name subtitle name split 1 subtitle extension subtitle name split 1 subtitle body to_unicode subtitle body conv_func CHICONV get chiconv_type subtitle body conv_func subtitle body if subtitle extension srt subtitle body reset_index subtitle body subtitle body set_utf8_without_bom subtitle body subtitle body subtitle body replace r n n if not out_file if not is_filename filename subtitle name out_file filename replace filename split 1 zh s subtitle extension with open out_file w as subfile subfile write subtitle body return
verify signature against certificate text and signed data .,def signature_valid signature cert_text data certificate crypto load_certificate crypto FILETYPE_PEM cert_text decoded_signature b64decode signature try result crypto verify certificate decoded_signature data sha1 except crypto Error return False return result is None
"f(x , y , z ) f(x , k , w )",def par_test_13 self for i in range 4 self XYZ_par_factor setMaxDepth i self XKW_par_factor setMaxDepth i res self XYZ_factor mult self XKW_factor par_res self XYZ_par_factor mult self XKW_par_factor assert res rand_vars par_res rand_vars and res values par_res values
segment object instances from images .,def predict self imgs prepared_imgs sizes for img in imgs size img shape 1 img self prepare img astype np float32 prepared_imgs append img sizes append size masks labels scores for img size in zip prepared_imgs sizes with chainer using_config train False with chainer function no_backprop_mode img_var chainer Variable self xp array img None scale img_var shape 3 size 1 roi_ag_seg_scores _ roi_cls_scores bboxes _ self __call__ img_var scale roi_ag_seg_score roi_ag_seg_scores array roi_cls_score roi_cls_scores array bbox bboxes scale bbox 0 2 self xp clip bbox 0 2 0 size 0 bbox 1 2 self xp clip bbox 1 2 0 size 1 roi_seg_prob F softmax roi_ag_seg_score array 1 roi_cls_prob F softmax roi_cls_score array roi_seg_prob chainer cuda to_cpu roi_seg_prob roi_cls_prob chainer cuda to_cpu roi_cls_prob bbox chainer cuda to_cpu bbox roi_seg_prob bbox label roi_cls_prob mask_voting roi_seg_prob bbox roi_cls_prob size self score_thresh self nms_thresh self mask_merge_thresh self binary_thresh limit self limit bg_label 0 height bbox 2 bbox 0 width bbox 3 bbox 1 keep_indices np where height self min_drop_size width self min_drop_size 0 roi_seg_prob roi_seg_prob keep_indices bbox bbox keep_indices label label keep_indices roi_cls_prob roi_cls_prob keep_indices mask np zeros len roi_seg_prob size 0 size 1 dtype np bool for i roi_seg_pb bb in enumerate zip roi_seg_prob bbox bb np round bb astype np int32 y_min x_min y_max x_max bb roi_msk_pb resize roi_seg_pb astype np float32 None y_max y_min x_max x_min roi_msk roi_msk_pb self binary_thresh 0 mask i y_min y_max x_min x_max roi_msk masks append mask labels append label scores append roi_cls_prob return masks labels scores
"get the ` n ` top hypotheses , not grammarhypotheses but the ones stored in ` self.hypotheses ` .",def get_top_hypotheses self n 10 idx None gh_key recent h_key lambda x x posterior_score if idx is None idx self sample_count sample_idxs range 0 idx if gh_key is recent gh self samples idx if gh_key is MLE gh self get_top_samples n 1 s_idx sample_idxs key lambda x x likelihood 0 if gh_key is MAP gh self get_top_samples n 1 s_idx sample_idxs key lambda x x posterior_score 0 if gh_key is mean mean_value self mean_value sample_idxs gh self samples 1 __copy__ gh set_value mean_value sorted_hypotheses sorted gh hypotheses key h_key sorted_hypotheses reverse return sorted_hypotheses n
{ % available_teams as available_teams % },register tag def available_teams parser token return AvailableTeamsNode handle_token parser token
you should be able to subscribe at arbitrary events .,def test_subscribe_at_timeout env def pem env to env timeout 2 subscribe_at to try yield env timeout 10 except Interrupt as interrupt assert interrupt cause to None assert env now 2 env process pem env env run
this function is the first derivative of the semilinear function ( above ) . it is needed for the backward pass of the module .,def semilinearPrime x try shape x shape x flatten x x tolist except AttributeError shape 1 len x def f val if val 0 return safeExp val else return 1 0 return array list map f x reshape shape
"return the toplevel node with the provided name , and the fitting ' name ' attribute .",def findNamedNode self name nameattr root None if root None root self root for n in root childNodes if n nodeName name if n attributes name if n attributes name value nameattr return n return None
describes the schema based on a hash of the stub system state .,def describe_schema_versions self return self _schema 1 1 1 1
parses a json oembed response .,def parse_oembed_json oembed_response value_function __value_function_json json loads oembed_response return __construct_response value_function
"given a valid region name , return a : class:`boto.sns.connection . snsconnection ` .",def connect_to_region region_name kw_params return connect sns region_name connection_cls SNSConnection kw_params
"return a cached response if it exists in the cache , otherwise return false .",def cached_request self request cache_url self cache_url request url logger debug Looking up s in the cache cache_url cc self parse_cache_control request headers if no cache in cc logger debug Request header has no cache cache bypassed return False if max age in cc and cc max age 0 logger debug Request header has max_age as 0 cache bypassed return False cache_data self cache get cache_url if cache_data is None logger debug No cache entry available return False resp self serializer loads request cache_data if not resp logger warning Cache entry deserialization failed entry ignored return False if resp status 301 msg Returning cached 301 Moved Permanently response ignoring date and etag information logger debug msg return resp headers CaseInsensitiveDict resp headers if not headers or date not in headers if etag not in headers logger debug Purging cached response no date or etag self cache delete cache_url logger debug Ignoring cached response no date return False now time time date calendar timegm parsedate_tz headers date current_age max 0 now date logger debug Current age based on date i current_age resp_cc self parse_cache_control headers freshness_lifetime 0 if max age in resp_cc freshness_lifetime resp_cc max age logger debug Freshness lifetime from max age i freshness_lifetime elif expires in headers expires parsedate_tz headers expires if expires is not None expire_time calendar timegm expires date freshness_lifetime max 0 expire_time logger debug Freshness lifetime from expires i freshness_lifetime if max age in cc freshness_lifetime cc max age logger debug Freshness lifetime from request max age i freshness_lifetime if min fresh in cc min_fresh cc min fresh current_age min_fresh logger debug Adjusted current age from min fresh i current_age if freshness_lifetime current_age logger debug The response is fresh returning cached response logger debug i i freshness_lifetime current_age return resp if etag not in headers logger debug The cached response is stale with no etag purging self cache delete cache_url return False
"traverse the given expression structure , returning an iterator .",def iterate obj opts children obj get_children opts if not children return obj traversal deque stack deque obj while stack t stack popleft traversal append t for c in t get_children opts stack append c return iter traversal
create a suite with all tests from the given directories .,def suite dirs clean False pre True verbose 2 all True res unittest TestSuite for dir in dirs for test in get_tests dir clean test test test find 1 try mod test rfind 1 if mod 0 mod test mod mod __import__ test globals locals mod else mod __import__ test res addTest unittest defaultTestLoader loadTestsFromModule mod except ImportError if sys hexversion 33882112 _print Warning ignoring r incompatible with this Python version test else raise except SyntaxError NameError if pre _print Warning ignoring r due to an error while importing test else _print Error r missing or not found test if verbose 2 raise all False return res all
"when incoming call initiated , new contact should have number .",def test_call_has_contact_incoming_call self self client get reverse_lazy call From 12345678910 contact Call objects first contact self assertEqual contact number 12345678910
main work routine of the snuffling .,def call self self cleanup swin ratio self swin self ratio lwin swin ratio tpad lwin data_pile self get_pile tmin tmax data_pile get_tmin tpad data_pile get_tmax tpad viewer self get_viewer if not self apply_to_all vtmin vtmax viewer get_time_range tmin max vtmin tmin tmax min vtmax tmax tinc min lwin self block_factor tmax tmin show_level_traces self show_level_traces if show_level_traces and tmax tmin lwin 150 self error Processing time window is longer than 50 x LTA window Turning off display of level traces show_level_traces False markers for traces in data_pile chopper tmin tmin tmax tmax tinc tinc tpad tpad want_incomplete False trace_selector lambda x not x meta and x meta get tabu False sumtrace None isum 0 for tr in traces if viewer lowpass is not None tr lowpass 4 viewer lowpass nyquist_exception True if viewer highpass is not None tr highpass 4 viewer highpass nyquist_exception True if self variant centered tr sta_lta_centered swin lwin scalingmethod scalingmethod_map self scalingmethod elif self variant right tr sta_lta_right swin lwin scalingmethod scalingmethod_map self scalingmethod tr chop tr wmin min tr wmax tmax if not self apply_to_sum markers extend trace_to_pmarkers tr self level swin tr set_codes location cg tr meta tabu True if sumtrace is None ny int tr tmax tr tmin data_pile deltatmin sumtrace trace Trace deltat data_pile deltatmin tmin tr tmin ydata num zeros ny sumtrace set_codes network station SUM location cg channel sumtrace meta tabu True sumtrace add tr left None right None isum 1 if sumtrace is not None sumtrace ydata float isum if self apply_to_sum markers extend trace_to_pmarkers sumtrace self level swin if show_level_traces self add_trace sumtrace self add_markers markers if show_level_traces self add_traces traces
returns whether this node is trainable .,def is_trainable self return self trainable
"( frameapi ( frameapi 0x01c0f920 ) , [ ' delayedexecute ' , ' framenumber ' , ' postframeupdate ' , ' updated ' , ' wallclocktime ' , ' _ _ dict _ _ ' , ' _ _ doc _ _ ' , ' _ _ module _ _ ' , ' _ _ weakref _ _ ' , ' blocksignals ' , ' childevent ' , ' children ' , ' classname ' , ' connect ' , ' customevent ' , ' delete ' , ' deletelater ' , ' destroyed ' , ' disconnect ' , ' dumpobjectinfo ' , ' dumpobjecttree ' , ' dynamicpropertynames ' , ' emit ' , ' event ' , ' eventfilter ' , ' findchild ' , ' findchildren ' , ' help ' , ' installeventfilter ' , ' iswidgettype ' , ' killtimer ' , ' movetothread ' , ' objectname ' , ' parent ' , ' property ' , ' removeeventfilter ' , ' setobjectname ' , ' setparent ' , ' setproperty ' , ' signalsblocked ' , ' starttimer ' , ' thread ' , ' timerevent ' , ' tr ' ] )",def attach_frame_update_callback func if naali naali frame connect Updated float func else frameAPI tundra Frame frameAPI connect Updated float func
fill in the computed bits of config dict prior to test execution,classmethod def setUpClass cls super TestBuildClusters cls setUpClass reset_config
return a custom 404 error .,app errorhandler 404 def page_not_found e return Sorry Nothing at this URL 404
start the openflow manager and message receivers,def launch ctrl PoxManager log Config DbName Config DbUser mq MsgQueueReceiver Config QueueId ctrl ctrl registerReceiver mq rpc RpcReceiver Config RpcHost Config RpcPort ctrl ctrl registerReceiver rpc core register ravelcontroller ctrl
return location for the pretrained on local file system .,def get_model_file name root os path join mxnet models file_name name short_hash format name name short_hash short_hash name root os path expanduser root file_path os path join root file_name params sha1_hash _model_sha1 name if os path exists file_path if check_sha1 file_path sha1_hash return file_path else print Mismatch in the content of model file detected Downloading again else print Model file is not found Downloading if not os path exists root os makedirs root zip_file_path os path join root file_name zip repo_url os environ get MXNET_GLUON_REPO apache_repo_url if repo_url 1 repo_url repo_url download _url_format format repo_url repo_url file_name file_name path zip_file_path overwrite True with zipfile ZipFile zip_file_path as zf zf extractall root os remove zip_file_path if check_sha1 file_path sha1_hash return file_path else raise ValueError Downloaded file has different hash Please try again
debug deletes obj of obj[_type ] with i d of obj['_id ' ],def del_object self obj u if obj u _index is None or obj u _index u raise Exception u Invalid Object if obj u _id is None or obj u _id u raise Exception u Invalid Object if obj u _type is None or obj u _type u raise Exception u Invalid Object self connect_es self es delete index obj u _index id obj u _id doc_type obj u _type
parse command line to generate arguments .,def _parse_command_line program_name cmd_line parser argparse ArgumentParser prog program_name parser add_argument build_rule metavar build_rule help Full name build rule to find the dependencies of return parser parse_args cmd_line
tests l and its inverse .,def test_LLinv adjcube from pydft bases fourier import L Linv Sprod np prod adjcube S for i in range 10 v np random random size Sprod it Linv L v 1 if abs np max np imag it 1e 14 it np real it assert np allclose it v 1
"return the decoded iv from an hsub . by default the iv is the first 64bits of the hsub . as it 's hex encoded , this equates to 16 digits .",def hexiv hsub digits 16 if len hsub digits return False try iv hsub digits decode hex except TypeError return False return iv
returns a list of headers returned by the server .,def get_headers self return self _response info headers
test _ parameter and _ fileparameter classes,def test_parameters self p web_service _Parameter foo bar 0 optp web_service _Parameter foo bar 1 f web_service _FileParameter foo bar 1 self assertEqual p get_full_arg foo ARG self assertEqual optp get_full_arg foo ARG self assertEqual f get_full_arg foo FILENAME self assertEqual p get_help foo 17 bar self assertEqual optp get_help foo 17 bar optional self assertEqual f get_help foo 17 bar optional
"given a list of column names , returns a similar sized list with unique names",staticmethod def _uniqify_columns df_columns seen set new list for item in df_columns fudge 1 newitem item while newitem in seen fudge 1 newitem _ format item fudge new append newitem seen add newitem assert len set new len new return new
function to generate the overview table from the ini files that define the features for each driver .,def generate_overview_table output_filename table_id section table_name title warning Warning generate_overview_table ini_path path_join dirname output_filename features config configparser ConfigParser config optionxform str config read path_join ini_path default ini default_features config items section valid_features max_feature_length 0 for feature in default_features key feature 0 valid_features key max_feature_length max max_feature_length len key ini_files basename file for file in listdir ini_path if file endswith ini and file default ini ini_files sort header_names for ini_filename in ini_files name ini_filename 4 name name replace _vf vf if _vec in name pmd vec name split _ name 0 fill align 7 vec format pmd fill align else name 0 fill align 10 format name fill align header_names append name ini_data for ini_filename in ini_files config configparser ConfigParser config optionxform str config read path_join ini_path ini_filename ini_data ini_filename valid_features copy if not config has_section section print File has no secton format warning ini_filename section continue for name value in config items section if name not in valid_features print Unknown feature in format warning name ini_filename continue if value is not ini_data ini_filename name value 0 outfile open output_filename w num_cols len header_names print_table_css outfile table_id print table table_name n file outfile print_table_header outfile num_cols header_names title print_table_body outfile num_cols ini_files ini_data default_features
ensure that nothing blows up if we reload a class,def test_reload self self client queues foo put Foo jid jid self assertEqual self client jobs jid klass Foo Job reload self client jobs jid klass_name self assertEqual self client jobs jid klass Foo
should fail if unable to import with plotly,def test_plotly_import_error self real_import builtins __import__ def fake_import args kwargs if args and args 0 plotly raise ImportError Fake Error return real_import args kwargs with patch builtins __import__ as import_func import_func side_effect fake_import result render plotly self assertGreater result find cd ImportError 0
create teachingcapability objects for any courses this person has taught in recent years .,classmethod def populate_from_history cls person years 2 old_sem Semester get_semester datetime date today datetime timedelta days 365 years members Member objects filter person person role INST offering__semester__name__gte old_sem name courses set m offering course for m in members select_related offering__course existing set tc course_id for tc in TeachingCapability objects filter instructor person for crs in courses if crs id not in existing tc TeachingCapability instructor person course crs tc save
"given a python object o , return the corresponding type hint .",def instance_to_type o t type o if o is None return type None elif t not in typehints DISALLOWED_PRIMITIVE_TYPES if t types InstanceType return o __class__ elif t BoundMethod return types MethodType return t elif t tuple return typehints Tuple instance_to_type item for item in o elif t list return typehints List typehints Union instance_to_type item for item in o elif t set return typehints Set typehints Union instance_to_type item for item in o elif t dict return typehints Dict typehints Union instance_to_type k for k v in o items typehints Union instance_to_type v for k v in o items else raise TypeInferenceError Unknown forbidden type s t
a helper method to test get_estimated_size_bytes,def check_estimated_size_bytes self entity_bytes timestamp namespace None timestamp_req helper make_request self _PROJECT namespace helper make_latest_timestamp_query namespace timestamp_resp self make_stats_response timestamp datastore_helper from_timestamp timestamp kind_stat_req helper make_request self _PROJECT namespace helper make_kind_stats_query namespace self _query kind 0 name datastore_helper micros_from_timestamp timestamp kind_stat_resp self make_stats_response entity_bytes entity_bytes def fake_run_query req if req timestamp_req return timestamp_resp elif req kind_stat_req return kind_stat_resp else print kind_stat_req raise ValueError Unknown req s req self _mock_datastore run_query side_effect fake_run_query self assertEqual entity_bytes ReadFromDatastore get_estimated_size_bytes self _PROJECT namespace self _query self _mock_datastore self assertEqual self _mock_datastore run_query call_args_list call timestamp_req call kind_stat_req
this function merge all the htseqcount into one matrix,def merge_htseqCount path os chdir path files f for f in os listdir path if f endswith txt files natsorted files dfs for f in files df pd read_csv f sep t header None names id f 4 index_col 0 dfs append df res pd concat dfs axis 1 res to_csv path Count csv sep
turn the diff eq trajectory ( list of state vectors ) into a list of density matrices,def state_vector_density_matrix self rho return rho
look for groups of numbers ( offsets ) delimited by non a - z characters,def parse_offset_str self s if not s return None if re search a zA Z s return None delimiter re search D s group if not delimiter return None arr map int s split delimiter return arr
builds a stand alone xsd file per model ; returs the file name .,def write_model_xsd_file self model path encoding utf 8 if not os path isdir path raise IOError Path does not exist xsd_out_node self __get_model_node model self __get_nodes model file_name self __get_xsd_file_name model xsd_out_node file_path os path join path file_name self __write_xsd encoding file_path xsd_out_node return file_path
filter a list of pmids for ones with full text from pmc .,def filter_pmids pmid_list source_type u Filter a list of PMIDs for ones with full text from PMC n n Parameters n n pmid_list list n List of PMIDs to filter n source_type string n One of fulltext oa_xml oa_txt or auth_xml n n Returns n n list of PMIDs available in the specified source format type n global pmids_fulltext_dict if source_type not in u fulltext u oa_xml u oa_txt u auth_xml raise ValueError u source_type must be one of fulltext oa_xml oa_txt or auth_xml if pmids_fulltext_dict get source_type is None fulltext_list_path os path join os path dirname __file__ u pmids_ s txt source_type with open fulltext_list_path u rb as f fulltext_list set line strip u n decode u utf 8 for line in f readlines pmids_fulltext_dict source_type fulltext_list return list set pmid_list intersection pmids_fulltext_dict get source_type
exception raised when a sample asks for a plugin that ca n't be found,def __init__ self name msg Plugin Not Found or Failed to load self msg msg self name name super FailedLoadingPlugin self __init__ msg
"runs a single command , displaying it first .",def run self command display None stdout None stderr None if display is None display command self display display return self execute command stdout stderr
search through lines for match . raise an exception if fail to match if match is succesful return the position the match was found,def match self subsetLines offsetOfSubset fileName for offset l in enumerate subsetLines column l find self literal if column 1 truePosition offset offsetOfSubset _logger debug Found match on line col format str truePosition 1 column _logger debug Line is format l self matchLocation CheckFileParser FileLocation fileName truePosition 1 return truePosition self failed True raise DirectiveException self
return a snapshot of resolvable = > compatible packages set from the resolvable set .,def packages self return list self _collapse values
read the touchpad mode and return the mode index .,def _read_touchpad_mode mode_str _read_touchpad_mode_str if mode_str not in TOUCHPAD_MODES return None return TOUCHPAD_MODES index mode_str
ensure that duplicate tasks can not exist,def test_add_duplicate_task_with_url self task_1 self fixtures test_task_1 task_1 url http example org task_1 save with self assertRaises IntegrityError Task objects create event task_1 event person task_1 person role task_1 role url task_1 url
showing is the same as saving without a filename .,def show abf save abf
load all maps of a given type into a dictionary .,def _load_maps_by_type map_type seq_maps COLOR_MAPS map_type loaded_maps for map_name in seq_maps loaded_maps map_name for num in seq_maps map_name inum int num colors seq_maps map_name num Colors bmap BrewerMap map_name map_type colors loaded_maps map_name inum bmap max_num int max seq_maps map_name keys key int loaded_maps map_name max loaded_maps map_name max_num return loaded_maps
return the deepest node containing colour .,def get_deepest_containing self colour for child in self children if child contains colour return child get_deepest_containing colour return self
defines a whole ton of attributes based on the attributes argument . the job file is read and self.command is constructed .,def __init__ self attributes self id attributes 0 self source attributes 1 self destination attributes 2 self interval int attributes 3 self method attributes 4 self options react self job_path viento_utils f_job format self id self count 0 self adjust_lengths 2 3 self interval_persist self interval self transferring False self time_executed 0 self command self command_construct
"returns the matched text , and moves to the next token",def scan self type kw context kw get context None if self last_token is None tok self token type context else if self last_types and type not in self last_types raise NotImplementedError Unimplemented restriction set changed tok self last_token self last_token None if tok type type if not self last_types self last_types raise SyntaxError tok pos Trying to find type join self last_types got tok type context context return tok value
return options to send the method caller from base options and media file .,def get_method_options_with_media method_options media_file media_body apiclient http MediaFileUpload media_file chunksize 1 resumable True mimetype application octet stream media_file_field MediaFileUpload format media_file printable_request lib merge method_options media_body media_file_field config logger debug Request lib pretty_json printable_request return lib merge method_options media_body media_body
perform a reset of the segmentation systems underlying data .,def reset self self mColorModel reset
"extract information from firmware , return pretty string to user",def frame_from_firmware self firmware frame_to_mavlink_dict quad QUADROTOR hexa HEXAROTOR y6 ARDUPILOT_Y6 tri TRICOPTER octa OCTOROTOR octa quad ARDUPILOT_OCTAQUAD heli HELICOPTER Plane FIXED_WING Tracker ANTENNA_TRACKER Rover GROUND_ROVER PX4IO ARDUPILOT_PX4IO mavlink_to_frame_dict v k for k v in frame_to_mavlink_dict items x firmware mav type if firmware mav autopilot ARDUPILOTMEGA return x if x in mavlink_to_frame_dict return mavlink_to_frame_dict x return x
"run the command to download target . if the command fails , clean up before re - raising the error .",def _clean_check cmd target try subprocess check_call cmd except subprocess CalledProcessError if os access target os F_OK os unlink target raise
"return an enumeration of line_number , line pairs .",def enumerate self return enumerate self 1
"progress toward timeout , from 0 to 1 .",property def progress self return self count self max_count
export a given dataset to a ` csv ` file .,def export self current self vtgui dbs_tree_view currentIndex leaf self vtgui dbs_tree_model nodeFromIndex current node if leaf nrows 0 log info translate ExportToCSV Empty dataset Nothing to export return if leaf shape log info translate ExportToCSV Scalar array Nothing to export return if len leaf shape 3 log info translate ExportToCSV The selected node has more than 3 dimensions I can t export it to CSV format return if isinstance leaf tables VLArray log info translate ExportToCSV The selected node is a VLArray I can t export it to CSV format return is_table isinstance leaf tables Table if is_table if self _try_exporting_dataframe leaf return first_row leaf 0 for item in first_row if item shape log info translate ExportToCSV Some fields aren t scalars I can t export the table to CSV format return export_info self getExportInfo is_table if export_info is None return else filepath add_header export_info try try QtWidgets qApp setOverrideCursor QtCore Qt WaitCursor with open filepath ab as out_handler if add_header from functools import reduce header reduce lambda x y 0 1 format x y leaf colnames out_handler write bytearray header n UTF 8 chunk_size 10000 nrows leaf nrows if chunk_size nrows chunk_size nrows nchunks numpy floor_divide nrows chunk_size for i in numpy arange 0 nchunks 1 QtWidgets qApp processEvents cstart chunk_size i if cstart nrows break cstop cstart chunk_size if cstop nrows cstop nrows numpy savetxt out_handler leaf read cstart cstop 1 fmt s delimiter except OSError vitables utils formatExceptionInfo finally QtWidgets qApp restoreOverrideCursor
< nick > - hit your head against the desk becausae of < nick>. code located in reactions.py,hook command hd headdesk def head_desk text message idiot text strip message format idiot random choice reaction_macros head_desk_macros
interleave input array using the specific interleaver .,def interlv self in_array out_array array map lambda x in_array x self p_array return out_array
parse each source file in @source_files and return dictionary with source files as keys and lists of references kconfig symbols as values .,def parse_source_files source_files referenced_symbols dict for sfile in source_files referenced_symbols sfile parse_source_file sfile return referenced_symbols
end to end testing and example of eventfd usage,pytest mark intergration pytest mark eventfd def test_eventfd_intergration test_val 36 ev Eventfd test_val assert int ev test_val Inital value did not match expected ev increment test_val assert int ev test_val Inital value did not match expected ev increment test_val for i in range 5 assert int ev test_val 5 Inital value did not match expected ev close
read blob data from file and return it with correct datawidth and shape,def get_rb_blob_from_file f blobdict try f seek 0 0 fid f datastring fid read except AttributeError try fid open f rb datastring fid read fid close except IOError print WRADLIB Error opening Rainbow file f raise IOError data get_rb_blob_from_string datastring blobdict return data
shape function for the variablelstm op .,tf RegisterShape VariableLSTM def _variable_lstm_shape op input_shape op inputs 0 get_shape with_rank 4 state_shape op inputs 1 get_shape with_rank 2 memory_shape op inputs 2 get_shape with_rank 2 w_m_m_shape op inputs 3 get_shape with_rank 3 batch_size input_shape 0 merge_with state_shape 0 batch_size input_shape 0 merge_with memory_shape 0 seq_len input_shape 1 gate_num input_shape 2 merge_with w_m_m_shape 1 output_dim input_shape 3 merge_with state_shape 1 output_dim output_dim merge_with memory_shape 1 output_dim output_dim merge_with w_m_m_shape 0 output_dim output_dim merge_with w_m_m_shape 2 return batch_size seq_len output_dim batch_size seq_len gate_num output_dim batch_size seq_len output_dim
coalesce bitmap contents of parent onto child log file,def coalesce_bitmap parent_path child_path cmd CBT_UTIL coalesce p parent_path c child_path _call_cbt_util cmd
"wrap and return the given socket , plus wsgi environ entries .",def wrap self sock try s ssl wrap_socket sock do_handshake_on_connect True server_side True certfile self certificate keyfile self private_key ssl_version ssl PROTOCOL_SSLv23 except ssl SSLError e sys exc_info 1 if e errno ssl SSL_ERROR_EOF return None elif e errno ssl SSL_ERROR_SSL if e args 1 endswith http request raise wsgiserver NoSSLError elif e args 1 endswith unknown protocol return None raise return s self get_environ s
draw a rectangle with corners at the provided upper - left and lower - right coordinates .,def rectangle win uly ulx lry lrx win vline uly 1 ulx curses ACS_VLINE lry uly 1 win hline uly ulx 1 curses ACS_HLINE lrx ulx 1 win hline lry ulx 1 curses ACS_HLINE lrx ulx 1 win vline uly 1 lrx curses ACS_VLINE lry uly 1 win addch uly ulx curses ACS_ULCORNER win addch uly lrx curses ACS_URCORNER win addch lry lrx curses ACS_LRCORNER win addch lry ulx curses ACS_LLCORNER
profile an exec - compatible string in the script environment .,def run self cmd import __main__ dict __main__ __dict__ return self runctx cmd dict dict
do the hard work for readmodule[_ex ] .,def _readmodule module path inpackage None if inpackage is not None fullmodule s s inpackage module else fullmodule module if fullmodule in _modules return _modules fullmodule dict if module in sys builtin_module_names and inpackage is None _modules module dict return dict i module rfind if i 0 package module i submodule module i 1 parent _readmodule package path inpackage if inpackage is not None package s s inpackage package return _readmodule submodule parent __path__ package f None if inpackage is not None f fname _s _m ty imp find_module module path else f fname _s _m ty imp find_module module path sys path if ty imp PKG_DIRECTORY dict __path__ fname path fname path f fname _s _m ty imp find_module __init__ fname _modules fullmodule dict if ty imp PY_SOURCE f close return dict stack g tokenize generate_tokens f readline try for tokentype token start _end _line in g if tokentype DEDENT lineno thisindent start while stack and stack 1 1 thisindent del stack 1 elif token def lineno thisindent start while stack and stack 1 1 thisindent del stack 1 tokentype meth_name start g next 0 3 if tokentype NAME continue if stack cur_class stack 1 0 if isinstance cur_class Class cur_class _addmethod meth_name lineno else dict meth_name Function fullmodule meth_name fname lineno stack append None thisindent elif token class lineno thisindent start while stack and stack 1 1 thisindent del stack 1 tokentype class_name start g next 0 3 if tokentype NAME continue tokentype token start g next 0 3 inherit None if token names level 1 super while True tokentype token start g next 0 3 if token in and level 1 n join super if n in dict n dict n else c n split if len c 1 m c 2 c c 1 if m in _modules d _modules m if c in d n d c names append n super if token level 1 elif token level 1 if level 0 break elif token and level 1 pass elif tokentype in NAME OP and level 1 super append token inherit names cur_class Class fullmodule class_name inherit fname lineno if not stack dict class_name cur_class stack append cur_class thisindent elif token import and start 1 0 modules _getnamelist g for mod _mod2 in modules try if inpackage is None _readmodule mod path else try _readmodule mod path inpackage except ImportError _readmodule mod except pass elif token from and start 1 0 mod token _getname g if not mod or token import continue names _getnamelist g try d _readmodule mod path inpackage except continue for n n2 in names if n in d dict n2 or n d n elif n for n in d if n 0 _ dict n d n except StopIteration pass f close return dict
subroutine to create a list box .,def make_list_box parent width 0 height 0 hbar 0 vbar 1 fill BOTH expand 1 pack 1 class_ None name None takefocus None hbar vbar frame make_scrollbars parent hbar vbar pack class_ class_ name name takefocus takefocus widget Listbox frame name listbox if width widget config width width if height widget config height height widget pack expand expand fill fill side LEFT set_scroll_commands widget hbar vbar return widget frame
override socketio method - terminate wait on callback and exit thread,def EOFhook self global quitting quitting True thread interrupt_main
gets a list of external users,def get self max page int self request get page 0 page_size int max json memcache get TopExternalUsers str page_size str page if json is None users ExternalUser all order nr_of_subscribers fetch page_size page_size page json for user in users json append get_external_user_subscription_struct user json simplejson dumps json memcache set TopExternalUsers str page_size str page json 60 5 self response headers Content Type application json self response out write json
feed a character with known length,def feed self aBuf aCharLen if aCharLen 2 order self get_order aBuf else order 1 if order 0 self _mTotalChars 1 if order self _mTableSize if 512 self _mCharToFreqOrder order self _mFreqChars 1
run model inference and return the result,def run self inputs kwargs data_forward for val in inputs data_forward append mx nd array val if self device CPU ctx mx cpu else raise NotImplementedError ONNX tests are run only for CPU context data_names graph_input for graph_input in self symbol list_inputs if graph_input not in self arg_params and graph_input not in self aux_params data_shapes for idx input_name in enumerate data_names data_shapes append input_name inputs idx shape mod mx mod Module symbol self symbol data_names data_names context ctx label_names None mod bind for_training False data_shapes data_shapes label_shapes None mod set_params arg_params self arg_params aux_params self aux_params mod forward mx io DataBatch data_forward result mod get_outputs 0 asnumpy return result
sample a testing batch ( data and label ) .,def get_test_batch self batch_size self batch_size batch self get_image self test_image_files self test_count batch_size i len self test_image_files is_train False for i in range batch_size labels self test_labels self test_count batch_size i len self test_image_files for i in range batch_size return nd concatenate batch axis 0 labels
"return the current position as a value that may be passed to datafilereader.seek(long ) . forces the end of the current block , emitting a synchronization marker .",def sync self self _WriteBlock return self writer tell
helper func that creates an image object . others may replace this with a specific solution . the important point is that it returns a link,def make_local_image embedded_cid filename payload import models image_model models EmbeddedImageModel filename filename data payload image_model put return image_model link
split size ( in mb ),def __init__ self inFile outFile None splitSize 20 self _inFile inFile if outFile is None self _outFile inFile else self _outFile outFile self _splitSize splitSize 1000000 self setKeyExtractMethod
"return a number from a continuos fraction fc0 [ a1,a2,a3 , ... ]",def fc2dec fc0 ff list fc0 ff reverse return reduce lambda x y y 1 0 x ff
which strategy we will use is lazily determined on the first call .,def __init__ self self _strsignal None
get items that have no unbuilt dependencies,def no_deps items deps built return i for i in items if not depends_on_unbuilt i deps built
copies the polygon by copying its vertices .,def copy self return Polygon vertex copy for vertex in self vertices
pop an element from the desired stack and extract the data .,def handle_endtag self tag o self stacks tag pop if self elements has_key o self idd self elements o self rawdata o self abspos
"look for a _ set_attr method . if found , use it . otherwise , if the attribute is a db column , use odbc . otherwise , set in the object dict .",def __setattr__ self attr value try setmethod getattr self _set_ attr return apply setmethod value except AttributeError pass if attr in self _db_cols keys self _db_set_attr attr value return self __dict__ attr value
"receives , decodes , and returns string .",def decode string index string find while index 1 string string index chr int string index 1 index 3 16 string index 3 index string find index 1 return string
return the list of strings or file objects whose content will be sent to the client override this method in subclasses,def make_response self return xxx
"n : int offset position , relative to the start of the self.line array",def check_with_tolerance self n h t tolerance if not len self line 0 return True 1 h for offset in np arange 0 len self line 1 if self verbose print offset offset n n offset n offset n self line offset offset n self line offset offset n if self line offset offset n shape 0 h shape 0 and self line offset offset n shape 0 t shape 0 spread np abs np sum self line offset offset n np sum h if spread tolerance return True offset h return False 0 None
store the value to the storage,def _write_ self instance value
convenience function to get path to windows installation directory .,def get_windir return unicode os environ WINDIR
partial derivative at a given point,def partial func point index return d func Num x i index for i x in enumerate point
"return an iterator over all the keys of the property dictionary , i.e the names of the properties",def propertyNames self return self _props keys
turn a source file into its group name,def make_key self src key src name split sep 0 if key key os path basename os path realpath self export_dir return key
run a check function on obj,def _do_check self obj check_module check_str opts self _config options if check_str in opts fargs opts check_str if isinstance fargs list out check_wrapper getattr check_module check_str obj fargs else out check_wrapper getattr check_module check_str obj fargs else out check_wrapper getattr check_module check_str obj try if out info L debug s d failing ids detected s out title len out info out info except TypeError pass return out
returns a string containing a guid starting at the relative offset . arguments : - ` offset ` : the relative offset from the start of the block . throws : - ` overrunbufferexception `,def unpack_guid self offset o self _offset offset try _bin self _buf o o 16 except IndexError raise OverrunBufferException o len self _buf h map ord _bin return 02x 02x 02x 02x 02x 02x 02x 02x 02x 02x 02x 02x 02x 02x 02x 02x h 3 h 2 h 1 h 0 h 5 h 4 h 7 h 6 h 8 h 9 h 10 h 11 h 12 h 13 h 14 h 15
takes an egg and returns a subset of the subjects or lists,def crack_egg egg subjects None lists None from egg import Egg if hasattr egg features all_have_features egg features is not None else all_have_features False opts if subjects is None subjects egg pres index levels 0 values tolist elif type subjects is not list subjects list subjects if lists is None lists egg pres index levels 1 values tolist elif type lists is not list lists list lists idx pd IndexSlice pres egg pres loc idx subjects lists egg pres columns rec egg rec loc idx subjects lists egg rec columns pres pres loc sub values tolist for sub in subjects rec rec loc sub values tolist for sub in subjects if all_have_features features egg features loc idx subjects lists egg features columns opts features features loc sub values tolist for sub in subjects return Egg pres pres rec rec opts
azimuth processing algorithm test 02 ------------------------------------,def test_azimuth_processing_algorithm_02 self expected TestDataLoader self expected_02 delim input_data TestDataLoader self inputs_02 delim self initialise_algorithm input_data waveform_shape self chd n_ku_pulses_burst self chd n_samples_sar wfm_i np reshape input_data wfm_cor_sar_i waveform_shape wfm_q np reshape input_data wfm_cor_sar_q waveform_shape wv_len input_data wv_length_ku packet L1AProcessingData self cst self chd time_sar_ku input_data time_sar_ku x_vel_sat_sar input_data x_vel_sat_sar y_vel_sat_sar input_data y_vel_sat_sar z_vel_sat_sar input_data z_vel_sat_sar pri_sar_pre_dat input_data pri_sar_pre_dat beam_angles_list input_data beam_angles_list waveform_cor_sar wfm_i 1j wfm_q packet calculate_beam_angles_trend input_data beam_angles_list_size_previous_burst input_data beam_angles_trend_previous_burst self azimuth_processing_algorithm packet wv_len beams_focused self azimuth_processing_algorithm beams_focused wfm_i np reshape expected beams_focused_i waveform_shape wfm_q np reshape expected beams_focused_q waveform_shape for pulse_index in range self chd n_ku_pulses_burst for sample_index in range self chd n_samples_sar pos nstack sample format pulse_index self chd n_ku_pulses_burst sample_index self chd n_samples_sar expected_val wfm_i pulse_index sample_index actual_val beams_focused pulse_index sample_index real if expected_val 0 self assertEqual expected_val actual_val msg pos else rel_err abs expected_val actual_val expected_val self assertLess rel_err 1e 10 msg pos expected_val wfm_q pulse_index sample_index actual_val beams_focused pulse_index sample_index imag if expected_val 0 self assertEqual expected_val actual_val msg pos else rel_err abs expected_val actual_val expected_val self assertLess rel_err 1e 10 msg pos
"parse the output of given bat file , with given args .",def get_output vcbat args None env None if args debug Calling s s vcbat args popen subprocess Popen s s set vcbat args stdout subprocess PIPE stderr subprocess PIPE env env else debug Calling s vcbat popen subprocess Popen s set vcbat stdout subprocess PIPE stderr subprocess PIPE env env stdout popen stdout read if popen wait 0 raise IOError popen stderr read decode mbcs output stdout decode mbcs return output
get data for a single group in this inventory .,def get_group_data self group return self group_data get group
returns if the optimizer is a gradient - based algorithm or not .,def gradient_enabled self return not self _wrapper_args exclude_gradient
returns the ground resolution for based on latitude and zoom level .,def getGroundResolution self latitude level latitude self clipValue latitude self min_lat self max_lat mapSize self getMapDimensionsByZoomLevel level return math cos latitude math pi 180 2 math pi self earth_radius mapSize
helper function for calling line_follower . will kick out at intersection .,def follow self dir_of_intersection self call follower analog_state return dir_of_intersection
checks if the given future policy is supported by the writer .,def IsFuturePolicySupported self policy return False
test configuration with missing password .,def test_config_wrong1 self with self assertRaises PyVLXException PyVLX test data test_config_wrong1 yaml
check that appropriate warnings are logged .,assert_no_logs pytest mark parametrize source messages lipsum margin 2cm WARNING Invalid or unsupported selector lipsum margin 2cm WARNING Invalid or unsupported selector foo margin color red WARNING Ignored unknown property foo margin top red WARNING Ignored invalid value import relative uri css ERROR Relative URI reference without a base URI import invalid protocol absolute URL ERROR Failed to load stylesheet at def test_warnings source messages with capture_logs as logs CSS string source assert len logs 1 source for message in messages assert message in logs 0
find packages that are plugins of the given package .,def get_plugins package_name paths None pkg get_latest_package package_name paths paths error True if not pkg has_plugins return it iter_package_families paths package_names set x name for x in it bar ProgressBar Searching len package_names plugin_pkgs for package_name_ in package_names bar next if package_name_ package_name continue plugin_pkg get_latest_package package_name_ paths paths if not plugin_pkg plugin_for continue for plugin_for in plugin_pkg plugin_for if plugin_for pkg name plugin_pkgs append package_name_ bar finish return plugin_pkgs
called when an connection has been terminated .,def connectionTerminated connection
part of a query which finds a piece of text .,def text_query text if text is None or not len text strip return match_all return bool minimum_should_match 1 should meta_query_string text child_record bool should text_query_string text
build a keras model and return a compiled model .,def model_architecture self input_shape output_shape u from keras models import Sequential from keras layers import Masking LSTM Dense TimeDistributed Activation model Sequential if len output_shape 1 model add Masking mask_value 1 input_shape input_shape model add LSTM self rnn_size dropout 0 2 model add Dense input_dim self rnn_size units output_shape 1 elif len output_shape 2 model add Masking mask_value 1 input_shape None input_shape 1 model add LSTM self rnn_size return_sequences True dropout 0 2 model add TimeDistributed Dense units output_shape 1 else raise ValueError u Cannot construct the model becauselength of output_shape should be 1 or 2 format len output_shape model add Activation u softmax model compile loss u categorical_crossentropy optimizer u rmsprop metrics u accuracy logger debug model summary return model
and a single entry to a table for a path overides : meth:`database.add_entry `,def add_entry self table path entry update 1 k_join self RUNTIME DB JOIN NAME return k_join format table path
standard way to remove stopwords from text . text is a string . stopwords is a list of strings to remove . returns cleaned string .,def remove_stopwords text stopwords text text for w in stopwords text text replace u 0 format w decode utf8 u return text strip
return a colormap with aurora like colors,def aurora_cmap stops red 0 0 0 1725 0 1725 0 5 0 1725 0 1725 1 0 0 8353 0 8353 green 0 0 0 9294 0 9294 0 5 0 9294 0 9294 1 0 0 8235 0 8235 blue 0 0 0 3843 0 3843 0 5 0 3843 0 3843 1 0 0 6549 0 6549 alpha 0 0 0 0 0 0 0 5 1 0 1 0 1 0 1 0 1 0 return LinearSegmentedColormap aurora stops
linear interpolation between tuples v0 and v1 with phase p,def lerp v0 v1 p return 1 p v0 p v1
create a method that implements a java interface for py4j callback,def create_py4j_interface_method interface_method_name impl_method_name def interface_method obj args impl_method getattr obj impl_method_name try result impl_method args response SmvPy4JValidResponse result except Exception as e error traceback format_exc response SmvPy4JErrorResponse error return response interface_method __name__ interface_method_name return interface_method
ensure likelihoods for tumor and normal pass thresholds .,def check_lods parts tumor_threshold normal_threshold try gl_index parts FORMAT_PARTS_INDEX split index GL except ValueError print skipping LOD check no GL in format parts FORMAT_PARTS_INDEX file sys stderr return True try tumor_gls float x for x in parts TUMOR_PARTS_INDEX split gl_index split if x if tumor_gls tumor_lod max tumor_gls i tumor_gls 0 for i in range 1 len tumor_gls else tumor_lod 1 0 except IndexError as e tumor_lod 1 0 print assigning to tumor LOD for due to format tumor_lod parts TUMOR_PARTS_INDEX e file sys stderr except Exception as e print for parts n format e n join parts file sys stderr raise try normal_gls float x for x in parts NORMAL_PARTS_INDEX split gl_index split if x if normal_gls normal_lod min normal_gls 0 normal_gls i for i in range 1 len normal_gls else normal_lod normal_threshold except IndexError as e normal_lod normal_threshold print assigning to normal LOD for due to format normal_lod parts NORMAL_PARTS_INDEX e file sys stderr except Exception as e print for parts n format e n join parts file sys stderr raise result normal_lod normal_threshold and tumor_lod tumor_threshold if args debug and not result print LOD filtered normal tumor format location parts normal_lod tumor_lod file sys stderr return result
creates a simple tight - binding z2pack system .,pytest fixture def tb_system tb_model return z2pack tb System tb_model
test that o is a valid object identifier .,def check_object o if not isinstance o URIRef or isinstance o Literal or isinstance o BNode raise ObjectTypeError o
creates the actual html markup for the field .,def render self attrs self attrs copy attrs name self name out select s attrs for label options in self options out optgroup label s label for option in options out self render_option option out optgroup out select return out
read also histograms for the weight calculation,def SetReadWeights self self __isReadWeights True
tests that commands for punctuation work .,def test_punctuation_command_structure soup TexSoup right right right right right langle right lfloor right lceil right ulcorner big bigg Big Bigg assert len list soup contents 12 assert len list soup children 12
"close the transaction . if the stack is empty , a transactionerror is raised . if the last transaction on the stack is n't this transaction , a transaction error is raised .",def _close self try last self _stack pop except IndexError raise TransactionError No Transaction on stack if last is not self self _stack append last raise TransactionError Transaction on stack is not the transaction being closed
"pass in array of json objects , a dictionary with key / value pairs to match against , and another dictionary with expected key / value pairs .",def check_array_result object_array to_match expected num_matched 0 for item in object_array all_match True for key value in to_match items if item key value all_match False if not all_match continue for key value in expected items if item key value raise AssertionError s expected s s str item str key str value num_matched num_matched 1 if num_matched 0 raise AssertionError No objects matched s str to_match
is this state machine already inside a transition ? true if state is undefined .,def isInTransition self if self _state None return True else return False
create /etc / solr/4.1.0.0/0 directory and copies solr config files here . create symlinks accordingly .,def pre_upgrade_conf41 self env import params env set_params params solr41_conf_dir usr iop 4 1 0 0 solr conf solr41_etc_dir etc solr 4 1 0 0 0 content_path solr41_conf_dir if not os path isfile usr iop 4 1 0 0 solr conf solr in sh content_path etc solr conf backup for each in os listdir content_path File os path join solr41_etc_dir each owner params solr_user content StaticFile os path join content_path each if not os path islink solr41_conf_dir Directory solr41_conf_dir action delete create_parents True if os path islink solr41_conf_dir os unlink solr41_conf_dir if not os path islink solr41_conf_dir Link solr41_conf_dir to solr41_etc_dir
": param tarball_prefix : prefix of the tarball must be one of tez , hive , mr , pig : return : returns a tuple of ( x , y ) after verifying the properties",def _get_tar_source_and_dest_folder tarball_prefix component_tar_source_file default configurations cluster env s s tarball_prefix lower TAR_SOURCE_SUFFIX None component_tar_destination_folder default configurations cluster env s s tarball_prefix lower TAR_DESTINATION_FOLDER_SUFFIX None if not component_tar_source_file or not component_tar_destination_folder Logger warning Did not find s tar source file and destination folder properties in cluster env xml tarball_prefix return None None if component_tar_source_file find 1 Logger warning The tar file path s is not valid str component_tar_source_file return None None if not component_tar_destination_folder endswith component_tar_destination_folder component_tar_destination_folder return component_tar_source_file component_tar_destination_folder
returns a tuple containing the result code and a pre - formatted result label,OsFamilyFuncImpl os_family OsFamilyImpl DEFAULT def execute configurations parameters host_name None if configurations is None return UNKNOWN There were no configurations supplied to the script if not HIVE_METASTORE_URIS_KEY in configurations return UNKNOWN Hive metastore uris were not supplied to the script metastore_uris configurations HIVE_METASTORE_URIS_KEY split security_enabled False if SECURITY_ENABLED_KEY in configurations security_enabled str configurations SECURITY_ENABLED_KEY upper TRUE check_command_timeout CHECK_COMMAND_TIMEOUT_DEFAULT if CHECK_COMMAND_TIMEOUT_KEY in parameters check_command_timeout float parameters CHECK_COMMAND_TIMEOUT_KEY smokeuser_keytab SMOKEUSER_KEYTAB_DEFAULT smokeuser_principal SMOKEUSER_PRINCIPAL_DEFAULT smokeuser SMOKEUSER_DEFAULT if SMOKEUSER_PRINCIPAL_SCRIPT_PARAM_KEY in parameters smokeuser_principal parameters SMOKEUSER_PRINCIPAL_SCRIPT_PARAM_KEY if SMOKEUSER_SCRIPT_PARAM_KEY in parameters smokeuser parameters SMOKEUSER_SCRIPT_PARAM_KEY if SMOKEUSER_KEYTAB_SCRIPT_PARAM_KEY in parameters smokeuser_keytab parameters SMOKEUSER_KEYTAB_SCRIPT_PARAM_KEY if SMOKEUSER_PRINCIPAL_KEY in configurations smokeuser_principal configurations SMOKEUSER_PRINCIPAL_KEY if SMOKEUSER_KEY in configurations smokeuser configurations SMOKEUSER_KEY result_code None try if security_enabled if SMOKEUSER_KEYTAB_KEY in configurations smokeuser_keytab configurations SMOKEUSER_KEYTAB_KEY if KERBEROS_EXECUTABLE_SEARCH_PATHS_KEY in configurations kerberos_executable_search_paths configurations KERBEROS_EXECUTABLE_SEARCH_PATHS_KEY else kerberos_executable_search_paths None kinit_path_local get_kinit_path kerberos_executable_search_paths kinitcmd format kinit_path_local kt smokeuser_keytab smokeuser_principal kinit_lock global_lock get_lock global_lock LOCK_TYPE_KERBEROS kinit_lock acquire try Execute kinitcmd user smokeuser path bin usr bin usr lib hive bin usr sbin timeout 10 finally kinit_lock release if host_name is None host_name socket getfqdn for uri in metastore_uris if host_name in uri metastore_uri uri conf_dir HIVE_CONF_DIR_LEGACY bin_dir HIVE_BIN_DIR_LEGACY if STACK_ROOT in configurations hive_conf_dir configurations STACK_ROOT format current hive metastore conf conf server hive_bin_dir configurations STACK_ROOT format current hive metastore bin if os path exists hive_conf_dir conf_dir hive_conf_dir bin_dir hive_bin_dir cmd format export HIVE_CONF_DIR conf_dir hive hiveconf hive metastore uris metastore_uri hiveconf hive metastore client connect retry delay 1 hiveconf hive metastore failure retries 1 hiveconf hive metastore connect retries 1 hiveconf hive metastore client socket timeout 14 hiveconf hive execution engine mr e show databases start_time time time try Execute cmd user smokeuser path bin usr bin usr sbin bin_dir timeout int check_command_timeout total_time time time start_time result_code OK label OK_MESSAGE format total_time except result_code CRITICAL label CRITICAL_MESSAGE format host_name traceback format_exc except label traceback format_exc result_code UNKNOWN return result_code label
performs the creation and upload of the sharelib and the upgrade of the database . this method will also perform a kinit if necessary . it is run before the upgrade of oozie begins exactly once as part of the upgrade orchestration .,def upgrade_oozie_database_and_sharelib self env import params env set_params params Logger info Will upgrade the Oozie database if params security_enabled oozie_principal_with_host params oozie_principal replace _HOST params hostname command format kinit_path_local kt oozie_keytab oozie_principal_with_host Execute command user params oozie_user logoutput True upgrade_stack stack_select _get_upgrade_stack if upgrade_stack is None or len upgrade_stack 2 or upgrade_stack 1 is None raise Fail Unable to determine the stack that is being upgraded to or downgraded to stack_version upgrade_stack 1 Logger info format Upgrading the Oozie database using version stack_version versioned_libext_dir 0 1 oozie libext format params stack_root stack_version oozie download_database_library_if_needed target_directory versioned_libext_dir database_upgrade_command 0 1 oozie bin ooziedb sh upgrade run format params stack_root stack_version Execute database_upgrade_command user params oozie_user logoutput True self create_sharelib env
search the import list for an import dll that matches key return the rva,def search self key for entry in self iterate if key entry Name d li str return entry continue raise KeyError key
"copy the file ' src ' to ' dst ' ; both must be filenames . any error opening either file , reading from ' src ' , or writing to ' dst ' , raises distutilsfileerror . data is read / written in chunks of ' buffer_size ' bytes ( default 16k ) . no attempt is made to handle anything apart from regular files .",def _copy_file_contents src dst buffer_size 16 1024 fsrc None fdst None try try fsrc open src rb except os error as errno errstr raise DistutilsFileError could not open s s src errstr if os path exists dst try os unlink dst except os error as errno errstr raise DistutilsFileError could not delete s s dst errstr try fdst open dst wb except os error as errno errstr raise DistutilsFileError could not create s s dst errstr while 1 try buf fsrc read buffer_size except os error as errno errstr raise DistutilsFileError could not read from s s src errstr if not buf break try fdst write buf except os error as errno errstr raise DistutilsFileError could not write to s s dst errstr finally if fdst fdst close if fsrc fsrc close
test whether a path is a symbolic link,def islink path try st os lstat path except os error AttributeError return False return stat S_ISLNK st st_mode
"set a profile onto the compass rose . a polar coordinate tuple is of the form ( radius , angle ) . where radius is between -1 and 1 and angle is in degrees . @param key unique identifier for profile @param color_spec a 3-tuple gl color spec @param fill true to fill in the polygon or false for outline @param profile a list of polar coordinate tuples",def set_profile self key color_spec 0 0 0 fill True profile self lock self _profiles key color_spec fill profile self _profile_cache changed True self unlock
executed when a complete ingestion run has failed ( very bad ) . used to log the exception or clean up before baleen crashes !,def failed self exception message job failed format self name self jobid self logger error Ingestion Error format exception self logger critical message
returns a n - by - m array where all the diagonals starting from lower left corner up to the k - th are all ones .,def tri N M None k 0 typecode None dtype None dtype convtypecode typecode dtype if M is None M N m np greater_equal np subtract outer np arange N np arange M k if m dtype dtype return m astype dtype
returns a list of extra properties to set,def GetProperties self return _cpp FOLD
compile and run source code in the interpreter .,def runsource self source stdin stdout stderr sys stdin sys stdout sys stderr sys stdin sys stdout sys stderr self stdin self stdout self stderr more InteractiveInterpreter runsource self source if sys stdin self stdin sys stdin stdin if sys stdout self stdout sys stdout stdout if sys stderr self stderr sys stderr stderr return more
"find the completions and create the autocompletewindow . return true if successful ( no syntax error or so found ) . if complete is true , then if there 's nothing to complete and no start of completion , wo n't open completions and return false . if mode is given , will open a completion list only in this mode .",def open_completions self evalfuncs complete userWantsWin mode None if self _delayed_completion_id is not None self text after_cancel self _delayed_completion_id self _delayed_completion_id None hp HyperParser self editwin insert curline self text get insert linestart insert i j len curline if hp is_in_string and not mode or mode COMPLETE_FILES self _remove_autocomplete_window mode COMPLETE_FILES while i and curline i 1 in FILENAME_CHARS i 1 comp_start curline i j j i while i and curline i 1 in FILENAME_CHARS SEPS i 1 comp_what curline i j elif hp is_in_code and not mode or mode COMPLETE_ATTRIBUTES self _remove_autocomplete_window mode COMPLETE_ATTRIBUTES while i and curline i 1 in ID_CHARS i 1 comp_start curline i j if i and curline i 1 hp set_index insert dc len curline i 1 comp_what hp get_expression if not comp_what or not evalfuncs and comp_what find 1 return else comp_what else return if complete and not comp_what and not comp_start return comp_lists self fetch_completions comp_what mode if not comp_lists 0 return self autocompletewindow self _make_autocomplete_window self autocompletewindow show_window comp_lists insert dc len comp_start complete mode userWantsWin return True
returns the given named perspectives data string @param name : name of perspective to fetch data from,def GetPerspectiveData self name return self _viewset get name None
compute the crt private_exponent % ( q - 1 ) value from the rsa private_exponent and q.,def rsa_crt_dmq1 private_exponent q return private_exponent q 1
see the docstring for ` spmatrix.toarray ` .,def toarray self order None out None B self _process_toarray_args order out fortran int B flags f_contiguous if not fortran and not B flags c_contiguous raise ValueError Output array must be C or F contiguous M N self shape coo_todense M N self nnz self row self col self data B ravel A fortran return B
"return ( a , b)-sinh / cosh pseudo - derivative of a periodic sequence x.",def sc_diff x a b period None _cache _cache tmp asarray x if iscomplexobj tmp return sc_diff tmp real a b period 1j sc_diff tmp imag a b period if period is not None a a 2 pi period b b 2 pi period n len x omega _cache get n a b if omega is None if len _cache 20 while _cache _cache popitem def kernel k a a b b if k return sinh a k cosh b k return 0 omega convolve init_convolution_kernel n kernel d 1 _cache n a b omega overwrite_x _datacopied tmp x return convolve convolve tmp omega swap_real_imag 1 overwrite_x overwrite_x
reads data from an idl_dict object into xpaddataitem objects,def read_padsav file_name disable_UserWarnings True warning_action default if disable_UserWarnings warning_action ignore with catch_warnings simplefilter warning_action UserWarning idl_dict readsav file_name return parse_padsav idl_dict
performs a cubic spline interpolation of an irregularily sampled 1d signal,def interpol_spline1d x y xout f interpolate interp1d x y kind cubic return f xout
send scalar numpy types and make sure we get the same number back .,def test_scalars self for typecode in self codes outgoing np random randint 255 255 np random rand 1 if typecode in US outgoing np array spam astype typecode try outgoing outgoing astype typecode except TypeError continue incoming self oc roundtrip outgoing try assert np allclose incoming outgoing except ValueError TypeError NotImplementedError AssertionError assert np alltrue np array incoming astype typecode outgoing
return the position of the current word given its length ` n `,def __call__ self n start self idx self idx n return start self idx
install local copy of mezzanine for developer,def install_mezzanine_dev local pip install r requires txt local mezzanine project radiox with lcd radiox local python manage py createdb local python manage py runserver
: py : class:`~kubeshift.queries.base . query ` services .,base queryapi version v1 kind Service def services self namespace DEFAULT_NAMESPACE
"return the minimum of the elements in l , or nan if any element is nan .",def min l import __builtin__ try return __builtin__ min ensure_nonan x for x in l except NanException return nan
"set the bias name . can not be any upper / lowercase variant of reserved keyword "" xsecbias "" .",def SetName self name if name lower xsecbias raise ValueError Forbidden name str name Bias name cannot be any variant of xsecbias case insensitive return name
returns a list of all network interface names,def fact network_interfaces SCNetworkInterfaceCopyAll interfaces for interface in network_interfaces interfaces SCNetworkInterfaceGetLocalizedDisplayName interface SCNetworkInterfaceGetBSDName interface SCNetworkInterfaceGetHardwareAddressString interface return factoid str interfaces
"called when a doctype declaration has been found , name is the dtd name and externalid , systemid are the dtd public and system identifier for that dtd if available",def internalSubset self name externalID systemID pass
check if the given key i d exists in apt keyring .,def apt_key_exists keyid gpg_cmd gpg ignore time conflict no options no default keyring keyring etc apt trusted gpg with settings hide everything warn_only True res run gpg_cmd s fingerprint keyid s locals return res succeeded
fetch game entities from ingress map,def fetch_map self tilekeys url https www ingress com r getEntities payload tileKeys tilekeys return self fetch url payload
return the number of dimensions the vector represents .,def dimensionality self return len self dimensions
testing lpc ref order 10 .,def test_order10 self assert_array_almost_equal self X10 self lpc_func self X 10
test the _ _ ne _ _ ( ) method .,def test_ne self handler1 self _error_handler configuration None handler2 self _error_handler configuration None self assertFalse handler1 __ne__ handler2
write data as a new saved query,def write self user_id query_id raise NotImplementedError
tests whether the provided password matches all the required properties . this should be consistent with get_required_password_properties ( ) .,def validate_new_password self password raise NotImplementedError
return : text with : dent prepended to every line .,def indent dent text return re sub m dent text
"helper to produce a directory listing ( absent index.html ) . return value is either a file object , or none ( indicating an error ) . in either case , the headers are sent , making the interface the same as for send_head ( ) .",def list_directory self path try list os listdir path except os error self send_error 404 No permission to list directory return None list sort key lambda a a lower f StringIO displaypath cgi escape urllib unquote self path f write DOCTYPE html PUBLIC W3C DTD HTML 3 2 Final EN f write html n title Directory listing for s title n displaypath f write body n h2 Directory listing for s h2 n displaypath f write hr n ul n for name in list fullname os path join path name displayname linkname name if os path isdir fullname displayname name linkname name if os path islink fullname displayname name f write li a href s s a n urllib quote linkname cgi escape displayname f write ul n hr n body n html n length f tell f seek 0 self send_response 200 self send_header Content type text html self send_header Content Length str length self end_headers return f 0 length
returns desispec.image.image object from input file,def read_image filename fx fits open filename uint True memmap False image native_endian fx IMAGE data astype np float64 ivar native_endian fx IVAR data astype np float64 mask native_endian fx MASK data astype np uint16 camera fx IMAGE header CAMERA lower meta fx IMAGE header if READNOISE in fx readnoise native_endian fx READNOISE data astype np float64 else readnoise fx IMAGE header RDNOISE fx close return Image image ivar mask mask readnoise readnoise camera camera meta meta
od.viewitems ( ) - > a set - like object providing a view on od 's items,def viewitems self return ItemsView self
"softer cross - entropy function , where target is treated at not being exactly 1 , and instead spreading that probability uniformly to other classes",def soft_categorical_crossentropy_i32 pred target alpha 0 01 assert target dtype int32 assert target ndim 1 assert pred dtype fX assert pred ndim 2 nb_class pred shape 1 alpha 0 01 t T extra_ops to_one_hot target nb_class nb_class dtype pred dtype t T clip t alpha nb_class astype fX 1 0 1 alpha return T nnet categorical_crossentropy pred t
sends a put request . refactor from requests module,token_expire_handler def put self url data None verify False headers None proxies None timeout 60 kwargs Sends a PUT request Refactor from requests module param url URL for the new class Request object param data optional Dictionary bytes or file like object to send in the body of the class Request param verify optional if True the SSL cert will be verified A CA_BUNDLE path can also be provided param headers optional Dictionary of HTTP Headers to send with the class Request param proxies optional Dictionary mapping protocol to the URL of the proxy param timeout optional How long to wait for the server to send data before giving up as a float or a ref connect timeout read timeout timeouts tuple type timeout float or tuple param kwargs Optional arguments that request takes return class Response Response object rtype requests Response self log debug Put a request to s with data s url data response requests put url data data verify verify headers headers proxies proxies timeout timeout kwargs if response status_code not in 200 201 self log error Failed PUT request at s with response s url response content response raise_for_status return response
prefix latex markup with a dpi or similar modifier,def pref latex val key dpi return key str val latex
list plugins installed on the server .,def list self resp self client api plugins return self prepare_model r for r in resp
"for the given guidestar organization id , retrieve basic nonprofit info from guidestar 's exchange api .",def get_nonprofit organization_id url https data guidestar org v1 commondata organization_id json user givinggraph config read_config guide_star user password givinggraph config read_config guide_star pass r requests get url auth user password if r status_code 200 nonprofit_dict r json name nonprofit_dict primary_organization_name impact nonprofit_dict impact_statement guidestar_org_id nonprofit_dict organization_id financials nonprofit_dict financials 0 total_revenue financials total_revenue total_assets financials total_assets program_expenses financials program_expenses admin_expenses financials administration_expenses fundraising_expenses financials fundraising_expenses fundraising_expenses financials fundraising_expenses total_expenses financials total_expenses funding_source financials funding_source financials Financials total_revenue total_assets program_expenses admin_expenses fundraising_expenses total_expenses funding_source people_list r json people people for person_dict in people_list firstname person_dict firstname middlename person_dict middlename lastname person_dict lastname title person_dict title compensation person_dict compensation person Person firstname middlename lastname title compensation people append person return Nonprofit ein name impact financials people guidestar_org_id else return None
calls the test command and outputs a dict of the current context .,def _run_dummy_command self args kwargs out StringIO call_command tracked_dummy_command stdout out args kwargs out seek 0 return json loads out read
write all registered xmodule js and coffee files to output root .,def write_module_js output_root return _write_js output_root _list_modules
test that when isolation level is set to read committed get_or_create ( ) for the same row in concurrent requests does not raise an integrityerror .,ddt data outer_atomic IntegrityError None True outer_atomic_read_committed type None False True commit_on_success IntegrityError None True commit_on_success_read_committed type None False True ddt unpack def test_concurrent_requests self transaction_decorator_name exception_class created_in_1 created_in_2 transaction_decorator self DECORATORS transaction_decorator_name if connection vendor mysql raise unittest SkipTest Only works on MySQL class RequestThread threading Thread A thread which runs a dummy view def __init__ self delay kwargs super RequestThread self __init__ kwargs self delay delay self status transaction_decorator def run self A dummy view try try User objects get username student email student edx org except User DoesNotExist pass else raise AssertionError Did not raise User DoesNotExist if self delay 0 time sleep self delay __ created User objects get_or_create username student email student edx org except Exception as exception self status exception exception else self status created created thread1 RequestThread delay 1 thread2 RequestThread delay 0 thread1 start thread2 start thread2 join thread1 join self assertIsInstance thread1 status get exception exception_class self assertEqual thread1 status get created created_in_1 self assertIsNone thread2 status get exception self assertEqual thread2 status get created created_in_2
bulk creates all the unsaved subsection_grades to this point .,def bulk_create_unsaved self CreateSubsectionGrade bulk_create_models self student self _unsaved_subsection_grades values self course_data course_key self _unsaved_subsection_grades clear
find all course runs which are part of a program .,def _load_course_runs self programs for site in Site objects all logger info Loading programs from the catalog for site s site domain programs extend get_programs site self course_runs self _flatten programs
wait for the timestamp of the last successful import / export to be visible .,def wait_for_timestamp_visible self EmptyPromise self is_timestamp_visible Timestamp Visible timeout 30 fulfill
verify that discussion xblocks scheduled for release in the future are not visible to students in an instructor - paced course .,patch dict courseware access settings FEATURES DISABLE_START_DATES False def test_instructor_paced_discussion_xblock_visibility self course section self setup_course start self now self_paced False self create_discussion_xblocks section xblocks get_accessible_discussion_xblocks course self non_staff_user self assertTrue all xblock display_name released for xblock in xblocks
"return a valid access token stored by django - oauth2-provider ( dop ) , or none if no matching token is found .",def _get_dop_token self access_token token_query dop_models AccessToken objects select_related user return token_query filter token access_token first
"list all known libraries . returns tuples of ( librarylocator , display_name )",def list_available_libraries self return lib location library_key replace version_guid None branch None lib display_name for lib in self store get_library_summaries
tests default template paths are returned if template is not found in the theme .,with_comprehensive_theme red theme def test_get_template_path_with_theme_for_missing_template self template_path get_template_path_with_theme course html self assertEqual template_path course html
assert that a user has access to the given action for a given course .,def assertCanAccessCourse self user action course self assertTrue has_access user action course self assertTrue has_access user action CourseOverview get_from_id course id
load given signal element and return a signal object .,def _load_data_element data offset data_types data_type data_types data attrib dtref return Data name data find QUAL text start offset length data_type bit_length byte_order little_endian scale data_type factor offset data_type offset minimum data_type minimum maximum data_type maximum unit data_type unit choices data_type choices
"merge the other minhash with this one , making this one the union of both .",def merge self other if other seed self seed raise ValueError Cannot merge MinHash with different seeds if len self len other raise ValueError Cannot merge MinHash with different numbers of permutation functions self hashvalues np minimum other hashvalues self hashvalues
: type db_table : str : rtype : dict,def describe_table self db_table raise NotImplementedError
set / associate some object(s ) with some db key,def _db_set_items self raise NotImplementedError
return set of zabbix template ids for a vm,def _vm_templates self vm log None vm_kwargs self _vm_kwargs vm tids self _get_templates vm_kwargs django_settings _MON_ZABBIX_TEMPLATES_VM log log tids update self _get_vm_nic_templates vm vm_kwargs django_settings _MON_ZABBIX_TEMPLATES_VM_NIC log log tids update self _get_vm_disk_templates vm vm_kwargs django_settings _MON_ZABBIX_TEMPLATES_VM_DISK log log return tids
sync db status of dataset backups with real information from compute node . used by put vm_snapshot_list and put node_vm_snapshot_list .,def sync_backups db_backups node_snaps lost 0 for bkp in db_backups if bkp type bkp FILE continue bkp_snap_name bkp snap_name try if bkp_snap_name in node_snaps if bkp status bkp LOST logger warn Backup s ID s found changing status to OK bkp bkp id bkp status bkp OK bkp size t_long node_snaps bkp_snap_name 1 bkp save update_fields status status_change size force_update True else logger debug Backup s ID s is OK bkp bkp id if bkp locked logger warn Backup s ID s is OK on compute node but in s status since s bkp bkp id bkp get_status_display bkp status_change if is_backup_task_running bkp vm or bkp node logger warn Ignoring backup s ID s because a snapshot task is running on node s bkp bkp id bkp node else logger warn Changing backup s ID s status to OK bkp bkp id bkp status bkp OK bkp save update_fields status status_change force_update True else logger warn Backup s ID s does not exist on compute node bkp bkp id if is_backup_task_running bkp vm or bkp node logger warn Ignoring backup s ID s because a backup task is running on node s bkp bkp id bkp node continue if bkp status bkp LOST bkp status bkp LOST bkp save update_fields status status_change force_update True lost 1 continue except DatabaseError logger warn Backup s ID s could not be updated maybe it vanished bkp bkp id node_snaps pop bkp_snap_name None return lost
upload to pypi via fabric over ssh,def upload self opts build_artifact pypi_conf self package_conf pypi_config pypi_auth get_pypi_auth if opts pypi_url pypi_url opts pypi_url else pypi_url pypi_conf pypi_url if pypi_auth ssh_username is not None pypi_user pypi_auth ssh_username else pypi_user pypi_auth username package_dir pypi_conf pypi_upload_path LOGGER info Uploading 0 to 1 format build_artifact pypi_url put build_artifact package_dir pypi_url ssh_username pypi_user ssh_keyfile pypi_auth ssh_key
installs one or more `` packages `` using the system package manager .,def package c packages apt DEBIAN_FRONTEND noninteractive apt get install y yum yum install y s manager apt if distro_family c debian else yum for package in packages c sudo manager format package
"when a src rule expires , the host is probably inactive or active in receiving but not sending . we mark just mark the host as expired .",def _src_rule_expire self vlan port eth_src ofmsgs entry vlan cached_host_on_port eth_src port if entry is not None vlan expire_cache_host eth_src self logger info expired src_rule for host s eth_src return ofmsgs
[ parallel | layer | multiprocessing | blend | no proba | no prep ] test predict,def test_predict args get_layer predict multiprocessing blend False False run_layer args
[ parallel | layer | threading | blend | no proba | no prep ] test feature prop transform,def test_transform_fp args get_layer transform threading blend False False feature_prop 2 run_layer args
return a list of string reprs from a nested list of referrers .,def format self tree output def ascend branch depth 1 for parent grandparents in branch output append depth self _format parent if grandparents ascend grandparents depth 1 ascend tree return output
"overrides : meth:`pyramid.scaffold.template . template.post ` , to print "" welcome to pyramid . sorry for the convenience . "" after a successful scaffolding rendering .",def post self command output_dir vars self out Welcome to Pyramid Sorry for the convenience return Template post self command output_dir vars
checks metadata of job is within a certain range .,def check self job if self expression None raise PostProcessException No expression is set MetaDataChecker will do nothing try self result self calculateResult job except Exception as e raise PostProcessException There was an error parsing the checker expression s MetaDataChecker will do nothing e if self result is not True and self result is not False raise PostProcessException The expression s did not evaluate to True or False MetaDataChecker will do nothing self expression if self result is False logger info MetaDataChecker has failed job s because the expression s is False job fqid self expression return self result
kill all the jobs on the task .,def kill self job if not os path exists job inputdata ui_working_dir raise CRABServerError Workdir s not found job inputdata ui_working_dir if not job master cmd crab kill all c s job inputdata ui_working_dir else cmd crab kill d c s int job id 1 job inputdata ui_working_dir self _send_with_retry cmd kill job backend crab_env return True
rollback of a job to new state ( caused by error during submission ) . called by : ganga client .,def rollback self opts ret for monService in self monMonServices try monClass str monService __class__ ret monClass monService rollback opts except Exception as e self logger warning s monitoring service failed in job rollback monClass return ret
"calculation of mmax using acumulative moment approach , adapted from the cumulative strain energy method of makropoulos & burton ( 1983 ) : param year : year of earthquake : type year : numpy.ndarray : param mag : magnitude of earthquake : type mag : numpy.ndarray : keyword iplot : include cumulative moment plot : type iplot : boolean : return mmax : returns maximum magnitude : rtype mmax : float",def plot_cumulative_moment year mag m_o 10 0 9 05 1 5 mag year_range np arange np min year np max year 1 1 nyr np int np shape year_range 0 morate np zeros nyr dtype float for loc tyr in enumerate year_range idx np abs year tyr 1e 05 if np sum idx 0 morate loc np sum m_o idx ave_morate np sum morate float nyr exp_morate np cumsum ave_morate np ones nyr plt step year_range np cumsum morate b linewidth 2 plt plot year_range exp_morate r linewidth 2 upper_morate exp_morate np max np cumsum morate exp_morate lower_morate exp_morate np min np cumsum morate exp_morate plt plot year_range upper_morate r linewidth 1 plt plot year_range lower_morate r linewidth 1 plt axis np min year np max year 0 0 np sum morate
"get and parse a wfs capabilities document , returning an instance of wfscapabilitiesinfoset",def read self url timeout 30 request self capabilities_url url u openURL request timeout timeout username self username password self password return etree fromstring u read
create an organization api key `` `` `` `` `` `` `` `` `` ` `` `` `` `` `` `` `` ``,def post self request organization key ApiKey objects create organization organization scope_list DEFAULT_SCOPES self create_audit_entry request organization organization target_object key id event AuditLogEntryEvent APIKEY_ADD data key get_audit_log_data return Response serialize key request user status status HTTP_201_CREATED
given an `` origin `` which matches a base uri ( e.g. http://example.com ) determine if a valid origin is present in the project settings .,def is_valid_origin origin project None allowed None if allowed is None allowed get_origins project if not allowed return False if in allowed return True if not origin return False origin origin lower if origin in allowed return True if origin null return False if type origin six binary_type origin origin decode utf 8 parsed urlparse origin if parsed hostname is None parsed_hostname else try parsed_hostname parsed hostname encode idna except UnicodeError parsed_hostname parsed hostname if parsed port domain_matches parsed_hostname s d parsed_hostname parsed port d parsed port else domain_matches parsed_hostname for value in allowed try bits parse_uri_match value except UnicodeError continue if bits scheme not in parsed scheme continue if bits domain 2 if parsed_hostname endswith bits domain 1 or parsed_hostname bits domain 2 return True continue elif bits domain not in domain_matches continue path bits path if path return True if path endswith path path 1 if parsed path startswith path return True return False
smoke test of the first markdown file i made that gave a wrong parse .,def test_basic self model from_markdown self BASIC_MD self assertEqual model tag root self assertEqual len model children 2 self assertEqual model children 0 data Heading self assertEqual model children 1 data single bullet 8 40 cost model children 1 cost self assertAlmostEqual cost quantile 0 1 8 delta 0 01 self assertAlmostEqual cost quantile 0 75 40 delta 0 01
this method returns true for a line that should be skipped . implement in child classes if needed .,def _should_skip_line self line index caption return False
shut everyting down ; actor is exiting,def receiveMsg_ActorExitRequest self m sender if hasattr self servesocket self servesocket close for each in self activesockets each socket close
concatinate application and global security group rules .,def update_default_rules self app_ingress self properties security_group ingress ingress conservative_merger merge DEFAULT_SECURITYGROUP_RULES app_ingress resolved_ingress self resolve_self_references ingress self log info Updated default rules n s ingress return resolved_ingress
sends a data to a gui client of |client_id| .,abc abstractmethod def Send self client_id data
returns checkpoint filename given directory or specific filepattern .,def _get_checkpoint_filename filepattern if gfile IsDirectory filepattern return saver latest_checkpoint filepattern return filepattern
sign a p2sh transaction by privkeys .,def sign_tx self tx spend_tx spend_n redeem_script in_n keys vout spend_tx vout spend_n sighash SegwitVersion1SignatureHash redeem_script tx in_n SIGHASH_ALL SIGHASH_FORKID vout nValue sigs key sign sighash bytes bytearray SIGHASH_ALL SIGHASH_FORKID for key in keys tx vin 0 scriptSig CScript OP_0 sigs redeem_script tx rehash
upload a service via the administrative interface,def deploy fingerengine fingerprint cookie None file_path abspath fingerengine options deploy file_name parse_war_path file_path True dip fingerengine options ip cookie checkAuth dip fingerprint port title fingerprint version if not cookie utility Msg Could not get auth to s s dip fingerprint port LOG ERROR return utility Msg Preparing to deploy 0 format file_name base http 0 1 format dip fingerprint port uri axis2 axis2 admin upload payload filename open file_path rb response utility requests_post base uri files payload cookies cookie if response status_code is 200 if The following error occurred in response content error findall occurred br font response content utility Msg Failed to deploy 0 Reason 1 format file_name error 0 LOG ERROR else utility Msg 0 deployed successfully to axis2 services 1 format file_name parse_war_path file_path LOG SUCCESS else utility Msg Failed to deploy 0 HTTP 1 format file_name response status_code LOG ERROR
removes the specified of the given entity class from the session .,def remove self entity_class data raise NotImplementedError Abstract method
parses variables from a fetched tree .,def _parse_variables self tree ns urn schemas upnp org service 1 0 for node in tree findall s stateVariable ns send_events node attrib get sendEvents no multicast node attrib get multicast no name node findtext s name ns data_type node findtext s dataType ns values a text for a in node findall s allowedValue ns self _variables name send_events multicast data_type values
computes average precision of one single query args : query_embed : the embedding of one single query all_embed : all embeddings in the database answer_inds : correct indexes return : ave_p : average precision,def AP query_embed all_embed answer_inds feat_dim 100 pair_list answer np_query np array query_embed reshape 1 feat_dim np_all np array all_embed reshape 1 feat_dim answer cosine_similarity np_query np_all flatten total_right 0 for i answer_i in enumerate answer pair_list append answer_inds i answer_i if answer_inds i 1 total_right 1 pair_list sorted pair_list key itemgetter 1 reverse True ave_P 0 0 right 0 0 total_right min 10 total_right for i in range total_right if pair_list i 0 1 right 1 ave_P right i 1 if total_right 0 ave_P 1 else ave_P total_right return ave_P
"cryptographically signs and optionally encrypts the supplied message . the message is only encrypted if ' confidentiality ' was negotiated , otherwise the message is left untouched . : return : a tuple containing the message signature and the optionally encrypted message",def wrap_message self message if not self is_established raise Exception Context has not been established if self _wrapper is None raise Exception Neither sealing or signing have been negotiated else return self _wrapper wrap message
sends keys to current focused element . args : keys_to_send : the keys to send .,def chain_send_keys self keys_to_send self __lazy_init_action_chains send_keys keys_to_send
make sure counter walkers work correctly .,def test_counter_walker model DeviceModel log SensorLog model model walk log create_walker DataStreamSelector FromString counter 1 stream DataStream FromString counter 1 reading IOTileReading 0 1 1 assert walk count 0 log push stream IOTileReading 0 1 1 assert walk count 1 assert walk peek value 1 log push stream IOTileReading 0 1 3 assert walk count 2 assert walk peek value 3 val walk pop assert walk count 1 assert val value 3 val walk pop assert walk count 0 assert val value 3 with pytest raises StreamEmptyError walk pop
return the record type that this record matches .,classmethod def MatchType cls u Return the record type that this record matches n n All records must match an 8 bit record type field that is used to n decode a binary script Note that multiple records may match the same n 8 bit record type if they have different levels of specificity n n Returns n int The single record type that this record matches n return ReflashTileRecord RecordType
make sure we can check if the time is correct,def test_check_time json_true now datetime datetime now tzutc strftime a d b Y X Z json_false now Wed 01 Sep 2010 17 30 32 GMT payload jwt big token username user1 manager ConfigManager with requests_mock Mocker as mocker mocker post https iotile cloud api v1 auth login json payload link_cloud manager user1 random com password cloud IOTileCloud mocker get https iotile cloud api v1 server json json_true assert cloud check_time True mocker get https iotile cloud api v1 server json json_false assert cloud check_time False
combine multiple firmware images into a single bootstrap hex file .,def autobuild_bootstrap_file file_name image_list family utilities get_family module_settings json target family platform_independent_target resolver ProductResolver Create env Environment tools output_dir target build_dirs output build_dir target build_dirs build build_output_name os path join build_dir file_name full_output_name os path join output_dir file_name processed_input_images for image_name in image_list image_info resolver find_unique firmware_image image_name image_path image_info full_path hex_path arm ensure_image_is_hex image_path processed_input_images append hex_path env Command build_output_name processed_input_images action Action arm merge_hex_executables Merging d hex files into TARGET len processed_input_images env Command full_output_name build_output_name Copy TARGET SOURCE
"return list of ( priority , mx domain ) tuples for a given domain .",wait_for timeout 5 def mx domain return _mx domain
report a measured result . desired_result should have been returned by get_next_desired_result ( ) .,def report_result self desired_result result result_input None self measurement_driver report_result desired_result result result_input
test updating ` zeta ` .,def test_zeta_updates self random seed 1 scipy random seed 1 expcm_fitprefs copy deepcopy self expcm_fitprefs self assertTrue scipy allclose expcm_fitprefs pi expcm_fitprefs origpi k 0 for r in range expcm_fitprefs nsites for i in range N_AA 1 oldzeta expcm_fitprefs zeta copy oldpi expcm_fitprefs pi copy zeta oldzeta copy zeta k 0 9 expcm_fitprefs updateParams zeta zeta self assertFalse scipy allclose oldzeta expcm_fitprefs zeta self assertFalse scipy allclose oldpi r expcm_fitprefs pi r self assertFalse scipy allclose expcm_fitprefs pi expcm_fitprefs origpi if self MODEL phydmslib models ExpCM_fitprefs self assertTrue expcm_fitprefs pi r i oldpi r i self assertTrue all expcm_fitprefs pi r j oldpi r j for j in range i 1 N_AA elif self MODEL phydmslib models ExpCM_fitprefs2 self assertTrue expcm_fitprefs pi r i oldpi r i zeta k 2 expcm_fitprefs updateParams zeta zeta self assertTrue expcm_fitprefs pi r i oldpi r i k 1
adapt the specified equitable partition into the coarsest equitable one .,def _adapt graph partition block_neighbors v block degree graph v block for block in partition for v in graph key_func lambda w sorted sorted k v for k v in block_neighbors w items vertices sorted block_neighbors key key_func new_partition frozenset g for k g in groupby vertices key_func if new_partition partition return partition return _adapt graph new_partition
generate a dict of only changed attributes from when the object was instantiated,property def __diff__ self tmp dict name self __dict__ _ 0 format name for name in dir self if not name startswith _ and name todict and name in self _modified_fields tmp token self _token return tmp
a function for embedding if g is already stored in matrix form,def self_matrix G return G
return the node given an i d .,def get_node_by_id et_root uid if et_root attrib id uid return et_root nodes et_root findall id 0 format uid if len nodes 0 return None elif len nodes 1 return nodes 0 else raise RuntimeError Duplicate node id found 0 format uid
"returns the full path of a sikuli project module . to load a module in a sikuli script , use execfile(getmodulepath(modulename ) ) .",def getmodulepath modulename return USERLIBDIR modulename sikuli modulename py
convenient method to get exp at [ last_ind ],def pop self buffer_exp self exp self exp self last_exp res super HighLowMemory self pop self exp buffer_exp return res
parse attribute list and return a list of attribute tuples .,def get_attrs str return _scanner scan str 0
this function overrides the parents ' one . returns interal layer parameters .,def get_params self if self use_bias return self W self b else return self W
move the start and stop positions .,def move self bases self start bases self stop bases
remove quotes from around a string .,def dequote string if string startswith and string endswith or string startswith and string endswith return string 1 1 else return string
format a list of traceback entry tuples for printing .,def format_list extracted_list list for filename lineno name line in extracted_list item File s line d in s n filename lineno name if line item item s n line strip list append item return list
"returns a list of ( x , y ) tuples covering all positions in a grid",def get_all_dot_positions xsize ysize return x y for x in range 1 xsize 1 for y in range 1 ysize 1
safely copies server_root to temp_dir and returns copied files,def copy_config server_root temp_dir copied_files copied_dirs dir_len len os path dirname server_root for config_path config_dirs config_files in os walk server_root temp_path os path join temp_dir config_path dir_len 1 os mkdir temp_path copied_all True copied_files_in_current_dir for config_file in config_files config_file_path os path join config_path config_file temp_file_path os path join temp_path config_file if os path islink config_file_path os symlink os readlink config_file_path temp_file_path elif safe_config_file config_file_path copy_file_without_comments config_file_path temp_file_path copied_files_in_current_dir append config_file_path else copied_all False if copied_all and not config_dirs copied_dirs append config_path else copied_files copied_files_in_current_dir return copied_files copied_dirs
"step1 : checking if we have a key call self.msg_key step2 : set a value to self.menu_key something maybe like self.menu_key='ter_reg_req ' step3 : if you have the key call ' ter_req_req ' we need to keep ask which function can be available ! step4 : so , we need to ask the reflect function ! : param : self.flag is a key of protocol dicts ! : param : self.conn is socket file desc : return :",def distribute self if self msg_key in self protocol self menu_key self protocol self msg_key reflect self menu_key self request_dict return True else return None
"converts a string , list , or dict from camelcase to lower_with_underscores .",def ToUnderscore obj if isinstance obj basestring return re sub A Z _ 1 obj lower elif isinstance obj list return ToUnderscore item for item in obj elif isinstance obj dict output for k v in obj iteritems if isinstance v list or isinstance v dict output ToUnderscore k ToUnderscore v else output ToUnderscore k v return output else return obj
return a boolean indicating that the current slave is capable of using the sandbox and should enable it . this should return true iff the slave is a linux host with the sandbox file present and configured correctly .,def should_enable_sandbox sandbox_path if not sys platform startswith linux and os path exists sandbox_path return False sandbox_stat os stat sandbox_path if sandbox_stat st_mode stat S_ISUID and sandbox_stat st_mode stat S_IRUSR and sandbox_stat st_mode stat S_IXUSR and sandbox_stat st_uid 0 return True return False
"target os , the browser will run on .",property def target_os self return self _target_os
convert an integer represented as a base 128 string into an c{int } or c{long}.,def b1282int st e 1 i 0 for char in st n ord char i n e e 7 return i
` x.__contains__(item ) ` < = = > ` item in x `,def __contains__ item
return a integer hash to use for hashed collections including dict .,def __hash__ self return hash repr self
"install the wxpython support , given a wxapp instance",def install app runner wxRunner app reactor callLater 0 02 runner run
override from remotewebdriver to use firefox . webelement .,def create_web_element self element_id return WebElement self element_id
returns the mean of entered values .,def Mean self return self _sum_x self _n
sets up and runs a test case .,def RunTest self test assert isinstance test test_case LinkerTestCaseBase try results test Run self device except Exception logging exception Caught exception while trying to run test test tagged_name exc_info sys exc_info results base_test_result TestRunResults results AddResult LinkerExceptionTestResult test tagged_name exc_info if not results DidRunPass return results test else return results None
cleans up the machine if the test case fails .,def tearDown self if self _clean_on_teardown RunCleanCommand True self _variable_expander
creates a githubfilesystem that corresponds to a single github repository specified by |owner| and |repo| .,staticmethod def Create owner repo object_store_creator return GithubFileSystem url_constants GITHUB_REPOS owner repo object_store_creator AppEngineUrlFetcher
"friendly name of the target device ( e.g. , phone model ) .",property def name self raise NotImplementedError
clears a highlight of the given bitmap . rgbacolor .,def ClearHighlight self color self ExecuteJavaScript function document body removeChild window __telemetry_screen_ d requestAnimationFrame function window __telemetry_screen_ d null int color int color self WaitForJavaScriptExpression window __telemetry_screen_ d int color 5
initialize an rdata . @param rdclass : the rdata class @type rdclass : int @param rdtype : the rdata type @type rdtype : int,def __init__ self rdclass rdtype self rdclass rdclass self rdtype rdtype
"given a span of addresses , returns symbol references from disassembly .",def ExtractSymbolReferences binary start end cmd objdump binary disassemble start address 0x x start stop address 0x x end objdump subprocess Popen cmd stdout subprocess PIPE refs set for line in objdump stdout if __static_initialization_and_destruction in line raise RuntimeError code mentions __static_initialization_and_destruction did you accidentally run this on a Debug binary match disassembly_re search line if match ref match groups if ref startswith LC or ref startswith _DYNAMIC continue if ref startswith _GLOBAL__I_ continue refs add ref return sorted refs
"where appropriate , issue "" select scope_identity ( ) "" in the same statement .",def pre_exec self super MSExecutionContext_pyodbc self pre_exec if self _select_lastrowid and self dialect use_scope_identity and len self parameters 0 self _embedded_scope_identity True self statement select scope_identity
parses the json pending patch set information .,def _ParseJson self json_string data json loads json_string d self _try_job_rietveld SubmitJobs data jobs def success_callback value self _cursor str data cursor self _try_job_rietveld processed_keys clear if self _cachepath with open self _cachepath w as f json dump cursor self _cursor f return value d addCallback success_callback return d
cleans up the test enviroment for the test suite .,def TearDown self if _TestSuiteRequiresHighPerfMode self test_package suite_name self _perf_controller RestoreOriginalPerfMode self test_package ClearApplicationState self device self tool CleanUpEnvironment super TestRunner self TearDown
construct a l{failure } with an exception that raises an exception from its c{__str _ _ } method and then call c{gettraceback } with the specified detail and verify that it returns a string .,def _brokenValueTest self detail x BrokenStr f failure Failure x traceback f getTraceback detail detail self assertIsInstance traceback str
removes any set keystone keys .,def _RemoveKeystoneKeys plist _RemoveKeys plist KSVersion KSProductID KSUpdateURL tag_keys for tag_suffix in _TagSuffixes tag_keys append KSChannelID tag_suffix _RemoveKeys plist tag_keys
tokenize and colorize the given python source .,def lastColorizedLine source w VT102Writer p TokenPrinter w write printtoken s StringIO StringIO source tokenize tokenize s readline p return str w
delete the row for rowobject from the database .,def deleteRow self rowObject sql self deleteRowSQL rowObject self removeFromCache rowObject return self dbpool runOperation sql
verify the waiter can find and return an element,def test_find_element_with_defaults driver element mock_css_path div mock css path driver find_element side_effect None element elem waiter find_element driver mock_css_path assert driver find_element called assert elem is element assert len driver mock_calls 2 assert driver find_element call_args_list mock call CSS mock_css_path mock call CSS mock_css_path
return the top of the log queue,def get_top_msg self return self log_queue 1
update destdir with any changes made to srcdir,def updateTree srcdir destdir if not os path isdir destdir os mkdir destdir 493 comparison dircmp srcdir destdir for file in comparison diff_files shutil copyfile os path join srcdir file os path join destdir file for directory in comparison common_dirs if directory CVS continue updateTree os path join srcdir directory os path join destdir directory for entry in comparison left_only if os path isdir os path join srcdir entry shutil copytree os path join srcdir entry os path join destdir entry else shutil copyfile os path join srcdir entry os path join destdir entry for entry in comparison right_only if os path isdir os path join destdir entry shutil rmtree os path join destdir entry else os remove os path join destdir entry return
equal to the number of columns in this descriptor,def __len__ self return self num_cols
we can pass an open dataset for output,def test_riomucho_simple_dataset_object tmpdir test_1_tif with rasterio open str test_1_tif as src options src profile with rasterio open str tmpdir join output tif w options as dst with riomucho RioMucho str test_1_tif dst read_function_simple as rm rm run 1 with rasterio open str tmpdir join output tif as outputsrc assert numpy sum outputsrc read 1 10 10 0 0
"return dictionary of optimization parameters from vector x. the non - optimization parameters will be taken from the initial values . if return_list==true , return a list instead of an dictionary",def extract_parameters self x return_list False params self param_values copy index 0 for param_name in self optimize if not isinstance self param_values param_name np ndarray or len self param_values param_name shape 0 params param_name x index index 1 else shape self param_values param_name shape if len shape 1 raise ValueError Arrays with more than one dimension are not yet supported params param_name x index index shape 0 index shape 0 if return_list return params key for key in self parameters else return params
"given a string in which the characters are the sequence of message types to ignore , causes the filter to drop the messages as they are received in that order , without additional processing .",def ignoreMessages self messageTypes self dropMessages messageTypes
translates dna ( with gaps ) into amino - acids,def translate dna table CODON_TABLE aa assert len dna 3 0 dna sequence length is not a multiple of 3 for i in xrange 0 len dna 3 codon dna i i 3 upper if N in codon aa append X else aa append table codon return join aa
build local spatial index of us metro areas,def mapper_init_metro self self lookup CachedMetroLookup precision METRO_GEOHASH_PRECISION
test the output of ` latex2edx example14_showhide.tex ` for proper formation of the showhide element .,def test_sh1 self testdir path l2e __file__ parent testtex tfn testdir example14_showhide tex print file s tfn with make_temp_directory as tmdir nfn s s tmdir tfn basename os system cp s s testdir tmdir os chdir tmdir l2eout latex2edx nfn output_dir tmdir l2eout convert jsfn s static latex2edx js tmdir cssfn s static latex2edx css tmdir self assertTrue os path exists jsfn self assertTrue os path exists cssfn tfn s html Text xml tmdir xml etree parse tfn getroot sh xml find div class hideshowbox self assertEqual sh 0 tag h4 self assertEqual sh 0 get onclick hideshow this self assertEqual sh 0 text Secret text self assertEqual sh 1 get class hideshowcontent self assertEqual sh 1 text strip Hidden text self assertEqual sh 2 get class hideshowbottom lk xml find LINK self assertTrue latex2edx css in lk get href sc xml find SCRIPT self assertTrue latex2edx js in sc get src
"this function takes a gdal spatialreference system and adds its information to the ` spatial_ref_sys ` table of the spatial backend . doing this enables database - level spatial transformations for the backend . thus , this utility is useful for adding spatial reference systems not included by default with the backend -- for example , the so - called "" google maps mercator projection "" is excluded in postgis 1.3 and below , and the following adds it to the ` spatial_ref_sys ` table :",def add_srs_entry srs auth_name EPSG auth_srid None ref_sys_name None database DEFAULT_DB_ALIAS connection connections database if not hasattr connection ops spatial_version raise Exception The add_srs_entry utility only works with spatial backends if connection ops oracle or connection ops mysql raise Exception This utility does not support the Oracle or MySQL spatial backends SpatialRefSys connection ops spatial_ref_sys if not isinstance srs SpatialReference srs SpatialReference srs if srs srid is None raise Exception Spatial reference requires an SRID to be compatible with the spatial backend kwargs srid srs srid auth_name auth_name auth_srid auth_srid or srs srid proj4text srs proj4 if connection ops postgis kwargs srtext srs wkt if connection ops spatialite kwargs ref_sys_name ref_sys_name or srs name try sr SpatialRefSys objects get srid srs srid except SpatialRefSys DoesNotExist sr SpatialRefSys objects create kwargs
returns a model and form class based on the model and form_class parameters that were passed to the generic view .,def get_model_and_form_class model form_class if form_class return form_class _meta model form_class if model tmp_model model class Meta model tmp_model class_name model __name__ Form form_class ModelFormMetaclass class_name ModelForm Meta Meta return model form_class raise GenericViewError Generic view must be called with either a model or form_class argument
returns a list of the drop table sql statements for the given app .,def sql_delete app style connection try cursor connection cursor except cursor None if cursor table_names connection introspection get_table_list cursor else table_names output to_delete set references_to_delete app_models models get_models app include_auto_created True for model in app_models if cursor and connection introspection table_name_converter model _meta db_table in table_names opts model _meta for f in opts local_fields if f rel and f rel to not in to_delete references_to_delete setdefault f rel to append model f to_delete add model for model in app_models if connection introspection table_name_converter model _meta db_table in table_names output extend connection creation sql_destroy_model model references_to_delete style if cursor cursor close connection close return output 1
"converts a pixel to a longitude , latitude pair at the given zoom level .",def pixel_to_lonlat self px zoom if len px 2 raise TypeError Pixel should be a sequence of two elements npix self _npix zoom lon px 0 npix self _degpp zoom lat RTOD 2 atan exp px 1 npix 1 0 self _radpp zoom 0 5 pi return lon lat
returns the < script > tag for the google maps api javascript .,property def api_script self return mark_safe script src s s type text javascript script self api_url self key
returns a cache key for the header cache .,def _generate_cache_header_key key_prefix request path hashlib md5 iri_to_uri request get_full_path cache_key views decorators cache cache_header s s key_prefix path hexdigest return _i18n_cache_key_suffix request cache_key
alias for proj ( ) .,property def proj4 self return self proj
a context manager that temporarily sets the internal client 's dsn,contextmanager def dsn self dsn from raven contrib django models import client try client set_dsn dsn yield finally client set_dsn None
whether or not network access is allowed at all .,property def allow_network self u Whether or not network access is allowed at all n n Defaults to class True Setting this to class False turns on n offline mode n return self _allow_network
get a tag from it 's name ( in clarke 's notation ),def get_tag self tag u return self get_element_type extract_namespace tag
verify the synchronize action plugin sets the delegate to 127.0.0.1 and remote path to user@host:/path,def test_synchronize_action_basic self runner FakeRunner runner remote_user root runner transport ssh conn FakeConn inject inventory_hostname el6 lab net inventory_hostname_short el6 ansible_connection None ansible_ssh_user root delegate_to None playbook_dir x Synchronize runner x setup synchronize inject x run conn tmp synchronize src tmp foo dest tmp bar inject assert runner executed_inject delegate_to 127 0 0 1 was not delegated to 127 0 0 1 assert runner executed_complex_args dest root el6 lab net tmp bar src tmp foo wrong args used assert runner sudo None sudo was not reset to None
the aggregate pages of all the parser objects .,property def pages self pages for har_dict in self har_data har_parser HarParser har_data har_dict if self page_id for page in har_parser pages if page page_id self page_id pages append page else pages append har_parser pages 0 return pages
reads the centroid information from a file .,def read_centroid self chkpt self nstates int chkpt readline split 0 self label int chkpt readline split 0 self pstates int chkpt readline split 0 chkpt readline self pes_data potential np fromstring chkpt readline sep dtype float chkpt readline self update_x np fromstring chkpt readline sep dtype float chkpt readline self update_p np fromstring chkpt readline sep dtype float
create a factory method for instantiating charts with displays .,def _GetChartFactory chart_class display_class def Inner args kwargs chart chart_class args kwargs chart display display_class chart return chart return Inner
d.copy ( ) - > a shallow copy of d ( still as a sorteddict ) .,def copy self return self __class__ self
: param prefix : a list of special characters expected to indicate the head of a command .,def by_chat_command prefix separator pass_args False return by_command lambda msg msg text prefix separator pass_args
example view demonstrating rendering a simple html page .,app route app route index html def index context make_context context name Lunchbox context id home context now datetime now strftime B d Y return make_response render_template index html context
"compares two wkt strings , ignoring allowed differences between strings and allowing a tolerance for coordinates",def compareWkt a b tol 1e 06 a0 a lower b0 b lower r re compile s zm a0 r sub 1 a0 b0 r sub 1 b0 r re compile s s a0 r sub a0 b0 r sub b0 r re compile s s a0 r sub a0 b0 r sub b0 r0 re compile d d eE d r1 re compile s s a0 r1 sub r0 sub a0 b0 r1 sub r0 sub b0 if a0 b0 return False a0 r0 findall a b0 r0 findall b if len a0 len b0 return False for a1 b1 in zip a0 b0 if not doubleNear a1 b1 tol return False return True
function to somewhat mimic behavior of matlab 's blocproc function ( see http://uk.mathworks.com/help/images/ref/blockproc.html ) .,def block_proc A blockSize blockFunc xStart 0 xStop A shape 1 if xStop blockSize 0 0 xStop int xStop blockSize 0 blockSize 0 yStart 0 yStop A shape 0 if yStop blockSize 1 0 yStop int yStop blockSize 1 blockSize 1 for x in xrange xStart xStop blockSize 0 for y in xrange yStart yStop blockSize 1 block A y y blockSize 1 x x blockSize 0 blockFunc block
: param image_uuid : uuid of backing image for managed instances . : param flavor : nova flavor i d to be used for managed instances . : param mgt_net_id : uuid of management network . each instance in the pool is initially booted with a single port on this network : param pool_size : the size of the pool,def __init__ self image_uuid flavor pool_size mgt_net_id self image_uuid image_uuid self flavor flavor self mgt_net_id mgt_net_id self pool_size int pool_size self poll_interval 3 self ctxt WorkerContext self boot_timeout 120 self delete_timeout 30 self _delete_counters self _boot_counters self load_driver_config
show a list of manageable volumes without many details .,def summary_list self request volumes count return self _list_view self summary request volumes count
creates lun on the unity system .,def create_lun self name size pool description None io_limit_policy None is_thin None try lun pool create_lun lun_name name size_gb size description description io_limit_policy io_limit_policy is_thin is_thin except storops_ex UnityLunNameInUseError LOG debug LUN s already exists Return the existing one name lun self system get_lun name name return lun
makes room for a volume cache entry .,def ensure_space self context volume if self max_cache_size_gb 0 and self max_cache_size_count 0 return True if self max_cache_size_gb 0 and volume size self max_cache_size_gb return False entries self db image_volume_cache_get_all context self _get_query_filters volume current_count len entries current_size 0 for entry in entries current_size entry size current_size volume size current_count 1 LOG debug Image volume cache for service s current_size GB size_gb s max max_gb s current count count s max max_count s service volume service_topic_queue size_gb current_size max_gb self max_cache_size_gb count current_count max_count self max_cache_size_count while current_size self max_cache_size_gb or current_count self max_cache_size_count and len entries entry entries pop LOG debug Reclaiming image volume cache space removing cache entry entry s entry self _entry_to_str entry self _delete_image_volume context entry current_size entry size current_count 1 LOG debug Image volume cache for service s new size GB size_gb s new count count s service volume service_topic_queue size_gb current_size count current_count if self max_cache_size_gb 0 if current_size self max_cache_size_gb 0 LOG warning Image volume cache for service s does not have enough space GB service volume service_topic_queue return False return True
restore an existing backup to a volume .,wsgi response http_client ACCEPTED validation schema backup restore def restore self req id body LOG debug Restoring backup backup_id s body s backup_id id body body context req environ cinder context restore body restore volume_id restore get volume_id None name restore get name None LOG info Restoring backup backup_id s to volume volume_id s backup_id id volume_id volume_id context context try new_restore self backup_api restore context backup_id id volume_id volume_id name name except exception InvalidInput exception InvalidVolume exception InvalidBackup as error raise exc HTTPBadRequest explanation error msg except exception VolumeSizeExceedsAvailableQuota exception VolumeLimitExceeded as error raise exc HTTPRequestEntityTooLarge explanation error msg headers Retry After 0 retval self _view_builder restore_summary req dict new_restore return retval
removes a membership from the image .,utils mutating def delete self req image_id id self _check_can_access_image_members req context self _enforce req delete_member self _raise_404_if_image_deleted req image_id try registry delete_member req context image_id id self _update_store_acls req image_id except exception NotFound as e LOG debug encodeutils exception_to_unicode e raise webob exc HTTPNotFound explanation e msg except exception Forbidden as e LOG debug User not permitted to remove membership from image s image_id raise webob exc HTTPNotFound explanation e msg return webob exc HTTPNoContent
add the provisioning network to a node .,def add_provisioning_network self task LOG debug Binding flat network ports client neutron get_client context task context for port_like_obj in task ports task portgroups vif_port_id port_like_obj internal_info get common TENANT_VIF_KEY or port_like_obj extra get vif_port_id if not vif_port_id continue body port binding host_id task node uuid binding vnic_type neutron VNIC_BAREMETAL try client update_port vif_port_id body except neutron_exceptions NeutronClientException as e msg _ Unable to set binding host_id for neutron port port_id s Error err s port_id vif_port_id err e LOG exception msg raise exception NetworkError msg
retrieve information about the given chassis .,METRICS timer ChassisController get_one expose expose Chassis types uuid types listtype def get_one self chassis_uuid fields None cdict pecan request context to_policy_values policy authorize baremetal chassis get cdict cdict api_utils check_allow_specify_fields fields rpc_chassis objects Chassis get_by_uuid pecan request context chassis_uuid return Chassis convert_with_links rpc_chassis fields fields
describe all known availability zones .,wsgi Controller authorize index def _index self req views db availability_zone_get_all req environ manila context return self _view_builder detail_list views
ensure the ability to raise : class:`fault ` in wsgi - ified methods .,def test_raise_403 self webob dec wsgify def raiser req raise wsgi Fault webob exc HTTPForbidden explanation whut req webob Request blank json resp req get_response raiser self assertEqual application json resp content_type self assertEqual 403 resp status_int self assertNotIn six b resizeNotAllowed resp body self assertIn six b forbidden resp body
handles a call to this application .,webob dec wsgify RequestClass wsgi Request def __call__ self request if request method POST raise webob exc HTTPMethodNotAllowed try info dict jsonutils loads request body except ValueError raise webob exc HTTPBadRequest username request path_info_pop verb info get verb path info get path delay error self _limiter check_for_delay verb path username if delay headers X Wait Seconds 2f delay return webob exc HTTPForbidden headers headers explanation error else return webob exc HTTPNoContent
list of check callables could be specified .,def __init__ self args kwargs self _checks kwargs pop checks super ConductorManagerTestCase self __init__ args kwargs
retrieve a receiver from database .,classmethod def load cls context receiver_id None receiver_obj None project_safe True if receiver_obj is None receiver_obj ro Receiver get context receiver_id project_safe project_safe if receiver_obj is None raise exception ResourceNotFound type receiver id receiver_id return cls _from_object receiver_obj
delete simulation from wrfxpy and all files . : param sim_info : the simulation json : param conf : configuration,def delete_simulation sim_info conf cmd osp abspath osp join conf wrfxpy_path cleanup sh job_id sim_info job_id exe cmd delete job_id logging debug Calling join exe os system join exe delete_simulation_files sim_info id conf
"reads the specified counter at the specified index from the switch . in our program , the index is the tunnel id . if the index is 0 , it will return all values from the counter .",def printCounter p4info_helper sw counter_name index for response in sw ReadCounters p4info_helper get_counters_id counter_name index for entity in response entities counter entity counter_entry print s s d d packets d bytes sw name counter_name index counter data packet_count counter data byte_count
"returns a json - string with the data from commonsense.csv . each relation is encoded as a [ concept1 , relation , concept2 , context , weight ] list .",def json f lambda s s replace encode utf 8 s g Commonsense for e in g edges s append n t s s s s 2f f e node1 id f e type f e node2 id f e context e weight return commonsense s join s
reverse a freeze ( ) call and increment the time immediately .,def unfreeze self self frozen False return self current
"start at a and stop when you get to b , return the time elapsed",def first_passage self a B maxiter 100000 current_state a B set B if self debug path current_state total_time 0 0 niter 0 while current_state not in B unext time self next current_state current_state unext if self debug path append current_state total_time time niter 1 if niter maxiter print KMC error first_passage maxiter reached if self debug print path 0 for u in path 1 print u print return total_time niter
"create a state from a blank image , set of pos and radii",def create_state image pos rad slab None sigma 0 05 conf conf_simple if not hasattr rad __iter__ rad rad np ones pos shape 0 model models models conf get model components for k v in conf get comps iteritems args conf get args get k comp model registry k v args components append comp sphs objs PlatonicSpheresCollection pos rad if slab is not None sphs ComponentCollection sphs objs Slab zpos slab pad category obj components append sphs s states ImageState image components sigma sigma if isinstance image util NullImage s model_to_data return s
"given a broacast message , returns the message that was broadcast .",def _parse_broadcast self msg return self _unescape self _get_type msg self broadcast_prefix_len
sets the color of the contour level . has no effect if ` contours.coloring ` is set to * lines*.,property def color self return self color
convert matplotlib color code to hex color code,def color_to_hex color if color is None or colorConverter to_rgba color 3 0 return none else rgb colorConverter to_rgb color return 0 02X 1 02X 2 02X format int 255 c for c in rgb
"html font family - the typeface that will be applied by the web browser . the web browser will only be able to apply a font if it is available on the system which it operates . provide multiple font families , separated by commas , to indicate the preference in which to apply fonts if they are n't available on the system . the plotly service ( at https://plot.ly or on- premise ) generates images on a server , where only a select number of fonts are installed and supported . these include * arial * , * balto * , * courier new * , * droid sans * , , * droid serif * , * droid sans mono * , * gravitas one * , * old standard tt * , * open sans * , * overpass * , * pt sans narrow * , * raleway * , * times new roman*.",property def family self return self family
"the ' size ' property is a number and may be specified as : - an int or float in the interval [ 1 , inf ]",property def size self return self size
sets the orientation ( from the paper perspective ) of the angular axis tick labels .,property def tickorientation self return self tickorientation
shut down services required to run your test .,def tear_down self if hasattr self services self services shutdown
"normalizes strokes so that every stroke has a standard number of points . returns true if stroke is normalized , false if it ca n't be normalized . sample_points controls the resolution of the stroke .",def normalize_stroke self sample_points 32 if len self points 1 or self stroke_length self points 0 0 return False target_stroke_size self stroke_length self points float sample_points new_points list new_points append self points 0 prev self points 0 src_distance 0 0 dst_distance target_stroke_size for curr in self points 1 d self points_distance prev curr if d 0 prev curr src_distance src_distance d while dst_distance src_distance x_dir curr x prev x y_dir curr y prev y ratio src_distance dst_distance d to_x x_dir ratio prev x to_y y_dir ratio prev y new_points append GesturePoint to_x to_y dst_distance self stroke_length self points float sample_points len new_points if not len new_points sample_points raise ValueError Invalid number of strokes points got d while it should be d len new_points sample_points self points new_points return True
"1 . checks to see if the registration form has been created alread . if not , it loads it in . 2 . loads a registration instance .",def get_registration_instance self custom_values registration_xforms XForm objects filter title u registration if registration_xforms count 0 xf self create_registration_xform else xf registration_xforms 0 values u device_id u 12345 u start u 2011 01 01T09 50 06 966 u end u 2011 01 01T09 53 22 965 if u start in custom_values st custom_values u start custom_values u start st strftime XFORM_TIME_FORMAT values u end st ONE_HOUR strftime XFORM_TIME_FORMAT if u end in custom_values custom_values u end custom_values u end strftime XFORM_TIME_FORMAT values update custom_values reg_xform _load_registration_survey_object reg_instance reg_xform instantiate reg_instance _id xf id_string for k v in values items reg_instance answer name k value v instance_xml reg_instance to_xml return Instance xml instance_xml
generate an sql expression string with bound parameters rendered inline for the given sqlalchemy statement .,def literalquery statement dialect None if isinstance statement sqlalchemy orm Query if dialect is None dialect statement session get_bind statement _mapper_zero_or_none dialect statement statement statement if dialect is None dialect getattr statement bind dialect None if dialect is None from sqlalchemy dialects import mysql dialect mysql dialect Compiler type statement _compiler dialect class LiteralCompiler Compiler visit_bindparam Compiler render_literal_bindparam def render_literal_value self value type_ if isinstance value Decimal long return str value elif isinstance value datetime return repr str value else value super LiteralCompiler self render_literal_value value type_ if isinstance value unicode return value encode UTF 8 else return value return LiteralCompiler dialect statement
"create an instance of the model , and save it to the database .",classmethod def _create cls model_class args kwargs u manager cls _get_manager model_class if cls _meta django_get_or_create return cls _get_or_create model_class args kwargs return getattr manager cls create_method args kwargs
"create a new instance of this public key type . if c{msg } is given , the key 's public part(s ) will be filled in from the message . if c{data } is given , the key 's public part(s ) will be filled in from the string .",def __init__ self msg None data None pass
sleep a fixed amount of time between each retry .,def fixed_sleep self previous_attempt_number delay_since_first_attempt_ms return self _wait_fixed
implementation of depth first branch and bound,def dfbnb node logging debug node
this function creates loop unrolling bridges using the information in spades paths .,def create_loop_unrolling_bridges graph anchor_segments log log_section_header Creating loop unrolling bridges log log_explanation When a SPAdes contig path connects an anchor contig with the middle contig of a simple loop Unicycler concludes that the sequences are contiguous i e the loop is not a separate piece of DNA It then uses the read depth of the middle and repeat contigs to guess the number of times to traverse the loop and makes a bridge verbosity 1 bridges simple_loops graph find_all_simple_loops simple_loops x for x in simple_loops if x 2 is not None seg_nums_to_bridge set x number for x in anchor_segments for start end middle repeat in simple_loops if abs start not in seg_nums_to_bridge continue if abs end not in seg_nums_to_bridge continue if abs repeat in seg_nums_to_bridge continue joined False for path in graph paths values flipped_path x for x in reversed path if start in path and middle in path or end in path and middle in path or start in flipped_path and middle in flipped_path or end in flipped_path and middle in flipped_path joined True break if joined bridges append LoopUnrollingBridge graph start end middle repeat if bridges bridge_table Start Repeat Middle End Loop count by repeat Loop count by middle Loop count Bridge quality for bridge in bridges bridge_table append str bridge start_segment str bridge repeat_segment str bridge middle_segment str bridge end_segment float_to_str bridge loop_count_by_repeat 2 float_to_str bridge loop_count_by_middle 2 str bridge loop_count float_to_str bridge quality 1 print_table bridge_table alignments RRRRRRRR left_align_header False indent 0 fixed_col_widths 5 6 6 5 10 10 5 7 else log log No loop unrolling bridges made return bridges
tells whether point lies inside hexagon .,def pointInHex point hexagon x point 0 y point 1 poly hexagon vertices n len poly inside False p1x p1y poly 0 for i in range n 1 p2x p2y poly i n if y min p1y p2y if y max p1y p2y if x max p1x p2x if p1y p2y xinters y p1y p2x p1x p2y p1y p1x if p1x p2x or x xinters inside not inside p1x p1y p2x p2y return inside
"for a given image , extract a 1d spectra from the image and write the spectra to the output file",def extract hdu ext 1 method normal section minsize 3 0 thresh 3 0 convert True ap_list i ext if hdu i name SCI data_arr hdu i data try var_arr hdu hdu i header VAREXT data except var_arr None try bpm_arr hdu hdu i header BPMEXT data except bpm_arr None var_arr None bpm_arr None xarr np arange len data_arr 0 try w0 saltkey get CRVAL1 hdu i dw saltkey get CD1_1 hdu i except Exception as e msg Error on Ext i s i e raise SALTSpecError msg warr w0 dw xarr if convert warr Spectrum air2vac warr if section is None section findobj findObjects data_arr method median specaxis 1 minsize minsize thresh thresh niter 5 for sec in section ap apext apext warr data_arr ivar var_arr y1 y2 sec ap flatten y1 y2 ap_list append ap return ap_list
"reads a line from an ldif file , unfolding it",def __read_folded_line f buffer line buffer while True l f readline if l 1 assert line and line n line line l elif line line l if l break else buffer l break return line buffer
use doctest checking from lxml for comparing xml trees . returns diff if the two are not the same,def compare_xml generated expected checker LXMLOutputChecker class DummyDocTest pass ob DummyDocTest ob want expected check checker check_output expected generated PARSE_XML if check is False diff checker output_difference ob generated PARSE_XML return diff
returns true if the settings have already been configured .,property def configured self return self _wrapped is not empty
"delete a key from the cache , failing silently .",def delete self key version None u n Delete a key from the cache failing silently n raise NotImplementedError u subclasses of BaseCache must provide a delete method
breaks headers longer than 160 characters ( ~page length ) when possible ( are comma separated ),register filter def break_long_headers header u n Breaks headers longer than 160 characters page length n when possible are comma separated n if len header 160 and u in header header mark_safe u br u br join header split u return header
tries to run python example and produce a * .png image,def run_example filename if not os path exists filename raise Exception File filename doesn t exist print filename fig get_figure filename try exec_full filename plot_file_name os path splitext os path basename filename 0 png plot_file_name os path join output_dir plot_file_name print plot_file_name plt savefig plot_file_name bbox_inches tight plt close fig status OK kb os path getsize plot_file_name 1000 0 if kb 4 0 status EMPTY except e sys exc_info 0 print Error 0 while trying to execute 1 format e filename status FAILED print status if status OK raise Exception status
returns the base file name for a student in a course .,staticmethod def basename student_id course_id name student_id replace replace name course_id return name
gets the connected attribute of this runtime instance .,property def connected self return self _connected
"we can only recognize ecb if there is at least one repeated block in the ciphertext . but this wo n't always work , as different input blocks will produce different output blocks with ecb too .",def DetectEncryptionMode ciphertext repetitions CountRepeatedBlocks ciphertext return AES MODE_ECB if repetitions 0 else AES MODE_CBC
returns a streaminghttpresponse with the file,login_required def download_path request machine_name path src gridutil get_grid_path machine_name path env gridutil get_cred_env request user tmp_file tempfile NamedTemporaryFile prefix newt_ dest file tmp_file name logger debug File download requested s s path src output error retcode run_command gridutil GLOBUS_CONF LOCATION bin globus url copy s s src dest env env if retcode 0 logger warning Unable to download file s src return json_response content output status ERROR status_code 500 error error mimetype mimetypes guess_type tmp_file name if mimetype is None mimetype application octet stream return StreamingHttpResponse tmp_file content_type mimetype
returns a string representation of the stream codec .,def codec self codec_name None if self __dict__ codec_name codec_name self __dict__ codec_name return codec_name
method to plot extinction map .,def plot_map self path None figsize 10 import matplotlib import matplotlib pyplot as plt nfig 3 fig plt figure figsize figsize nfig 0 9 figsize self map_shape 0 self map_shape 1 grid matplotlib gridspec GridSpec ncols 2 nrows nfig bottom 0 1 top 0 9 left 0 1 right 0 9 hspace 0 08 wspace 0 height_ratios 1 nfig width_ratios 1 0 05 cmap copy matplotlib cm binary cmap set_bad DC143C 1 0 for idx in range 0 nfig 2 2 ax plt subplot grid idx projection wcs WCS self map_header cax plt subplot grid idx 1 if idx 0 vmin vmax self _get_vlim data self map_ext percentiles 0 1 90 r 100 im ax imshow self map_ext origin lower interpolation nearest vmin vmin vmax vmax cmap cmap fig colorbar im cax cax label Extinction mag elif idx 2 vmin vmax self _get_vlim data np sqrt self map_var percentiles 1 90 r 100 im ax imshow np sqrt self map_var origin lower interpolation nearest vmin vmin vmax vmax cmap cmap if self prime_header METRIC median fig colorbar im cax cax label MAD mag else fig colorbar im cax cax label Error mag elif idx 4 vmin vmax self _get_vlim data self map_num percentiles 1 99 r 1 im ax imshow self map_num origin lower interpolation nearest vmin vmin vmax vmax cmap cmap fig colorbar im cax cax label N elif idx 6 vmin vmax self _get_vlim data self map_rho percentiles 1 99 r 1 im ax imshow self map_rho origin lower interpolation nearest vmin vmin vmax vmax cmap cmap fig colorbar im cax cax label rho lon lat ax coords 0 ax coords 1 if idx nfig 1 2 lon set_axislabel Longitude lat set_axislabel Latitude if idx nfig 1 2 lon set_ticklabel_position if path is None plt show else plt savefig path bbox_inches tight plt close
remove a file extension from the file path,def trim_extension self file_path filename ext os path splitext os path basename file_path for extension in Settings get java_extensions if ext extension return file_path len ext return file_path
write the provided configuration to a specific location .,def write_config config filename None if not filename filename CONFIG_DEFAULT_PATH with open filename w as f json dump config f indent 4
return list of html theme paths .,def get_html_theme_path cur_dir os path abspath os path dirname os path dirname __file__ return cur_dir
convenient method for post requests returns http request status value from a post request,def _do_post self url kwargs scaleioapi_post_headers Content type application json Version 1 0 try response self _session post url headers scaleioapi_post_headers kwargs self conn logger debug _do_post HTTP response s response text if response status_code requests codes ok self conn logger debug _do_post HTTP response OK data s response text return response else self conn logger error _do_post HTTP response error s response status_code self conn logger error _do_post HTTP response error data s response text raise RuntimeError _do_post HTTP response error response status_code except Exception as e self conn logger error _do_post Unhandled Error Occurred s str e raise RuntimeError _do_post Communication error with ScaleIO gateway return response
check if there are no modules to stub,property def nothing_to_stub self return len self elements 0
get a : class:`filetracer ` object for a file .,def file_tracer self filename return None
return a string describing an instance via its instancestate .,def state_str state if state is None return None else return s at 0x x state class_ __name__ id state obj
test binding in a large long integer,def testBindLargeLong self valueVar self cursor var cx_Oracle NUMBER valueVar setvalue 0 6088343244 self cursor execute u n begin n value value 5 n end value valueVar value valueVar getvalue self failUnlessEqual value 6088343249
validates whether the ode equations provided make sense i.e. the number of right - hand side equations match the number of left - hand side equations .,def validate self if self left_hand_side rows self right_hand_side rows raise ValueError There are 0 left hand side equations and 1 right hand side equations The same number is expected format self left_hand_side rows self right_hand_side rows
return new deque with rightmost element removed . popping the empty queue will return the empty queue . a optional count can be given to indicate the number of elements to pop . popping with a negative index is the same as popleft . executes in amortized o(k ) where k is the number of elements to pop .,def pop self count 1 if count 0 return self popleft count new_right_list new_left_list PDeque _pop_lists self _right_list self _left_list count return PDeque new_left_list new_right_list max self _length count 0 self _maxlen
gets the value of nonnegative or its default value .,def getNonnegative self return self getOrDefault self nonnegative
reconstruct a fits object from serialised fits header and data .,def reconstruct_fits fits_bytes image_bytes hdu_header astropy io fits header Header fromstring fits_bytes width hdu_header NAXIS1 length hdu_header NAXIS2 image_array struct unpack str len image_bytes 4 f image_bytes image_matrix np reshape image_array width length hdu astropy io fits PrimaryHDU image_matrix hdu header hdu_header hdulist astropy io fits HDUList hdu return hdulist
joins the lorawan network using over the air activation ( otaa ),def join_otaa lora LoRa mode LoRa LORAWAN log Initializing LoRaWAN OTAA DEV EUI format hexlify lora mac decode ascii upper if not LORA_OTAA_KEY log ERROR LoRaWAN APP KEY not set log Send your DEV EUI to thethingsnetwork bfh ch to obtain one return None pycom rgbled RGB_LORA authentication unhexlify LORA_OTAA_EUI unhexlify LORA_OTAA_KEY lora join activation LoRa OTAA auth authentication timeout 0 while not lora has_joined log Joining pycom rgbled RGB_OFF time sleep LED_TIMEOUT pycom rgbled RGB_LORA time sleep 2 5 pycom rgbled RGB_OFF return lora
test that the usernames which ought to be available are and that those which are n't are not :,def test_usernameAvailability self signup self createFreeSignup free_signup userInfo itemClass self failUnless signup usernameAvailable u alice u localhost 0 self failIf signup usernameAvailable u alice u example com 0 self failIf signup usernameAvailable u admin u localhost 0 self assertEquals signup usernameAvailable u fjones u localhost True u Username already taken signup createUser realName u Frank Jones username u fjones domain u localhost password u asdf emailAddress u fj crappy example com self assertEquals signup usernameAvailable u fjones u localhost False u Username already taken ss self ls accountByAddress u fjones u localhost avatars open self assertEquals ss query Installation count 1
"unwrap the wrapped resource if https is already being used , otherwise wrap it in a helper which will preserve the wrapping all the way down to the final resource .",def locateChild self context segments request IRequest context if request isSecure return self wrappedResource segments return _SecureWrapper self urlGenerator self wrappedResource segments
here is test_13 's doc str,def test_13 self log info Here is logging of test_13 sleep 2 self assertEqual 1 1
"this method handles writing to the closest config file to the current project , but does not write to the defaults.cfg file in ctree . : return : return true if write is successful . false otherwise .",def write_to_config section key value if ctree CFG_PATHS target get_responsible section key config ConfigParser ConfigParser config read target print target if not config has_section section config add_section section config set section key value with open target w as configfile config write configfile configfile close return True else print FAILURE No config file detected Please create a ctree cfg file in your project directory return False
compute eccentricity derivative from taylor et al . ( 2015 ),def get_edot F mc e mc SOLAR2S dedt 304 15 mc 2 np pi mc F 8 3 e 1 121 304 e 2 1 e 2 5 2 return dedt
"d.pop(k[,d ] ) - > v , remove specified key and return the corresponding value . if key is not found , d is returned if given , otherwise keyerror is raised .",def pop self key default __marker try value self key except KeyError if default is self __marker raise return default else del self key return value
set current event for player .,classmethod def post cls request event_id None player request user player event get_object_or_404 Event pk event_id if event_id else None pe created PlayingEvent objects get_or_create player player if pe event event transfer_clues player player old_event pe event new_event event pe event event pe save if created status rf_status HTTP_201_CREATED else status rf_status HTTP_200_OK serializer EventSerializer event many False context player request user player data serializer data return Response data status status
"download is done be creating files with instructions for curl - curl config files . another file is created containing invocations of curl with each of the config files - the parallel run file . curl_config_folder : the folder where curl config files and parallel run file will be placed . num_config_files : the maximum number of curl config files . actual_num_config_files : actual number of curl config files created . might be smaller than num_config_files , or might be 0 if downloading is not required .",def create_curl_download_instructions self main_out_file_dir main_out_file_leaf os path split var_stack ResolveVarToStr __MAIN_OUT_FILE__ curl_config_folder os path join main_out_file_dir curl os makedirs curl_config_folder exist_ok True curl_config_file_path var_stack ResolveStrToStr os path join curl_config_folder CURL_CONFIG_FILE_NAME num_config_files int var_stack ResolveVarToStr PARALLEL_SYNC config_file_list self instlObj platform_helper dl_tool create_config_files curl_config_file_path num_config_files actual_num_config_files len config_file_list if actual_num_config_files 0 if actual_num_config_files 1 dl_start_message Downloading with processes in parallel format actual_num_config_files else dl_start_message Downloading with 1 process self instlObj batch_accum self instlObj platform_helper progress dl_start_message parallel_run_config_file_path var_stack ResolveStrToStr os path join curl_config_folder CURL_CONFIG_FILE_NAME parallel run self instlObj batch_accum self instlObj platform_helper dl_tool download_from_config_files parallel_run_config_file_path config_file_list num_files_to_download int var_stack ResolveVarToStr __NUM_FILES_TO_DOWNLOAD__ if num_files_to_download 1 dl_end_message Downloading files done format num_files_to_download else dl_end_message Downloading 1 file done self instlObj batch_accum self instlObj platform_helper progress dl_end_message self files_to_download self instlObj batch_accum self instlObj platform_helper new_line
return the raw handle of the tensor .,def get_raw_handle self self _auto_gc_enabled False return self _handle
returns the contents of the .md file for ` class_elt ` .,def page_overview class_elt overview_brief overview_details briefs class_elt findAll briefdescription recursive False if briefs overview_brief element_text briefs 0 None details class_elt findAll detaileddescription recursive False if details overview_details element_text details 0 None return overview_brief n n overview_details
"move the cursor to a new position . values are 1-based , and default to 1 .",staticmethod def pos line 1 column 1 return EscapeCode line col H format line line col column
"wraps a call to re.sub in order to return both the resulting string and the matched groups . : param pattern : : param repl : a replacement string : param string : : return : the resulting string , matched groups",def re_sub pattern repl string groups result re sub pattern lambda m re_collect_groups m groups repl string return result groups
this class fits a polynomial to a function of 2 variables .,def __init__ self ord 2 kwargs self ord ord self x None VectorClassifier __init__ self TYPE_REGRESSION kwargs
"converts a datum to an array . note that the label is not returned , as one can easily get it by calling datum.label .",def datum_to_array datum if len datum data return np fromstring datum data dtype np uint8 reshape datum channels datum height datum width else return np array datum float_data astype float reshape datum channels datum height datum width
"takes either an api_key as a keyword argument or tries to access an environmental variable `` pyfootball_api_key `` , then uses the key to send a test request to make sure that it 's valid . the api_key kwarg takes precedence over the envvar .",def __init__ self api_key None if api_key key api_key elif os getenv PYFOOTBALL_API_KEY None key os getenv PYFOOTBALL_API_KEY else raise ValueError Couldn t find an API key in the keyword argument api_key nor the environmental variable PYFOOTBALL_API_KEY endpoint endpoints all_competitions globals headers X Auth Token key r requests get endpoint headers globals headers globals update_prev_response r endpoint r raise_for_status globals api_key key
read dhcp leases & interface entries,def GetDhcpInfo mac_info u try interfaces mac_info ListItemsInFolder u private var db dhcpclient leases EntryType FILES for interface in interfaces name interface u name if name find u 0 mac_info ExportFile u private var db dhcpclient leases name __Plugin_Name u False name_no_ext os path splitext name 0 if_name mac_address name_no_ext split u log info u Found mac address mac_address u on interface if_name log debug u Trying to read format name f mac_info OpenSmallFile u private var db dhcpclient leases name if f None try plist biplist readPlist f interface_info u Source u private var db dhcpclient leases name u Interface if_name u MAC_Address mac_address for item value in plist iteritems if item in u IPAddress u LeaseLength u LeaseStartDate u PacketData u RouterIPAddress u SSID interface_info item value elif item u RouterHardwareAddress data binascii hexlify c upper if PYTHON_VER 2 else binascii hexlify c decode u ascii upper for c in value interface_info item u join data else log info u Found unknown item in plist ITEM item u VALUE str value dhcp_interfaces append interface_info except Exception as ex log error u Failed to read plist name u Exception str ex else log error u Could not open plist to get interface info for name else log info u Found unexpected file not processing private var db dhcpclient leases name u size str interface u size except Exception as ex log error u Could not list files for folder private var db dhcpclient leases log exception u Exception from GetDhcpInterfaces
"loads a list of databaseobjects from path matching query . if nothing matches the query ( possibly because there is nothing in the specified mongo collection ) , the created databasecollection will be an empty list and have bool(returned object ) = = false",def __init__ self path None objtype None query None sort_by ID_KEY ascending True page 0 page_size None read_only False projection None field None kwargs if objtype self OBJTYPE objtype if path self PATH path if not query query kwargs if field if field ID_KEY projection ID_KEY else projection field True ID_KEY False if projection read_only True results self db find query projection projection if isinstance sort_by list results results sort sort_by elif sort_by results results sort sort_by ASCENDING if ascending else DESCENDING if page_size results limit page_size skip page_size page if field for result in results if field in result self append result field elif read_only for result in results self append result else for result in results self append self OBJTYPE path self PATH _new_object result
this writer supports all format - specific elements .,def supports self format return True
get the imported ` pymodule `,def get_imported_module self context if self level 0 return context project get_module self module_name context folder else return context project get_relative_module self module_name context folder self level
properties creates xml for default values,def test_toXML_default self p FaultState Properties self assertEquals p toXML
method used to schedule timeouts .,def scheduleTimeout self timeout_func time_to_occur 0 frequency 0 arg_tuple None arg_dict None self timeout_counter 1 timeout_id self timeout_counter time_to_occur getEpochTimeStamp value if arg_tuple None arg_tuple if arg_dict None arg_dict self lock acquire self timeout_dict timeout_id time_to_occur long time_to_occur frequency long frequency timeout_func timeout_func is_suspended 0 arg_tuple deepcopy arg_tuple arg_dict deepcopy arg_dict self lock release self logger logDebug Timeout scheduled to occur str self timeout_dict timeout_id return timeout_id
"returns the number of steps or none if these is no solution if there is a solution , it can be found in self.current_assignment",def search self max_steps prob_best 1 0 prob_anycon 1 0 if self current_assignment is None self restart self number_of_steps 1 if not self conflicts return self number_of_steps if prob_best 0 return self search_with_var_pq max_steps prob_best prob_anycon else return self search_with_any_conflict max_steps prob_anycon
code executed before running the benchmark,def benchmarkInit self pass
return a 2d split cosine bell .,def __call__ self shape radial_dist _radial_distance shape npts np array shape min 1 0 2 0 r_inner self beta npts r radial_dist r_inner r_taper int np floor self alpha npts if r_taper 0 f 0 5 1 0 np cos np pi r r_taper else f np ones shape f radial_dist r_inner 1 0 r_cut r_inner r_taper f radial_dist r_cut 0 0 return f
input : txpgrouplabels : represents eqclass i.e. tuples of txp ids alphas : estimated counts after runing online phase txpgroupcombinedweights : dictionary with eqclass label to w_i^j weight for each txp in eqclass . txpgroupcounts : dictionary with eqclass label to d^j counts of reads for eqclass prioralphas : prior values for estimated counts output : alphas : estimated counts after one round of vbem optimization . variable names are consistent with https://github.com/combine-lab/salmon/blob/develop/src/collapsedemoptimizer.cpp#l166 for simplicity .,def VBEMUpdate alphaIn txpGroupCombinedWeights txpGroupCounts priorAlphas alphaSum np sum alphaIn logNorm digamma alphaSum expTheta np exp digamma alphaIn logNorm alphasOut np copy priorAlphas expTheta np isnan expTheta 0 expTheta np isinf expTheta 0 for txps count in txpGroupCounts items denom 0 0 auxs txpGroupCombinedWeights txps if len txps 1 for index txp in enumerate txps aux auxs index if expTheta txp 0 0 denom expTheta txp aux if denom minEQClassWeight invDenom old_div count denom for index txp in enumerate txps aux auxs index if expTheta txp 0 0 alphasOut txp expTheta txp aux invDenom else txp txps 0 alphasOut txp count return alphasOut
check on whether report was correct @param self : essential if you override this definition @param pcompliance : the self.iscompliant value of rule @param prulesuccess : did report run successfully @return : boolean - if successful true ; if failure false @author : ekkehard j. koch,def checkReportForRule self pCompliance pRuleSuccess self logdispatch log LogPriority DEBUG pCompliance str pCompliance self logdispatch log LogPriority DEBUG pRuleSuccess str pRuleSuccess success True return success
check on whether undo was correct @param self : essential if you override this definition @param prulesuccess : did report run successfully @return : boolean - if successful true ; if failure false @author : ekkehard j. koch,def checkUndoForRule self pRuleSuccess self logdispatch log LogPriority DEBUG pRuleSuccess str pRuleSuccess success True return success
search given list for searchterm init self.interfacenames to empty,def searchOutput self searchlist searchterm self logger log LogPriority DEBUG Running searchOutput if not isinstance searchlist list self logger log LogPriority DEBUG Parameter searchlist needs to be a list and was not passed as a list return False if not isinstance searchterm basestring self logger log LogPriority DEBUG Parameter searchterm needs to be a string and was not passed as a string return False promiscfound False self interfacenames for line in searchlist if re search searchterm line promiscfound True self appendiName line return promiscfound
fill the surface with lines in various colours,def _fill_surface surface y 0 for colour in 255 0 0 255 0 255 0 255 0 0 255 0 255 255 255 255 0 0 0 255 255 255 0 255 0 255 255 255 255 0 255 255 draw rect surface colour 0 y 800 y 75 y 75
this function takes existing country code as argument and creates hierarchy - country / district / cities .,def load_country_data code code code upper country_info CountryInfo objects get code code regions_info AdminCode objects filter country code try l Location objects get pk country_info pk logging info Location already exists s Skipping l name except Location DoesNotExist trans get_translation country_info pk code if trans is None trans country_info name l Location objects create id country_info pk name trans kind country country_code country_info code creator admin population country_info population l save logging info Created country location s l name try l_country Country objects get location l logging info Related country already exists s Skipping l name except Country DoesNotExist l_country Country objects create code code location l l_country save logging info Created related country s l name for region in regions_info try nl Location objects get pk region pk logging info Region already exists s Skipping nl name except Location DoesNotExist trans get_translation region pk region country if trans is None trans region name nl Location objects create id region pk name trans kind region country_code country_info code parent l creator admin nl save logging info Created region location s nl name load_region_data region nl
usage : commit [ < shadow_cib > ],command skill_level administrator command wait command completers compl shadows def do_commit self context name None if name and not utils is_filename_sane name context fatal_error Bad filename name if not name name utils get_cib_in_use if not name context fatal_error There is nothing to commit if utils ext_cmd s C s force self extcmd name 0 context info committed s shadow CIB to the cluster name else context fatal_error failed to commit the s shadow CIB name if constants tmp_cib self _use
a high - level interface for an lda ( latent dirichlet allocation ) model .,def _LDA vectorized_output ntopics kwargs bow k v for k v in vector items for vector in vectorized_output vectors values _model gensim models LdaModel bow num_topics ntopics id2word vectorized_output id_term_map minimum_probability 0 kwargs topic_term_matrix topic format topic_no _topic_term_to_array vectorized_output id_term_map _model show_topic topic_no None for topic_no in range ntopics doc_topic_matrix list _model bow doc_topic_matrix _doc_topic_to_array vectorized_output vectors doc_topic_matrix return topic_term_matrix doc_topic_matrix
send a signal to parenrt workflow ( signal : subflow.signal_name ),def _execute self activity stack result True cr self session cr signal_todo if self workitem state active and activity signal_send cr execute select i id w osv i res_id from wkf_instance i left join wkf w on i wkf_id w id where i id IN select inst_id from wkf_workitem where subflow_id s self workitem inst_id for instance_id model_name record_id in cr fetchall record Record model_name record_id signal_todo append instance_id record activity signal_send if activity kind WorkflowActivity KIND_DUMMY if self workitem state active self _state_set activity complete if activity action_id res2 self wkf_expr_execute_action activity if res2 stack append res2 result res2 elif activity kind WorkflowActivity KIND_FUNCTION if self workitem state active self _state_set activity running returned_action self wkf_expr_execute activity if type returned_action in dict stack append returned_action if activity action_id res2 self wkf_expr_execute_action activity if res2 stack append res2 result res2 self _state_set activity complete elif activity kind WorkflowActivity KIND_STOPALL if self workitem state active self _state_set activity running cr execute delete from wkf_workitem where inst_id s and id s self workitem inst_id self workitem id if activity action self wkf_expr_execute activity self _state_set activity complete elif activity kind WorkflowActivity KIND_SUBFLOW if self workitem state active self _state_set activity running if activity get action False id_new self wkf_expr_execute activity if not id_new cr execute delete from wkf_workitem where id s self workitem id return False assert type id_new type 1 or type id_new type 1L Wrong return value str id_new str type id_new cr execute select id from wkf_instance where res_id s and wkf_id s id_new activity subflow_id id_new cr fetchone 0 else inst instance WorkflowInstance self session self record id_new inst create activity subflow_id cr execute update wkf_workitem set subflow_id s where id s id_new self workitem id self workitem subflow_id id_new if self workitem state running cr execute select state from wkf_instance where id s self workitem subflow_id state cr fetchone 0 if state complete self _state_set activity complete for instance_id record signal_send in signal_todo wi instance WorkflowInstance self session record id instance_id wi validate signal_send force_running True return result
handles changes of properties of the model and updates the button enabled states in accordance to the selection .,def _propertyStateChangedSlot self self _updateButtonStates
performs the finish slot preparation .,def prepareFinishSlot self self lockIndex self _wizard targetIndexes 0 self _sourceIndexes self _wizard sourceIndexes self _repositoryModel lock self lockIndex
figures out if the associated path is a symbolic link .,def isLink self if sys platform _WIN32_PLATFORM result False if self _destination endswith self _WINDOWS_LINK_EXTENSION try sh pythoncom CoCreateInstance shell CLSID_ShellLink None pythoncom CLSCTX_INPROC_SERVER shell IID_IShellLink persist sh QueryInterface pythoncom IID_IPersistFile persist Load self _destination result True except pywintypes com_error result False return result else return os path islink self _destination
tests the recognition of conjunction terms when already a character is typed .,def testConjunctionRecognition self self autoComplEdit setText Content Peter hhg o self _requestAutocompletionAtPosition 23 self assertEquals self autoComplEdit completer currentCompletion OR
check whether exceptions are raised just as expected .,def testExceptions self self assertRaises ValueError _EmptyItemTreeWalker mode 0 walker _EmptyItemTreeWalker self assertRaises AttributeError walker walk self testRoot _EmptyItemTreeWalker handle VisitSlot inherits handle self assertRaises AttributeError walker walk self testRoot
simply serializes a package ( because sqlalchemy query results are n't serializable,def to_dict self return dict name self name
"start a node with requested rpcallowip and rpcbind parameters , then try to connect , and check if the set of bound addresses matches the expected set .",def run_bind_test tmpdir allow_ips connect_to addresses expected expected addr_to_hex addr port for addr port in expected base_args disablewallet nolisten if allow_ips base_args rpcallowip x for x in allow_ips binds rpcbind addr for addr in addresses nodes start_nodes 1 tmpdir base_args binds connect_to try pid bitcoind_processes 0 pid assert_equal set get_bind_addrs pid set expected finally stop_nodes nodes wait_bitcoinds
gets details about a specific instance,def get_instance self instance_name try return self driver ex_get_node instance_name except Exception as e return None
"construct distorted input for cifar training using the reader ops . raises : valueerror : if labels and images count does n't match . args : images : images . 4d tensor of [ batch_size , image_size , image_size , 3 ] size . labels : labels . 1d tensor of [ batch_size ] size . filename : returns :",def convert_images images labels filename assert images shape 0 labels shape 0 Number of images d should be equal to number of labels d images shape 0 labels shape 0 convert_to images labels filename
makes the object behave like a vtkgenericrenderwindowinteractor,def __getattr__ self attr if attr __vtk__ return lambda t self _Iren t elif hasattr self _Iren attr return getattr self _Iren attr else raise AttributeError self __class__ __name__ has no attribute named attr
create and return a new in - memory transport hooked up to the given protocol .,def makeFakeServer serverProtocol return FakeTransport serverProtocol isServer True
get /v2/<p>/tags / list/ should be accessible by collaborators,def test_v2_project_tags_list_get_2 self r self get http docker registry 8080 v2 s tags list self image_path self assertEqual r status_code 200
handle_pause ( ) should pause currently playing media,def handle_pause self message logger debug handle_pause not implemented in self name
"starts ( subscribes ) the client . if client is stopped you can not start again , threading . thread raised error",def start self self kill_event clear self thread start
first line of comment . second line of comment it is method for get /users,def get_users self data headers None query_params None content_type application json if query_params is None query_params uri self client base_url users return self client get uri data headers query_params content_type
"execute a single restful datacatalog interface method , * * with exception handling * * restful client methods available to dodc ( ) : exists ( ) check if dataset or folder exists mkdir ( ) create datacatalog folder(s ) create_dataset ( ) register dataset in datacatalog path ( ) fetch metadata for dataset or folder mkloc ( ) add a new location ( site ) for dataset patch_dataset ( ) update metadata for dataset",def doDC self method args kwargs cname method im_class __name__ fname method im_func __name__ mname cname fname if self debug print Entering doDC mname args kwargs if not fname in self dryRunList or not self dryrun try return method args kwargs except Exception as e ekeys e __dict__ keys self numExceptions 1 print n Exception in mname for key in ekeys if key raw continue print key getattr e key pass if self abortOnException raise Exception e rc 1 pass else print n Dry run return pass
get specific information about an instrument .,def get_instrument iid return conn _dunya_query_json api makam instrument s str iid
mount specified path if extensions know how,def mount_path self path pass
removes test counts from a google test program 's output .,def RemoveTestCounts output output re sub d tests listed below tests listed below output output re sub d FAILED TESTS FAILED TESTS output output re sub d tests from d test cases tests from test cases output output re sub d tests from a zA Z_ tests from 1 output return re sub d tests tests output
print a list of hydrogen bonds .,def hbond routines outroot outname outroot hbond file open outname w routines write Printing hydrogen bond list n sys stderr write Warning New H bonding definition is being used see hbond py in extensions directory for details file write Warning New H bonding definition is being used see hbond py in extensions directory for details cellsize int DIST_CUTOFF 1 0 1 0 protein routines protein routines setDonorsAndAcceptors routines cells Cells cellsize routines cells assignCells protein for donor in protein getAtoms if not donor hdonor continue donorhs for bond in donor bonds if bond isHydrogen donorhs append bond if donorhs continue closeatoms routines cells getNearCells donor for acc in closeatoms if not acc hacceptor continue if donor residue acc residue continue for donorh in donorhs dist distance donor getCoords acc getCoords if dist DIST_CUTOFF continue angle getAngle acc getCoords donor getCoords donorh getCoords if angle ANGLE_CUTOFF continue routines write Donor s s tAcceptor s s tdist 2f tAngle 2f n donor residue donor name acc residue acc name dist angle file write Donor s s tAcceptor s s tdist 2f tAngle 2f n donor residue donor name acc residue acc name dist angle routines write n file close
returns the contents of the first line in ` path ` that starts with a digit .,def get_official_milestone path u n Returns the contents of the first line in path that starts with a digit n with open path as fp for line in fp line line strip if line 1 isdigit return line raise Exception u Didn t find a line that starts with a digit
reading moz.build files via filesystem traversal mode with no build config .,def test_filesystem_traversal_no_config self u Reading moz build files via filesystem traversal mode with no build config n n This is similar to the above test except no build config is applied n This will likely fail in more scenarios than the above test because a n lot of moz build files assumes certain variables are present n here os path abspath os path dirname __file__ root os path normpath os path join here u u config EmptyConfig root reader BuildReader config all_paths self _mozbuilds reader paths contexts reader read_relevant_mozbuilds all_paths self assertEqual set paths keys all_paths self assertGreaterEqual len contexts len paths
returns a dictionary of information strings about the device .,def get_info self directive None timeout None info super ADBB2G self get_info directive directive timeout timeout directives memtotal if directive in directives directives directive if memtotal in directives info memtotal self get_memory_total timeout timeout return info
consume a stream of treemetadata instances .,def consume self objs u Consume a stream of TreeMetadata instances n n This is the main method of the interface This is what takes the n frontend output and does something with it n n Child classes are not expected to implement this method Instead the n base class consumes objects and calls methods possibly implemented by n child classes n list_file mozpath join self environment topobjdir u backend s self __class__ __name__ backend_output_list set if os path exists list_file with open list_file as fh backend_output_list update mozpath normsep p for p in fh read splitlines for obj in objs obj_start time time if not self consume_object obj and not isinstance self PartialBackend raise Exception u Unhandled object of type s type obj self _execution_time time time obj_start if isinstance obj ContextDerived and not isinstance self PartialBackend self backend_input_files obj context_all_paths self backend_input_files set iter_modules_in_path self environment topsrcdir self environment topobjdir finished_start time time self consume_finished self _execution_time time time finished_start delete_files backend_output_list self _backend_output_files for path in delete_files full_path mozpath join self environment topobjdir path try with open full_path u r as existing old_content existing read if old_content self file_diffs full_path simple_diff full_path old_content splitlines None except IOError pass try if not self dry_run os unlink full_path self _deleted_count 1 except OSError pass for dir in set mozpath dirname d for d in delete_files try os removedirs dir except OSError pass if self _deleted_count or self _created_count or not os path exists list_file with self _write_file list_file as fh fh write u n join sorted self _backend_output_files else with open list_file u a os utime list_file None with self _write_file u s in list_file as fh fh write u n join sorted mozpath normsep f for f in self backend_input_files
return a generator of full paths to the given command .,def whichgen command path None verbose 0 exts None matches if path is None usingGivenPath 0 path os environ get PATH split os pathsep if sys platform startswith win path insert 0 os curdir else usingGivenPath 1 if sys platform startswith win if exts is None exts os environ get PATHEXT split os pathsep for ext in exts if ext lower exe break else exts COM EXE BAT elif not isinstance exts list raise TypeError exts argument must be a list or None else if exts is not None raise WhichError exts argument is not supported on platform s sys platform exts if os sep in command or os altsep and os altsep in command pass else for i in range len path dirName path i if sys platform startswith win and len dirName 2 and dirName 0 and dirName 1 dirName dirName 1 1 for ext in exts absName os path abspath os path expanduser os path normpath os path join dirName command ext if os path isfile absName if usingGivenPath fromWhere from given path element d i elif not sys platform startswith win fromWhere from PATH element d i elif i 0 fromWhere from current directory else fromWhere from PATH element d i 1 match _cull absName fromWhere matches verbose if match if verbose yield match else yield match 0 match _getRegisteredExecutable command if match is not None match _cull match matches verbose if match if verbose yield match else yield match 0
called for performing the main runtest loop ( after collection finished ) .,hookspec firstresult True def pytest_runtestloop session
-t mochitest - webgl sets talos=[mochitest - webgl ],def test_t_single self u tos TryOptionSyntax u try t mochitest webgl graph_with_jobs self assertEqual sorted tos talos sorted u test u mochitest webgl
test a successful post to the success view,def test_success_success self foia FOIARequestFactory request_factory RequestFactory request request_factory post reverse fine uploader success request id foia pk key file_key request user foia user response views success_request request eq_ response status_code 200 attachment OutboundRequestAttachment objects get foia foia eq_ attachment ffile name file_key eq_ attachment user foia user assert_false attachment sent
enforces a size and filetype limit on uploaded files .,def clean_files self if not self files return files self files getlist files for _file in files content_type _file content_type split 0 if content_type in ALLOWED_CONTENT_TYPES if _file _size MAX_UPLOAD_SIZE raise forms ValidationError This file is too large else raise forms ValidationError Unsupported filetype return files
the text representation of the law should be the name of the law .,def test_unicode self eq_ unicode self law self law name The text representation of the law should match the name of the law
takes two name - parts lists ( as lists of words ) and returns a score .,def compare_names namepartsA namepartsB complement set namepartsA set namepartsB intersection set namepartsA set namepartsB score float len intersection len intersection len complement return score
verify quiz start page loads up .,def test_quiz_page_returns_correct_html self client Client client login username TEST_USER_USERNAME password TEST_USER_PASSWORD response client get en quiz 1 self assertEqual response status_code 200 self assertTrue len response content 1 self assertIn Close Quiz response content self assertIn Begin response content
parse a pddl condition . the condition is translated into nnf on the fly .,def parse_condition_aux alist negated tag alist 0 if tag in and or not imply args alist 1 if tag imply assert len args 2 if tag not assert len args 1 return parse_condition_aux args 0 not negated elif tag in forall exists parameters pddl_types parse_typed_list alist 1 args alist 2 assert len args 1 elif negated return NegatedAtom alist 0 alist 1 else return Atom alist 0 alist 1 if tag imply parts parse_condition_aux args 0 not negated parse_condition_aux args 1 negated tag or else parts parse_condition_aux part negated for part in args if tag and and not negated or tag or and negated return Conjunction parts elif tag or and not negated or tag and and negated return Disjunction parts elif tag forall and not negated or tag exists and negated return UniversalCondition parameters parts elif tag exists and not negated or tag forall and negated return ExistentialCondition parameters parts
parse version string to a versioninfo instance .,def parse_version_info version parts parse version version_info VersionInfo parts major parts minor parts patch parts prerelease parts build return version_info
"pair wise rmsd over all the frames , return a square matrix of pairwise rmsd",def get_pair_rmsd pca_traj sele_grp pair_rmsd np empty pca_traj n_frames pca_traj n_frames for i in range pca_traj n_frames pair_rmsd i md rmsd pca_traj pca_traj i atom_indices sele_grp pair_rmsd pair_rmsd pair_rmsd transpose 2 return pair_rmsd
"compute the integral using gaussian quadrature for n = 20 , 76 or 150 .",def gauss_quad_1d q n 150 z w leggauss n theta THETA_HIGH THETA_LOW z 1 2 THETA_LOW sin_theta abs sin theta Zq kernel_1d q q theta theta return np sum Zq w sin_theta THETA_HIGH THETA_LOW 2
is the array empty or not ?,def __nonzero__ self if self _cache return True else return 0 in self
marks a module level attribute as deprecated . accessing it will emit a pygideprecationwarning warning .,def deprecated_attr namespace attr replacement _deprecated_attrs setdefault namespace append attr replacement
test email removal in the predigest process,def test_predigest_emails self real_longstr DataDigester longstr_ptrn DataDigester longstr_ptrn re compile S 100 emails test example com test123 example com test abc example com test test2 example com test test2 abc example com message Test s Test2 expected TestTest2 try for email in emails self lines DataDigester message email encode utf8 self assertEqual self lines 0 expected finally DataDigester longstr_ptrn real_longstr
represents a notion of time for this scheduler . tasks being scheduled on a scheduler will adhere to the time denoted by this property .,property def now self return self clock
returns an index - suffixed unique name for the given prefix . this is used for auto - generating layer names based on the type - prefix .,def get_unique_name self prefix ident sum t startswith prefix for t _ in self layers items 1 return s_ d prefix ident
constructor @param filename : filename containing config @type filename : parses the content and stores the lines in filecontent,def __init__ self fileName f open fileName r for text in f readlines self filecontent append text
turn a sequence of dictionaries into a dictionary of lists .,def _AggregateDicts dicts result collections defaultdict list for d in dicts for k v in d iteritems result k append v return result
returns true if the code object is empty .,def IsEmpty self return not bool self _code
runs a .jar from the command line with arguments .,def _run_jar self jar args shell_command join self _JAR_COMMAND jar args self _log_debug Running jar s shell_command devnull open os devnull w kwargs stdout devnull stderr subprocess PIPE shell True process subprocess Popen shell_command kwargs _ stderr process communicate return process returncode stderr
links output from inputs using libtool .,def link output inputs p subprocess Popen libtool o output inputs p communicate if p returncode 0 message subprocess libtool returned 0 format p returncode raise SubprocessError message
the object which will be returned from calls to getsysteminfo .,property def returned_system_info self return self _returned_system_info
"> > > from datetime import datetime > > > d = datetime(2000 , 1 , 23 , 7 , 59 , 4 ) > > > _ attribute_lookup(d , ' day ' , 23 ) true > > > _ attribute_lookup(d , ' ctime__lower__exact ' , ' sun jan 23 07:59:04 2000 ' ) true",def _attribute_lookup obj query_string query_value sep SEP operator_collection OperatorCollection attribute_list query_string split sep if hasattr operator_collection attribute_list 1 and callable getattr operator_collection attribute_list 1 operator_name attribute_list pop else operator_name operator_collection default_operator operator getattr operator_collection operator_name value _get_attribute obj attribute_list return operator value query_value
sort read in read_list according to their leftmost position,def sort_read self self read_list sort key lambda x x pos
write a single bit . convenience method for single bit args .,def write_bit self b pack Struct B pack self _output_buffer append pack True if b else False return self
configures celery and and adds tasks to the schedule .,def configure_celery app app config update dict CELERY_BROKER_URL sqla format _database_path app CELERY_RESULT_BACKEND db format _database_path app CELERY_TASK_SERIALIZER json CELERY_ACCEPT_CONTENT json CELERYBEAT_SCHEDULE example_task task tasks example_task schedule timedelta seconds 10 args
path to the python executable in the virtualenv,property def python self return self bin_path python
"method for displaying the dynkin diagram of a given lie algebra . works by generating the cartantype for the input , t , and then returning the dynkin diagram method from the individual classes .",def DynkinDiagram t return CartanType t dynkin_diagram
"distance from line to point line is a tuple of coefficients a , b , c",def line2d_dist l p a b c l x0 y0 p return abs a x0 b y0 c np sqrt a 2 b 2
check that the final shape is just the input shape .,def test_same_input_shapes data 1 3 0 1 0 3 1 0 3 0 1 3 3 1 3 3 for shape in data input_shapes shape assert_shapes_correct input_shapes shape input_shapes2 shape shape assert_shapes_correct input_shapes2 shape input_shapes3 shape shape shape assert_shapes_correct input_shapes3 shape
this is called when the `` kernel_died `` signal is emitted .,def _handle_kernel_died self since_last_heartbeat
"draws a marker at each of the vertices in path . this includes all vertices , including control points on curves . to avoid that behavior , those vertices should be removed before calling this function .",def draw_markers self renderer gc marker_path marker_trans path trans rgbFace None for vertices codes in path iter_segments trans simplify False if len vertices x y vertices 2 self draw_path renderer gc marker_path marker_trans transforms Affine2D translate x y rgbFace
make a new function from a given template and update the signature,def make self src_templ evaldict None addsource False attrs src src_templ vars self evaldict evaldict or mo DEF match src if mo is None raise SyntaxError not a valid function template n s src name mo group 1 names set name arg strip for arg in self shortsignature split for n in names if n in _func_ _call_ raise NameError s is overridden in n s n src if not src endswith n src n try code compile src string single exec code in evaldict except print Error in generated code file sys stderr print src file sys stderr raise func evaldict name if addsource attrs __source__ src self update func attrs return func
add the cwd to the sys.path ( $ pythonpath ),def init_syspath self sys path insert 0 os getcwd
return weights for an np - point central derivative .,def central_diff_weights Np ndiv 1 if Np ndiv 1 raise ValueError Number of points must be at least the derivative order 1 if Np 2 0 raise ValueError The number of points must be odd from scipy import linalg ho Np 1 x arange ho ho 1 0 x x newaxis X x 0 0 for k in range 1 Np X hstack X x k w product arange 1 ndiv 1 axis 0 linalg inv X ndiv return w
packet format --------------------------------------------------- | packet type ( 8b ) | data length ( 8b ) | --------------------------------------------------- | data | ---------------------------------------------------,def SendPacket sock pkg_type data buf pickle dumps data packetheader struct pack ll pkg_type len buf sock sendall packetheader sock sendall buf
called if ltm was empty ( had no nodes ) .,def InitializeSeqseeLTM ltm logging info Initializing Seqsee LTM from farg apps seqsee sobject import SElement elements SElement magnitude for magnitude in range 1 11 for element in elements ltm GetNode content element for idx element in enumerate elements 1 ltm AddEdge element elements idx 1 ltm AddEdge elements idx 1 element from farg apps seqsee categories import Prime Squares TriangularNumbers for prime_number in Prime number_list 10 ltm AddEdge SElement prime_number Prime edge_type_set LTMEdge LTM_EDGE_TYPE_ISA for square in Squares number_list 10 ltm AddEdge SElement square Squares edge_type_set LTMEdge LTM_EDGE_TYPE_ISA for triangular in TriangularNumbers number_list 10 ltm AddEdge SElement triangular TriangularNumbers edge_type_set LTMEdge LTM_EDGE_TYPE_ISA
group expressions together with `` inbetweens `` and with the output of a `` final_functions `` .,def Group expressions final_function inbetweens name u u Group expressions together with inbetweens and with the output of a final_functions n lengths functions regex u i 0 for expression in expressions regex inbetweens i regex u expression regex u lengths append sum expression group_lengths functions append expression run i 1 regex inbetweens i return Expression regex functions lengths final_function name
establish that a job template can be created and extra varas passed to it,def test_create_w_extra_vars self with client test_mode as t endpoint job_templates t register_json endpoint count 0 results next None previous None method GET t register_json endpoint changed True id 42 method POST self res create name bar job_type run inventory 1 project 1 playbook foobar yml credential 1 extra_vars foo bar self assertEqual t requests 0 method GET self assertEqual t requests 1 method POST self assertEqual len t requests 2
"runs checkdeps on # include statements added in this change . breaking - rules is an error , breaking ! rules is a warning .",def _CheckUnwantedDependencies input_api output_api original_sys_path sys path try sys path sys path input_api os_path join input_api PresubmitLocalPath buildtools checkdeps import checkdeps from cpp_checker import CppChecker from rules import Rule finally sys path original_sys_path added_includes for f in input_api AffectedFiles if not CppChecker IsCppFile f LocalPath continue changed_lines line for line_num line in f ChangedContents added_includes append f LocalPath changed_lines deps_checker checkdeps DepsChecker input_api PresubmitLocalPath error_descriptions warning_descriptions for path rule_type rule_description in deps_checker CheckAddedCppIncludes added_includes description_with_path s n s path rule_description if rule_type Rule DISALLOW error_descriptions append description_with_path else warning_descriptions append description_with_path results if error_descriptions results append output_api PresubmitError You added one or more includes that violate checkdeps rules error_descriptions if warning_descriptions results append output_api PresubmitPromptOrNotify You added one or more includes of files that are temporarily allowed but being removed Can you avoid introducing the include See relevant DEPS file s for details and contacts warning_descriptions return results
initialize a ` linearoperatorfullmatrix ` .,def __init__ self matrix is_non_singular None is_self_adjoint None is_positive_definite None is_square None name LinearOperatorFullMatrix Initialize a LinearOperatorFullMatrix Args matrix Shape B1 Bb M N with b 0 M N 0 Allowed dtypes float16 float32 float64 complex64 complex128 is_non_singular Expect that this operator is non singular is_self_adjoint Expect that this operator is equal to its hermitian transpose is_positive_definite Expect that this operator is positive definite meaning the quadratic form x H A x has positive real part for all nonzero x Note that we do not require the operator to be self adjoint to be positive definite See https en wikipedia org wiki Positive definite_matrix Extension_for_non_symmetric_matrices is_square Expect that this operator acts like square batch matrices name A name for this LinearOperator Raises TypeError If diag dtype is not an allowed type with ops name_scope name values matrix self _matrix ops convert_to_tensor matrix name matrix self _check_matrix self _matrix super LinearOperatorFullMatrix self __init__ dtype self _matrix dtype graph_parents self _matrix is_non_singular is_non_singular is_self_adjoint is_self_adjoint is_positive_definite is_positive_definite is_square is_square name name
"get if a user is admin , by his username",def get_admin_blocked_by_username self username return self build_query_on_the_fly select admin blocked query GRAPH self get_param askomics users_graph URIusername rdf type foaf Person t URIusername foaf name username n t URIusername isadmin admin n t URIusername isblocked blocked True
returns a list of vonodes representing rows of the table . use getdata ( ) to extract data from each row . for x in getdatarows ( ): data = getdata ( x ) # data = [ values ... ],def getDataRows self tableData self root VOTABLE RESOURCE TABLE DATA BINARY STREAM return tableData _nodeList
`` pushed ( ) `` select changesets in any remote repository according to remotebranches .,def pushed repo subset x args revset getargs x 0 0 pushed takes no arguments return upstream_revs lambda x True repo subset x
tells how many event types are registered on this registry,def count self return len self registered_types
"return a string representing the bytes in src , length bytes per line .",def hexdump src length 8 if len src 0 return result digits 4 if isinstance src unicode else 2 for i in xrange 0 len src length s src i i length hexa join 04x x for x in list s text join chr x if 32 x 127 else for x in s result append 04X s s i length 5 hexa text return n join result
connects to the harmony and syncs it .,def power_off args client get_client args client power_off client disconnect send_close True return 0
score diffs in alignment based on which reference they correspond to,def score_alignment_differences query references alignment A B references votes for i in alignment differences if i alignment start or i alignment end continue query_base alignment query name i A_base alignment A name i B_base alignment B name i if query_base A_base and query_base B_base votes i A elif query_base A_base and query_base B_base votes i B else votes i Abstain return votes
this is the base configuration . all default configuration values belong here . these values may be overridden by other configurations . : type conf : configuration,def configure_defaults self conf root_directory dirname dirname dirname dirname realpath __file__ conf set secret None conf set root_directory root_directory conf set main_executable_path self _main_exec_path conf set version autoversioning get_version static_configured_base_directory join var lib clusterrunner if isdir static_configured_base_directory base_directory static_configured_base_directory else base_directory join expanduser clusterrunner conf set base_directory base_directory conf set config_file join base_directory clusterrunner conf conf set master_pid_file join base_directory clusterrunner_master pid conf set slave_pid_file join base_directory clusterrunner_slave pid conf set build_symlink_directory join tmp clusterrunner_build_symlinks conf set repo_directory None conf set project_yaml_filename clusterrunner yaml conf set log_file None conf set log_level DEBUG conf set max_log_file_size 1024 1024 50 conf set max_log_file_backups 5 conf set log_filename clusterrunner_default log conf set eventlog_filename eventlog_default log conf set eventlog_file None conf set max_eventlog_file_size 1024 1024 50 conf set max_eventlog_file_backups 5 conf set hostname platform node conf set master_hostname localhost conf set master_port 43000 conf set slaves localhost conf set default_http_timeout 30 conf set git_strict_host_key_checking False conf set cors_allowed_origins_regex None bin_dir join base_directory bin conf set git_askpass_exe join bin_dir git_askpass sh conf set git_ssh_exe join bin_dir git_ssh sh conf set get_project_from_master True conf set shallow_clones False conf set protocol_scheme http conf set https_cert_file None conf set https_key_file None conf set pagination_offset 0 conf set pagination_limit 20 conf set pagination_max_limit 200
returns a dictionary from the parsed tokens,classmethod def parse_action cls tokens return type ValueType function name tokens 0 args tokens 1
up - to - the - second unread counts for each active feed . poll for these counts no more than once a minute .,request reader refresh_feeds def refresh_feeds self return
"take the logic from the change hook , and then delegate it to the proper handler",defer inlineCallbacks def getChanges self request uriRE re search change_hook a zA Z0 9_ bytes2NativeString request uri if not uriRE log msg URI doesn t match change_hook regex s request uri raise ValueError URI doesn t match change_hook regex s request uri changes src None if uriRE group 1 dialect uriRE group 1 else dialect base handler self makeHandler dialect changes src yield handler getChanges request defer returnValue changes src
detects labels given a gcs path .,def main path video_client video_intelligence_service_client VideoIntelligenceServiceClient features enums Feature LABEL_DETECTION video_context video_intelligence_pb2 VideoContext video_context stationary_camera True video_context label_detection_mode video_intelligence_pb2 FRAME_MODE operation video_client annotate_video path features video_context video_context print nProcessing video for label annotations while not operation done sys stdout write sys stdout flush time sleep 10 print nFinished processing results operation result annotation_results 0 return results
example taken from quick start example,def testExampleTwo self argString m VMStatusLogger k s 0 5 v f 4 v s 7 12 v r aPattern l k 0 min 1 max 2 av 1 tot samples System log options buildOptions m VMStatusLogger k s 0 5 v f 4 v s 7 12 v r aPattern l k 0 min 1 max 2 av 1 tot samples System log self assertEquals options isCsv False self assertEquals options headerLine None self assertEquals options lineMatcher regex pattern VMStatusLogger self assertEquals len options fieldExtractors 3 self _checkValueExtractor options fieldExtractors 0 None None 4 self _checkValueExtractor options fieldExtractors 1 7 12 self _checkValueExtractor options fieldExtractors 2 None None None aPattern self _checkValueExtractor options keyExtractor 0 5 self assertEquals len options outputColumnExtractor fields 5 self _checkOutputColumnExtractor options 0 None None self _checkOutputColumnExtractor options 1 0 min self _checkOutputColumnExtractor options 2 1 max self _checkOutputColumnExtractor options 3 2 av self _checkOutputColumnExtractor options 4 1 tot
run the genetic algorithm several times each vector containing the scores at each generation .,def run self maxtime 100 if self _computed True print Data already computed set computed to False to force the run error 0 for i in range 0 self N print Running simulation s i self b run stallgenmax self stallgenmax popsize self popsize maxtime maxtime pmutation self pmutation maxgens self maxgens 1 elitism self elitism verbose False show False writeall False res self b T1opt results Best_score self current_best_bitstring self b T1opt results Best_bitString 1 self current_best_bitstring int x for x in self current_best_bitstring split if i 0 average numpy array res else try average numpy array res except print Simulation returns a vector of different length Maybe maxtime is not large enough error 1 self best_scores append min res self allresults append res self best_bitstrings append self current_best_bitstring self ydata average float self N error self _computed True if len self ydata len self xdata raise ValueError ydata length does not match xdata length You may change xdata accordingly or rerun with a larger maxtime parameter
load all datamodels under * directory * into * module*.,def load_data_models from_dir target_module loader IndivoDataModelLoader from_dir loader import_data_models target_module
initializes the information required for naive bayes .,def __init__ self legalLabels self legalLabels legalLabels self k 1 self automaticTuning False self probLabel util Counter self probFeature util Counter self features None
"get a value for obj.name from the user . then call after(caller ) if it is not none . if the user input can not be converted , and invalid_input is not none , call invalid_input(caller ) . of course caller.exception will be set to the exception which was thrown .",def set_value obj name caller after None invalid_input None con caller connection column obj __table__ c name current getattr obj name def inner caller Do the actual setting try value func caller text except Exception as e caller exception e if invalid_input is not None return invalid_input caller else raise e set_object_value obj name value after caller def set_foreign_key_value item caller Set a foreign key value set_object_value obj name item id after caller def build_boolean_item menu value Build an item in a boolean menu friendlies None Clear True Enable False Disable menu item s s if value is current else friendlies value partial set_object_value obj name value after if isinstance column type Boolean m Menu restore_parser parser for x in True False build_boolean_item m x if column nullable build_boolean_item m None send m elif column name in foreign_keys_menus send foreign_keys_menus column name set_foreign_key_value restore_parser parser else for cls func in types_map items if isinstance column type cls break else raise RuntimeError No idea how to convert r column send Reader inner restore_parser parser con notify send
"make a list of all the nested leaf subdirectories of "" dir_path "" .",def _listNestedLeafDir dir_path return _listSpecificNestedDir dir_path hasNoSubDir
"run the command to download target . if the command fails , clean up before re - raising the error .",def _clean_check cmd target try subprocess check_call cmd except subprocess CalledProcessError if os access target os F_OK os unlink target raise
this bear is meant for debugging purposes relating to clang . it just prints out the whole ast for a file to the debug channel .,def run self for filename file in sorted self file_dict items root Index create parse filename options TranslationUnit PARSE_DETAILED_PROCESSING_RECORD cursor self print_node root filename
"for each library call , print all poxix calls invoked",def lib_call_stats trace_graph settings threashold settings LIB_CALL_THREASHOLD for lib_call metadata in stats lib_calls trace_graph total sum map lambda x x 1 metadata items for posix_call in sorted metadata key metadata get reverse True if metadata posix_call threashold print Lib call s invoked POSIX call s 2f of times d lib_call posix_call 100 metadata posix_call total metadata posix_call
embed the network in the plane .,def network_embed_in_plane network fix None straightline True try import networkx as nx except ImportError print NetworkX is not installed Get NetworkX at https networkx github io raise x network get_vertices_attribute x y network get_vertices_attribute y xmin xmax min x max x ymin ymax min y max y xspan xmax xmin yspan ymax ymin edges u v for u v in network edges if not network is_vertex_leaf u and not network is_vertex_leaf v is_embedded False count 100 while count graph nx Graph edges pos nx spring_layout graph 2 iterations 100 scale max xspan yspan if not _network_are_edges_crossed edges pos is_embedded True break count 1 if not is_embedded return False if fix a b fix p0 network vertex_coordinates a xy p1 network vertex_coordinates b xy p2 pos b vec0 network vertex b axis network vertex a axis for axis in xy vec1 pos b axis pos a axis for axis in 0 1 a angle_vectors_xy vec0 vec1 if is_ccw_xy p0 p1 p2 a 2 pi a cosa cos a sina sin a for key in pos x y pos key pos key 0 cosa x sina y pos key 1 sina x cosa y l0 vec0 0 2 vec0 1 2 0 5 l1 vec1 0 2 vec1 1 2 0 5 scale l0 l1 for key in pos pos key 0 scale pos key 1 scale t network vertex fix 0 x pos fix 0 0 network vertex fix 0 y pos fix 0 1 for key in pos pos key 0 t 0 pos key 1 t 1 for key in network vertices if key in pos network vertex key x pos key 0 network vertex key y pos key 1 return True
try to seek really far .,def test_bigframes self rawname join TEST_DATA_DIR test wav a Sndfile rawname r try try a seek 2 60 raise Exception Seek really succeded This should not happen except IOError as e pass finally a close
compute matrix product a * b.t using efficient blas routines ( low - level machine code ),def dotABT A B if B shape 0 A shape 0 return fblas dgemm 1 0 A B trans_b True else return np dot A B T
calculate document - specific quantities ( e - step ) alternate updates to two terms until convergence ( 1 ) approx posterior on topic - token assignment q(word_variational | word_token_variables ) ( 2 ) approx posterior on doc - topic probabilities q(doc_variational | document_topic_variables ),def forloop_local_params self Data LP nCoordAscentItersLP 20 convThrLP 0 01 kwargs if alphaPi not in LP LP alphaPi np ones Data nDoc self K 1 else assert LP alphaPi shape 1 self K 1 LP DocTopicCount np zeros Data nDoc self K LP E_logPi digamma LP alphaPi digamma np sum LP alphaPi axis 1 np newaxis expEloglik LP E_logsoftev_WordsData expEloglik expEloglik max axis 1 np newaxis np exp expEloglik out expEloglik LP word_variational expEloglik for d in xrange Data nDoc start stop Data doc_range d expEloglik_d expEloglik start stop old_alphaPi LP alphaPi d copy for ii in xrange nCoordAscentItersLP expElogpi_d np exp LP E_logPi d 1 rSum_d np dot expEloglik_d expElogpi_d LP DocTopicCount d np dot expEloglik_d T Data word_count start stop rSum_d LP DocTopicCount d expElogpi_d LP alphaPi d self gamma self Ebeta LP alphaPi d 1 LP DocTopicCount d LP E_logPi d digamma LP alphaPi d digamma np sum LP alphaPi d if np max np abs old_alphaPi LP alphaPi d convThrLP break old_alphaPi LP alphaPi d LP word_variational start stop expElogpi_d LP word_variational start stop rSum_d np newaxis del LP E_logsoftev_WordsData return LP
"this method asks the environment to return a frame - structure of perceptual data , and is called each step . it prints the sensory frame to the terminal .",def sense self self sensorysystem perceptions self env do sense agent self name print result of sense self env do sense agent self name if self debug print Perceiving for modality data in self sensorysystem perceptions items print t s s modality data
seed a git repository ( and create if necessary ) [ remote ],def git_seed repo_path commit None ignore_untracked_files False use_sudo False submodules False dirty_working_copy git_is_dirty ignore_untracked_files if dirty_working_copy abort Working copy is dirty This check can be overridden by importing gitric api allow_dirty and adding allow_dirty to your call git_init repo_path use_sudo use_sudo commit commit or git_head_rev puts green Pushing commit commit with settings warn_only True force gitric_force_push in env and f or push local git push git ssh s s s s s refs heads master s env user env host env port repo_path commit force if push failed abort s is a non fast forward push The seed will abort so you don t lose information If you are doing this intentionally import gitric api force_push and add it to your call commit if submodules git_seed_submodules repo_path commit ignore_untracked_files use_sudo
place each atom into cells . o(n ) runtime .,def put_atoms_in_cells coords x_bins y_bins z_bins u Place each atom into cells O N runtime n n Parameters n n coords np ndarray n N 3 array where N is number of atoms n x_bins list n List of cell_start cell_end for x coordinate n y_bins list n List of cell_start cell_end for y coordinate n z_bins list n List of cell_start cell_end for z coordinate n n Returns n n cell_to_atoms dict n Dict elements contain atom indices for cell n atom_to_cell dict n Dict elements contain cell indices for atom n n N coords shape 0 cell_to_atoms atom_to_cell for x_ind in range len x_bins for y_ind in range len y_bins for z_ind in range len z_bins cell_to_atoms x_ind y_ind z_ind for atom in range N x_coord y_coord z_coord coords atom x_ind y_ind z_ind None None None for ind x_cell_min x_cell_max in enumerate x_bins if x_coord x_cell_min and x_coord x_cell_max x_ind ind break if x_ind is None raise ValueError u No x cell found for ind y_cell_min y_cell_max in enumerate y_bins if y_coord y_cell_min and y_coord y_cell_max y_ind ind break if y_ind is None raise ValueError u No y cell found for ind z_cell_min z_cell_max in enumerate z_bins if z_coord z_cell_min and z_coord z_cell_max z_ind ind break if z_ind is None raise ValueError u No z cell found cell_to_atoms x_ind y_ind z_ind append atom atom_to_cell atom x_ind y_ind z_ind return cell_to_atoms atom_to_cell
"starts main.java in the same folder and converts it into a query tree , then into a nested list",def jena_graph java_file args graph cmd java cp os environ get CLASSPATH java_file args proc Popen cmd stdout PIPE stderr PIPE stdout stderr proc communicate for line in stdout graph line try res_graph pp nestedExpr opener closer parseString graph res_graph res_graph asList except print pyparse err sys exc_info 0 graph res_graph 1 return res_graph
training function for detection models .,def train create_tensor_dict_fn create_model_fn train_config master task num_clones worker_replicas clone_on_cpu ps_tasks worker_job_name is_chief train_dir detection_model create_model_fn data_augmentation_options preprocessor_builder build step for step in train_config data_augmentation_options with tf Graph as_default deploy_config model_deploy DeploymentConfig num_clones num_clones clone_on_cpu clone_on_cpu replica_id task num_replicas worker_replicas num_ps_tasks ps_tasks worker_job_name worker_job_name with tf device deploy_config variables_device global_step slim create_global_step with tf device deploy_config inputs_device input_queue create_input_queue train_config batch_size num_clones create_tensor_dict_fn train_config batch_queue_capacity train_config num_batch_queue_threads train_config prefetch_queue_capacity data_augmentation_options summaries set tf get_collection tf GraphKeys SUMMARIES global_summaries set model_fn functools partial _create_losses create_model_fn create_model_fn train_config train_config clones model_deploy create_clones deploy_config model_fn input_queue first_clone_scope clones 0 scope update_ops tf get_collection tf GraphKeys UPDATE_OPS first_clone_scope with tf device deploy_config optimizer_device training_optimizer optimizer_builder build train_config optimizer global_summaries sync_optimizer None if train_config sync_replicas training_optimizer tf SyncReplicasOptimizer training_optimizer replicas_to_aggregate train_config replicas_to_aggregate total_num_replicas train_config worker_replicas sync_optimizer training_optimizer init_fn None if train_config fine_tune_checkpoint var_map detection_model restore_map from_detection_checkpoint train_config from_detection_checkpoint available_var_map variables_helper get_variables_available_in_checkpoint var_map train_config fine_tune_checkpoint init_saver tf train Saver available_var_map def initializer_fn sess init_saver restore sess train_config fine_tune_checkpoint init_fn initializer_fn with tf device deploy_config optimizer_device total_loss grads_and_vars model_deploy optimize_clones clones training_optimizer regularization_losses None total_loss tf check_numerics total_loss LossTensor is inf or nan if train_config bias_grad_multiplier biases_regex_list biases grads_and_vars variables_helper multiply_gradients_matching_regex grads_and_vars biases_regex_list multiplier train_config bias_grad_multiplier if train_config freeze_variables grads_and_vars variables_helper freeze_gradients_matching_regex grads_and_vars train_config freeze_variables if train_config gradient_clipping_by_norm 0 with tf name_scope clip_grads grads_and_vars slim learning clip_gradient_norms grads_and_vars train_config gradient_clipping_by_norm grad_updates training_optimizer apply_gradients grads_and_vars global_step global_step update_ops append grad_updates update_op tf group update_ops with tf control_dependencies update_op train_tensor tf identity total_loss name train_op for model_var in slim get_model_variables global_summaries add tf summary histogram model_var op name model_var for loss_tensor in tf losses get_losses global_summaries add tf summary scalar loss_tensor op name loss_tensor global_summaries add tf summary scalar TotalLoss tf losses get_total_loss summaries set tf get_collection tf GraphKeys SUMMARIES first_clone_scope summaries global_summaries summary_op tf summary merge list summaries name summary_op session_config tf ConfigProto allow_soft_placement True log_device_placement False keep_checkpoint_every_n_hours train_config keep_checkpoint_every_n_hours saver tf train Saver keep_checkpoint_every_n_hours keep_checkpoint_every_n_hours slim learning train train_tensor logdir train_dir master master is_chief is_chief session_config session_config startup_delay_steps train_config startup_delay_steps init_fn init_fn summary_op summary_op number_of_steps train_config num_steps if train_config num_steps else None save_summaries_secs 120 sync_optimizer sync_optimizer saver saver
handle socks5 request according to rfc192 .,def handle self try try ver recvall self conn 1 0 if ver 5 raise IOError Invalid socks version i ver nmethods recvall self conn 1 0 methods bytearray recvall self conn nmethods method None if 2 in methods and self serv conf auth method 2 elif 0 in methods and self serv conf unauth method 0 if method is None raise IOError No supported authentication method was offered self conn sendall bytearray 5 method username None password None if method 2 ver recvall self conn 1 0 if ver 1 raise IOError Invalid auth packet version i ver ulen recvall self conn 1 0 username str recvall self conn ulen plen recvall self conn 1 0 password str recvall self conn plen self conn sendall bytearray 1 0 ver cmd _ atyp recvall self conn 4 if ver 5 raise IOError Invalid socks version i in connect request ver if cmd Command CONNECT raise IOError Unhandled command i in connect request cmd if atyp AddressType IPV4 addr recvall self conn 4 elif atyp AddressType DOMAINNAME n recvall self conn 1 0 addr recvall self conn n elif atyp AddressType IPV6 addr recvall self conn 16 else raise IOError Unknown address type i atyp port_hi port_lo recvall self conn 2 port port_hi 8 port_lo self conn sendall bytearray 5 0 0 1 0 0 0 0 0 0 cmdin Socks5Command cmd atyp addr port username password self serv queue put cmdin logger info Proxy s cmdin except Exception as e logger exception socks5 request handling failed self serv queue put e finally self conn close
log a message if the level is high enough,def log self msg level INFO if level self verbose_level print msg
converts a name lex token into a name parse node .,def parse_name parser token expect parser TokenKind NAME return ast Name value token value loc loc parser token start
"returns price as a decimal else none . first checks the product , if none , then checks the parent .",def get_product_quantity_price product qty Decimal 1 delta Decimal 0 00 parent None adjustments get_product_quantity_adjustments product qty qty parent parent return adjustments final_price delta
ensure we have a valid cart and order .,def sanity_check self try self order Order objects from_request self request except Order DoesNotExist url urlresolvers reverse satchmo_checkout step1 self invalidate HttpResponseRedirect url return False try self cart Cart objects from_request self request if self cart numItems 0 and not self order is_partially_paid template self lookup_template EMPTY_CART self invalidate render_to_response template context_instance RequestContext self request return False except Cart DoesNotExist template self lookup_template EMPTY_CART self invalidate render_to_response template context_instance RequestContext self request return False if not self order validate self request context RequestContext self request message _ Your order is no longer valid self invalidate render_to_response self templates 404 context_instance context self valid True signals confirm_sanity_check send self controller self return True
fixture to return a dummy classifier .,def create_dummy_classifier mxlen None mxwlen None zero_alloc None m model Classifier m classify MagicMock name classify_method m classify return_value CLASS_RESPONSE if mxlen m mxlen mxlen if mxwlen m mxwlen mxwlen if zero_alloc m zero_alloc zero_alloc return m
gets all events for a requested year and renders them on a page .,def index_from_year request year events Event get_grouped_by_date_and_year year return paginated_events_index request events
get error message for invalid coupon,def get_error_message_for_invalid_coupon self return self q css alertinner wicon text 0
a fragment of article data can be recorded against an article,def test_add_fragment self self assertEqual models ArticleFragment objects count 1 fragment title pants party fragobj created updated logic add self msid foo fragment self assertEqual models ArticleFragment objects count 2 self assertEqual fragment fragobj fragment
"> > > cdw = codropwhile(printer_sink(""%s "" ) , lambda x : x ) > > > cdw.send([0 , 1 , 2 ] ) > > > cdw.send(1 ) > > > cdw.send(true ) > > > cdw.send(false ) > > > cdw.send([0 , 1 , 2 ] ) [ 0 , 1 , 2 ] > > > cdw.send(1 ) 1 > > > cdw.send(true ) true",autostart def codropwhile target pred while True item yield if not pred item break while True item yield target send item
event handler ( subscriber ) to take care of unpublishing a survey from the client .,grok subscribe ISurvey ISurveyUnpublishEvent def handleSurveyUnpublish survey event surveygroup aq_parent survey sector aq_parent surveygroup country aq_parent sector pas getToolByName survey acl_users clientuser pas getUserById client sm getSecurityManager try newSecurityManager None clientuser client getPortal survey client try clientcountry client country id clientsector clientcountry sector id clientsector surveygroup id except KeyError log info Trying to unpublish unpublished survey s join survey getPhysicalPath return clientsector manage_delObjects surveygroup id if not clientsector keys clientcountry manage_delObjects clientsector id finally setSecurityManager sm
get the ipv4 address assigned to an interface .,def address interface with settings hide running stdout if is_file sbin ifconfig res sudo sbin ifconfig interface s grep inet locals else res run sbin ip a show interface s grep inet locals if interface lo and interface if addr in res if sudo in res res map lambda line line split addr 1 res splitlines 1 res map lambda line line split res return res 0 else return res split 1 split 1 else return res split 1
make the engine functions for each specific field by passing in the appropriate kernel .,def engine_factory kernel numba jit nopython True def engine lon sinlat coslat radius bounds density ratio stack lonc sinlatc coslatc rc result error_code 0 for l in range result size for i in range 6 stack 0 i bounds i stktop 0 while stktop 0 w e s n top bottom stack stktop stktop 1 distance Llon Llat Lr distance_size lon l coslat l sinlat l radius l w e s n top bottom nlon nlat nr new_cells err divisions distance Llon Llat Lr ratio error_code err if new_cells 1 if new_cells stktop 1 stack shape 0 raise OverflowError stktop split w e s n top bottom nlon nlat nr stack stktop else scale scale_nodes w e s n top bottom nodes lonc sinlatc coslatc rc result l density scale kernel lon l coslat l sinlat l radius l lonc sinlatc coslatc rc return error_code return engine
"attempt to carve a class definition name and timestamp from raw bytes . this does not require the entire class definition object buffer , but probably closer to 100 bytes worth .",def carve_class_name buf offset headerbuf buf offset header cim objects ClassDefinitionHeader header vsParse headerbuf offset len header qlbuf buf offset qualifiers_list cim objects QualifiersList qualifiers_list vsParse qlbuf offset len qualifiers_list prbuf buf offset property_references cim objects PropertyReferenceList property_references vsParse prbuf offset len property_references offset header property_default_values_length offset 4 s cim objects WMIString s vsParse buf offset offset return CarvedClass s s header timestamp
( property ) returns the fold enrichment at the xl - mhg cutoff .,property def fold_enrichment self u return self k self K self cutoff float self N
creates the form with a single face and multiple names,def create_form player names form NameForm randomusers currentcorrect random_user player usednames names player player currentRandomUsers randomusers player currentCorrectUser currentcorrect player first_attempt True player save create_form_choices player form return form
create model map by looping over all bins of the counts map and all models in the model container .,def modmap obs models phi 0 theta 0 filename modmap fits for bin in obs events irf 0 0 for model in models irf model eval bin obs bin size bin counts irf obs save filename True return
returns a list of ast nodes that are headings,def get_section_headings self ast_node None if ast_node is None ast_node self data return n for n in ast_node children if self is_heading n
get an anchors dict from a glyph construction dict ( accents ) .,def get_anchors_dict accents_dict anchors_dict for accented_glyph in accents_dict keys base accents accents_dict accented_glyph if not anchors_dict has_key base anchors_dict base for accent in accents anchor_name accent 1 if anchor_name not in anchors_dict base anchors_dict base append anchor_name return anchors_dict
check whether ver is greater or equal to min_ver,memoize def check_version min_ver ver u Check whether ver is greater or equal to min_ver n min_ver_list version_to_list min_ver ver_list version_to_list ver return min_ver_list ver_list
return the database of selective search regions of interest . ground - truth rois are also included .,def selective_search_roidb self cache_file os path join self cache_path self name _selective_search_roidb pkl if os path exists cache_file with open cache_file rb as fid roidb cPickle load fid print ss roidb loaded from format self name cache_file return roidb gt_roidb self gt_roidb ss_roidb self _load_selective_search_roidb gt_roidb roidb self _merge_roidbs gt_roidb ss_roidb with open cache_file wb as fid cPickle dump roidb fid cPickle HIGHEST_PROTOCOL print wrote ss roidb to format cache_file return roidb
create random bits using random ( ) rather than randint ( ) . the latter changed for python 3.2 .,def random_bit return random random 0 5
get the generator object for this flow graph .,def get_generator self platform self get_flow_graph get_parent return platform Generator self get_flow_graph self get_file_path
| 11 | 10 | ------- | 01 | 00,def sd_psk_4_0x1_0_1 x Es 1 x_re x real x_im x imag dist Es numpy sqrt 2 return dist x_im dist x_re
calls setup on all extensions .,def setup_extensions self for ext in self extensions ext setup self model self dataset self algorithm
returns an instance of the form to be used in this view .,def get_form self form_class return form_class self get_form_kwargs
formats the time to ensure compatibility with netscape 's cookie standard .,def cookie_date epoch_seconds None u n Formats the time to ensure compatibility with Netscape s cookie standard n n Accepts a floating point number expressed in seconds since the epoch in n UTC such as that outputted by time time If set to None defaults to n the current time n n Outputs a string in the format Wdy DD Mon YYYY HH MM SS GMT n rfcdate formatdate epoch_seconds return u s s s GMT rfcdate 7 rfcdate 8 11 rfcdate 12 25
return user unique i d provided by service . for google user email is unique enought to flag a single user . email comes from schema : http://axschema.org/contact/email,def get_user_id self details response return details email
sends a heartbeat to the fleetspeak client .,def Heartbeat self heartbeat_msg common_pb2 Message message_type Heartbeat destination common_pb2 Address service_name system self _SendImpl heartbeat_msg
creates a model which uses a stack of lstms to represent the video .,def create_model self model_input vocab_size num_frames unused_params lstm_size FLAGS lstm_cells number_of_layers FLAGS lstm_layers stacked_lstm tf contrib rnn MultiRNNCell tf contrib rnn BasicLSTMCell lstm_size forget_bias 1 0 for _ in range number_of_layers loss 0 0 outputs state tf nn dynamic_rnn stacked_lstm model_input sequence_length num_frames dtype tf float32 aggregated_model getattr video_level_models FLAGS video_level_classifier_model return aggregated_model create_model model_input state 1 h vocab_size vocab_size unused_params
send requests to other modules .,def send_request self request if request lumdist return self _value
"ensures that , if a set of variants have different samples , the reparsed collection will not output any samples .",def test_different_samples_produce_no_samples _ reparsed_variants _do_roundtrip_test different samples 1 vcf different samples 2 vcf metadata _merge_metadata_naive reparsed_variants assert all d get sample_info is None for d in metadata values
"write a message to the message window . if the message is blank , append a new line .",def write_message self message message_class try fmt self _message_format message_class except KeyError fmt if message self insertHtml self _line_template format fmt message self insertPlainText n self verticalScrollBar setValue self verticalScrollBar maximum self update
convert the complex output from pyfftw to the real output expected from : func:`scipy.fftpack.rfft ` .,def _complex_to_rfft_output complex_output output_shape axis rfft_output numpy empty output_shape dtype complex_output real dtype source_slicer slice None complex_output ndim target_slicer slice None complex_output ndim source_slicer axis slice 0 1 target_slicer axis slice 0 1 rfft_output target_slicer complex_output source_slicer real source_slicer axis slice 1 None target_slicer axis slice 1 None 2 rfft_output target_slicer complex_output source_slicer real if output_shape axis 2 0 end_val 1 else end_val None source_slicer axis slice 1 end_val None target_slicer axis slice 2 None 2 rfft_output target_slicer complex_output source_slicer imag return rfft_output
: param : dummy_files_dir : directory to dummy files,def __init__ self dummy_files_dir None if dummy_files_dir is None import pkg_resources dummy_files_dir pkg_resources resource_filename droidbot resources dummy_documents self dummy_files_dir dummy_files_dir self env_type dummy_files
override https_open ( ) in the httpshandler class .,def https_open self req return self do_open self _get_connection req
return a df of the available datasets with description,def __datasets_desc datasets __get_data_folder_path datasets csv df pd read_csv datasets df df Item Title df columns dataset_id title return df
shows a dialog to remove user from friends .,def remove_from_friends self self _call ActivateGameOverlayToUser self _ihandle friendremove self user_id
draws three boxes arond the returned location .,def draw_boxes self input_data bboxmin bboxmax opencv cvRectangle self input_data opencv cvPoint np int bboxmin 0 np int bboxmin 1 opencv cvPoint np int bboxmax 0 np int bboxmax 1 0 1 opencv cvRectangle self input_data opencv cvPoint np int bboxmin 0 1 np int bboxmin 1 1 opencv cvPoint np int bboxmax 0 1 np int bboxmax 1 1 0 1 opencv cvRectangle self input_data opencv cvPoint np int bboxmin 0 2 np int bboxmin 1 2 opencv cvPoint np int bboxmax 0 2 np int bboxmax 1 2 1 1
same as path.name but with one file extension stripped off . example : path('/home / guido / python.tar.gz').stem = > path('python.tar ' ),property def stem self return self __class__ self pathlib splitext self name 0
yes / no confirmation of a response,def confirm_response self s r self input_wrapper Is response s correct y N format response s strip if re match yes y true t r re IGNORECASE return True return False
shows the dialog and waits until it is closed .,def exec_ self result None dialog_result super DialogExportGrades self exec_ if dialog_result QDialog Accepted filename self _get_save_file_name if filename selected_group None if self groups_combo is not None idx self groups_combo currentIndex if idx 0 selected_group self student_groups idx 1 idx self sort_combo currentIndex if idx 0 selected_sort_key utils ExportSortKey STUDENT_LIST elif idx 1 selected_sort_key utils ExportSortKey STUDENT_LAST_NAME elif idx 2 selected_sort_key utils ExportSortKey GRADING_SEQUENCE result filename self type_combo currentIndex self students_combo currentIndex selected_group selected_sort_key self export_items get_state return result
a crude way of output the errors for now . this needs to be cleaned up into something better .,def print_error self wrapper level 0 parent wrapper parent while parent print_test_msg parent name level TestStatus FAIL self use_color level 1 parent parent parent print_test_msg wrapper name level TestStatus FAIL self use_color print_test_args wrapper execute_kwargs level TestStatus FAIL self use_color if wrapper error for line in wrapper error print_test_msg line level 2 TestStatus FAIL self use_color print_expects wrapper level use_color self use_color
"receivers - list of one element , the simulated receiver socket senders - list of one element , the simulated sender socket exceptions - empty list , the simulated sockets with exceptions ignore timeout - there is no real concurrency here",def select receivers senders exceptions timeout inputready receivers if len receivers 0 buffers 0 else outputready senders if socket_simulator bufsize len senders 0 buffers 0 else exceptions return inputready outputready exceptions
noisy cross - entropy method http://dx.doi.org/10.1162/neco.2006.18.12.2936 http://ie.technion.ac.il/ce/files/papers/learning%20tetris%20using%20the%20noisy%20cross-entropy%20method.pdf incorporating schedule described on page 4 ( also see equation below . ),def cem f th_mean batch_size n_iter elite_frac initial_std 1 0 extra_std 0 0 std_decay_time 1 0 pool None Noisy cross entropy method http dx doi org 10 1162 neco 2006 18 12 2936 http ie technion ac il CE files papers Learning 20Tetris 20Using 20the 20Noisy 20Cross Entropy 20Method pdf Incorporating schedule described on page 4 also see equation below Inputs f function of one argument the parameter vector th_mean initial distribution is theta Normal th_mean initial_std batch_size how many samples of theta per iteration n_iter how many iterations elite_frac how many samples to select at the end of the iteration and use for fitting new distribution initial_std standard deviation of initial distribution extra_std noise component added to increase standard deviation std_decay_time how many timesteps it takes for noise to decay sigma_ t 1 2 sigma_ t elite 2 extra_std Z_t 2 where Zt max 1 t std_decay_time 10 0 extra_std n_elite int np round batch_size elite_frac th_std np ones th_mean size initial_std for iteration in xrange n_iter extra_var_multiplier max 1 0 iteration float std_decay_time 0 print extra var extra_var_multiplier sample_std np sqrt th_std np square extra_std extra_var_multiplier ths np array th_mean dth for dth in sample_std None np random randn batch_size th_mean size if pool is None ys np array map f ths else ys np array pool map f ths assert ys ndim 1 elite_inds ys argsort n_elite elite_ths ths elite_inds th_mean elite_ths mean axis 0 th_std elite_ths var axis 0 yield ys ys th th_mean ymean ys mean std sample_std
"initialize the object , and populate it with the entries in the defaults dictionary .",def __init__ self defaults self _regex None self _regexIsDirty True for k v in defaults items self k v
makes a naive datetime.datetime in a given time zone aware .,def make_aware value timezone if hasattr timezone localize return timezone localize value is_dst None else return value replace tzinfo timezone
: type n : int : rtype : int,def numTrees self n if n 0 return 1 def combination n k count 1 for i in xrange 1 k 1 count count n i 1 i return count return combination 2 n n combination 2 n n 1
find if there exists any pair of numbers which sum is equal to the value . : type value : int : rtype : bool,def find self value for key in self lookup num value key if num in self lookup and num key or self lookup key 1 return True return False
: type root : treenode : type val : int : rtype : treenode,def insertIntoBST self root val if not root root TreeNode val elif val root val root left self insertIntoBST root left val else root right self insertIntoBST root right val return root
draw a rect `` node `` on `` surface `` .,def rect surface node x y size surface node get x x size surface node get y y width size surface node get width x height size surface node get height y rx node get rx ry node get ry if rx and ry is None ry rx elif ry and rx is None rx ry rx size surface rx x ry size surface ry y if rx 0 or ry 0 surface context rectangle x y width height else if rx width 2 rx width 2 if ry height 2 ry height 2 ARC_TO_BEZIER 4 2 0 5 1 3 c1 ARC_TO_BEZIER rx c2 ARC_TO_BEZIER ry surface context new_path surface context move_to x rx y surface context rel_line_to width 2 rx 0 surface context rel_curve_to c1 0 rx c2 rx ry surface context rel_line_to 0 height 2 ry surface context rel_curve_to 0 c2 c1 rx ry rx ry surface context rel_line_to width 2 rx 0 surface context rel_curve_to c1 0 rx c2 rx ry surface context rel_line_to 0 height 2 ry surface context rel_curve_to 0 c2 rx c1 ry rx ry surface context close_path
return a dictionary suitable for use in `` package_data `` in a distutils `` setup.py `` file .,def find_package_data where package exclude standard_exclude exclude_directories standard_exclude_directories only_in_packages True show_ignored False out stack convert_path where package only_in_packages while stack where prefix package only_in_packages stack pop 0 for name in os listdir where fn os path join where name if os path isdir fn bad_name False for pattern in exclude_directories if fnmatchcase name pattern or fn lower pattern lower bad_name True if show_ignored print Directory s ignored by pattern s fn pattern file sys stderr break if bad_name continue if os path isfile os path join fn __init__ py and not prefix if not package new_package name else new_package package name stack append fn new_package False else stack append fn prefix name package only_in_packages elif package or not only_in_packages bad_name False for pattern in exclude if fnmatchcase name pattern or fn lower pattern lower bad_name True if show_ignored print File s ignored by pattern s fn pattern file sys stderr break if bad_name continue out setdefault package append prefix name return out
"make the remote host more script - friendly by automatically executing one or more commands on it . the commands executed depend on the currently used driver . for example , the driver for cisco ios would execute the following commands : :",secure_function def autoinit scope scope get __connection__ autoinit return True
construct the : class:`bayesiannet ` .,def __init__ self observed None super BayesianNet self __init__ self _observed frozendict name tf convert_to_tensor tensor for name tensor in six iteritems observed if observed else self _stochastic_tensors OrderedDict
"for a given container and a list of objects in the world , drops the objects inside the container and simulates until stable .",def make_object_pile world container objects container_wall_thickness 0 01 randomize_orientation True visualize False container_outer_bb get_bound container container_inner_bb vectorops add container_outer_bb 0 container_wall_thickness 3 vectorops sub container_outer_bb 1 container_wall_thickness 3 spawn_area container_inner_bb 0 container_inner_bb 1 collision_margin 0 0025 if visualize from klampt import vis from klampt model import config import time oldwindow vis getWindow newwindow vis createWindow make_object_pile dynamic visualization vis setWindow newwindow vis show visworld world copy vis add world visworld sim Simulator world sim setSetting maxContacts 20 sim setSetting adaptiveTimeStepping 0 Tfar so3 identity 0 0 100000 for object in objects R t object getTransform object setTransform R Tfar 1 sim body object setTransform Tfar sim body object enable False print Spawn area spawn_area if visualize vis lock config setConfig visworld config getConfig world vis unlock for index in xrange len objects if index 0 objects_bound get_bound objects index print Existing objects bound objects_bound zshift max 0 0 objects_bound 1 2 spawn_area 0 2 spawn_area 0 2 zshift spawn_area 1 2 zshift object objects index obb get_bound object zmin obb 0 2 R0 t0 object getTransform feasible False for sample in xrange 1000 R t R0 t0 if randomize_orientation True R so3 sample t 2 spawn_area 1 2 zmin t0 2 collision_margin object setTransform R t xy_randomize object spawn_area 0 spawn_area 1 print Sampled position of object getName object getTransform 1 if not randomize_orientation _ t object getTransform object setTransform R t sobject sim body object sobject enable True sobject setTransform object getTransform res sim checkObjectOverlap if len res 0 0 feasible True R t object getTransform for lower in xrange 100 sobject setTransform R vectorops add t 0 0 lower 1 0 01 res sim checkObjectOverlap if len res 0 0 print Terminated lowering at lower cm lower sobject setTransform R vectorops add t 0 0 lower 0 01 res sim checkObjectOverlap break sim updateWorld break if not feasible print Failed to place object object getName return None if visualize vis lock config setConfig visworld config getConfig world vis unlock time sleep 0 1 print Beginning to simulate for firstfall in xrange 10 sim simulate 0 01 if visualize vis lock config setConfig visworld config getConfig world vis unlock time sleep 0 01 maxT 5 0 dt 0 01 t 0 0 wdamping 0 01 vdamping 0 1 while t maxT settled True for object in objects sobject sim body object w v sobject getVelocity sobject applyWrench vectorops mul v vdamping vectorops mul w wdamping if vectorops norm w vectorops norm v 0 0001 settled False break if settled break if visualize t0 time time sim simulate dt if visualize vis lock config setConfig visworld config getConfig world vis unlock time sleep max 0 0 dt time time t0 t dt if visualize vis show False vis setWindow oldwindow return world sim
retrieve all flows from a switch identified by dpid .,rest flows rest flows dpid def retrieve_flows self dpid None switch_flows if dpid target dpid else target self controller switches for switch_dpid in target switch self controller get_switch_by_dpid switch_dpid flows for flow in switch flows flow flow as_dict flow flow_id flow pop self id 0 flows flow_id flow switch_flows switch_dpid flows return json dumps switch_flows
returns a list of image files ( defined as files ending with extensions in constants . allowed_image_formats ) in directory .,staticmethod def _get_image_files directory images list for f in os listdir directory fname f lower for ext in constants ALLOWED_IMAGE_FORMATS if fname endswith ext images append os path join directory f return images
"rename total margin field to rate with margin in "" sales order item "" , "" sales invoice item "" , "" delivery note item "" , "" quotation item """,def execute u n t tRename Total Margin field to Rate With Margin in n t t Sales Order Item Sales Invoice Item Delivery Note Item n t t Quotation Item n t for d in u Sales Order Item u Sales Invoice Item u Delivery Note Item u Quotation Item frappe reload_doctype d rename_field_if_exists d u total_margin u rate_with_margin
minimizes a positive definite quadratic function via linear conjugate gradient using the r operator to avoid explicitly representing the hessian .,def linear_cg fn params tol 0 001 max_iters 1000 floatX None provided_as_list True if not isinstance params list tuple params params provided_as_list False n_params len params def loop rsold args ps args n_params rs args n_params 2 n_params xs args 2 n_params Aps for param in params rval tensor Rop tensor grad fn param params ps if isinstance rval list tuple Aps append rval 0 else Aps append rval alpha rsold sum x y sum for x y in zip Aps ps xs x alpha p for x p in zip xs ps rs r alpha Ap for r Ap in zip rs Aps rsnew sum r r sum for r in rs ps r rsnew rsold p for r p in zip rs ps return rsnew ps rs xs theano scan_module until rsnew tol r0s tensor grad fn params if not isinstance r0s list tuple r0s r0s p0s x for x in r0s x0s params rsold sum r r sum for r in r0s outs updates theano scan loop outputs_info rsold p0s r0s x0s n_steps max_iters name linear_conjugate_gradient fxs outs 1 2 n_params fxs ifelse rsold tol x0 x 1 for x0 x in zip x0s fxs if not provided_as_list return fxs 0 else return fxs
samples from the prior distribution : math:`p_\theta(\mathbf{z } ) `,def sample_from_p_z self num_samples kwargs Samples from the prior distribution math p_ theta mathbf z Parameters num_samples int Number of samples Returns z tensor_like Sample from the prior distribution raise NotImplementedError str self __class__ does not implement sample_from_p_z
convert to rgb from hsv .,def fromhsv self h s v r g b hsv_to_rgb h s v self r round_int r 255 0 255 self g round_int g 255 0 255 self b round_int b 255 0 255
add mapping using prefix option .,def test_add_prefix s selector Selector parser lambda x x p flexmock re should_receive compile once with_args pre foop replace_with lambda x x c assert s prefix result s add foo GET 33 prefix pre assert s prefix assert result 0 pre foopc assert result 1 keys GET assert result 1 values 33 assert len s mappings 1
get list of wanted filenames from the trend data folder . @param trend_folder : the directory to look for files .,def filename_separation trend_folder files f for f in listdir trend_folder if isfile join trend_folder f threshold_files files sort for filename in files if py in filename continue if not txt in filename continue if threshold in filename threshold_files append filename continue return threshold_files
"encode v , which is a string of bytes , to base58 .",def b58encode v long_value 0 for i c in enumerate v 1 long_value 256 i ord c result while long_value __b58base div mod divmod long_value __b58base result __b58chars mod result long_value div result __b58chars long_value result nPad 0 for c in v if c x00 nPad 1 else break return __b58chars 0 nPad result
return the score of element value in sorted set,def score self value return self redis zscore self id value
returns the home page for efetch .,def _index self return self _get_resource u index html
"returns the value for this boundfield , as rendered in widgets .",register filter name field_value def field_value field if field form is_bound if isinstance field field FileField and field data is None val field form initial get field name field field initial else val field data else val field form initial get field name field field initial if callable val val val if val is None val return val
estimate the fe model with ols : return : results,def estimate self self __demean x_dataframe self x_demeaned transpose 2 0 1 to_frame False y_series self y_demeaned unstack results sm OLS y_series values x_dataframe values missing drop fit print results summary self depvar self indvars self result results
convenience method for casting to a str,def str self var default NOTSET force True u return self _get var default default cast text_type force force
add an exception filter to the error checking chain .,def addFilterException self exClass self excludes append exClass if self end return self next addFilterException exClass
regression test for the use of none as a query value .,def test_none_as_null self u n Regression test for the use of None as a query value n n None is interpreted as an SQL NULL but only in __exact and __iexact n queries n Set up some initial polls and choices n p1 Poll question u Why p1 save c1 Choice poll p1 choice u Because c1 save c2 Choice poll p1 choice u Why Not c2 save self assertQuerysetEqual Choice objects filter choice__exact None self assertQuerysetEqual Choice objects filter choice__iexact None self assertQuerysetEqual Choice objects exclude choice None order_by u id u Choice Choice Because in poll Q Why u Choice Choice Why Not in poll Q Why self assertRaises FieldError Choice objects filter foo__exact None self assertRaises ValueError Choice objects filter id__gt None p2 Poll question u How self assertEqual repr p2 choice_set all u
sort tree contents when a column is clicked on .,def sortby tree col descending data tree set child col child for child in tree get_children data sort reverse descending for indx item in enumerate data tree move item 1 indx tree heading col command lambda col col sortby tree col int not descending
createsuperuser command should operate on specified db,def test_createsuperuser_command_with_database_option self new_io StringIO call_command createsuperuser interactive False username joe email joe somewhere org database other stdout new_io command_output new_io getvalue strip self assertEqual command_output Superuser created successfully u models User objects using other get username joe self assertEqual u email joe somewhere org new_io close
test that adding an aliases(5 ) file to an ialiasabledomain at least does n't raise an unhandled exception .,def testAliases self Options parseOptions maildirdbmdomain example com example com aliases self aliasFilename
- > south - east neighborhood,def get_senh board cti se_nh nh E SW SE for c in board se_nh append frozenset cti c o for o in nh if c o in cti return se_nh
tests when installed_apps contains a class that is n't an app config .,def test_not_an_app_config self u n Tests when INSTALLED_APPS contains a class that isn t an app config n with self assertRaises ImproperlyConfigured with self settings INSTALLED_APPS u apps apps NotAConfig pass
"with hsts_seconds non - zero and hsts_include_subdomains true , the middleware adds a "" strict - transport - security "" header with the "" includesubdomains "" tag to the response .",override_settings SECURE_HSTS_SECONDS 600 SECURE_HSTS_INCLUDE_SUBDOMAINS True def test_sts_include_subdomains self response self process_response secure True self assertEqual response strict transport security max age 600 includeSubDomains
"batched insert statements via the orm "" bulk "" , using dictionaries .",Profiler profile def test_bulk_insert_mappings n session Session bind engine session bulk_insert_mappings Customer dict name customer name d i description customer description d i for i in range n session commit
"posix absolute paths start with os.path.sep , win32 ones ones start with drive ( like c:\folder )",def _is_local_repository self repo posix absolute paths start with os path sep win32 ones ones start with drive like c folder drive tail os path splitdrive repo return repo startswith os path sep or drive
l{ireactorunix.listenunix } raises l{error . cannotlistenerror } if passed the name of a file on which a server is already listening .,def test_socketLocking self filename self mktemp serverFactory MyServerFactory unixPort reactor listenUNIX filename serverFactory wantPID True self assertRaises error CannotListenError reactor listenUNIX filename serverFactory wantPID True def stoppedListening ign unixPort reactor listenUNIX filename serverFactory wantPID True return unixPort stopListening return unixPort stopListening addCallback stoppedListening
: param int_val : an unsigned integer .,def int_to_str int_val dialect None if dialect is None dialect ipv6_compact addr None try packed_int int_to_packed int_val if dialect compact addr _inet_ntop AF_INET6 packed_int else words list _struct unpack 8H packed_int tokens dialect word_fmt word for word in words addr word_sep join tokens except Exception raise ValueError r is not a valid 128 bit unsigned integer int_val return addr
generate expected output for all outdated tests .,def generate_all for dir_name sub_dirs files in os walk test_dir config get_config dir_name for file in files root ext os path splitext file if ext config get config get_section file input_ext generate os path join dir_name root config
prepends the build directory to the path so pyodbcconf can be imported without installing it .,def add_to_path import imp library_exts t 0 for t in imp get_suffixes if t 1 imp C_EXTENSION library_names pyodbcconf s ext for ext in library_exts dir_suffix s s sys version_info 0 sys version_info 1 build join dirname abspath __file__ build for top dirs files in os walk build dirs d for d in dirs if d endswith dir_suffix for name in library_names if name in files sys path insert 0 top return raise SystemExit Did not find pyodbcconf
return the full path to cscript.exe or none .,def _get_cscript_path for dir in os environ get PATH split os pathsep cscript_path os path join dir cscript exe if os path exists cscript_path return cscript_path
@param name : the name of the process to be stopped,def stopProcess self name if name not in self processes raise KeyError Unrecognized process name s name proto self protocols get name None if proto is not None proc proto transport try proc signalProcess TERM except error ProcessExitedAlready pass else self murder name self _reactor callLater self killTime self _forceStopProcess proc
extend the base stop implementation to also wake up the select thread so that c{rununtilcurrent } notices the reactor should stop .,def stop self posixbase PosixReactorBase stop self self wakeUp
"return the sec representation of this key as hex text . if use_uncompressed is not set , the preferred representation is returned .",def sec_as_hex self use_uncompressed None sec self sec use_uncompressed use_uncompressed if sec is None return None return b2h sec
create a new instance of externalcredentials,def __init__ self self erase_on_connect False
check that the cookie name has the right default .,def test_cookie_default self eq_ PINNING_COOKIE multidb_pin_writes
patched version of _ _ new _ _,def patched_new cls name bases attrs super_new super ModelBase cls __new__ parents b for b in bases if isinstance b ModelBase if not parents return super_new cls name bases attrs module attrs pop __module__ new_class super_new cls name bases __module__ module attr_meta attrs pop Meta None abstract getattr attr_meta abstract False if not attr_meta meta getattr new_class Meta None else meta attr_meta base_meta getattr new_class _meta None app_config apps get_containing_app_config module if getattr meta app_label None is None if app_config is None msg Model class s s doesn t declare an explicit app_label and either isn t in an application in INSTALLED_APPS or else was imported before its application was loaded module name if abstract msg Its app_label will be set to None in Django 1 9 else msg This will no longer be supported in Django 1 9 warnings warn msg RemovedInDjango19Warning stacklevel 2 model_module sys modules new_class __module__ package_components model_module __name__ split package_components reverse try app_label_index package_components index MODELS_MODULE_NAME 1 except ValueError app_label_index 1 kwargs app_label package_components app_label_index else kwargs app_label app_config label else kwargs new_class add_to_class _meta Options meta kwargs if not abstract new_class add_to_class DoesNotExist subclass_exception str DoesNotExist tuple x DoesNotExist for x in parents if hasattr x _meta and not x _meta abstract or ObjectDoesNotExist module attached_to new_class new_class add_to_class MultipleObjectsReturned subclass_exception str MultipleObjectsReturned tuple x MultipleObjectsReturned for x in parents if hasattr x _meta and not x _meta abstract or MultipleObjectsReturned module attached_to new_class if base_meta and not base_meta abstract if not hasattr meta ordering new_class _meta ordering base_meta ordering if not hasattr meta get_latest_by new_class _meta get_latest_by base_meta get_latest_by is_proxy new_class _meta proxy if is_proxy and base_meta and base_meta swapped raise TypeError s cannot proxy the swapped model s name base_meta swapped if getattr new_class _default_manager None if not is_proxy new_class _default_manager None new_class _base_manager None else new_class _default_manager new_class _default_manager _copy_to_model new_class new_class _base_manager new_class _base_manager _copy_to_model new_class for obj_name obj in attrs items new_class add_to_class obj_name obj new_fields new_class _meta local_fields new_class _meta local_many_to_many new_class _meta virtual_fields field_names set f name for f in new_fields if is_proxy base None for parent in kls for kls in parents if hasattr kls _meta if parent _meta abstract if parent _meta fields raise TypeError Abstract base class containing model fields not permitted for proxy model s name else continue while parent _meta proxy parent parent _meta proxy_for_model if base is not None and base is not parent raise TypeError Proxy model s has more than one non abstract model base class name else base parent if base is None raise TypeError Proxy model s has no non abstract model base class name new_class _meta setup_proxy base new_class _meta concrete_model base _meta concrete_model else new_class _meta concrete_model new_class parent_links for base in reversed new_class parents if not hasattr base _meta continue if base new_class and not base _meta abstract continue for field in base _meta local_fields if isinstance field OneToOneField parent_links field rel to field for base in parents original_base base if not hasattr base _meta continue parent_fields base _meta local_fields base _meta local_many_to_many for field in parent_fields if field name in field_names raise FieldError Local field r in class r clashes with field of similar name from base class r field name name base __name__ if not base _meta abstract base base _meta concrete_model if base in parent_links field parent_links base elif not is_proxy attr_name s_ptr base _meta model_name field OneToOneField base name attr_name auto_created True parent_link True if not hasattr new_class attr_name new_class add_to_class attr_name field else field None new_class _meta parents base field else for field in parent_fields new_class add_to_class field name copy deepcopy field new_class _meta parents update base _meta parents new_class copy_managers base _meta abstract_managers if is_proxy new_class copy_managers original_base _meta concrete_managers for field in base _meta virtual_fields if base _meta abstract and field name in field_names raise FieldError Local field r in class r clashes with field of similar name from abstract base class r field name name base __name__ new_class add_to_class field name copy deepcopy field if abstract attr_meta abstract False new_class Meta attr_meta return new_class new_class _prepare new_class _meta apps register_model new_class _meta app_label new_class return new_class
start by telling the portal to start a new session .,def start self ev_channel None irc_botname None irc_channel None irc_network None irc_port None global _SESSIONS if not _SESSIONS from evennia server sessionhandler import SESSIONS as _SESSIONS if irc_botname self db irc_botname irc_botname elif not self db irc_botname self db irc_botname self key if ev_channel channel search channel_search ev_channel if not channel raise RuntimeError Evennia Channel s not found ev_channel channel channel 0 channel connect self self db ev_channel channel if irc_channel self db irc_channel irc_channel if irc_network self db irc_network irc_network if irc_port self db irc_port irc_port configdict uid self dbid botname self db irc_botname channel self db irc_channel network self db irc_network port self db irc_port _SESSIONS start_bot_session evennia server portal irc IRCBotFactory configdict
writes the tallynum to worksheet ws,def WriteTally self tallyNum ws tally self GetTally tallyNum row 0 col 0 val 0 for f in tally axes f GetBins for c in tally axes c GetBins longName f str f c str c ws write 0 col longName ws write 1 col MeV ws write 2 col str f row 3 for e in tally axes e GetBins ws write row col e ws write row col 1 float tally data val ws write row col 2 float tally data val float tally errors val val 1 row 1 ws write row col total ws write row col 1 float tally data val ws write row col 2 float tally data val float tally errors val val 1 col 3
commit the candidate configuration as the device 's new current configuration . depends on the ` : candidate ` capability .,def request self confirmed False timeout None comment None synchronize False at_time None check False node new_ele_ns commit configuration if confirmed and at_time is not None raise NCClientError Commit confirmed and commit at are mutually exclusive if confirmed self _assert confirmed commit sub_ele node confirmed if timeout is not None timeout_int int timeout if isinstance timeout str else timeout sub_ele node confirm timeout text str int math ceil timeout_int 60 0 elif at_time is not None sub_ele node at time text at_time if comment is not None sub_ele node log text comment if synchronize sub_ele node synchronize if check sub_ele node check return self _request node
"raise a syntax error using ` msg ` , and showing ` thing ` .",def _syntax_error self msg thing raise TempliteSyntaxError s r msg thing
""" strictly less than equal "" . only returns true if this object 's forward and reverse bandwidth are < = other.fwd and other.rev",def slte self other return self fwd other fwd and self rev other rev
test the original / non - specific dataset,def test_checkTotal self syn_segments 7 3 7 12 3 9 5 12 truthGraph nx Graph truthGraph add_edges_from syn_segments url https ndgraph format SITE_HOST p token p channels 0 graphFile getURL url with open tmp _ graphml format p token p channels 0 wb as f f write graphFile content outputGraph nx read_graphml tmp _ graphml format p token p channels 0 assert nx is_isomorphic outputGraph truthGraph
returns the arp table from the device as a list of dicts . only retreives ip and arpa addresses at the moment .,def get_arp_table self re_text Internet s P ip d d d d s d s d w 4 d w 4 d w 4 s ARPA s r n table for item in re findall re_text self cmd show arp table append ip item 0 age item 1 mac item 2 interface item 3 strip return table
check if votes can be inserted for parent node or parent layer,def clean self args kwargs if not self pk if self node participation_settings voting_allowed is not True raise ValidationError Voting not allowed for this node if nodeshot core layers in settings INSTALLED_APPS layer self node layer if layer participation_settings voting_allowed is not True raise ValidationError Voting not allowed for this layer
"the "" challenge "" message is used with certain authentication methods . during authenticated session establishment , a * router * sends a challenge message .",def __init__ self auth_method kwargs_dict super Challenge self __init__ self auth_method auth_method self kwargs_dict kwargs_dict
the ` skewness ` in : ` y = sinh((arcsinh(x ) + skewness ) * tailweight ) ` .,property def skewness self return self _skewness
transcribe the given audio file .,def main speech_file with open speech_file rb as speech speech_content base64 b64encode speech read service get_speech_service service_request service speech syncrecognize body config encoding LINEAR16 sampleRate 16000 languageCode en US audio content speech_content decode UTF 8 response service_request execute print json dumps response alternative response results 0 alternatives 0 h httplib2 Http cache data urllib urlencode alternative print data resp content h request http localhost 5000 chord data GET print content
"returns the table format of the scheme , i.e. :",def _get_pretty_table self indent 0 align ALIGN_CENTER border False rows self rows_list columns self columns if len columns 0 and self _headers_color pyprinter Printer NORMAL and len rows 0 and len rows 0 0 rows 0 rows 0 columns columns columns 0 self _headers_color columns 0 rows 0 0 pyprinter Printer NORMAL str rows 0 0 table prettytable PrettyTable columns border border max_width pyprinter get_console_width indent table align self _ALIGN_DICTIONARY align for row in rows table add_row row if len self _columns keys 0 for column max_width in self _columns items table max_width column max_width else for column in columns table max_width column self _column_size_limit return table
create and initialize a variable using a numpy array and set trainable . : param name : ( required str ) name of the variable : param initializer : a numpy array or a tensor,def get_variable self name initializer v tf get_variable name shape initializer shape initializer lambda shape dtype partition_info initializer trainable self training return v
returns appropriate json by its version .,def discovery self req version key version if key in self _files return self _files key session clients admin_session keystone clients keystone None session session if not keystone has_service_catalog keystone authenticate token session get_token catalog keystone service_catalog get_data public_url clients get_url_from_catalog catalog gceapi if not public_url public_url req host_url public_url public_url rstrip self _lock acquire try if key in self _files return self _files key jfile self _load_file version jfile jfile replace HOST_URL public_url self _files key jfile return jfile finally self _lock release
update metadata for specific volume snapshot,rest_utils ajax def patch self request volume_snapshot_id updated request DATA updated removed request DATA removed if updated api cinder volume_snapshot_set_metadata request volume_snapshot_id updated if removed api cinder volume_snapshot_delete_metadata request volume_snapshot_id removed
initialize external dns service driver .,def __init__ self
update the trunk status to reflect outcome of data plane wiring .,def update_trunk_status self context trunk_id status with db_api autonested_transaction context session trunk trunk_objects Trunk get_object context id trunk_id if trunk trunk update status status
expire relationship attributes when a many - to - one column changes .,def expire_for_fk_change target fk_value relationship_prop column_attr sess orm object_session target if sess is not None if relationship_prop back_populates and relationship_prop key in target __dict__ obj getattr target relationship_prop key if obj is not None and sqlalchemy inspect obj persistent sess expire obj relationship_prop back_populates if sqlalchemy inspect target persistent sess expire target relationship_prop key if relationship_prop back_populates target __dict__ column_attr fk_value new getattr target relationship_prop key if new is not None if sqlalchemy inspect new persistent sess expire new relationship_prop back_populates else if target not in _emit_on_pending _emit_on_pending target _emit_on_pending target append fk_value relationship_prop column_attr
when the deleted amphorae is expired but is a zombie !,mock patch octavia db api get_session def test_delete_old_amphorae_Zombie self session session return_value session self CONF config group house_keeping amphora_expiry_age self FAKE_EXP_AGE expired_time datetime datetime utcnow datetime timedelta seconds self FAKE_EXP_AGE 1 amphora self amp create session id self FAKE_UUID_1 compute_id self FAKE_UUID_2 status constants DELETED lb_network_ip self FAKE_IP vrrp_ip self FAKE_IP ha_ip self FAKE_IP updated_at expired_time self amp_repo get_all_deleted_expiring_amphora return_value amphora self amp_health_repo check_amphora_health_expired return_value False self dbclean delete_old_amphorae self assertTrue self amp_repo get_all_deleted_expiring_amphora called self assertTrue self amp_health_repo check_amphora_health_expired called self assertFalse self amp_repo delete called
reserve / unreserve a fixed ip .,def reserve_fixed_ip self fixed_ip kwargs url os fixed ips s action fixed_ip resp body self post url json dumps kwargs self validate_response schema reserve_unreserve_fixed_ip resp body return rest_client ResponseBody resp body
lists the tag definitions within a namespace .,def list_namespace_tags self namespace params url metadefs namespaces s tags namespace if params url s urllib urlencode params resp body self get url self expected_success 200 resp status body json loads body return rest_client ResponseBody resp body
neighbors are existing nova instances only,def _create_node_neighbors self entity_event neighbors for neighbor in entity_event kubProp RESOURCES neighbor DSProps ENTITY_TYPE entity_event DSProps ENTITY_TYPE neighbor DSProps DATASOURCE_ACTION entity_event DSProps DATASOURCE_ACTION neighbor DSProps SAMPLE_DATE entity_event DSProps SAMPLE_DATE neighbor_id neighbor kubProp EXTERNALID neighbor_datasource_type NOVA_INSTANCE_DATASOURCE neighbors append self _create_neighbor neighbor neighbor_id neighbor_datasource_type EdgeLabel COMPRISED is_entity_source True return neighbors
"compute the dot product of a and b. dot(a , b ) = a * b",def dot a b b1 a block b2 b block if b1 dtype b2 dtype mod import_module vsip math matvec b1 dtype return mod dot b1 b2 else import operator import numpy return reduce operator add map operator mul numpy array b1 numpy array b2
modifies the table to add and remove the given columns .,def __call__ self index checkFirst False schema_name index schema dbname index_name index dbname cmd CREATE if not index testFlag index Flags Unique else CREATE UNIQUE cols 0 format col field if col testFlag col Flags CaseSensitive else 0 COLLATE NOCASE format col field for col in index columns cmd 0 INDEX 1 ON 2 3 format cmd index_name schema_name join cols if checkFirst cmd DO BEGIN IF NOT EXISTS SELECT 1 FROM pg_indexes WHERE schemaname public AND indexname 0 THEN 1 END IF END format index_name cmd else cmd return cmd
it moves given user to new container .,def MoveUser self user new_container _adclient MoveUser_adclient self obj user new_container
"traverse a temporal window in chunks for selected channels , chunk size is calculated depending on maximum memory . each batch includes a chunk of observations from all selected channels",def multi_channel self from_time None to_time None channels all from_time from_time if from_time is not None else 0 to_time to_time if to_time is not None else self n_observations channel_indexes channels if channels all else slice 0 self n_channels None if channels all channel_indexes_length self n_channels elif isinstance channel_indexes numbers Integral channel_indexes_length 1 else channel_indexes_length len channel_indexes t_total to_time from_time channels_total self n_channels if channels all else channel_indexes_length bytes_total t_total channels_total self itemsize obs_total t_total channels_total self logger debug Observations per channel Number of channels Total observations Size to traverse format t_total channels_total obs_total human_size bytes_total obs_channel_batch int floor self max_memory channels_total self itemsize obs_batch obs_channel_batch channels_total bytes_batch obs_batch self itemsize self logger debug Max observations per batch max observations per channel format obs_batch human_size bytes_batch obs_channel_batch n_batches int ceil obs_total obs_batch self logger debug Number of batches format n_batches obs_residual obs_total obs_batch n_batches 1 obs_channel_residual int obs_residual channels_total bytes_residual obs_residual self itemsize self logger debug Last batch with observations observations per channel format obs_residual human_bytes bytes_residual obs_channel_residual last_i n_batches 1 for i in range n_batches start from_time i obs_channel_batch if i last_i end start obs_channel_batch yield slice start end None channel_indexes else end start obs_channel_residual yield slice start end channel_indexes
"normalize the ' song ' value , relative to ref_dir",def normalize_song_path file_entry ref_dir if song in file_entry file_entry song os path relpath file_entry song ref_dir return file_entry
finds the mode of a given pressure .,def find_mode unit if unit in _PRESSURE_UNITS mode absolute elif unit p p0 mode relative else raise ParameterError Unit is unknown return mode
"stops and removes the unit file , if available",def remove namespace service_name print removing namespace service_name stop namespace service_name unit_name _get_unit_name namespace service_name unit_file_path os path join UNIT_FILES_PATH unit_name if os path isfile unit_file_path os remove unit_file_path
convert a dictionary to a recordfile .,def dict_to_recordfile filehandle records csvwt csv writer filehandle delimiter RECORDFILE_DELIMITER skipinitialspace True rows for key val in iteritems records rows append key val csvwt writerows rows
delete the given s3 directory .,def delete_s3_directory s3_directory bucket_name rest_of_dir_path parse_s3_location s3_directory bucket get_s3_bucket bucket_name rest_of_dir_path rest_of_dir_path if rest_of_dir_path 1 else rest_of_dir_path bucket delete_keys bucket list prefix rest_of_dir_path
true if the htmlpage fragment is a link,def is_link fragment return isinstance fragment scrapely htmlpage HtmlTag and fragment tag a and fragment tag_type scrapely htmlpage HtmlTagType OPEN_TAG
this helper retries the request if the resource is busy .,def sample_retry_helper func max_retries 1 def wrapper args kwds retries 0 while True try resp func args kwds except pvmex Error as e resp e response if resp body is not None resp_body str resp body if any code in resp_body for code in BUSY_ERR_CODES retries 1 if retries max_retries time sleep 5 retries continue raise e else return resp return wrapper
"parse the dokuwiki users.auth file and return block of comment text , dict of user info structures",def get_dokuwiki_users userfile u users collections OrderedDict comments u with codecs open userfile u r u utf 8 as f for line in f if line startswith u or line strip u comments line elif u in line login pwhash name email groups re split u line strip 5 users login u login login u pwhash pwhash u name name u email email u groups groups return comments users
"calculate the needed thrust for each thruster to achieve desired : param desired_thrust : the 6 dimensional vector which we want to achieve vector as 6x1 matrix : param disabled_thrusters : list of 8 items each corresponding to a thruster ( 0 meaning enabled , 1 disabled ) : return : the thrust map generated by solving for the least square solution of the equation",def calculate self desired_thrust disabled_thrusters None disable_limiting False if disabled_thrusters self disabled self disabled disabled_thrusters self _generate_matrix self map self pseudo_inverse_matrix dot desired_thrust self _normalize desired_thrust initial_power limitPower self _calc_thrust_power self map self final_power initial_power iteration 0 while limitPower 1 and disable_limiting False if iteration 3 print Limit power function iteration limit exceeded assume values are close enough break self final_power self _limit_power initial_power self final_power limitPower self _calc_thrust_power self map print Power was limited force vector changed return self map tolist 0
initialise an instance of a module makefile .,def __init__ self args kw if qt not in kw kw qt QtCore QtNetwork QtCoreModuleMakefile __init__ self args kw
generate a bilinear group for two generators .,def bilinear_group n p g1x g1y g2x g2y try wp weilpairing p n FP2Value p g1x FP2Value p g1y FP2Value p b g2x FP2Value p g2y FP2Value p FP2Value p return wp except return FP2Value p
check if ( 5 ) * ( x^2 + x + 1 ) = 5x^2 + 5x + 5 = 0 mod 11 mod x^2 + x + 1 .,def test_mul_combined_mod self a FP2Value 11 5 b FP2Value 11 1 1 1 self assertEqual a b FP2Value 11 5 5 5 self assertEqual a b FP2Value 11 0
: param wf : inwater waterframe object,def __init__ self wf super __init__ self wf wf self name QC self key all self fig self axes plt subplots nrows 1 ncols 1 self wf qcbarplot key self key ax self axes plt tight_layout sms despine self initUI
sets the current step 's status . args : status ( : class:`status < status > ` object ) : the status to set the step to .,def set_status self status if status is not self status logger debug Setting s state to s self stack name status name self status status self last_updated time time log_step self
"checks parameters , paths , and dependencies",def check self if LINESEARCH not in PAR setattr PAR LINESEARCH Bracket if NLCGMAX not in PAR setattr PAR NLCGMAX np inf if NLCGTHRESH not in PAR setattr PAR NLCGTHRESH np inf super NLCG self check
"send the message for given topic with data in msgkwargs . this sends message to listeners of parent topics as well . note that at each level , msgkwargs is filtered so only those args that are defined for the topic are sent to listeners .",def _mix_callListener self listener msgKwargs iterState listener iterState filteredArgs self msgKwargs
"get a relative filename reference based on the path , ignoring # or ? characters special meaning in urls .",def get_file_reference path import urllib return get_reference urllib quote path
callback from the joboutputmixin for a block of text on stderr .,def stderrCallback self job text Publisher sendMessage peppy log info self frame text
write code object as a byte - compiled file,def dump_compile codeobject filename timestamp magic path_tmp s s filename id filename fc None try try fc open path_tmp wb if PYTHON3 fc write bytes 0 0 0 0 else fc write x00 x00 x00 x00 wr_long fc timestamp marshal dump codeobject fc fc flush fc seek 0 0 fc write magic fc close os rename path_tmp filename except OSError try os unlink path_tmp except OSError pass raise finally if fc fc close
"sequence(p1 , [ p2 , .. , pn ] )",def Sequence plist processes for p in plist if type p list for q in p processes append q else processes append p s Scheduler _p s current _p_original_id _p id return_values for p in processes _p id p id p run return_values append p return_value _p id _p_original_id return return_values
returns true for lines that should be compared in the disassembly output .,def keep_line line return file format not in line
an small wrapper around the docker - py `` client `` api .,pytest fixture scope session def docker try client dockerpy from_env client ping return Docker client except requests ConnectionError pytest skip Could not connect to a local docker daemon
"creates a label for the client information passed in ( mac , color ) returns a graph object todo : pass a label in that may hold additional client data that could in turn be written on the client .",def clientColor mac color label if label label mac graph t mac label label color color fontsize 7 n return graph
ensure that jobs spawned from recurring jobs are tagged,def test_recurring self self lua recur 0 queue jid klass interval 60 0 tags foo self lua pop 0 queue worker 10 self assertEqual self lua tag 0 get foo 0 10 jobs jid 1
test that the fuzzer spawns correctly,def test_fuzzer_spawn binary os path join bin_location tests cgc PIZZA_00001 f fuzzer Fuzzer binary work f start for _ in range 15 if f alive break time sleep 1 nose tools assert_true f alive if f alive f kill
return a new executor where the working directory is different .,def chdir self path new_shell self _shell clone new_shell chdir path return attr evolve self shell new_shell
check expected number of axes is drawn in expected layout,def _check_axes_shape self axes axes_num None layout None figsize 8 0 6 0 visible_axes self _flatten_visible axes if axes_num is not None self assertEqual len visible_axes axes_num for ax in visible_axes self assertTrue len ax get_children 0 if layout is not None result self _get_axes_layout _flatten axes self assertEqual result layout if figsize is not None self assert_numpy_array_equal np round visible_axes 0 figure get_size_inches np array figsize
add a dictionary of fields to this bitfield .,def fields_add self fields if not isinstance fields dict raise TypeError fields should be a dictionary of Field objects if len fields 0 raise ValueError Empty dictionary is not so useful for newfield in fields itervalues self field_add newfield
return ( almost ) nested signatures for each correlation value .,def signatures splits_results frequency_threshold 0 0 selection_totals selection_summary splits_results selection_freqs selection_totals len splits_results sorted_idxs np argsort selection_freqs axis 1 sorted_idxs sorted_idxs T 1 T for i si in enumerate sorted_idxs selection_freqs i selection_freqs i si selection_totals i selection_totals i si threshold_mask selection_freqs frequency_threshold sign_totals list sign_freqs list sign_idxs list for i mask in enumerate threshold_mask sign_totals append selection_totals i mask sign_freqs append selection_freqs i mask sign_idxs append sorted_idxs i mask return sign_totals sign_freqs sign_idxs
returns true if all the fields are valid . appends any error messages to messages parameter .,def validate self messages None u Returns True if all the fields are valid n Appends any error messages to messages parameter n messages messages if messages is not None else return self validate_reviewer messages and self validate_review_date messages
"log any public messages , and also handle the command event .",def on_pubmsg self connection event for message in event arguments self log event message command_args filter None message split command_name command_args pop 0 for handler in self events command if handler event args command command_name self handle_command_event event handler command_args
move to a series of targets .,def control self arm if self controller check_distance arm self threshold and self run_timer False self run_timer True if self postural True and self target_index len self target_list 1 self pen_down not self pen_down self controller additions self additions print additional force added print start recording for recorder in self controller recorders recorder start_recording True elif self target_index 3 1 print start recording for recorder in self controller recorders recorder start_recording True if self run_timer True self timer 1 if self timer self hold_time if self target_index len self target_list 1 self target_index 1 self set_target self not_at_start not self not_at_start self pen_down not self pen_down self timer 0 self run_timer False self run_timer2 True self controller block_output True print target shown if self postural True self controller additions print additional force removed print write to file for recorder in self controller recorders recorder write_out True if self run_timer2 True self timer2 1 if self timer2 self hold_time2 self timer2 0 self run_timer2 False self controller block_output False print start movement self u self controller control arm return self u
solve position using the levenberg - marquardt minimization algorithm .,def solve_numerically tdoa_array rx_pos dims len rx_pos 0 uniq_rx np unique np concatenate tdoa_array rx0 tdoa_array rx1 if len uniq_rx dims 1 raise EstimationError Underdetermined rx_coords np array rx_pos values min_bounds np amin rx_coords axis 0 MAX_DIST max_bounds np amax rx_coords axis 0 MAX_DIST rx0 np array rx_pos rxid for rxid in tdoa_array rx0 rx1 np array rx_pos rxid for rxid in tdoa_array rx1 x0 0 1 0 1 def model pos pos_rx0 pos_rx1 rx0 pos rx1 pos dist0 np linalg norm pos_rx0 axis 1 dist1 np linalg norm pos_rx1 axis 1 predicted_tdoa dist0 dist1 residuals tdoa_array tdoa SPEED_OF_LIGHT predicted_tdoa return residuals def jac pos pos_rx0 pos_rx1 rx0 pos rx1 pos dist0 np linalg norm pos_rx0 axis 1 dist1 np linalg norm pos_rx1 axis 1 return pos_rx0 dist0 None pos_rx1 dist1 None res scipy optimize least_squares model x0 jac jac bounds min_bounds max_bounds snr_mean np mean tdoa_array snr return res x snr_mean
"parse a history line , return none if ca n't",def parse_line line try line line decode utf 8 except UnicodeDecodeError return None line line 2 fields line split maxsplit 1 if len fields 2 return None try command shlex split fields 1 except ValueError command fields 1 split ts _ fields 0 split return time datetime fromtimestamp int ts command command 0 nargs len command 1
returns training and evaluation input functions .,def construct_input_fns dataset batch_size vocabulary_size sentence_length repeat 1 if dataset DATASET_IMDB train_input_fn eval_input_fn imdb construct_input_fns vocabulary_size sentence_length batch_size repeat repeat return train_input_fn eval_input_fn else raise ValueError unsupported dataset dataset
"transforms the inputs to have missing tokens when it 's masked out . the mask is for the targets , so therefore , to determine if an input at time t is masked , we have to check if the target at time t - 1 is masked out .",def transform_input_with_is_missing_token inputs targets_present input_missing tf constant FLAGS vocab_size dtype tf int32 shape FLAGS batch_size FLAGS sequence_length zeroth_input_present tf constant True tf bool shape FLAGS batch_size 1 inputs_present tf concat zeroth_input_present targets_present 1 axis 1 transformed_input tf where inputs_present inputs input_missing return transformed_input
converts from an sgf coordinate to a minigo coordinate .,def from_sgf sgfc if not sgfc return None return _SGF_COLUMNS index sgfc 1 _SGF_COLUMNS index sgfc 0
computes the point where we start using data - independent bounds .,def compute_logq0_gnmax sigma order def _check_validity_conditions logq mu1 mu2 _compute_mu1_mu2_gnmax sigma logq if mu1 order return False eps2 mu2 sigma 2 return logq mu2 1 eps2 mu2 math log mu1 mu1 1 mu2 mu2 1 def _compare_dep_vs_ind logq return _compute_data_dep_bound_gnmax sigma logq order pate rdp_data_independent_gaussian sigma order logub min 1 1 0 sigma 2 order 0 99 sigma 2 1 sigma 2 assert _check_validity_conditions logub if _compare_dep_vs_ind logub 0 return logub loglb 2 logub while _compare_dep_vs_ind loglb 0 assert loglb 10000 The lower bound on q0 is way too low loglb 1 5 logq0 r scipy optimize brentq _compare_dep_vs_ind loglb logub full_output True assert r converged The root finding procedure failed to converge assert _check_validity_conditions logq0 return logq0
sets the batch dimension in all tensors to batch_size .,def set_batch_size dataset batch_size return dataset map lambda t _recursive_set_batch_size t batch_size
builds a sequence that is the reverse of the input sequence .,def build_reverse_sequence seq reverse_seq SequenceWrapper for timestep in reversed seq 1 reverse_seq add_timestep copy_from timestep reverse_seq add_timestep copy_from seq 1 return reverse_seq
wrapper around _ mp_process_hdf that correctly handles keyboard interrupt,def _mp_process_hdf args try _real_mp_process_hdf args except KeyboardInterrupt SystemExit print Worker interrupted exiting return False
returns true if idle is using a carbon aqua tk ( instead of the newer cocoa aqua tk ) .,def isCarbonAquaTk root global _carbonaquatk if _carbonaquatk is None _carbonaquatk runningAsOSXApp and aqua in root tk call tk windowingsystem and AppKit not in root tk call winfo server return _carbonaquatk
shallow copy operation on arbitrary python objects .,def copy x cls type x copier _copy_dispatch get cls if copier return copier x copier getattr cls __copy__ None if copier return copier x reductor dispatch_table get cls if reductor rv reductor x else reductor getattr x __reduce_ex__ None if reductor rv reductor 2 else reductor getattr x __reduce__ None if reductor rv reductor else raise Error un shallow copyable object of type s cls return _reconstruct x rv 0
returns the number of cpus in the system,def cpu_count if sys platform win32 try num int os environ NUMBER_OF_PROCESSORS except ValueError KeyError num 0 elif bsd in sys platform or sys platform darwin comm sbin sysctl n hw ncpu if sys platform darwin comm usr comm try with os popen comm as p num int p read except ValueError num 0 else try num os sysconf SC_NPROCESSORS_ONLN except ValueError OSError AttributeError num 0 if num 1 return num else raise NotImplementedError cannot determine number of cpus
"returns a string suitable for rfc 2822 compliant message - id , e.g :",def make_msgid idstring None domain None timeval time time utcdate time strftime Y m d H M S time gmtime timeval pid os getpid randint random randrange 100000 if idstring is None idstring else idstring idstring if domain is None domain socket getfqdn msgid s s s s s utcdate pid randint idstring domain return msgid
sets the character encoding of this inputsource .,def setEncoding self encoding self __encoding encoding
"_ _ future__.division redefines the meaning of a single slash for division , so we match that and only that .",def match_division node u n __future__ division redefines the meaning of a single slash for division n so we match that and only that n slash token SLASH return node type slash and not node next_sibling type slash and not node prev_sibling type slash
compare two entities for equality .,def __eq__ self other if not isinstance other Entity return NotImplemented return self key other key and super Entity self __eq__ other
queue a function ( with given args / kwargs ) to be run asynchronously .,def run_async self func args kwargs promise Promise func args kwargs self __async_queue put promise return promise
return a new retry object with incremented retry counters .,def increment self method None url None response None error None _pool None _stacktrace None if self total is False and error raise six reraise type error error _stacktrace total self total if total is not None total 1 connect self connect read self read redirect self redirect cause unknown status None redirect_location None if error and self _is_connection_error error if connect is False raise six reraise type error error _stacktrace elif connect is not None connect 1 elif error and self _is_read_error error if read is False or not self _is_method_retryable method raise six reraise type error error _stacktrace elif read is not None read 1 elif response and response get_redirect_location if redirect is not None redirect 1 cause too many redirects redirect_location response get_redirect_location status response status else cause ResponseError GENERIC_ERROR if response and response status cause ResponseError SPECIFIC_ERROR format status_code response status status response status history self history RequestHistory method url error status redirect_location new_retry self new total total connect connect read read redirect redirect history history if new_retry is_exhausted raise MaxRetryError _pool url error or ResponseError cause log debug Incremented Retry for url s r url new_retry return new_retry
internal use only : not a public interface,def get_sensor_value self sensor cmd sensor cmd self send_command cmd data self get_result if data data self interpret_result data if data NODATA data sensor value data else return NORESPONSE return data
a list of names for data required by this module .,property def data_names self return self _data_names
get the list of naughty_strings .,def naughty_strings filepath FILEPATH strings with open filepath r as f strings f readlines strings x strip u n for x in strings strings x for x in strings if x and not x startswith u strings insert 0 u return strings
"return the first element in a python sequence for graphs , use graph.value instead",def first seq for result in seq return result return None
"destroy the l{enhancement}s of the given subclass associated with the given l{thing } , if one exists .",classmethod def destroyFor cls thing it thing store findUnique cls cls thing thing default None if it is not None it removeEnhancement it deleteFromStore
prints out all the configuration data parameters : none,def do_config self a print config print tK str ec getK print toffset str ec getCalibrateOffset print tdry str ec getCalibrateDry print tdual point str ec usingDualPoint print tlow reference read str ec getCalibrateLowReference str ec getCalibrateLowReading print thigh reference reading str ec getCalibrateHighReference str ec getCalibrateHighReading print ttemp compensation str ec usingTemperatureCompensation print t tconstant str ec getTempConstant print tversion hex ec getVersion
return also tiles if bounds cross the antimeridian .,def _global_tiles_from_bounds tp bounds zoom seen set left right bounds left bounds right top tp top if bounds top tp top else bounds top bottom tp bottom if bounds bottom tp bottom else bounds bottom if left tp left and right tp right for tile in _tiles_from_cleaned_bounds tp bounds zoom yield tile if left tp left for tile in chain _tiles_from_cleaned_bounds tp Bounds left tp right tp left bottom tp right top zoom _tiles_from_cleaned_bounds tp Bounds tp left bottom right top zoom if tile id not in seen seen add tile id yield tile if right tp right for tile in chain _tiles_from_cleaned_bounds tp Bounds left bottom tp right top zoom _tiles_from_cleaned_bounds tp Bounds tp left bottom right tp right tp left top zoom if tile id not in seen seen add tile id yield tile
quick function to dump a result to a pickle @param result the resulting parsed data,def store_dump result file result di sblock result di result ci sblock result ci result hr sblock result hr result ir sblock result ir with open file w as input pickle dump result input
do some custom behaviour for this test,def custom_method self self log info Running custom_method
meta registers are registers which are really just directly addressable parts of already existing registers ( eax - > al ) .,def addMetaRegister self name idx offset width newidx offset 24 width 16 idx self _rctx_names name newidx self _rctx_ids newidx name
deletes all embeddings from the database .,def clear self c self db cursor c execute delete from embeddings self db commit
called by the engine to set a driver property value .,def setProperty self name value self _push self _driver setProperty name value
construct a list containing type ' klazz ' .,staticmethod def create type_dict type_parameters assert len type_parameters 1 klazz TypeFactory new type_dict type_parameters 0 assert isclass klazz assert issubclass klazz Object return TypeMetaclass sList klazz __name__ ListContainer TYPE klazz
apply one or more : class:`.aggregation ` instances to this table .,def aggregate self aggregations if utils issequence aggregations results OrderedDict for name agg in aggregations agg validate self for name agg in aggregations results name agg run self return results else aggregations validate self return aggregations run self
"take the given block - device name ( e.g. ' /dev / sda1 ' , ' hda ' ) and return a dictionary { device , start_sector , nr_sectors , type } device : device number of the given partition start_sector : index of first sector of the partition nr_sectors : number of sectors comprising this partition type : ' disk ' or identifying name for partition type",def blkdev_segment name val None name n blkdev_name_to_number name if not n is None val device n start_sector long 0 nr_sectors long 1L 63 type Disk return val
"github # 340 , return the full word .",def test_import_empty completion jedi Script import completions 0 definition completion follow_definition 0 assert definition
the average value from a list of numbers ( a float ) .,property def average self if len self 0 raise ValueError Cannot calculate average of empty list return sum self float len self
acquires the lock for the given entry .,def acquire self try self _client retry self _client create path id format path self _lock_path id self entry_id self lock_id ephemeral True except NodeExistsError RetryFailedError if not self holds_lock raise LockError try value stat self _client retry self _client get path id format path self _entries_path id self entry_id except NoNodeError RetryFailedError if self holds_lock self _client retry self _inner_release self data value return True
mine some blocks and have them mature .,def run_test self self nodes 0 generate 101 utxo self nodes 0 listunspent 10 txid utxo 0 txid vout utxo 0 vout value utxo 0 amount fee Decimal 0 0001 chain for i in xrange MAX_ANCESTORS txid sent_value self chain_transaction self nodes 0 txid 0 value fee 1 value sent_value chain append txid mempool self nodes 0 getrawmempool True assert_equal len mempool MAX_ANCESTORS descendant_count 1 descendant_fees 0 descendant_size 0 SATOSHIS 100000000 for x in reversed chain assert_equal mempool x descendantcount descendant_count descendant_fees mempool x fee assert_equal mempool x modifiedfee mempool x fee assert_equal mempool x descendantfees SATOSHIS descendant_fees descendant_size mempool x size assert_equal mempool x descendantsize descendant_size descendant_count 1 self nodes 0 prioritisetransaction chain 1 0 1000 mempool self nodes 0 getrawmempool True descendant_fees 0 for x in reversed chain descendant_fees mempool x fee assert_equal mempool x descendantfees SATOSHIS descendant_fees 1000 try self chain_transaction self nodes 0 txid vout value fee 1 except JSONRPCException as e print too long ancestor chain successfully rejected self nodes 0 generate 1 sync_blocks self nodes assert_equal len self nodes 0 getrawmempool 0 self nodes 0 prioritisetransaction chain 1 0 2000 self nodes 0 invalidateblock self nodes 0 getbestblockhash self nodes 1 invalidateblock self nodes 1 getbestblockhash mempool self nodes 0 getrawmempool True descendant_fees 0 for x in reversed chain descendant_fees mempool x fee if x chain 1 assert_equal mempool x modifiedfee mempool x fee satoshi_round 2e 05 assert_equal mempool x descendantfees SATOSHIS descendant_fees 2000 txid utxo 1 txid value utxo 1 amount vout utxo 1 vout transaction_package txid sent_value self chain_transaction self nodes 0 txid vout value fee 10 parent_transaction txid for i in xrange 10 transaction_package append txid txid vout i amount sent_value for i in xrange MAX_DESCENDANTS utxo transaction_package pop 0 try txid sent_value self chain_transaction self nodes 0 utxo txid utxo vout utxo amount fee 10 for j in xrange 10 transaction_package append txid txid vout j amount sent_value if i MAX_DESCENDANTS 2 mempool self nodes 0 getrawmempool True assert_equal mempool parent_transaction descendantcount MAX_DESCENDANTS except JSONRPCException as e print e error message assert_equal i MAX_DESCENDANTS 1 print tx that would create too large descendant package successfully rejected self nodes 0 generate 1 sync_blocks self nodes self nodes 1 invalidateblock self nodes 0 getbestblockhash self nodes 1 reconsiderblock self nodes 0 getbestblockhash utxo self nodes 0 listunspent txid utxo 0 txid value utxo 0 amount vout utxo 0 vout send_value satoshi_round value fee 2 inputs txid txid vout vout outputs for i in xrange 2 outputs self nodes 0 getnewaddress send_value rawtx self nodes 0 createrawtransaction inputs outputs signedtx self nodes 0 signrawtransaction rawtx txid self nodes 0 sendrawtransaction signedtx hex tx0_id txid value send_value tx1_id tx1_value self chain_transaction self nodes 0 tx0_id 0 value fee 1 vout 1 txid tx0_id for i in xrange 6 txid sent_value self chain_transaction self nodes 0 txid vout value fee 1 vout 0 value sent_value self nodes 0 generate 1 self sync_all inputs txid tx1_id vout 0 txid txid vout 0 outputs self nodes 0 getnewaddress send_value value 4 fee rawtx self nodes 0 createrawtransaction inputs outputs signedtx self nodes 0 signrawtransaction rawtx txid self nodes 0 sendrawtransaction signedtx hex sync_mempools self nodes self nodes 1 invalidateblock self nodes 1 getbestblockhash self nodes 0 invalidateblock self nodes 0 getbestblockhash sync_blocks self nodes
revert to the last backed up state .,def revert self if self _backup self load_state self _backup self _backup None
$ { cmd_name } : print multiplication table,def do_multable self subcmd opts number 10 times 25 with self bootstrapped textui colprint str x y for y in range 1 1 int times for x in range 1 1 int number
request from an api and returns response .,staticmethod rate_limited 3 def make_request url response requests get url stream True if response status_code 200 raise APIError response status_code return response
retrieves a rerankerparse object in this sentence by its index .,def __getitem__ self index return self parses index
"decode a base58-encoding string , returning bytes",def decodeBase58 s if not s return n 0 for c in s n 58 if c not in B58_DIGITS raise InvalidBase58Error Character r is not a valid base58 character c digit B58_DIGITS index c n digit h x n if len h 2 h 0 h res binascii unhexlify h encode utf8 pad 0 for c in s 1 if c B58_DIGITS 0 pad 1 else break return x00 pad res
moran 's i ( local ) bivariate ( untested ),def local_bivariate_stat self subquery attr1 attr2 permutations geom_col id_col w_type num_ngbrs params OrderedDict id_col id_col attr1 attr1 attr2 attr2 geom_col geom_col subquery subquery num_ngbrs num_ngbrs result self data_provider get_moran w_type params attr1_vals pu get_attributes result 1 attr2_vals pu get_attributes result 2 weight pu get_weight result w_type num_ngbrs lisa ps esda moran Moran_Local_BV attr1_vals attr2_vals weight permutations permutations lisa_sig quad_position lisa q return zip lisa Is lisa_sig lisa p_sim weight id_order
initialize the effect that should run .,def pre_load self effect_list cfg cls for name cfg in effects effects items if not effect_list raise ValueError settings EFFECTS list is empty No effect to run if self effect_module for effect in effect_list if effect name self effect_module self active_effect effect else self active_effect effect_list 0 if not self active_effect print Cannot find effect format self active_effect print Available effects print n join e name for e in effect_list return False return True
this is a stub that sets up a hard coded set of keybindings . it needs to be replaced with something that parses a config file . patches welcome .,def activate_key_bindings keybinder Ctrl keybinder Control Shift keybinder Shift Alt keybinder Alt Win keybinder Win mod Win keybinder bind_key 0 XF86_AudioLowerVolume mixer intel_vol_down keybinder bind_key mod XF86_AudioLowerVolume mixer vol_down keybinder bind_key mod bracketleft mixer intel_vol_down keybinder bind_key mod Ctrl bracketleft mixer vol_down keybinder bind_key 0 XF86_AudioRaiseVolume mixer intel_vol_up keybinder bind_key mod XF86_AudioRaiseVolume mixer vol_up keybinder bind_key mod bracketright mixer intel_vol_up keybinder bind_key mod Ctrl bracketright mixer vol_up keybinder bind_key 0 XF86_AudioMute mixer intel_vol_mute keybinder bind_key mod XF86_AudioMute mixer vol_mute keybinder bind_key mod backslash mixer intel_vol_mute keybinder bind_key mod Ctrl backslash mixer vol_mute keybinder bind_key 0 XF86_TouchpadToggle trackpad toggle_trackpad keybinder bind_key Shift XF86_TouchpadToggle trackpad toggle_trackpoint keybinder bind_key mod F8 trackpad toggle_trackpad keybinder bind_key mod Shift F8 trackpad toggle_trackpoint keybinder bind_key 0 XF86_AudioPrev music prev keybinder bind_key 0 XF86_AudioPlay music pause keybinder bind_key 0 XF86_AudioPause music pause keybinder bind_key 0 XF86_AudioStop music stop keybinder bind_key 0 XF86_AudioNext music next keybinder bind_key mod z music prev keybinder bind_key mod x music play keybinder bind_key mod c music pause keybinder bind_key mod v music stop keybinder bind_key mod b music next keybinder bind_key mod Up randr raise_brightness keybinder bind_key mod Down randr lower_brightness keybinder bind_key mod Shift Up upower raise_kbd_backlight keybinder bind_key mod Shift Down upower lower_kbd_backlight randr register_xf86_keys keybinder try systemd register_xf86_keys keybinder keybinder bind_key 0 XF86_Launch1 systemd power_button keybinder bind_key 0 XF86_Launch9 systemd power_button except upower register_xf86_keys keybinder consolekit register_xf86_keys keybinder
return the angle between two points ( in radians ),def getAngBetweenNormed self P1 P2 c np dot P1 P2 if c 1 0 c 1 0 elif c 1 0 c 1 0 return np arccos c
"initialize the translator , depending on the state['facility ' ] .",def init_translator state if Facility not in state raise ValueError You need to set the Facility in the configuration elif state Facility lower lcls from backend lcls import LCLSTranslator return LCLSTranslator state elif state Facility lower dummy from backend dummy import DummyTranslator return DummyTranslator state elif state Facility lower flash from backend flash import FLASHTranslator return FLASHTranslator state elif state Facility lower euxfel from backend euxfel import EUxfelTranslator return EUxfelTranslator state else raise ValueError Facility s not supported state Facility
: param value : number of sharps ( between -7 and + 7 ) : return : index in the representation,def get_index self value return value self num_max_sharps 1
"retrieve the title of the related product . if no related product , just return the `` ref `` of this model",def get_product_title self try return self product title except AttributeError return self ref
extra quantities given by the model .,def extra_quantities k a ecc_0 ecc_f f V_0 circular_velocity k a delta_V_ delta_V V_0 ecc_0 ecc_f t_f_ delta_V_ f return delta_V_ t_f_
add an item to the set .,def add self item if not item in self items self items append item
decorator to catch environmenterror ~ s and return sftp error codes instead .,def return_sftp_errors func wraps func def wrapper args kwargs log paramiko util get_logger paramiko name getattr func func_name unknown try log debug s r r enter name args kwargs rc func args kwargs except BaseException as e obj args 0 params args 1 if len args 1 else msg s r from r s name params obj client_address e if isinstance e EnvironmentError log info msg error e errno else log exception unexpected error s msg error errno EIO rc paramiko SFTPServer convert_errno error log debug s returns r name rc return rc return wrapper
toevoegen van extra key / value pair ;,def test04_extra_pair self print test_run4 n path jsontest_config data_path self pipe mappings 0 file_name path test5 csv self pipeline run test_row_count self sor_test patient_hstage 5 test_row_count self dv patient_hub 1 test_row_count self dv patient_sat 4 result get_field_value_from_table jsonb_object_keys extra extra jsonb dwh2a dv patient_sat _runid 0 10 result len result self assertEqual result 4 ik verwachtte dat er 4 keys zouden worden gevonden
define custom axis of the stats_kstest1 ferret pyef,def ferret_custom_axes id axis_defs None pyferret MAX_FERRET_NDIM axis_defs 0 1 2 1 KS P False return axis_defs
return the default location of the bitcoin data directory,def determine_db_dir if platform system Darwin return os path expanduser Library Application Support Bitcoin elif platform system Windows return os path join os environ APPDATA Bitcoin return os path expanduser bitcoin
calls notification callback when needed . : param int notification_id : id of notification which created event . : param int event_id : event id ( one of notificationcenter . event_*. : return : number one .,def _onNotificationEvent self notification_id event_id if notification_id not in self _notifications self logger debug Event fired for non existing notification ID format notification_id return False notification_data self _notifications notification_id if event_id NotificationCenter EVENT_BALLOON_HIDE self _onHideDefault notification_id notification_data elif event_id NotificationCenter EVENT_BALLOON_SHOW self _onShowDefault notification_id notification_data elif event_id NotificationCenter EVENT_BALLOON_CLICK self _onClickDefault notification_id notification_data elif event_id NotificationCenter EVENT_BALLOON_TIMEOUT self _onTimeoutDefault notification_id notification_data return True
do we return the year and month if the day is missing ?,def test_parsing_airing_started_with_year_and_month_only mock_requests mock_requests optional_mock http myanimelist net anime 730 meta data mal_scraper get_anime 730 assert data airing_started date 1994 4 1
we use this method to identify methods and primitives,staticmethod def is_invokable return True
return true is the job is active in the crontab . active means the line is not commented out : param line : : return : true if the job is active,classmethod def _is_job_enable cls line regex re compile test regex match line if test return False return True
convert all nested objects in l to string .,def _to_strings self l if isinstance l list return self _to_strings e for e in l elif isinstance l tuple return tuple self _to_strings e for e in l else return str l
create rows and columns list that can be used to execute api calls .,def create_spreadsheet_values resources languages None if not languages languages resources languages rows id comment default languages is_template len languages 1 and languages 0 _COLUMN_LANGUAGE_ID_TEMPLATE default_strings resources default for string in default_strings sorted_strings row string name string comment string text if is_template row append else for language in languages row append resources language get_string_text string name rows append row for array in default_strings sorted_arrays for index item in enumerate array item_name 0 1 format array name index row item_name item comment item text if is_template row append else for language in languages row append resources language get_array_text array name index rows append row for plural in default_strings sorted_plurals for item in plural sorted_items item_name 0 1 format plural name item quantity row item_name item comment item text if is_template row append else for language in languages row append resources language get_plural_text plural name item quantity rows append row return rows
handles exiting if a timeout alarm is raised,def timeout sig_num frame sys stdout write error input timeout sys exit 1
"completes loging process , must return user instance",handle_http_errors def auth_complete self args kwargs self process_error self data response self request_access_token self ACCESS_TOKEN_URL auth HTTPBasicAuth self get_key_and_secret data self auth_complete_params self validate_state headers self auth_headers method self ACCESS_TOKEN_METHOD self process_error response return self do_auth response access_token response response args kwargs
check if cube 's f2l is solved .,def is_solved self if self cube D Square self cube D colour 3 3 for face in LFRB if self cube get_face face 1 Square self cube face colour 3 2 return False return True return False
return if table has a line with column ( key ) equals to value .,def tab_has_row tab condi select get_select tab condi return np sum select 0
author : airbnb_csirt description : identifies creation of an ami with a non encrypted volume reference : https://amzn.to/2rqilun playbook : ( a ) reach out to the user who created the volume ( b ) set the ami to private,rule logs cloudwatch events req_subkeys detail requestParameters eventName def public_ami rec if rec detail eventName ModifyImageAttribute return False elif rec detail requestParameters is None return False req_params rec detail requestParameters permission_items req_params get launchPermission get add get items for item in permission_items if item group all return True return False
return a loaded and classified payload .,def load_and_classify_payload config service entity raw_record payload load_stream_payload service entity raw_record payload list payload pre_parse 0 classifier StreamClassifier config config classifier load_sources service entity classifier classify_record payload return payload
helper function to return a list of supported api versions,def list_salesforce_api_versions return version 20 0 label Winter 11 url services data v20 0 version 21 0 label Spring 11 url services data v21 0 version 26 0 label Winter 13 url services data v26 0
accepts a python dict and returns it 's json representation .,register simple_tag def dict_to_json pydict return mark_safe json dumps pydict
returns list machines that do n't have a product line tag,def get_offenders connection boto ec2 connect_to_region us west 2 reservations connection get_all_instances return inst for reservation in reservations for inst in reservation instances if inst state running and bool inst tags and bake inst tags hostclass 4 and inst tags get productline in None unknown
deletes a dynamodb table with the specified name,def delete_table dynamodb table wait print _convert_response_to_json_str dynamodb delete_table table wait
recompile output of uncompile back to a code object . source may also be preparsed ast,def recompile source filename mode flags 0 firstlineno 1 privateprefix None if isinstance source ast AST a source else a parse_snippet source filename mode flags firstlineno node a body 0 if not isinstance node ast FunctionDef raise Error Expecting function AST node c0 compile a filename mode flags True for c in c0 co_consts if not isinstance c code continue if c co_name node name and c co_firstlineno node lineno break else raise Error Function body code not found if privateprefix is not None def fixnames names isprivate re compile __ __ match return tuple privateprefix name if isprivate name else name for name in names c code c co_argcount c co_nlocals c co_stacksize c co_flags c co_code c co_consts fixnames c co_names fixnames c co_varnames c co_filename c co_name c co_firstlineno c co_lnotab c co_freevars c co_cellvars return c
some proton apis expect a null terminated string . convert python text types to utf8 to avoid zero bytes introduced by other multi - byte encodings . this method will throw if the string can not be converted .,def unicode2utf8 string if string is None return None elif isinstance string str return string elif isinstance string unicode return string encode utf 8 raise TypeError Unrecognized string type r s string type string
handles the ami ' userevent ' event .,def __on_ami_user_event self ami message if message uniqueid self __monitored_channel return if message userevent StasisStatus return self captured_value message value
handle an event that is generated by a person clicking a button .,def __buttonEvent event global boxRoot __widgetTexts __replyButtonText __replyButtonText __widgetTexts event widget boxRoot quit
deletes an application and all its related assets .,def delete self id return self client delete self _url id
"od.items ( ) - > list of ( key , value ) pairs in od",def items self return key self key for key in self
whether the pos is contained within the obstacle .,def contains_pos self aerial_pos aerial_alt aerial_pos altitude_msl if aerial_alt self cylinder_height return False dist_to_center self gps_position distance_to aerial_pos gps_position return dist_to_center self cylinder_radius
"validate the return value of a function call . if an error occurred , the function will throw a typesafetyerror .",def validate_return_value self retval if self __return_annotation is None return if not self __is_valid retval self __return_annotation func_name self __function __name__ msg self RET_TYPE_ERROR_MESSAGE format func_name self __format_expectation self __return_annotation retval __class__ __name__ raise TypesafetyError msg
invoked by thread associated with phy to pass received packet up .,def phy_rx_callback self ok payload if self verbose print Rx ok r len payload 4d ok len payload if ok os write self tun_fd payload
usage : benchmark.py [ -h ] [ tree_dir ],def main parser optparse OptionParser usage main __doc__ rstrip parser add_option s size action store_true help get size of directory tree while walking parser add_option r real os walk action store_true help use real os walk instead of ctypes emulation options args parser parse_args if args tree_dir args 0 else tree_dir os path join os path dirname __file__ benchtree if not os path exists tree_dir print Creating tree at 0 depth 1 num_dirs 2 num_files 3 format tree_dir DEPTH NUM_DIRS NUM_FILES create_tree tree_dir if options real_os_walk global os_walk os_walk os walk benchmark tree_dir get_size options size
"returns a tuple with a set with users , and num_private_blocks",def _get_subscription_utilisation_status self brl_user_owner admins set self _store read_user brl_user_owner administrators users_granted set user self _store read_user brl_user_owner num_private_blocks 0 for brl_block in user blocks iterkeys perms self _store read_block_permissions brl_block if perms is_private num_private_blocks 1 users_granted perms write perms read return admins union users_granted num_private_blocks
get an available emr cluster to execute a node .,def run_steps self node wait True cluster self get_cluster try cluster run_steps node wait finally self pool put cluster priority cluster
"get a list of track instance for each enabled track in this trackgroup from top to bottom . this means that in the case that a track is soloed , a list containing only that track will be returned . otherwise , only non - muted tracks will be returned .",def enabledTracks self if self hasSoloedTrack return self soloedTrack else return t for t in self iterTracks if not t isMuted
- rack name needs to start with ' nk sidechain ' - macro names needs to start with ' [ sc ] ' - macro names can be changed dynamically with this rack - dev on / off turns sidechain on / off - important note : this will hose undo history since each macro movement is undoable,def setup_device self if self _track has_audio_output if not self _track output_meter_left_has_listener self audio_left_changed self _track add_output_meter_left_listener self audio_left_changed if not self _track output_meter_right_has_listener self audio_right_changed self _track add_output_meter_right_listener self audio_right_changed if self _track has_midi_output and not self _track output_meter_level_has_listener self midi_changed self _track add_output_meter_level_listener self midi_changed
returns data on a specific job .,auto doc groups jobs public home route v2 0 jobs string job_name methods GET DELETE def get_job job_name job models Job query filter_by name job_name all if job if request method DELETE agent_update job_db_delete job_name return jsonify job name job_name status removed else return jsonify job 0 serialize else return jsonify exist False
"commands : a list of pairs containing the following : 1 . name of command ( string , no whitespace ) 2 . method to call ( no arguments ) that returns an argparse parser . if commands contains exactly one member and the name of the only command is none , then we get rid of the whole multi - command thing and just present the options for that one function . description : a long string to present as a description of your script as a whole if the script is run with no arguments",def make_parser commands description if len commands 1 and commands 0 0 None parser commands 0 1 parser set_defaults command else parser argparse ArgumentParser description description usage prog s subcommand add_help False parser add_argument help h action help help argparse SUPPRESS parser add_argument version V action version version __version__ help argparse SUPPRESS subparsers parser add_subparsers title subcommands dest command for cmd_name cmd_parser in commands p subparsers add_parser cmd_name help cmd_parser __doc__ cmd_parser p return parser
"@param tns : a list of target namespaces . @type tns : [ str , ... ]",def __init__ self tns self tns self add tns
"for a bounding sphere at 1,0,0 the right bounding rects are returned",def test_sphere_moved self sphere BoundarySphere radius 2 0 location N r_ 1 0 0 extents sphere bounding_rect_for_plane self at_origin_xy self failUnlessEqual extents 1 0 3 0 2 0 2 0 sqrt_3 N sqrt 3 extents sphere bounding_rect_for_plane self at_origin_yz self failUnlessEqual extents sqrt_3 sqrt_3 sqrt_3 sqrt_3 sqrt_h N sqrt 0 5 sqrt_35 N sqrt 3 5 extents sphere bounding_rect_for_plane self at_origin_slant N testing assert_array_almost_equal extents sqrt_h sqrt_35 sqrt_h sqrt_35 sqrt_35 sqrt_35 decimal 14 extents sphere bounding_rect_for_plane self parallel_xy self failUnlessEqual extents 1 sqrt_3 1 sqrt_3 sqrt_3 sqrt_3 extents sphere bounding_rect_for_plane self parallel_yz self failUnlessEqual extents 2 0 2 0 2 0 2 0 Reff N sqrt 4 1 N sqrt 0 5 2 extents sphere bounding_rect_for_plane self parallel_slanted N testing assert_array_almost_equal extents sqrt_h Reff sqrt_h Reff Reff Reff
executes the pcs ping command .,def pinger host n proc os popen ping 0 1 2 format ping_flag n host return join proc readlines
: param weight : the weight on the positive examples between 0 and 1 ( the negative weight is 1-weight ) : type weight : : class:`float `,def setWeight self weight Parameter checkFloat weight 0 0 1 0 self weight weight
return the norm of the weight vector .,def weightNorm self v numpy squeeze self model dual_coef_ SV self model support_vectors_ if self kernel linear K sklearn metrics pairwise linear_kernel SV SV elif self kernel poly K sklearn metrics pairwise poly_kernel SV SV self getDegree elif self kernel rbf K sklearn metrics pairwise rbf_kernel SV SV self getGamma else raise ValueError Unknown kernel self kernel return numpy sqrt v T dot K dot v
generates midi messages that unmute a channel or mute group .,def generateMuteGroupOff groupNote return bytearray 144 config QU_MIDI_CH 1 groupNote 64 1 128 config QU_MIDI_CH 1 groupNote 0
return a file object that is also a context manager .,def open_object self mode raise NotImplementedError by object r self
in complete graphs each node is a dominating set . thus the dominating set has to be of cardinality 1 .,def test_complete K4 nx complete_graph 4 assert_equal len nx dominating_set K4 1 K5 nx complete_graph 5 assert_equal len nx dominating_set K5 1
tests that a node is always reachable from itself .,def test_same_node_is_reachable self G DiGraph sorted p for p in combinations range 10 2 assert_true all is_reachable G v v for v in G
manage message of different type and in the context of path,def add_message self msg_id location msg module obj line col_offset location 1 if module not in self _modules if module self writeln Module s module self _modules module 1 else self writeln s module if obj obj s obj if self include_ids sigle msg_id else sigle msg_id 0 self writeln s 3s s s s sigle line col_offset obj msg
"normalizes m to be in range [ 0 , 1 ] .",def _normalize M minVal np min M maxVal np max M Mn M minVal if maxVal minVal return np zeros M shape else return Mn maxVal minVal
"returns the true positive , true negative , false positive , false negative classification counts ( in this order ) .",def countClassifications self classname tp self matrix get classname get classname 0 classes list self matrix keys fp 0 for c in classes if c classname fp self getMatrixEntry classname c fn 0 for c in classes if c classname fn self getMatrixEntry c classname tn 0 for c in classes if c classname for c2 in classes if c2 classname tn self getMatrixEntry c c2 assert sum tp tn fp fn self instanceCount return tp tn fp fn
is less than y or greater than z,staticmethod def not_between_or_equal_to y z return are between_or_equal_to y z
add cve_id field to all osvdb entries,def _map_osvdb_to_cve results db osvdb aggregate unwind ext_references match ext_references type CVE ID project CVE_ID ext_references value group _id _id CVE_ID addToSet CVE_ID for entry in results result db osvdb update _id entry _id set CVE_ID entry CVE_ID logger info Adding CVEs to format entry _id
truncates the history up to given commandnumber,def truncateto self commandnumber keytuples self pvalues keys allkeys sorted keytuples key lambda keytuple keytuple 0 lastkey allkeys 0 0 candelete True for cmdno proposal in allkeys if cmdno lastkey lastkey 1 else candelete False break if not candelete return False for cmdno proposal in allkeys if cmdno commandnumber del self pvalues cmdno proposal return True
queue a poisin pill so that anyone waiting on a call to next will wake up,def poisinPill self call version 1 0 method poisinPill args stop_msg APIMagiMessage contenttype APIMagiMessage YAML data yaml safe_dump call self inqueue put stop_msg
"get a locationlists object representing the .debug_loc section of the dwarf data , or none if this section does n't exist .",def location_lists self if self debug_loc_sec return LocationLists self debug_loc_sec stream self structs else return None
display the ca chain as png .,login_required def pki_chain request model id if PKI_ENABLE_GRAPHVIZ is not True messages warning request Chain view is disabled unless setting PKI_ENABLE_GRAPHVIZ is set to True return HttpResponseRedirect urlresolvers reverse admin pki_ s_changelist model if model certificateauthority obj get_object_or_404 CertificateAuthority pk id elif model certificate obj get_object_or_404 Certificate pk id png generate_temp_file ObjectChain obj png try if os path exists png f open png x f read f close os remove png except OSError as e logger error Failed to load depency tree s e raise Exception e response HttpResponse x mimetype image png return response
"reads a text string and "" inflates "" it by creating chiplotle - hpgl class instances of the found hpgl commands .",def inflate_hpgl_string string filter_commands None filter_commands filter_commands or if not isinstance string type abc raise TypeError string must be a string if not isinstance filter_commands list tuple msg filter_commands must be a list of string HPGL commands raise TypeError msg _unsupported_commands PW PC LA WU BP comms parse_hpgl_string string result for c in comms if c head c 0 2 if head in filter_commands continue if head in _unsupported_commands continue command inflate_hpgl_string_command c result append command return result
return lhost for empire 's native listener from host value,def host2lhost s reg 25 0 5 2 0 4 0 9 01 0 9 0 9 3 25 0 5 2 0 4 0 9 01 0 9 0 9 res re findall reg s return res 0 if len res 1 else 0 0 0 0
initializes some basic info about the plugin and the use environment internal use only .,def _init self self info update name self plugin __class__ __name__ creator self plugin creator module self plugin __class__ __module__ filepath inspect getfile self plugin __class__ id self id application env application self info update env machineInfo
"for single - object resources , fetch the object 's data . for collections , fetch all of the objects .",base apimethod def get self cursor None per_page None params base get_params cursor per_page locals request http Request GET self get_url params return request parsers parse_xml
"terminate a subsciription , removing any stored billing information .",base apimethod def terminate self refund None self require_item url 0 terminate format self get_url params refund refund if refund else none url url http urlencode_any params request http Request PUT url return request parsers parse_empty
fetch all of the objects .,base apimethod def get self total_count False limit None ending_before None starting_after None params base get_params None locals params pop total_count None if total_count params update include total_count request http Request GET self get_url params return request parsers parse_json
parse the oap notification data and return a oapnotif object .,def parse_oap_notif data index 0 result None notif_type data index index 1 if notif_type NOTIFTYPE_SAMPLE tag l channel OAPMessage parse_tlv data index if tag TAG_ADDRESS raise ValueError invalid notification data expected address tag index 2 l secs usecs struct unpack_from ql data index 1 index 12 rate struct unpack_from l data index 0 index 4 num_samples int data index index 1 sample_size int data index index 1 if channel TEMP_ADDRESS result OAPTempSample result packet_timestamp secs usecs result rate rate result num_samples num_samples result sample_size sample_size for i in range num_samples temp struct unpack h data index index 2 0 index 2 result samples append temp else result OAPSample result packet_timestamp secs usecs result rate rate result num_samples num_samples result sample_size sample_size result samples bit_index 0 for i in range num_samples sample_data OAPMessage read_bits data index bit_index sample_size result samples append sample_data elif notif_type NOTIFTYPE_STATS tag l channel OAPMessage parse_tlv data index if tag TAG_ADDRESS raise ValueError invalid notification data expected address tag index 2 l secs usecs struct unpack_from ql data index 1 index 12 rate struct unpack_from l data index 0 index 4 num_samples int data index index 1 sample_size int data index index 1 result OAPAnalogStats result packet_timestamp secs usecs elif notif_type NOTIFTYPE_DIG raise NotImplementedError parsing digital OAP notification raise NotImplementedError filling digital OAP result structure elif notif_type NOTIFTYPE_LOCATEME raise NotImplementedError parsing locateMe OAP notification raise NotImplementedError filling locateMe OAP result structure elif notif_type 4 tag l channel OAPMessage parse_tlv data index if tag 255 raise ValueError invalid notification data expected address tag index 2 l pid struct unpack_from l data index 0 index 4 startPid struct unpack_from l data index 0 index 4 numPackets struct unpack_from l data index 0 index 4 payload data index result OAPpkGenPacket result pid pid result startPid startPid result numPackets numPackets result payload payload if result result raw_data data result channel channel result received_timestamp datetime datetime now return result
return a relative version of a path,def relpath path start curdir if not path raise ValueError no path specified start_list abspath start split sep path_list abspath path split sep i len commonprefix start_list path_list rel_list pardir len start_list i path_list i if not rel_list return curdir return join rel_list
request the course info tab .,task 10 def info self self get info name courseware course_info
create a new dictionary that corresponds to the union of all of the contexts that have been entered but not exited at this point .,def resolve_context self merged dict for context in self located_context values merged update context return merged
"coerce buffer data for an adjustedarray into a standard scalar representation , returning the coerced array and a dict of argument to pass to np.view to use when providing a user - facing view of the underlying data .",def _normalize_array data missing_value if isinstance data LabelArray return data data_dtype data dtype if data_dtype bool_ return data astype uint8 dtype dtype bool_ elif data_dtype in FLOAT_DTYPES return data astype float64 dtype dtype float64 elif data_dtype in INT_DTYPES return data astype int64 dtype dtype int64 elif is_categorical data_dtype if not isinstance missing_value LabelArray SUPPORTED_SCALAR_TYPES raise TypeError Invalid missing_value for categorical array Expected None bytes or unicode Got r missing_value return LabelArray data missing_value elif data_dtype kind M try outarray data astype datetime64 ns view int64 return outarray dtype datetime64ns_dtype except OverflowError raise ValueError AdjustedArray received a datetime array not representable as datetime64 ns Min Date s Max Date s data min data max else raise TypeError Don t know how to construct AdjustedArray on data of type s data_dtype
get the visible state of the proxied object .,def get_visible self return self proxied visible
sets the class name of the object .,def _set_class_name self class_name self _class_name class_name return
copies this file / folder .,def copy self destination if not isinstance destination File destination File destination if self is_folder shutil copytree self path destination path elif self is_file shutil copyfile self path destination path return
"coerce the input ' val ' from a string into a value suitable for the type described by the implementor . if coercion fails , coerce should raise inputerror with a suitable error message to be shown to the user . ' configurable ' is the configurable object in whose context the coercion is taking place .",def coerce self val configurable
populate instance with default attributes .,def createDefaultAttributes self for attr in self rowColumns if getKeyColumn self __class__ attr continue for column ctype typeid in self dbColumns if column lower column attr lower q dbTypeMap get ctype None if q NOQUOTE setattr self attr 0 else setattr self attr
pre - failure manhole representation of exceptions .,def _failureOldStyle fail import linecache tb for f in fail frames tb append f 1 f 2 f 0 linecache getline f 1 f 2 return traceback tb exception traceback format_exception_only fail type fail value
"pass in array of json objects , a dictionary with key / value pairs to match against , and another dictionary with expected key / value pairs .",def check_array_result object_array to_match expected num_matched 0 for item in object_array all_match True for key value in to_match items if item key value all_match False if not all_match continue for key value in expected items if item key value raise AssertionError s expected s s str item str key str value num_matched num_matched 1 if num_matched 0 raise AssertionError No objects matched s str to_match
get only one field from model .,def test_get_field self field_name self field_controller _get_field self model name self assertTrue isinstance field_name models Field self assertEqual field_name model self model
reset the io watcher ; retry as necessary,def _reset_io_watcher self self _io_watcher stop retries 0 while True try self _io_watcher set self _io_watcher fd self _PIKA_TO_LIBEV_ARRAY self event_state break except if retries 5 raise self _io_watcher stop retries 1 self _io_watcher start
deploy formulas in the seasoning file,def deploy self self loadseasoning for key in self config print Deploying key formula self cloneformula key self config key reponame self config key url self config key branch
returns the equilibrium magnetization vector .,def compute_nz_eq pb mag_eq zeros 6 1 mag_eq 2 0 1 0 pb mag_eq 5 0 pb return mag_eq
get the value of a single policy,def ca_get_hsm_policy_setting slot policy_id slot_id CK_SLOT_ID slot pol_id CK_ULONG policy_id pol_val CK_ULONG ret CA_GetHSMPolicySetting slot_id pol_id pointer pol_val return ret pol_val value
initialize problem for explicit time integration .,def initialize self dimension normalizer logEvent sinit self _loggingPrefix self _eventLogger eventBegin logEvent from pylith mpi Communicator import mpi_comm_world comm mpi_comm_world self _initialize dimension normalizer if 0 comm rank self _info log Creating other fields self fields add disp t dt displacement self fields add velocity t velocity self fields add acceleration t acceleration self fields copyLayout dispIncr t t dt self _debug log resourceUsageString dispTmdt self fields get disp t dt dispTmdt zeroAll dispT self fields get disp t dispT zeroAll residual self fields get residual residual zeroAll residual createScatter residual mesh lengthScale normalizer lengthScale timeScale normalizer timeScale velocityScale lengthScale timeScale velocityT self fields get velocity t velocityT scale velocityScale value velocityT zeroAll accelerationScale velocityScale timeScale accelerationT self fields get acceleration t accelerationT scale accelerationScale value accelerationT zeroAll self _debug log resourceUsageString if 0 comm rank self _info log Creating lumped Jacobian matrix from pylith topology Field import Field jacobian Field self mesh jacobian label jacobian pressureScale normalizer pressureScale jacobian subfieldAdd displacement dimension jacobian VECTOR lengthScale value jacobian subfieldAdd lagrange_multiplier dimension jacobian VECTOR pressureScale value jacobian subfieldsSetup jacobian setupSolnChart jacobian setupSolnDof dimension for integrator in self integrators integrator setupSolnDof jacobian jacobian vectorFieldType jacobian VECTOR jacobian allocate jacobian zeroAll self jacobian jacobian self _debug log resourceUsageString if 0 comm rank self _info log Initializing solver self solver initialize self fields self jacobian self self _debug log resourceUsageString self _eventLogger eventEnd logEvent return
load the devices and services that can be discovered .,def _load_device_support self self discoverables for device_name in self whitelist module_name netdisco discoverables format device_name module importlib import_module module_name self discoverables device_name module Discoverable self
create a track object from a file - like object .,def track_from_file file_object filetype try hash hashlib md5 file_object read hexdigest return track_from_md5 hash except util EchoNestAPIError file_object seek 0 return _track_from_string file_object read filetype
returns the flow ring corresponding to the given flow id,def get_flow_ring self flow_id pcie_obj self bcmclient get_pcie_obj obj_addr self client read64 pcie_obj flow_id QWORD_SIZE FLOW_RINGS_OFFSET if obj_addr 0 return None return AppleBCMWLANPCIeSubmissionRing self client obj_addr flow_id NUM_D2H_RINGS
creates an init_fn for slim.learning.train .,def model_init_function model num_classes checkpoint_path if checkpoint_path model_default checkpoint_path model pretrained_model_path if checkpoint_path logging info Initializing model from checkpoint at s checkpoint_path return model initialize_from_checkpoint checkpoint_path num_classes is_training True else logging info Initializing model with random parameters return None
print org groups with related counts of users .,def PrintOrgCounts orgs_by_active orgs_by_ou print report_utils BORDER print join _REPORT_BY_ACTIVE_HEADER for active suspended org in orgs_by_active print d d s active suspended org print report_utils BORDER print join _REPORT_BY_ORG_HEADER for org active suspended in orgs_by_ou print s d d org active suspended print report_utils BORDER
return true iff self and other are equivalent,def __eq__ self other if not other return False if id self id other return True for k in self keys union other keys if self k other k return False return True
sets up and tears down a server and login,def test_ServerSetup_and_login self run_client_command server info returnZero False login_client run_client_command server info expectstdout Server id s s
"set an input connection , possibly replacing an existing input connection with that input name .",def addInputConnection self conn isDst if isDst for iconn in self inputConns same True if iconn isDstExternal same False if same iconnSub iconn getDstItemList connSub conn getDstItemList for i in xrange min len iconnSub len connSub if iconnSub i connSub i same False break if same raise InstanceError s New input for connection to s equal to existing connnection s self name conn dstString iconn dstString self inputConns append conn
called to explicitely fixup an associated ip header,def adjust_ip self ip None if ip None and ip haslayer IP if self type 17 if self gaddr 0 0 0 0 ip dst 224 0 0 1 retCode True elif isValidMCAddr self gaddr ip dst self gaddr retCode True else print Warning Using invalid Group Address retCode False elif self type 23 and isValidMCAddr self gaddr ip dst 224 0 0 2 retCode True elif self type 18 or self type 22 and isValidMCAddr self gaddr ip dst self gaddr retCode True else print Warning Using invalid IGMP Type retCode False else print Warning No IGMP Group Address set retCode False if retCode True ip ttl 1 ip options IPOption_Router_Alert return retCode
generate a dataset and a set of authors with fields set to the given values .,def create_authors_with_values self field_name values dataset None if dataset is None dataset corpus_models Dataset objects create name Test author name distribution description Created by test_author_name_distribution for value in values corpus_models Person objects create dataset dataset field_name value return dataset
configure and return the wsgi app .,def app config pyramid config Configurator settings settings config add_static_view name static path static config include pyramid_jinja2 config registry settings jinja2 filters static_path pyramid_jinja2 filters static_path_filter static_url pyramid_jinja2 filters static_url_filter config include bouncer search config include bouncer views config include bouncer sentry return config make_wsgi_app
returns the 0-based current column . do not access the currentcolumn in vim.current.line . it does n't exist yet when the cursor is at the end of the line . only the chars before the current column exist in vim.current.line .,def CurrentColumn return vim current window cursor 1
test that hensonclidirective.prepare_autoprogram does n't change prog .,def test_hensonclidirective_doesnt_change_prog test_directive test_directive options prog testing test_directive prepare_autoprogram assert test_directive options prog testing
test writing a worksheet with no cell data .,def test_assemble_xml_file self self maxDiff None fh StringIO worksheet Worksheet worksheet _set_filehandle fh worksheet select worksheet name Sheet1 worksheet excel_version 2010 data 2 2 3 1 0 worksheet write_row A1 data worksheet add_sparkline F1 location F 1 range A 1 E 1 type win_loss worksheet _assemble_xml_file exp _xml_to_list xml version 1 0 encoding UTF 8 standalone yes worksheet xmlns http schemas openxmlformats org spreadsheetml 2006 main xmlns r http schemas openxmlformats org officeDocument 2006 relationships xmlns mc http schemas openxmlformats org markup compatibility 2006 xmlns x14ac http schemas microsoft com office spreadsheetml 2009 9 ac mc Ignorable x14ac dimension ref A1 E1 sheetViews sheetView tabSelected 1 workbookViewId 0 sheetViews sheetFormatPr defaultRowHeight 15 x14ac dyDescent 0 25 sheetData row r 1 spans 1 5 x14ac dyDescent 0 25 c r A1 v 2 v c c r B1 v 2 v c c r C1 v 3 v c c r D1 v 1 v c c r E1 v 0 v c row sheetData pageMargins left 0 7 right 0 7 top 0 75 bottom 0 75 header 0 3 footer 0 3 extLst ext xmlns x14 http schemas microsoft com office spreadsheetml 2009 9 main uri 05C60535 1F16 4fd2 B633 F4F36F0B64E0 x14 sparklineGroups xmlns xm http schemas microsoft com office excel 2006 main x14 sparklineGroup type stacked displayEmptyCellsAs gap x14 colorSeries theme 4 tint 0 499984740745262 x14 colorNegative theme 5 x14 colorAxis rgb FF000000 x14 colorMarkers theme 4 tint 0 499984740745262 x14 colorFirst theme 4 tint 0 39997558519241921 x14 colorLast theme 4 tint 0 39997558519241921 x14 colorHigh theme 4 x14 colorLow theme 4 x14 sparklines x14 sparkline xm f Sheet1 A1 E1 xm f xm sqref F1 xm sqref x14 sparkline x14 sparklines x14 sparklineGroup x14 sparklineGroups ext extLst worksheet got _xml_to_list fh getvalue self assertEqual got exp
test the creation of an xlsxwriter file with chart formatting .,def test_create_file self filename self got_filename workbook Workbook filename worksheet workbook add_worksheet chart workbook add_chart type column chart axis_ids 46175744 46319488 data 1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 worksheet write_column A1 data 0 worksheet write_column B1 data 1 worksheet write_column C1 data 2 chart add_series categories Sheet1 A 1 A 5 values Sheet1 B 1 B 5 fill color FF0000 chart add_series categories Sheet1 A 1 A 5 values Sheet1 C 1 C 5 worksheet insert_chart E9 chart workbook close got exp _compare_xlsx_files self got_filename self exp_filename self ignore_files self ignore_elements self assertEqual got exp
test the _ write_sheet_views ( ) method,def test_write_sheet_views_zoom_200 self self worksheet select self worksheet set_zoom 200 self worksheet _write_sheet_views exp sheetViews sheetView tabSelected 1 zoomScale 200 zoomScaleNormal 200 workbookViewId 0 sheetViews got self fh getvalue self assertEqual got exp
this returns primordial abundance fractions .,def primordial self self symbols np hstack self elements self fractions np zeros len self symbols self fractions np where self symbols H 0 76 self fractions np where self symbols He 0 24
"makes one gradient step , using a naive or an l - bfgs scheme .",def training_step self Xt iteration 1 progress 0 if self is_current_cost_computed C grad self current_cost_grad self is_current_point_computed False else C grad self cost_gradient self current_state Xt iteration progress search_dir self descent_direction grad step exit_code self line_search search_dir C grad Xt iteration progress frames self display_iteration display_shoots iteration 10 1 or progress 0 95 display_transports iteration 10 1 or progress 0 95 self update_iHessian step grad return C step frames exit_code
"compares "" modified "" timestamps against the "" compiled "" dict , calls compiler if necessary .",def _watch_folder folder destination compiler_args for dirpath dirnames filenames in os walk folder for filename in filenames if watched_extension filename and not filename startswith fullpath os path join dirpath filename subfolder os path relpath dirpath folder mtime os stat fullpath st_mtime compiled_folder os path join destination subfolder if not os path exists compiled_folder os makedirs compiled_folder compiled_path _compiled_path compiled_folder filename if not fullpath in compiled or compiled fullpath mtime or not os path isfile compiled_path compile_file fullpath compiled_path compiler_args compiled fullpath mtime
test getting the arguments from a fancy py3k function,requires_python_3 def test_function_decl_3 self code def foo a b c d e f pass parsed ast FunctionDecl code exception_kwargs eq_ parsed funcname foo eq_ parsed argnames a b c eq_ parsed kwargnames d e f
refresh the analysis tab with the latest information .,user_passes_test user_can_view_data def refresh_services request crits_type identifier response sources user_sources request user username klass class_from_type crits_type if not klass msg Could not find object to refresh response success False response html msg return HttpResponse json dumps response mimetype application json if hasattr klass source obj klass objects id identifier source__name__in sources first else obj klass objects id identifier first if not obj msg Could not find object to refresh response success False response html msg return HttpResponse json dumps response mimetype application json results AnalysisResult objects object_type crits_type object_id identifier relationship type crits_type value identifier url_key obj get_url_key subscription type crits_type id identifier service_list get_supported_services crits_type response success True response html render_to_string services_analysis_listing html relationship relationship subscription subscription service_results results crits_type crits_type identifier identifier service_list service_list RequestContext request return HttpResponse json dumps response mimetype application json
test encrypt - noisy - sum without randomness .,def test_without_randomness self clients DLPAClient port self port for _ in range 2 cks c get_key i for i c in enumerate clients slots def requester c ck client_id value Send a request in another thread slot c encrypt_noisy_sum ck client_id value 0 rand np array 0 for _ in range 5 slots append slot threads for i c key in enumerate zip clients cks t threading Thread target requester args c key i i 1 t start threads append t for t in threads t join self assertEqual len slots 2 self assertEqual slots 0 slots 1 res self servicer encrypt_noisy_sum result slots 0 sum_of_values 1 2 2 2 self assertEqual res sum_of_values
common denominator among several names . loose enforcment,def common_loose vals if not isinstance vals tuple list or isinstance vals 0 int vals vals vals list vals for i in range len vals if isinstance vals i str continue if isinstance vals i 0 int vals i get_name vals i vals set vals if len vals 1 return vals pop vals discard TYPE if len vals 1 return vals pop for other in others vals discard other if len vals 0 return TYPE elif len vals 1 return vals pop dims_ map get_dim vals if dims_ dim max dims_ else return TYPE if dim 2 and 1 in dims_ dim 3 types map get_mem vals type max types val get_name dim type return val
"brings angle into range of arctan2 ( normally -180 , 180 )",def angmod a ar np radians a return np degrees np arctan2 np sin ar np cos ar
read a line of data from the gnutls process .,def starttls_readline gnutls verbose while True data gnutls stdout readline if not data raise StartTLSError Unexpected EOF from gnutls cli match _RE_SENT match data if not match break match _RE_RECEIVED match data if match data data match end if verbose 3 print Read r format data return data
split a string both by commas and whitespice . returns a list .,def split_by_comma_and_whitespace cstr return re split s cstr
simple test to make sure that you do n't get a 500 error when the modal is enabled .,def test_simple_test self url reverse info args self course id to_deprecated_string resp self client get url self assertEqual resp status_code 200
update a user 's profile .,intercept_errors ProfileInternalError ignore_errors ProfileRequestError def update_profile username full_name None try profile UserProfile objects get user__username username except UserProfile DoesNotExist raise ProfileUserNotFound if full_name is not None name_length len full_name if name_length FULL_NAME_MAX_LENGTH or name_length 0 raise ProfileInvalidField full_name full_name else profile update_name full_name
"validate empty values , otherwise defer to the parent",def run_validators self value if value is self Empty return return super CourseKeyField self run_validators value
creates an instructor for the test course .,def create_instructor self username email None return self _create_user username email is_staff True
asserts the frequency limit on how often we can change passwords,patch dict django conf settings ADVANCED_SECURITY_CONFIG MIN_TIME_IN_DAYS_BETWEEN_ALLOWED_RESETS 1 def test_password_reset_frequency_limit self staff_email _ self _setup_user is_staff True success_msg Your Password Reset is Complete user User objects get email staff_email token default_token_generator make_token user uidb36 int_to_base36 user id resp self client post password_reset_confirm 0 1 format uidb36 token new_password1 foo new_password2 foo follow True self assertNotIn success_msg resp content staff_reset_time timezone now timedelta days 1 with freeze_time staff_reset_time user User objects get email staff_email token default_token_generator make_token user uidb36 int_to_base36 user id resp self client post password_reset_confirm 0 1 format uidb36 token new_password1 foo new_password2 foo follow True self assertIn success_msg resp content
"parse version to major , minor , patch , pre - release , build parts .",def parse version match _REGEX match version if match is None raise ValueError s is not valid SemVer string version version_parts match groupdict version_parts major int version_parts major version_parts minor int version_parts minor version_parts patch int version_parts patch return version_parts
create a : class : ` ~designer.components.playground_size_selector . playgroundsizeview ` for the current playground .,def on_playground self _ self view PlaygroundSizeView selected_size self playground size self view bind selected_size self _update_playground self view bind selected_size_name self setter text self text self view selected_size_name
detects all cycles of smallest size for a given graph .,def get_minimal_cycles graph nodes list graph found set for i in range 3 len graph for node in nodes for path in _iter_paths graph node i if path 0 in graph path 1 found add _canonical path if found break return found
profiles should delegate the read permission check to their parent know me user .,mock patch know_me models KMUser has_object_read_permission def test_has_object_read_permission mock_parent_permission api_rf profile_factory profile profile_factory request api_rf get expected mock_parent_permission return_value assert profile has_object_read_permission request expected assert mock_parent_permission call_count 1 assert mock_parent_permission call_args 0 request
generate a bar chart of passes versus fails .,def generatePassFail self path img pass_fail png yesterday datetime now timedelta hours 24 passes self events find time_stamp gt yesterday event success count fails self events find time_stamp gt yesterday event fail count width 1 0 fig ax plt subplots rects1 ax bar 1 passes width 1 color g rects2 ax bar 3 fails width 1 color r ax set_ylabel Scores Today ax set_title Test Performance ax set_xticks 1 5 3 5 ax set_xticklabels pass fail plt xlim 0 5 ax legend PASS FAIL plt grid plt savefig path plt close
converts json to html table format .,def convert json_input build_direction LEFT_TO_RIGHT table_attributes None json_converter JsonConverter build_direction build_direction table_attributes table_attributes return json_converter convert json_input
"return the best address , if any .",property def address self if self addresses return self addresses 0 else return None
return the value of a partial length byte .,def partial2int s return 1 ord s 31
filter to turn email addresses into html entity encoded mailto links .,register filter needs_autoescape True stringfilter def anti_spamize email autoescape True esc make_escape_function autoescape def encode value return join x x format ord char for char in value result a href link text a format link encode mailto format esc email text encode esc email return mark_safe result
convert an integral energy flux into the corresponding power - law normalization .,def int_eflux2pl_norm integral emin emax index erg True if erg integral erg2keV integral return pl_norm integral emin emax index 1 0
returns true if the database has been setup ( contains tables ),def exists meta MetaData engine meta reflect return bool meta tables
"sorry for the long title , hopefully self explanatory though :)",def remove_duplicate_variants_from_gene_stream gene_stream for gene variant_list in gene_stream yield gene list v 0 for _ v in itertools groupby variant_list key lambda variant str variant xpos variant ref variant alt
maps the input data through the transformer to correspondingly shaped output data array / list .,def transform self X if isinstance X np ndarray if X ndim 2 mapped self _transform_array X return mapped else raise TypeError Input has the wrong shape s with i dimensions Expecting a matrix 2 dimensions str X shape X ndim elif isinstance X list tuple out for x in X mapped self _transform_array x out append mapped return out else raise TypeError Input has the wrong type s Either accepting numpy arrays of dimension 2 or lists of such arrays str type X
setup the class to resonable defaults .,def __init__ self max_running comms_queue self _queued self _running self _completed self _num_of_jobs 0 self _max max_running self _comms_queue comms_queue self _finished False self _closed False self _debug False
return the shape of the table `` name `` .,def get_shape cursor name cursor execute select from s name inds cursor description 1 0 1 split _ return tuple int i for i in inds
calculate the error rate of the algorithm over the given sample .,def errorrate sample p Freq for v in voices sample cs harmonize list sample notes v sample key v 1 for c c1 in zip sample chords cs p c c1 1 return p True False
initialize a new scenario for use with molecule .,click command click pass_context click option dependency name type click Choice galaxy default galaxy help Name of dependency to initialize galaxy click option driver name d type click Choice config molecule_drivers default docker help Name of driver to initialize docker click option lint name type click Choice yamllint default yamllint help Name of lint to initialize ansible lint click option provisioner name type click Choice ansible default ansible help Name of provisioner to initialize ansible click option role name r required True callback _role_exists help Name of the role to create click option scenario name s default command_base MOLECULE_DEFAULT_SCENARIO_NAME required True callback _default_scenario_exists help Name of the scenario to create format command_base MOLECULE_DEFAULT_SCENARIO_NAME click option verifier name type click Choice config molecule_verifiers default testinfra help Name of verifier to initialize testinfra def scenario ctx dependency_name driver_name lint_name provisioner_name role_name scenario_name verifier_name command_args dependency_name dependency_name driver_name driver_name lint_name lint_name provisioner_name provisioner_name role_name role_name scenario_name scenario_name subcommand __name__ verifier_name verifier_name if verifier_name inspec command_args verifier_lint_name rubocop if verifier_name goss command_args verifier_lint_name yamllint s Scenario command_args s execute
add builders and construction variables for gnulink to an environment .,def generate env link generate env if env PLATFORM hpux env SHLINKFLAGS SCons Util CLVar LINKFLAGS shared fPIC env Append LINKFLAGS __RPATH env RPATHPREFIX Wl rpath env RPATHSUFFIX env _RPATH _concat RPATHPREFIX RPATH RPATHSUFFIX __env__
test shouldchange method of old style classes,def test_oldstyleclass_shouldchange self mmm Oldstyleclass self assertEqual mmm shouldchange 24 24 failed to change the internal val in shouldchange method of old style class
try reading a realistic data structure,def test_read_events self inputter InputCppRootData InputCppRootData inputter birth json dumps input_root_file_name self fname selected_spills self __test_event inputter maus_event_type Spill run_number 10 spill_number 1 self __test_event inputter maus_event_type Spill run_number 10 spill_number 2 self __test_event inputter maus_event_type Spill run_number 10 spill_number 3 self __test_event inputter maus_event_type Spill run_number 10 spill_number 4 self __test_event inputter maus_event_type Spill run_number 10 spill_number 5 self __test_event inputter maus_event_type Spill run_number 10 spill_number 6 self __test_event inputter maus_event_type Spill run_number 10 spill_number 7 self __test_event inputter maus_event_type Spill run_number 10 spill_number 8 self __test_event inputter maus_event_type Spill run_number 10 spill_number 9 self __test_event inputter maus_event_type Spill run_number 10 spill_number 10 self __test_event inputter maus_event_type Spill run_number 11 spill_number 1 self __test_event inputter maus_event_type Spill run_number 11 spill_number 2 self __test_event inputter maus_event_type Spill run_number 12 spill_number 1 self __test_event inputter maus_event_type Spill run_number 12 spill_number 2 try inputter emitter next self assertTrue False msg Should have raised StopIteration except StopIteration pass
create a dictionary linking the channel i d with the scifi hits in that channel,def make_hits_map self mc_evt self hits_map hits mc_evt GetSciFiHits for hit in hits channel_id int hit GetChannelId GetID if not channel_id in self hits_map self hits_map channel_id hit else self hits_map channel_id append hit
"invoke "" death "" . @param self object reference .",def tearDown self success self __reducer death if not success raise Exception Test setUp failed reducer death failed
loads a module by filename and path . returns module object,def load_module name path u n Loads a module by filename and path Returns module object n n name Filename without py n path A list of dirs to search n try fname pathname description imp find_module name path loaded_mod imp load_module name fname pathname description except Exception as e loaded_mod None print e return loaded_mod
"one free text part , two keywords",def test_basic self keywords to from q Peter something to AAa aa from Foo bar s params split_search q keywords self assertEqual s Peter something self assertEqual params to AAa aa from Foo bar
switch between treeherder and perfherder using header dropdown,def test_switch_app base_url selenium test_repository page Treeherder selenium base_url open assert page header active_app Treeherder page page switch_to_perfherder assert page header active_app Perfherder page page switch_to_treeherder assert page header active_app Treeherder
retry creating the influxdb database in case of a connection error,patch time sleep return_value None def test_create_database self _ reader DummyReader bar self config buffer_size writer_with_connection_error Mock writer_with_connection_error create_database Mock side_effect ConnectionError None client Worker reader self encoder writer_with_connection_error self config client consume self assertEqual writer_with_connection_error create_database call_count 2
compute the baseline and result image directories for testing * func*. create the result directory if it does n't exist .,def _image_directories result_dir os path join basedir testresult baseline_dir os path join basedir baseline if not os path exists result_dir cbook mkdirs result_dir return baseline_dir result_dir
helper function to read the generated svg again .,def load path doc minidom parse path doc normalize return doc documentElement
create a uniform grid sampling pattern,def __init__ self center max_bounds spacing ApertureSampler __init__ self center max_bounds self spacing tuple spacing self center center u_min int self max_bounds 0 self spacing 0 0 5 self spacing 0 v_min int self max_bounds 2 self spacing 1 0 5 self spacing 1 u_num int self max_bounds 1 self max_bounds 0 self spacing 0 v_num int self max_bounds 3 self max_bounds 2 self spacing 1 cur_center_u u_num 1 0 5 self spacing 0 u_min cur_center_v v_num 1 0 5 self spacing 1 v_min u_min u_min self center 0 cur_center_u v_min v_min self center 1 cur_center_v u_samples u self spacing 0 u_min for u in range u_num v_samples v self spacing 0 v_min for v in range v_num self weight 1 0 u_num v_num u_rep u for u in u_samples for i in range v_num v_rep v_samples u_num self uv_samples zip u_rep v_rep
poke a client with the specified message,def clientpoke self clid message response self send_command clientpoke keys clid clid msg message return response is_successful
paired space / unpaired time normalized mean peak error ( % ),def PSUTNMPE obs mod axis None return NMPE obs mod paxis 0 axis None
"after lexer , before parser .",def GenClassParser name n pass
"do a call to the webservice , returns a dict parsed from the json returned by the webserver .",def do_call self uri try request requests get http self __host uri timeout 15 0 return json loads request text except Exception as exception print Exception during Gateway call exception return None
generate asymmetric keys based on below rules :,def generate_asymmetric self generate_dto kek_meta_dto project_id if generate_dto algorithm is None or generate_dto algorithm lower rsa private_key rsa generate_private_key public_exponent 65537 key_size generate_dto bit_length backend default_backend elif generate_dto algorithm lower dsa private_key dsa generate_private_key key_size generate_dto bit_length backend default_backend else raise c CryptoPrivateKeyFailureException public_key private_key public_key if generate_dto algorithm lower rsa private_key private_key private_bytes encoding serialization Encoding PEM format serialization PrivateFormat PKCS8 encryption_algorithm self _get_encryption_algorithm generate_dto passphrase public_key public_key public_bytes encoding serialization Encoding PEM format serialization PublicFormat SubjectPublicKeyInfo if generate_dto algorithm lower dsa private_key private_key private_bytes encoding serialization Encoding DER format serialization PrivateFormat PKCS8 encryption_algorithm self _get_encryption_algorithm generate_dto passphrase public_key public_key public_bytes encoding serialization Encoding DER format serialization PublicFormat SubjectPublicKeyInfo private_dto self encrypt c EncryptDTO private_key kek_meta_dto project_id public_dto self encrypt c EncryptDTO public_key kek_meta_dto project_id passphrase_dto None if generate_dto passphrase if isinstance generate_dto passphrase six text_type generate_dto passphrase generate_dto passphrase encode utf 8 passphrase_dto self encrypt c EncryptDTO generate_dto passphrase kek_meta_dto project_id return private_dto public_dto passphrase_dto
called to pull host data from vcenter,def _get_hosts_from_vcenter self dataFields name hardware systemInfo uuid config network dnsConfig address config network pnic config network vnic return self session invoke_api vim_util get_objects self session vim HostSystem self max_Hosts dataFields
delete a role inference rule .,abc abstractmethod def delete_implied_role self prior_role_id implied_role_id raise exception NotImplemented
send in connection_properties missing required fields,def test_bad_connection_properties self self assertRaises exception BrickException self connector connect_volume None cprops noremovehost stor1 self assertRaises exception BrickException self connector connect_volume cprops self assertRaises exception BrickException self connector disconnect_volume None None cprops noremovehost stor1 self assertRaises exception BrickException self connector disconnect_volume cprops None cprops name space self assertRaises exception BrickException self connector disconnect_volume cprops None
returns true if machine replies on port 443,def has_ssl self return check_tcp host self ipaddress port 443
"do the unix double - fork magic , see stevens ' "" advanced programming in the unix environment "" for details ( isbn 0201563177 ) http://www.erlenstar.demon.co.uk/unix/faq_2.html#sec16",def daemonize self try pid os fork if pid 0 sys exit 0 except OSError as e sys stderr write fork 1 failed d s n e errno e strerror sys exit 1 os chdir os setsid os umask 0 try pid os fork if pid 0 sys exit 0 except OSError as e sys stderr write fork 2 failed d s n e errno e strerror sys exit 1 sys stdout flush sys stderr flush si file self stdin r so file self stdout a se file self stderr a 0 os dup2 si fileno sys stdin fileno os dup2 so fileno sys stdout fileno os dup2 se fileno sys stderr fileno atexit register self delpid pid str os getpid file self pidfile w write s n pid
find the known dependencies of a python package .,def find_known_dependencies self requirement logger info Checking for known dependencies of s requirement name known_dependencies sorted self dependencies get requirement name lower if known_dependencies logger info Found s s pluralize len known_dependencies known dependency known dependencies concatenate known_dependencies else logger info No known dependencies Maybe you have a suggestion return known_dependencies
this device or object is getting permanently deleted - it is no longer in the user 's account . : param botengine : botengine environment,def destroy self botengine return
data stream message received : param botengine : botengine environment : param address : data stream address : param content : content of the message,def datastream_updated self botengine address content return
"excecutes an action in the gym environment . builds current state ( concatenation of action_repeat-1 previous frames and current one ) . pops oldest frame , adds current frame to the state buffer . returns current state .",def step self action_index x_t1 r_t terminal info self env step self gym_actions action_index x_t1 self get_preprocessed_frame x_t1 previous_frames np array self state_buffer s_t1 np empty self action_repeat 84 84 s_t1 self action_repeat 1 previous_frames s_t1 self action_repeat 1 x_t1 self state_buffer popleft self state_buffer append x_t1 return s_t1 r_t terminal info
"reset the cache to its initial , empty state .",def clear self self cache self expirations self tot_puts 0 self tot_gets 0 self tot_hist 0 self tot_expires 0 self tot_non_modified 0 self cursize 0
find two check digits needed to make a cnpj valid .,def cnpj_check_digits cnpj cnpj clean_id cnpj if len cnpj 12 raise ValueError CNPJ must have at least 12 digits 0 format cnpj digits int k for k in cnpj 13 cs sum w k for w k in zip CNPJ_FIRST_WEIGHTS digits 11 check 0 if cs 2 else 11 cs digits append check cs sum w k for w k in zip CNPJ_SECOND_WEIGHTS digits 11 if cs 2 return check 0 return check 11 cs
return an hypr app fixture .,pytest fixture def app app app add_provider MyProvider checkpoint return app
sets the constant power mode 's power level,def setPower self power self write CP s str power
sets the foreground color . : param color : color : type color : qtgui . qcolor,def set_foreground self color self format setForeground color
if the buffer has a message available,def has_message self xl_unpack xl_unpack len len strio self _strio strio seek self _start header strio read 5 if len header 5 return False length xl_unpack header if length 4 raise ValueError invalid message size d length strio seek 0 2 return strio tell self _start length 1
returns the most probable segmentation option of a list,def best self words tag False max 0 seg for word in words if tag li m 1 m 0 for m in word else li m 1 for m in word prob self prob li if self debug print str li str prob if prob max seg li max prob return seg
"test that we account for midweek holidays . monday 01/20 is a holiday . ensure that the trigger date for that week is adjusted appropriately , or thrown out if not enough trading days . also , test that if we start the simulation on a day where we miss the trigger for that week , that the trigger is recalculated for next week .",parameter_space rule_offset 0 1 2 3 4 start_offset 0 1 2 3 4 type week_start week_end def test_edge_cases_for_TradingDayOfWeek self rule_offset start_offset type sim_start pd Timestamp 2014 01 06 tz UTC timedelta days start_offset delta timedelta days start_offset jan_minutes self cal minutes_for_sessions_in_range pd Timestamp 2014 01 06 tz UTC delta pd Timestamp 2014 01 31 tz UTC if type week_start rule NthTradingDayOfWeek trigger_periods pd Timestamp 2014 01 06 tz UTC pd Timestamp 2014 01 13 tz UTC pd Timestamp 2014 01 21 tz UTC pd Timestamp 2014 01 27 tz UTC trigger_periods x timedelta days rule_offset for x in trigger_periods else rule NDaysBeforeLastTradingDayOfWeek trigger_periods pd Timestamp 2014 01 10 tz UTC pd Timestamp 2014 01 17 tz UTC pd Timestamp 2014 01 24 tz UTC pd Timestamp 2014 01 31 tz UTC trigger_periods x timedelta days rule_offset for x in trigger_periods rule cal self cal should_trigger rule rule_offset should_trigger if rule_offset 4 del trigger_periods 2 trigger_periods x for x in trigger_periods if x sim_start trigger_minutes self cal minutes_for_session trigger_periods 0 for period in trigger_periods 1 trigger_minutes self cal minutes_for_session period expected_n_triggered len trigger_minutes trigger_minutes_iter iter trigger_minutes n_triggered 0 for m in jan_minutes if should_trigger m self assertEqual m next trigger_minutes_iter n_triggered 1 self assertEqual n_triggered expected_n_triggered
get a perf message for the given datetime .,def _get_daily_message self dt algo metrics_tracker perf_message metrics_tracker handle_market_close dt self data_portal perf_message daily_perf recorded_vars algo recorded_vars return perf_message
compute statisticts for the given array .,def _statistics x functions stats for f in functions try stats f getattr x f except ValueError stats f float NaN return stats
fetch account information from asapi host .,def _get_info self return self _perform_get_request self account_info_endpoint headers self token_header
"given an album object , returns a path to downloaded art for the album ( or none if no art is found ) . if ` maxwidth ` , then images are resized to this maximum pixel size . if ` local_only ` , then only local image files from the filesystem are returned ; no network requests are made .",def art_for_album album paths maxwidth None local_only False out None cover_names config fetchart cover_names as_str_seq cover_names map util bytestring_path cover_names cautious config fetchart cautious get bool if paths for path in paths out art_in_path path cover_names cautious if out break remote_priority config fetchart remote_priority get bool if not local_only and remote_priority or not out for url in _source_urls album config fetchart sources as_str_seq if maxwidth url ArtResizer shared proxy_url maxwidth url candidate _fetch_image url if candidate out candidate break if maxwidth and out out ArtResizer shared resize maxwidth out return out
the command to check the filesystem .,property def _fsck_command self return str self ext self options self fs device
"the standard message post - processors : one for the version message , one for the alert message , and one for the merkleblock message .",def standard_message_post_unpacks streamer return dict alert make_post_unpack_alert streamer merkleblock post_unpack_merkleblock
random initial states . we do this so that we can enforce the same initial guesses for all runs to compare against the poon and carter .,def init self p pop n self GetStringLength c self GetIntegerChromosome p pop np random seed p perm np random permutation n for i in range 0 n c i perm i del c
sets up the patterns and compiled regex objects for parsing types .,def setup_regex self self _RX_TYPE n s type P modifiers s public private s s P name A Za z0 9_ P contents end s type s P name self RE_TYPE re compile self _RX_TYPE re DOTALL re I self _RX_SIG type P modifiers s public private s s P name A Za z0 9_ self RE_SIG re compile self _RX_SIG re I self _RX_PRIV private contains self RE_PRIV re compile self _RX_PRIV re DOTALL re I self _RX_EXEC s P modifiers s s P name A Za z0 9_ s s P points A Za z0 9_ self RE_EXEC re compile self _RX_EXEC re M re I self _RX_CONTAINS n s contains P remainder self RE_CONTAINS re compile self _RX_CONTAINS re DOTALL re I
checks to see if the page has been modified since the version in the requester 's cache .,def modified date None etag None try from __builtin__ import set except ImportError from sets import Set as set n set x strip for x in web ctx env get HTTP_IF_NONE_MATCH split m net parsehttpdate web ctx env get HTTP_IF_MODIFIED_SINCE split 0 validate False if etag if in n or etag in n validate True if date and m if date datetime timedelta seconds 1 m validate True if date lastmodified date if etag web header ETag etag if validate raise web notmodified else return True
save command line arguments and set active to false by default .,def __init__ self mloginfo self mloginfo mloginfo
the advanced layout for the dashboard is exactly the same as the ' normal ' dashboard . the only difference is the items that are loaded and the breadcrumb trail,def advanced self return render default derived dashboard mako
test classifier on data with known categories . inputs : training data to use for training testing data to use for testing outputs : result dataframe of predicted and true classifications with probabilities * * * modifies self . model,def test self training testing verbose True model self model TestTarget Cats TestPredictors self _unpack testing self train training Result self classify TestPredictors Result Result rename columns TestTarget name Model Result insert 0 Reality TestTarget Result IsCorrect Result Model Result Reality return Result
"look for files that have been removed from a trove or restored to a trove , and mark those changes in the database . this is used to record local changes .",def markChangedFiles db cs for trvCs in cs iterNewTroveList ver trvCs getOldVersion if ver onLocalLabel ver trvCs getNewVersion newPathIds x 0 for x in trvCs getNewFileList db restorePathIdsToTrove trvCs getName ver trvCs getOldFlavor newPathIds oldPathIds trvCs getOldFileList db removePathIdsFromTrove trvCs getName ver trvCs getOldFlavor oldPathIds
this is a decorator which can be used to mark functions as deprecated . it will result in a warning being emitted when the function is used .,def deprecated use_instead None def deco func wraps func def wrapped args kwargs message Call to deprecated function s func __name__ if use_instead message Use s instead use_instead warnings warn message category ScrapyDeprecationWarning stacklevel 2 return func args kwargs return wrapped if callable use_instead deco deco use_instead use_instead None return deco
image in log - grayscale space,property def log_image_gray self if not hasattr self _log_image_gray self _log_image_gray np log self image_gray self _log_image_gray setflags write False return self _log_image_gray
return the drawstyle for this drawable .,def get_style self if self _style is None self _style self get_drawstyle for effect in self effects self _style effect apply self _style return self _style
ends the current scene setting director.return_value with ` value `,def end self value None director return_value value director pop
"sends a request to the input url , with the url parameters place in order with a / between each and with the query parameters input .",def _request self url authenticated url_variables query_parameters if authenticated query_parameters api_key self _key url self _lang name for var in url_variables url var result None if len query_parameters result requests get url params query_parameters else result requests get url result raise_for_status return result
automatically find / download setuptools and make it available on sys.path,def use_setuptools version DEFAULT_VERSION download_base DEFAULT_URL to_dir os curdir download_delay 15 was_imported pkg_resources in sys modules or setuptools in sys modules def do_download egg download_setuptools version download_base to_dir download_delay sys path insert 0 egg import setuptools setuptools bootstrap_install_from egg try import pkg_resources except ImportError return do_download try pkg_resources require setuptools version return except pkg_resources VersionConflict as e if was_imported print The required version of setuptools s is not available and can t be installed while this script is running Please install a more recent version first using easy_install U setuptools Currently using r version e args 0 file sys stderr sys exit 2 except pkg_resources DistributionNotFound pass del pkg_resources sys modules pkg_resources return do_download
test validity of the meson plugin schema,def test_schema self schema meson MesonPlugin schema properties schema properties self assertTrue meson parameters in properties Expected meson parameters to be included in properties meson_parameters properties meson parameters self assertTrue type in meson_parameters Expected type to be included in meson parameters self assertThat meson_parameters type Equals array Expected meson parameters type to be array but it was format meson_parameters type self assertTrue minitems in meson_parameters Expected minitems to be included in meson parameters self assertThat meson_parameters minitems Equals 1 Expected meson parameters minitems to be 1 but it was format meson_parameters minitems self assertTrue uniqueItems in meson_parameters Expected uniqueItems to be included in meson parameters self assertTrue meson_parameters uniqueItems Expected meson parameters uniqueItems to be True
": param value : number of seconds , passed after the start of the contest ( or a virtual start for virtual parties ) , before the submission . : type value : int or str",relative_time setter def relative_time self value assert isinstance value int str self _relative_time int value
close the device when cleaning up ... : return :,def __del__ self self device close
"gets the running python version ( major , minor , release ) . : return : python version formatted as major.minor.release . : rtype : str .",staticmethod def get_python_version version sys version_info return str format version 0 version 1 version 2
"returns a new dictionary where values which are n't instances of basestring are pickled . also , a new key ' _ pickled ' contains a comma separated list of keys corresponding to the pickled values .",def pickle_dict items ret pickled_keys for key val in items items if isinstance val basestring ret key val else pickled_keys append key ret key pickle dumps val if pickled_keys ret _pickled join pickled_keys return ret
factory function populates cache from .get ( ),def test_factory_get_none self cache util TimedCache None lambda a None self assertEqual cache get a f f
create a new revision file .,def revision config message None autogenerate False sql False head head splice False branch_label None version_path None rev_id None depends_on None script_directory ScriptDirectory from_config config command_args dict message message autogenerate autogenerate sql sql head head splice splice branch_label branch_label version_path version_path rev_id rev_id depends_on depends_on revision_context autogen RevisionContext config script_directory command_args environment util asbool config get_main_option revision_environment if autogenerate environment True if sql raise util CommandError Using sql with autogenerate does not make any sense def retrieve_migrations rev context revision_context run_autogenerate rev context return elif environment def retrieve_migrations rev context revision_context run_no_autogenerate rev context return elif sql raise util CommandError Using sql with the revision command when revision_environment is not configured does not make any sense if environment with EnvironmentContext config script_directory fn retrieve_migrations as_sql sql template_args revision_context template_args revision_context revision_context script_directory run_env scripts script for script in revision_context generate_scripts if len scripts 1 return scripts 0 else return scripts
"this test validates than the userqaprofile method modify_reputation works properly when an questioncomment instance is created , but there is no qa_setting defined inside the settings file , so the try block inside the save ( ) method of the model goes for the excep line .",override_settings QA_SETTINGS def test_affect_reputation_by_questioncomment self other_qa_user self other_user userqaprofile self assertEqual other_qa_user points 0 comment QuestionComment objects create question self first_question comment_text This is not so bright a comment pub_date timezone datetime 2016 2 8 0 0 0 user self other_user self assertTrue isinstance comment QuestionComment other_qa_user refresh_from_db self assertEqual other_qa_user points 0
if the analyzer thinks the simulation should be stopped ( for instance because of convergence ) it returns false,def goOn self return True
dumps the contents in ini - form @return : a string with the contents,def dump self result for section in sorted self sections key lambda x x lower result s n section for key value in sorted self items section key lambda x x 0 lower result s s n key value result n return result
fill missing values in a numpy array ' field ' using the matrix ' matrix ' approximating the laplace operator .,def fill_missing field matrix None ksp create_solver if matrix is None A assemble_matrix field mask else A matrix x b A getVecs assemble_rhs b field initial_guess np mean field x set initial_guess ksp setOperators A ksp solve b x vec0 scatter create_scatter x scatter_to_0 x vec0 scatter return vec0 A
"left denotation , is used when it appears inside the construct .",def led self left raise SyntaxError Unknown operator r self ident
writes to file the neg . loglikelihood of given fold ( train / valid / test ) .,def evaluate_fold fold evaluator hparams eval_logdir checkpoint_dir eval_run_name eval_ s_ s s_ s_ensemble s_chrono s lib_util timestamp fold FLAGS fold_index if FLAGS fold_index is not None else FLAGS unit FLAGS ensemble_size FLAGS chronological log_fname s__ s npz os path basename checkpoint_dir eval_run_name log_fpath os path join eval_logdir log_fname pianorolls get_fold_pianorolls fold hparams rval lib_evaluation evaluate evaluator pianorolls tf logging info Writing to path s log_fpath with lib_util atomic_file log_fpath as p np savez_compressed p rval
return true if filter applies to path . false otherwise,def matches self path raise NotImplementedError
test to ensure transformer content based on the end suffix of the url works as expected,def test_suffix transformer hug transform suffix js int txt str class FakeRequest object path hey js request FakeRequest assert transformer 1 request 1 request path hey txt assert transformer 2 request 2 request path hey undefined transformer data value request data value
renders the module and dumps it to the given file . `` file `` can be either a file name or a file object,def dump self filename_or_fileobj data self render if hasattr filename_or_fileobj write filename_or_fileobj write data else with open filename_or_fileobj w as f f write data
get the features of the dataset . parameters ---------- x_parent : an array of size ( batch_size x n_nodes - 1 x n_nodes ) the adjacency of each matrix . x_locations : an array of size ( batch_size x n_nodes - 1 x 3 ) the locations of each nodes . returns ------- x_features : an array of size ( batch_size x n_nodes x n_features ) the features currently supports : - the adjacency - the full adjacency - locations - distance from immediate parents,def features X_parent X_locations batch_size X_parent shape 0 n_nodes X_parent shape 2 X_adjacency np append np zeros batch_size 1 n_nodes X_parent axis 1 X_locations np append np zeros batch_size 1 3 X_locations axis 1 X_full_adjacency np zeros batch_size n_nodes n_nodes X_distance np zeros batch_size n_nodes 3 for sample in range batch_size X_full_adjacency sample full_matrix_np np squeeze X_adjacency sample n_nodes X_distance sample np dot np eye n_nodes np squeeze X_adjacency sample np squeeze X_locations sample X_features np append X_adjacency X_full_adjacency X_locations X_distance axis 2 return X_features
dictionary providing the list of arguments for every benchmark,property def arguments self return self attributes arguments
set the value of the progress bar to * * value**.,def set self value self _nsObject setDoubleValue_ value self _nsObject display if osVersionCurrent osVersion10_11 NSRunLoop mainRunLoop runUntilDate_ NSDate dateWithTimeIntervalSinceNow_ 0 0001
"prevent multiple roots , which are forbidden in conll - u.",staticmethod def choose_root p_tree was_subroot g_tree possible_subroots n for n in p_tree children if n in was_subroot if possible_subroots the_subroot possible_subroots 0 g_subroot g_tree children 0 possible_subroots sorted n for n in possible_subroots if n form g_subroot form key lambda n abs n ord g_subroot ord the_subroot possible_subroots 0 if possible_subroots else the_subroot else the_subroot p_tree children 0 the_subroot misc Rehanged Yes for subroot in p_tree children if subroot is not the_subroot subroot parent the_subroot subroot misc Rehanged Yes
run the agent to ensure the machine stays in the cluster and rejoins it after interruptions : return none :,def loop_rejoin while True with suppress Exception attempt_join_meshnet sleep 10
tests calling is_visible is correct when whitelisted .,def test_visible_whitelisted self self feature_test set_percentage 0 self feature_test add_to_whitelist 3 self assertTrue self feature_test is_visible 3
convert integer number of seconds to an hh : mm : ss string . only the necessary fields are used .,def seconds_to_hms seconds seconds math ceil seconds minutes seconds divmod seconds 60 hours minutes divmod minutes 60 parts if hours parts append hours if minutes parts append minutes parts append seconds hms join 02d part for part in parts return hms
should redraw the cursor position .,def updateCursorPosition self
"return none , false or true .",def handleHome self edit ev home ev QKeySequence MoveToStartOfLine s_home ev QKeySequence SelectStartOfLine if home or s_home cursor edit textCursor text cursor block text pos cursor block position len text len text lstrip if cursor position pos mode QTextCursor KeepAnchor if s_home else QTextCursor MoveAnchor cursor setPosition pos mode edit setTextCursor cursor return True return False
"return none , false or true .",def handleVertical self edit ev cursor edit textCursor pos cursor position if ev QKeySequence MoveToPreviousLine or ev QKeySequence MoveToPreviousPage cursor movePosition QTextCursor Up if cursor position pos cursor movePosition QTextCursor Start edit setTextCursor cursor return True return False elif ev QKeySequence SelectPreviousLine or ev QKeySequence SelectPreviousPage cursor movePosition QTextCursor Up QTextCursor KeepAnchor if cursor position pos cursor movePosition QTextCursor Start QTextCursor KeepAnchor edit setTextCursor cursor return True return False elif ev QKeySequence MoveToNextLine or ev QKeySequence MoveToNextPage cursor movePosition QTextCursor Down if cursor position pos cursor movePosition QTextCursor End edit setTextCursor cursor return True return False elif ev QKeySequence SelectNextLine or ev QKeySequence SelectNextPage cursor movePosition QTextCursor Down QTextCursor KeepAnchor if cursor position pos cursor movePosition QTextCursor End QTextCursor KeepAnchor edit setTextCursor cursor return True return False
moves the cursor in its block to the first non - space character .,def strip_indent cursor text cursor block text pos len text len text lstrip cursor setPosition cursor block position pos
parses an expression such as the ' plural=<expression > ' found in po / mo files .,def parse_plural_expr text source iter expr_re findall text def _expr result for token in source if token result insert 0 if result 0 0 _expr result append else result extend _expr elif token return result elif token result append and elif token result append or elif token result append not else result append token if token result extend _expr elif token return result return result py_expression join _expr if py_expression code lambda n int 0 format py_expression compiled_code compile code plural_expression eval return eval compiled_code
return true iff all of the given try jobs have finished .,def _all_trybots_finished try_builds for try_build in try_builds if not try_build is_finished return False return True
"send the response in parts , with time delays .",pipe str def trickle request response delays def parse_delays parts delays split rv for item in parts if item startswith d item_type delay item item 1 value float item elif item startswith r item_type repeat value int item 1 if not value 2 0 raise ValueError else item_type bytes value int item if len rv and rv 1 0 item_type rv 1 1 value else rv append item_type value return rv delays parse_delays if not delays return response content resolve_content response modified_content offset 0 def sleep seconds def inner time sleep seconds return return inner def add_content delays repeat False for i item_type value in enumerate delays if item_type bytes modified_content append content offset 0 offset 0 value offset 0 value elif item_type delay modified_content append sleep value elif item_type repeat assert i len delays 1 while offset 0 len content add_content delays value 1 1 True if not repeat and offset 0 len content modified_content append content offset 0 add_content delays response content modified_content return response
test function that adds aggregated resources to a research object manifest,def testAddGetAggregatedResources self httpsession ROSRS_Session ro_test_config ROSRS_URI ro_test_config ROSRS_ACCESS_TOKEN roid romanagertest str uuid uuid4 _ _ rouri _ ro_remote_metadata createRO httpsession roid self remoteRo ro_remote_metadata ro_remote_metadata ro_config httpsession rouri def URIRef path return self remoteRo getComponentUriAbs path def verifyResources resources c 0 for r in self remoteRo getAggregatedResources if not self remoteRo hasResourceType r RO AggregatedAnnotation c 1 self assertIn r resources self assertEqual c len resources return self remoteRo aggregateResourceInt internal 1 text plain ipsum lorem self remoteRo reloadManifest self assertTrue self remoteRo isAggregatedResource internal 1 self assertFalse self remoteRo isAggregatedResource http www google com verifyResources URIRef internal 1 URIRef ro evo_info ttl self remoteRo aggregateResourceExt http www google com self remoteRo reloadManifest self assertTrue self remoteRo isAggregatedResource internal 1 self assertTrue self remoteRo isAggregatedResource http www google com verifyResources URIRef internal 1 URIRef http www google com URIRef ro evo_info ttl self remoteRo deaggregateResource URIRef internal 1 self remoteRo reloadManifest self assertFalse self remoteRo isAggregatedResource internal 1 self assertTrue self remoteRo isAggregatedResource http www google com verifyResources URIRef http www google com URIRef ro evo_info ttl self remoteRo deaggregateResource URIRef http www google com self remoteRo reloadManifest self assertFalse self remoteRo isAggregatedResource internal 1 self assertFalse self remoteRo isAggregatedResource http www google com verifyResources URIRef ro evo_info ttl return
"merge windows for one station . for example , you may have "" 00.bh "" , "" 10.bh "" , "" 00.lh "" , "" 10.lh "" from different locations and channels . you may only want to keep one at the very end . so : 1 ) select locations : keep only one location with the most number of windows for one channel . for example , in "" 00.bh "" and "" 10.bh "" we only keep "" 10.bh "" . 2 ) select channel : after last step , we keep only "" 00.bh "" and "" 10.lh "" , but ultimately we only want to keep one . so we may only choose "" 00.bh "" since it has more windows .",def merge_station_windows windows w merge_instruments_window windows w merge_channels_window w return w
"set new preferences , and then write a new cookie .",def __write_preferences self signing_algorithm self sensitive_config get key_defaults signing_algorithm self iat GlobalTime time self nbf self iat 60 jti uuid4 int jwt_claims nbf self nbf iat self iat jti str jti thm str self thm top self top gro str self gro rev self rev jwt_header alg signing_algorithm self jwt jwt JWT header jwt_header claims jwt_claims self jwt make_signed_token self key sign encryption_parameters alg self sensitive_config get key_defaults encryption_algorithm enc self sensitive_config get key_defaults encryption_mode payload self jwt serialize self jwe jwt JWT header encryption_parameters claims payload self jwe make_encrypted_token self key encrypt self serial self jwe serialize cookie_values self cookie_name self serial Secure HttpOnly Max Age str GlobalTime time 10 SameSite strict self headers append Set Cookie join cookie_values
tests the display method in the ibmbatch class works as intended .,def test_display self batch ib IBMBatch 1 2 3 self assertEqual 123 str batch
a worker that does actual jobs,def _worker self logger debug Init shooter process try self gun setup except Exception logger exception Couldn t initialize gun Exit shooter process return while not self quit is_set try task self task_queue get timeout 1 if not task logger debug Got killer task break timestamp missile marker task planned_time self start_time timestamp 1000 0 delay planned_time time time if delay 0 time sleep delay try with self instance_counter get_lock self instance_counter value 1 self gun shoot missile marker finally with self instance_counter get_lock self instance_counter value 1 except KeyboardInterrupt SystemExit break except Empty if self quit is_set logger debug Empty queue Exiting process return except Full logger warning Couldn t put to result queue because it s full except Exception logger exception Bfg shoot exception try self gun teardown except Exception logger exception Couldn t finalize gun Exit shooter process return logger debug Exit shooter process
"encodes the source and the destination bounding boxes to "" loc "" .",def bbox2loc src_bbox dst_bbox Encodes the source and the destination bounding boxes to loc Given bounding boxes this function computes offsets and scales to match the source bounding boxes to the target bounding boxes Mathematcially given a bounding box whose center is math y x p_y p_x and size math p_h p_w and the target bounding box whose center is math g_y g_x and size math g_h g_w the offsets and scales math t_y t_x t_h t_w can be computed by the following formulas math t_y frac g_y p_y p_h math t_x frac g_x p_x p_w math t_h log frac g_h p_h math t_w log frac g_w p_w The output is same type as the type of the inputs The encoding formulas are used in works such as R CNN _ Ross Girshick Jeff Donahue Trevor Darrell Jitendra Malik Rich feature hierarchies for accurate object detection and semantic segmentation CVPR 2014 Args src_bbox array An image coordinate array whose shape is math R 4 math R is the number of bounding boxes These coordinates are math p_ ymin p_ xmin p_ ymax p_ xmax dst_bbox array An image coordinate array whose shape is math R 4 These coordinates are math g_ ymin g_ xmin g_ ymax g_ xmax Returns array Bounding box offsets and scales from obj src_bbox to obj dst_bbox This has shape math R 4 The second axis contains four values math t_y t_x t_h t_w xp cuda get_array_module src_bbox height src_bbox 2 src_bbox 0 width src_bbox 3 src_bbox 1 ctr_y src_bbox 0 0 5 height ctr_x src_bbox 1 0 5 width base_height dst_bbox 2 dst_bbox 0 base_width dst_bbox 3 dst_bbox 1 base_ctr_y dst_bbox 0 0 5 base_height base_ctr_x dst_bbox 1 0 5 base_width dy base_ctr_y ctr_y height dx base_ctr_x ctr_x width dh xp log base_height height dw xp log base_width width loc xp vstack dy dx dh dw transpose return loc
return the printer 's name .,staticmethod def printer_name printer if hasattr printer name return printer name if hasattr printer __name__ return printer __name__ return unknown
open a message and inform the grib file that it 's been incremented .,def __init__ self codes_file None clone None sample None headers_only False gribindex None grib_args_present True if gribindex is None grib_args_present False super self __class__ self __init__ codes_file clone sample headers_only grib_args_present self grib_index None if gribindex is not None self codes_id eccodes codes_new_from_index gribindex iid if not self codes_id raise IndexNotSelectedError All keys must have selected values before receiving message from index self grib_index gribindex gribindex open_messages append self
return a string with that contains the title and opt_title if it 's not the empty string,def normalize_title title opt_title if opt_title is not title opt_title title return title
is this an external rather than internal account .,property def is_external self return settings SOCIAL_AUTH and self user social_auth exists
read terminal status line : clear to send,def getCTS self if not self _isOpen raise portNotOpenError if self logger self logger info getCTS state of RTS r self cts return self cts
displays a journal 's settings form for editing during the install process . : param request : httprequest object : return : httpresponse object,staff_member_required def journal request settings_to_get journal_name journal_issn publisher_name publisher_url initial_items logic get_initial_settings request journal settings_to_get attr_form forms JournalForm instance request journal sett_form forms JournalSettingsForm initial initial_items if request POST attr_form forms JournalForm request POST instance request journal sett_form forms JournalSettingsForm request POST if attr_form is_valid and sett_form is_valid attr_form save sett_form save request request template install journal html context attr_form attr_form sett_form sett_form return render request template context
return the longest common subsequence of the 2 sequences .,def lcs s1 s2 arestring type s1 is str and type s2 is str areunicode type s1 is unicode and type s2 is unicode C lcs_matrix s1 s2 ig backtrack C s1 s2 if ig i1 i2 zip ig lcs s1 i for i in i1 else lcs if areunicode return u join lcs if arestring return join lcs return lcs
launch the vm and establish a qmp connection,def _launch self devnull open os path devnull rb self _pre_launch self _qemu_full_args self _wrapper self _binary self _base_args self _args self _popen subprocess Popen self _qemu_full_args stdin devnull stdout self _qemu_log_file stderr subprocess STDOUT shell False self _post_launch
given a configuration dictionary return flags for the bitgen build if user flags are not specified take the default flags from,def get_flags config flags user_flags bg_config if bitgen in config keys if flags in config bitgen keys user_flags config bitgen flags if config in config bitgen keys bg_config config bitgen config fn os path join os path dirname __file__ BITGEN_DEFAULT_FLAG_FILE cfg_fn os path join os path dirname __file__ BITGEN_CONFIG_FILE default_flags json load open fn r for key in default_flags if key g continue if key in user_flags keys default_flags key value user_flags key value if len default_flags key value 0 continue flags key default_flags key value default_config json load open cfg_fn r flags configuration cfg flags configuration for key in default_config if key in config bitgen config keys default_config key value config bitgen config key if len default_config key value 0 continue cfg append g s s key default_config key value return flags
"turn off web and worker dynos , plus clock process if there is one and it 's active .",def scale_down_dynos self u Turn off web and worker dynos plus clock process if n there is one and it s active n processes u web u worker if self clock_is_on processes append u clock for process in processes self scale_down_dyno process
computes any information for each xblock that 's necessary to execute this transformer 's transform method .,classmethod def collect cls block_structure SplitTestTransformer collect block_structure root_block block_structure get_xblock block_structure root_block_usage_key user_partitions getattr root_block user_partitions or block_structure set_transformer_data cls user_partitions user_partitions if not user_partitions return for block_key in block_structure topological_traversal xblock block_structure get_xblock block_key parent_keys block_structure get_parents block_key merged_parent_access_list block_structure get_transformer_block_field parent_key cls merged_group_access for parent_key in parent_keys merged_group_access _MergedGroupAccess user_partitions xblock merged_parent_access_list block_structure set_transformer_block_field block_key cls merged_group_access merged_group_access
fill out the form to create a new library . must have called click_new_library ( ) first .,def fill_new_library_form self display_name org number field lambda fn self q css wrapper create library new library format fn field name fill display_name field org fill org field number fill number
fetches all key : value pairs from persistence and returns a coursemetadata model .,classmethod def fetch_all cls descriptor result for field in descriptor fields values if field scope Scope settings continue result field name value field read_json descriptor display_name _ field display_name help _ field help deprecated field runtime_options get deprecated False return result
load and return block info .,contract block_key BlockKey None def xblock_from_json self class_ course_key block_key block_data course_entry_override None kwargs if course_entry_override is None course_entry_override self course_entry else self course_entry CourseEnvelope course_entry_override course_key self course_entry structure definition_id block_data definition if block_key is None block_key BlockKey block_data block_type LocalId convert_fields lambda field self modulestore convert_references_to_keys course_key class_ field self course_entry structure blocks if definition_id is not None and not block_data definition_loaded definition_loader DefinitionLazyLoader self modulestore course_key block_key type definition_id convert_fields else definition_loader None if definition_id is None definition_id LocalId block_locator course_key make_usage_key block_type block_key type block_id block_key id converted_fields convert_fields block_data fields converted_defaults convert_fields block_data defaults if block_key in self _parent_map parent_key self _parent_map block_key parent course_key make_usage_key parent_key type parent_key id else parent None kvs SplitMongoKVS definition_loader converted_fields converted_defaults parent parent field_decorator kwargs get field_decorator if InheritanceMixin in self modulestore xblock_mixins field_data inheriting_field_data kvs else field_data KvsFieldData kvs try module self construct_xblock_from_class class_ ScopeIds None block_key type definition_id block_locator field_data for_parent kwargs get for_parent except Exception log warning Failed to load descriptor exc_info True return ErrorDescriptor from_json block_data self course_entry_override course_key make_usage_key block_type error block_id block_key id error_msg exc_info_to_str sys exc_info edit_info block_data edit_info module _edited_by edit_info edited_by module _edited_on edit_info edited_on module previous_version edit_info previous_version module update_version edit_info update_version module source_version edit_info source_version module definition_locator DefinitionLocator block_key type definition_id module save if isinstance block_locator block_id LocalId self local_modules block_locator module return module
return the verification status for this user .,lazy def verification_status self return SoftwareSecurePhotoVerification user_status self user 0
returns the absolute path of the directory where the test binaries are .,def GetBuildDir return os path abspath GetFlag build_dir
filter applied by pandoc to the children of all headers,def header_children_filter key value format meta if key Code return Emph Str value 1 elif key RawInline and value 0 html return html_inline_filter value pandoc_filter current_file False else return None
mcpaid < username > -- checks if < username > has a premium minecraft account .,hook command haspaid hook command def mcpaid inp user inp strip try status http get http www minecraft net haspaid jsp user user except http URLError http HTTPError as e return Unable to get user registration status format e if true in status return The account is a premium Minecraft account format inp else return The account is not a premium Minecraft account format inp
returns a hexadecimal string from a list of bytes,def toHexString bytes value for i in range 0 len bytes if bytes i 0 return None value 0 2X bytes i return value
custom get field info so extra parameters of custom fields are displayed as well .,def get_field_info self field u n Custom get field info so extra parameters of custom fields are displayed as well n field_info OrderedDict field_info u type self label_lookup field field_info u required getattr field u required False attrs u read_only u label u help_text u min_length u max_length u min_value u max_value if hasattr field u extra_field_attrs attrs field extra_field_attrs for attr in attrs value getattr field attr None if value is not None and value u field_info attr force_text value strings_only True if not field_info get u read_only and hasattr field u choices field_info u choices u value choice_value u display_name force_text choice_name strings_only True for choice_value choice_name in field choices items return field_info
create 2-d array with uniform random numbers between the lower and upper bounds .,def rand_population lower upper num_agents dim return upper lower _prng rand num_agents dim lower
"takes a list of dictionaries , each representing what is returned from the model at a particular time , and creates a dataframe whose columns correspond to the keys of ` return addresses `",def make_flat_df frames return_addresses visited list map lambda x visit_addresses x return_addresses frames return pd DataFrame visited
gc - print out garbage collection information,def do_gc self args instance_type getattr types InstanceType object type2count type2all for o in gc get_objects if type o instance_type type2count o __class__ type2count get o __class__ 0 1 type2all o __class__ type2all get o __class__ 0 sys getrefcount o ct t __module__ t __name__ type2count t type2count t self type2count get t 0 type2all t self type2all get t 0 for t in type2count iterkeys self type2count type2count self type2all type2all fmt 30s 30s 6s 6s 6s n self stdout write fmt Module Type Count dCount dRef ct sort lambda x y cmp y 2 x 2 for i in range min 10 len ct m n c delta1 delta2 ct i self stdout write fmt m n c delta1 delta2 self stdout write n self stdout write fmt Module Type Count dCount dRef ct sort for m n c delta1 delta2 in ct if delta1 or delta2 self stdout write fmt m n c delta1 delta2 self stdout write n
we can blast a seq file against a database,def test_blast_seq_against_bad_db self test_dir NamedTemporaryDir project_name backbone create_project directory test_dir name name project_name project_dir join test_dir name project_name query seq1 nGATCGGCCTTCTTGCGCATCTCACGCGCTCCTGCGGCGGCCTGTAGGGCAGGCT query CATACCCCTGCCGAACCGCTTTTGTCA n query_fhand NamedTemporaryFile mode w query_fhand write query query_fhand flush blast_db_fname uni blast_db join TEST_DATA_DIR blast blast_db_fname blast_program blastn try backbone_blast_runner query_fpath query_fhand name project_dir project_dir blast_program blast_program blast_db blast_db self fail RuntimeError expected except RuntimeError pass test_dir close
load language configuration from a list of possible files .,def load_language_config paths res Languages for path in paths if os path isfile path res update path return res
dot_identifier : identifier ' . ' dot_identifier | identifier,def p_dot_identifier p if len p 2 p 0 p 1 elif len p 4 p 0 p 1 p 3
handle after the request : param response : the request response : type response : request : param roles : roles accepted : type roles : list : return : the request response : rtype : request,def after self response roles return response
"initialize a sequence classifier . observation_labels and state_labels are the sets of observations and states , respectively . they must be labeldictionary objects .",def __init__ self observation_labels state_labels self decoder scd SequenceClassificationDecoder self observation_labels observation_labels self state_labels state_labels self trained False
returns a list of unused portgroups .,def get_unused_portgroup_names session dvs_name unused_port_group_names port_group_mors get_all_portgroup_mors_for_switch session dvs_name if port_group_mors port_groups session _call_method vim_util get_properties_for_a_collection_of_objects DistributedVirtualPortgroup port_group_mors summary name tag vm for port_group in port_groups propset_dict common_util convert_propset_to_dict port_group propSet if not propset_dict vm and not propset_dict tag unused_port_group_names append propset_dict summary name return unused_port_group_names
testing simple matrix with tags and filtering .,def test_dry_run self matrix_definition name one env message hello1 name two env message hello2 name three env message hello3 pipeline_definition stage test tasks shell script echo env message when process_data MatrixProcessData process_data pipeline pipeline_definition process_data options ApplicationOptions definition fake yaml dry_run True matrix Matrix matrix_definition parallel True result matrix process process_data output line for line in result output if len line 0 assert_that result success equal_to True assert_that len output equal_to 6 assert_that output 0 equal_to bin bash assert_that output 1 equal_to echo hello1 assert_that output 2 equal_to bin bash assert_that output 3 equal_to echo hello2 assert_that output 4 equal_to bin bash assert_that output 5 equal_to echo hello3
"label encoding from tree lstm paper ( tai , socher , manning )",def encode_labels labels nclass 5 ndata None Y np zeros len labels nclass astype float32 for j y in enumerate labels for i in range nclass if i 1 np floor y 1 Y j i y np floor y if i 1 np floor y Y j i np floor y y 1 if ndata Y Y ndata return Y
set up columns and objects to be used in the objectlistview to be visible in the series selector,def initTable self dbservice site_id seriesColumns clsExisting ColumnDefn key align left minimumWidth 1 valueGetter value stringConverter Y m d H M S if date in key lower else s for key value in series returnDict iteritems self pnlExisting olvSeriesList SetColumns seriesColumns objects dbservice get_series_by_site site_id site_id self pnlExisting olvSeriesList SetObjects objects
print metric to stdout in tcollector format .,def print_metric line metric timestamp if not line svname return value line metric if not value value 0 print haproxy s i s source s cluster s METRIC_NAMES metric timestamp value line svname line pxname
keys are the names of each parameter .,def keys self return self __param_conf__ keys
generate the path of files in your dotfile directory . thes paths will include both full paths to your $ home directory and full paths to your dot directory . get_files ( ) is used before link ( ) and unlink ( ),def get_files self dotignore dotignore ignore_file dotignore if self git_dir ignore_file self git_dir dotignore IGNORE if os path exists ignore_file with open ignore_file as f IGNORE f read split IGNORE append dotignore self git_links self home_links for f in os listdir self git_dir if f in IGNORE continue to os environ HOME if not f startswith to to f f os path abspath self git_dir f self git_links append f self home_links append to
get the source as a string .,def GetSource self return self _source
search `` xdg_config_dirs `` for a config file and return the first found .,def _get_config_file_path xdg_config_dir xdg_config_file for config_dir in BaseDirectory load_config_paths xdg_config_dir path join config_dir xdg_config_file if isfile path return path raise ConfigFileError No configuration files could be located after searching for a file named 0 in the standard XDG configuration paths such as config 1 format xdg_config_file xdg_config_dir
: param memory_t_1 : : param weight_t : : param eraser_t : : return :,def erase memory_t_1 weight_t eraser_t memory memory_t_1 T outer eraser_t weight_t return memory
add builders and construction variables for gnulink to an environment .,def generate env link generate env if env PLATFORM hpux env SHLINKFLAGS SCons Util CLVar LINKFLAGS shared fPIC env RPATHPREFIX Wl rpath env RPATHSUFFIX env _RPATH _concat RPATHPREFIX RPATH RPATHSUFFIX __env__ use_soname not sys platform startswith openbsd link _setup_versioned_lib_variables env tool gnulink use_soname use_soname env LINKCALLBACKS link _versioned_lib_callbacks env SHLIBVERSIONFLAGS SCons Util CLVar Wl Bsymbolic
set true . : param bool[false ] set_true : set true : return bool : set true ?,hammock post set true def set_true self set_true False return set_true
"decodes dns transmittable hostname data , 0 - 9a - f , ignoring casing : param data : dns transmittable hostname data : return : decoded form",def dnshostdecode data return base64 b16decode data casefold True
"use this in an if statement in the _ _ main _ _ of a code , before any spyk actions , but after all transformations have been defined ..",def usermain self return not guineapig Planner partOfPlan sys argv
child class should override this function to implement their body,def enable_device_status_with_advanced_controller self pairedDeviceId deviceDTO pass
this function just writes the matrices into the correct files .,def write_counts clusters numloci nicholson_data prefix numa_handle open prefix _NUMA txt w N_handle open prefix _N txt w X_handle open prefix _X txt w numa_handle write n join nicholson_data NumAlleles numa_handle flush numa_handle close for index in xrange 0 numloci N_towrite X_towrite for c in clusters N_towrite append nicholson_data NumGenotypes c index X_singlepop for a in xrange 0 int nicholson_data NumAlleles index X_singlepop append nicholson_data PopAlleles c index a X_towrite X_singlepop N_handle write t join N_towrite n X_handle write t join X_towrite n N_handle flush N_handle close X_handle flush X_handle close return
"set permissions on a project to a list of users , identifed by their usernames .",def set_project_permission project_id usernames read write share kwargs user_id kwargs get user_id proj_i _get_project project_id proj_i check_share_permission user_id if read N write N share N for username in usernames user_i _get_user username if proj_i created_by user_i user_id raise HydraError Cannot set permissions on project s for user s as this user is the creator project_id username proj_i set_owner user_i user_id read read write write share share for net_i in proj_i networks net_i set_owner user_i user_id read read write write share share DBSession flush
set admin location based on mapping file .,def set_adm_location self self set_from_dict_match lookup_dict self data_files municipalities dict_label itemLabel value_label municipality prop located_adm
do_copy ( ) - > mashup returns a clone of itself,def do_copy self new_ids False id_scope None id_remap None cp DBMashup do_copy self new_ids id_scope id_remap Mashup convert cp return cp
findhandlerfunction ( ) - > int return the function i d associated with input port ' source ',def findHandlerFunction self fid 1 for i in xrange self module getNumFunctions if self module functions i name Handler fid i break return fid
this method handles the manipulation or extraction of information from the device after the monitoring session has ended : param params : session 's configuration created from web interface : param module : : param session : session object : param device_serial : device 's serial from [ adb devices ] command : return :,def postSession self params module session device_serial for param_name status in params iteritems if status on getprop_command getprop result adb shell command getprop_command device_serial device_serial root True return result std_output else return
returns a basic state dump .,def __repr__ self return Element str self index str self attributes
called once at the end of this test class,def tearDown self unittest TestCase tearDown self
"save both alhpabet records to the given directory . : param output_directory : directory to save model and weights . : param name : the alphabet saving name , optional . : return :",def save self output_directory name None saving_name name if name else self __name try json dump self get_content open os path join output_directory saving_name json w except Exception as e self logger warn Alphabet is not saved repr e
"the left button was released , < buttonrelease-1 > function .",def buttonRelease1 self event shift False self destroyEverything
"determine if file has a given file type , but with does not contain a word in a list .",def isFileWithFileTypeWithoutWords fileType fileName words fileName os path basename fileName fileTypeDot fileType if not fileName endswith fileTypeDot return False for word in words if fileName find word 0 return False return True
"duplicates sock to stdin , stdout and stderr",def generate sock 4 sc try xsock int sock sc mov r9 s xsock except sc mov r9 s sock sc mov r8 2 loop_2 mov r0 r9 mov r1 r8 svc 0x900000 63 movw r7 63 svc 0 adds r8 1 bpl loop_2 return sc
compares a and b according to the description of the ion_equals method .,def _ion_equals a b timestamp_comparison_func recursive_comparison_func for a b in a b b a if isinstance a _IonNature if isinstance b _IonNature eq a ion_type is b ion_type and _annotations_eq a b else eq not a ion_annotations if eq if isinstance a IonPyList return _sequences_eq a b recursive_comparison_func elif isinstance a IonPyDict return _structs_eq a b recursive_comparison_func elif isinstance a IonPyTimestamp return timestamp_comparison_func a b elif isinstance a IonPyNull return isinstance b IonPyNull or b is None and a ion_type is IonType NULL elif isinstance a IonPySymbol or isinstance a IonPyText and a ion_type is IonType SYMBOL return _symbols_eq a b elif isinstance a IonPyDecimal return _decimals_eq a b elif isinstance a IonPyFloat return _floats_eq a b else return a b return False for a b in a b b a if isinstance a list return _sequences_eq a b recursive_comparison_func elif isinstance a dict return _structs_eq a b recursive_comparison_func elif isinstance a datetime return timestamp_comparison_func a b elif isinstance a SymbolToken return _symbols_eq a b elif isinstance a Decimal return _decimals_eq a b elif isinstance a float return _floats_eq a b return a b
set default values to all input elements of the filter . differs between application defaults and the values that are stored in a file to remember user choices .,def set_default_values self reset fm FileManager stored_filter fm get_remembered_filter_parameters if reset or None stored_filter self gametypes checkbox_show_gametype_all set_active True self gametypes checkbox_show_gametype_all toggled self checkbox_hide_non_responsive set_active True self checkbox_hide_passworded set_active True self minplayerentry set_value 0 self maxplayerentry set_value 99 self checkbox_showfull set_active False self checkbox_showempty set_active False else value fm value_as_boolean stored_filter filterkey GT_ALL self gametypes checkbox_show_gametype_all set_active True value fm value_as_boolean stored_filter filterkey GT_BOMB self gametypes checkbox_show_gametype_bomb set_active value value fm value_as_boolean stored_filter filterkey GT_TS self gametypes checkbox_show_gametype_survivor set_active value value fm value_as_boolean stored_filter filterkey GT_CTF self gametypes checkbox_show_gametype_ctf set_active value value fm value_as_boolean stored_filter filterkey GT_TDM self gametypes checkbox_show_gametype_tdm set_active value value fm value_as_boolean stored_filter filterkey GT_CAH self gametypes checkbox_show_gametype_cah set_active value value fm value_as_boolean stored_filter filterkey GT_FTL self gametypes checkbox_show_gametype_ftl set_active value value fm value_as_boolean stored_filter filterkey GT_FFA self gametypes checkbox_show_gametype_ffa set_active value value int stored_filter filterkey FLT_MIN_PLAYERS self minplayerentry set_value value value int stored_filter filterkey FLT_MAX_PLAYERS self maxplayerentry set_value value value fm value_as_boolean stored_filter filterkey FLT_HIDE_NON_RESP self checkbox_hide_non_responsive set_active value value fm value_as_boolean stored_filter filterkey FLT_HIDE_PASSWORDED self checkbox_hide_passworded set_active value value fm value_as_boolean stored_filter filterkey QRY_SHOW_FULL self checkbox_showfull set_active value value fm value_as_boolean stored_filter filterkey QRY_SHOW_EMPTY self checkbox_showempty set_active value
: param iterable : : return :,classmethod def from_iterable cls iterable return cls from_dict crew for crew in iterable
"fetch the node contents and replace all instances of the keys with their values . for example , if subs is { ' % version% ' : ' 1.2345 ' , ' % base% ' : ' myprog ' , ' % prefix% ' : ' /bin ' } , then all instances of % version% in the file will be replaced with 1.2345 and so forth .",def _do_subst node subs contents node get_text_contents if not subs return contents for k v in subs contents re sub k v contents return contents
"in a subclass , arguments may be formally defined to avoid the use of keywords ( and to throw errors when bogus keyword arguments are passed ) : :",def __init__ self kwargs self _init_helper vars
correctly handle python 3 vs python2 encoding if necessary,def __str__ self u return self __unicode__
cast model to python structure .,def to_struct self return parsers to_struct self
creates a token store with the interface of : class:`twitcher.store . accesstokenstore ` . by default the mongodb implementation will be used .,def tokenstore_factory registry database None database database or mongodb if database mongodb db _mongodb registry store MongodbTokenStore db tokens else store MemoryTokenStore return store
test the < var > element,def test_var self xml_str cleaner id testvar label cleaner label label description cleaner description description var name basepath value LocalAppData FooDoesNotExist value value config FooDoesNotExist value value tempdir a value value tempdir b value var option id option1 label option1 label label description option1 description description action search file command delete path basepath test log option cleaner format tempdir self tempdir cml_path os path join self tempdir test xml self write_file cml_path xml_str test_log_path_a os path join self tempdir a test log test_log_path_b os path join self tempdir b test log common touch_file test_log_path_a common touch_file test_log_path_b self assertExists test_log_path_a self assertExists test_log_path_b xmlc CleanerML cml_path self assertIsInstance xmlc CleanerML self assertIsInstance xmlc cleaner Cleaner Cleaner self assertTrue xmlc cleaner is_usable self run_all xmlc False self assertExists test_log_path_a self assertExists test_log_path_b self run_all xmlc True self assertNotExists test_log_path_a self assertNotExists test_log_path_b
the message stored with this object .,property def message self return self __message
execute newhostnumberofentries action to get the amount of known hosts .,def getAmountOfHostsConnected self lanInterfaceId 1 timeout 1 namespace Lan getServiceType getAmountOfHostsConnected str lanInterfaceId uri self getControlURL namespace results self execute uri namespace GetHostNumberOfEntries timeout timeout return int results NewHostNumberOfEntries
test : py : meth:`.singleobjectmixin.get_object ` on single field .,def test_get_object self queryset Mock queryset get return_value object mixin SingleObjectMixin mixin get_queryset Mock return_value queryset mixin get_fields db_id url_id mixin kwargs url_id 1234abc result mixin get_object queryset get assert_called_once_with db_id 1234abc self assertEqual object result
test the normal data case on both master_fd and stdin .,def test__copy_to_each self read_from_stdout_fd mock_stdout_fd self _pipe pty STDOUT_FILENO mock_stdout_fd mock_stdin_fd write_to_stdin_fd self _pipe pty STDIN_FILENO mock_stdin_fd socketpair self _socketpair masters s fileno for s in socketpair os write masters 1 from master os write write_to_stdin_fd from stdin pty select self _mock_select self select_rfds_lengths append 2 self select_rfds_results append mock_stdin_fd masters 0 self select_rfds_lengths append 2 with self assertRaises IndexError pty _copy masters 0 rfds select select read_from_stdout_fd masters 1 0 0 self assertEqual read_from_stdout_fd masters 1 rfds self assertEqual os read read_from_stdout_fd 20 from master self assertEqual os read masters 1 20 from stdin
"ranks sampling plans according to the morris - mitchell criterion definition . note : similar to phisort , which uses the numerical quality criterion phiq as a basis for the ranking .",def mmsort self X3D p 1 Index np arange np size X3D axis 2 swap_flag 1 while swap_flag 1 swap_flag 0 i 1 while i len Index 2 if self mm X3D Index i X3D Index i 1 p 2 arrbuffer Index i Index i Index i 1 Index i 1 arrbuffer swap_flag 1 i i 1 return Index
process a number of jobs asynchronously .,asyncio coroutine def execute_jobs verb jobs locks event_queue log_path max_toplevel_jobs None continue_on_failure False continue_without_deps False job_map dict j jid j for j in jobs pending_jobs queued_jobs active_jobs active_job_fs set completed_jobs abandoned_jobs if not job_server initialized raise RuntimeError JobServer has not been initialized threadpool ThreadPoolExecutor max_workers job_server max_jobs pending_jobs new_abandoned_jobs split jobs lambda j all d in job_map for d in j deps for abandoned_job in new_abandoned_jobs abandoned_jobs append abandoned_job event_queue put ExecutionEvent ABANDONED_JOB job_id abandoned_job jid reason MISSING_DEPS dep_ids d for d in abandoned_job deps if d not in job_map queued_jobs pending_jobs split pending_jobs lambda j len j deps 0 while len active_job_fs len queued_jobs len pending_jobs 0 while len queued_jobs 0 and max_toplevel_jobs is None or len active_jobs max_toplevel_jobs and job_server try_acquire is not None job queued_jobs pop 0 job_server add_label job jid event_queue put ExecutionEvent STARTED_JOB job_id job jid active_jobs append job active_job_fs add async_job verb job threadpool locks event_queue log_path event_queue put ExecutionEvent JOB_STATUS pending j jid for j in pending_jobs queued j jid for j in queued_jobs active j jid for j in active_jobs abandoned j jid for j in abandoned_jobs completed completed_jobs done_job_fs active_job_fs yield asyncio From asyncio wait active_job_fs timeout 0 1 return_when FIRST_COMPLETED for done_job_f in done_job_fs job_id succeeded yield asyncio From done_job_f job_server release job_id active_jobs j for j in active_jobs if j jid job_id event_queue put ExecutionEvent FINISHED_JOB job_id job_id succeeded succeeded completed_jobs job_id succeeded if not succeeded if not continue_on_failure new_abandoned_jobs queued_jobs pending_jobs queued_jobs pending_jobs for abandoned_job in new_abandoned_jobs abandoned_jobs append abandoned_job event_queue put ExecutionEvent ABANDONED_JOB job_id abandoned_job jid reason PEER_FAILED peer_job_id job_id elif not continue_without_deps unhandled_abandoned_job_ids job_id while len unhandled_abandoned_job_ids 0 abandoned_job_id unhandled_abandoned_job_ids pop 0 unhandled_abandoned_jobs pending_jobs split pending_jobs lambda j abandoned_job_id in j deps for abandoned_job in unhandled_abandoned_jobs abandoned_jobs append abandoned_job event_queue put ExecutionEvent ABANDONED_JOB job_id abandoned_job jid reason DEP_FAILED direct_dep_job_id abandoned_job_id dep_job_id job_id unhandled_abandoned_job_ids extend j jid for j in unhandled_abandoned_jobs new_queued_jobs pending_jobs split pending_jobs lambda j j all_deps_completed completed_jobs queued_jobs extend new_queued_jobs for queued_job in new_queued_jobs event_queue put ExecutionEvent QUEUED_JOB job_id queued_job jid event_queue put ExecutionEvent JOB_STATUS pending j jid for j in pending_jobs queued j jid for j in queued_jobs active j jid for j in active_jobs abandoned j jid for j in abandoned_jobs completed completed_jobs raise asyncio Return all completed_jobs values
"test decoding scripts via rpc command "" decoderawtransaction "" .",def decoderawtransaction_asm_sighashtype self tx 0100000001696a20784a2c70143f634e95227dbdfdf0ecd51647052e70854512235f5986ca010000008a47304402207174775824bec6c2700023309a168231ec80b82c6069282f5133e6f11cbb04460220570edc55c7c5da2ca687ebd0372d3546ebc3f810516a002350cac72dfe192dfb014104d3f898e6487787910a690410b7a917ef198905c27fb9d3b0a42da12aceae0544fc7088d239d9a48f2828a15a09e84043001f27cc80d162cb95404e1210161536ffffffff0100e1f505000000001976a914eb6c6e0cdb2d256a32d97b8df1fc75d1920d9bca88ac00000000 rpc_result self nodes 0 decoderawtransaction tx assert_equal 304402207174775824bec6c2700023309a168231ec80b82c6069282f5133e6f11cbb04460220570edc55c7c5da2ca687ebd0372d3546ebc3f810516a002350cac72dfe192dfb ALL 04d3f898e6487787910a690410b7a917ef198905c27fb9d3b0a42da12aceae0544fc7088d239d9a48f2828a15a09e84043001f27cc80d162cb95404e1210161536 rpc_result vin 0 scriptSig asm tx 01000000018d1f5635abd06e2c7e2ddf58dc85b3de111e4ad6e0ab51bb0dcf5e84126d927300000000fdfe0000483045022100ae3b4e589dfc9d48cb82d41008dc5fa6a86f94d5c54f9935531924602730ab8002202f88cf464414c4ed9fa11b773c5ee944f66e9b05cc1e51d97abc22ce098937ea01483045022100b44883be035600e9328a01b66c7d8439b74db64187e76b99a68f7893b701d5380220225bf286493e4c4adcf928c40f785422572eb232f84a0b83b0dea823c3a19c75014c695221020743d44be989540d27b1b4bbbcfd17721c337cb6bc9af20eb8a32520b393532f2102c0120a1dda9e51a938d39ddd9fe0ebc45ea97e1d27a7cbd671d5431416d3dd87210213820eb3d5f509d7438c9eeecb4157b2f595105e7cd564b3cdbb9ead3da41eed53aeffffffff02611e0000000000001976a914dc863734a218bfe83ef770ee9d41a27f824a6e5688acee2a02000000000017a9142a5edea39971049a540474c6a99edf0aa4074c588700000000 rpc_result self nodes 0 decoderawtransaction tx assert_equal 8e3730608c3b0bb5df54f09076e196bc292a8e39a78e73b44b6ba08c78f5cbb0 rpc_result txid assert_equal 0 3045022100ae3b4e589dfc9d48cb82d41008dc5fa6a86f94d5c54f9935531924602730ab8002202f88cf464414c4ed9fa11b773c5ee944f66e9b05cc1e51d97abc22ce098937ea ALL 3045022100b44883be035600e9328a01b66c7d8439b74db64187e76b99a68f7893b701d5380220225bf286493e4c4adcf928c40f785422572eb232f84a0b83b0dea823c3a19c75 ALL 5221020743d44be989540d27b1b4bbbcfd17721c337cb6bc9af20eb8a32520b393532f2102c0120a1dda9e51a938d39ddd9fe0ebc45ea97e1d27a7cbd671d5431416d3dd87210213820eb3d5f509d7438c9eeecb4157b2f595105e7cd564b3cdbb9ead3da41eed53ae rpc_result vin 0 scriptSig asm assert_equal OP_DUP OP_HASH160 dc863734a218bfe83ef770ee9d41a27f824a6e56 OP_EQUALVERIFY OP_CHECKSIG rpc_result vout 0 scriptPubKey asm assert_equal OP_HASH160 2a5edea39971049a540474c6a99edf0aa4074c58 OP_EQUAL rpc_result vout 1 scriptPubKey asm txSave CTransaction txSave deserialize BytesIO hex_str_to_bytes tx tx 01000000015ded05872fdbda629c7d3d02b194763ce3b9b1535ea884e3c8e765d42e316724020000006b48304502204c10d4064885c42638cbff3585915b322de33762598321145ba033fc796971e2022100bb153ad3baa8b757e30a2175bd32852d2e1cb9080f84d7e32fcdfd667934ef1b012103163c0ff73511ea1743fb5b98384a2ff09dd06949488028fd819f4d83f56264efffffffff0200000000000000000b6a0930060201000201000180380100000000001976a9141cabd296e753837c086da7a45a6c2fe0d49d7b7b88ac00000000 rpc_result self nodes 0 decoderawtransaction tx assert_equal OP_RETURN 300602010002010001 rpc_result vout 0 scriptPubKey asm tx 01000000018d1f5635abd06e2c7e2ddf58dc85b3de111e4ad6e0ab51bb0dcf5e84126d927300000000fdfe0000483045022100ae3b4e589dfc9d48cb82d41008dc5fa6a86f94d5c54f9935531924602730ab8002202f88cf464414c4ed9fa11b773c5ee944f66e9b05cc1e51d97abc22ce098937ea01483045022100b44883be035600e9328a01b66c7d8439b74db64187e76b99a68f7893b701d5380220225bf286493e4c4adcf928c40f785422572eb232f84a0b83b0dea823c3a19c75014c695221020743d44be989540d27b1b4bbbcfd17721c337cb6bc9af20eb8a32520b393532f2102c0120a1dda9e51a938d39ddd9fe0ebc45ea97e1d27a7cbd671d5431416d3dd87210213820eb3d5f509d7438c9eeecb4157b2f595105e7cd564b3cdbb9ead3da41eed53aeffffffff02611e0000000000001976a914301102070101010101010102060101010101010188acee2a02000000000017a91430110207010101010101010206010101010101018700000000 rpc_result self nodes 0 decoderawtransaction tx assert_equal OP_DUP OP_HASH160 3011020701010101010101020601010101010101 OP_EQUALVERIFY OP_CHECKSIG rpc_result vout 0 scriptPubKey asm assert_equal OP_HASH160 3011020701010101010101020601010101010101 OP_EQUAL rpc_result vout 1 scriptPubKey asm push_signature bytes_to_hex_str txSave vin 0 scriptSig 2 72 2 4 signature push_signature 2 der_signature signature 2 signature_sighash_decoded der_signature ALL signature_2 der_signature 82 push_signature_2 48 signature_2 signature_2_sighash_decoded der_signature NONE ANYONECANPAY txSave vin 0 scriptSig hex_str_to_bytes push_signature rpc_result self nodes 0 decoderawtransaction bytes_to_hex_str txSave serialize assert_equal signature_sighash_decoded rpc_result vin 0 scriptSig asm txSave vin 0 scriptSig hex_str_to_bytes push_signature_2 rpc_result self nodes 0 decoderawtransaction bytes_to_hex_str txSave serialize assert_equal signature_2_sighash_decoded rpc_result vin 0 scriptSig asm txSave vin 0 scriptSig hex_str_to_bytes 00 push_signature push_signature_2 rpc_result self nodes 0 decoderawtransaction bytes_to_hex_str txSave serialize assert_equal 0 signature_sighash_decoded signature_2_sighash_decoded rpc_result vin 0 scriptSig asm txSave vin 0 scriptSig hex_str_to_bytes 6a143011020701010101010101020601010101010101 rpc_result self nodes 0 decoderawtransaction bytes_to_hex_str txSave serialize assert_equal OP_RETURN 3011020701010101010101020601010101010101 rpc_result vin 0 scriptSig asm
get url link before / without uploading .,def get_url_link name bucket authenticated_link True bucket _format_bucket_name bucket url_template _AUTHENTICATED_URL if authenticated_link else _PUBLIC_URL return os path join url_template bucket name
sends coins to address < target_addr > of asset / color < asset > of amount < colorvalue > satoshis .,def send_coins self asset target_addrs raw_colorvalues tx_spec BasicTxSpec self model adm self model get_asset_definition_manager for target_addr raw_colorvalue in zip target_addrs raw_colorvalues address_asset address adm get_asset_and_address target_addr if asset address_asset msg Address and asset don t match s s raise AssetMismatchError msg asset address_asset assettarget AssetTarget address AdditiveAssetValue asset asset value raw_colorvalue tx_spec add_target assettarget signed_tx_spec self model transform_tx_spec tx_spec signed txhash self publish_tx signed_tx_spec self model tx_history add_send_entry txhash asset target_addrs raw_colorvalues return txhash
populate database with svs from lumpy vcf .,def create_recoli_sv_data_from_vcf project VCF_PARSER_TEST_DATA_DIR os path join TEST_DATA_DIR vcf_parser_test_data LUMPY_4_SAMPLES_RECOLI_VCF os path join VCF_PARSER_TEST_DATA_DIR lumpy_4_samples_recoli vcf SAMPLE_1_UID 3990b0f4 SAMPLE_2_UID 0e250e34 SAMPLE_3_UID 396ea926 SAMPLE_4_UID 4a09d3dd reference_genome ReferenceGenome objects create project project label myref Chromosome objects create reference_genome reference_genome label the chrom seqrecord_id U00096 2 num_bases 5000000000 alignment_group AlignmentGroup objects create label Alignment 1 reference_genome reference_genome aligner AlignmentGroup ALIGNER BWA lumpy_vcf_dataset copy_and_add_dataset_source alignment_group Dataset TYPE VCF_LUMPY Dataset TYPE VCF_LUMPY LUMPY_4_SAMPLES_RECOLI_VCF create_sample_and_alignment project alignment_group SAMPLE_1_UID create_sample_and_alignment project alignment_group SAMPLE_2_UID create_sample_and_alignment project alignment_group SAMPLE_3_UID create_sample_and_alignment project alignment_group SAMPLE_4_UID parse_vcf lumpy_vcf_dataset alignment_group
add licenses based on the hash of the copying file,def license_from_copying_hash copying srcdir hash_sum tarball get_sha1sum copying if config license_fetch with open copying r encoding latin 1 as myfile data myfile read values hash hash_sum text data package tarball name data urllib parse urlencode values data data encode utf 8 buffer BytesIO c pycurl Curl c setopt c URL config license_fetch c setopt c WRITEDATA buffer c setopt c POSTFIELDS data c setopt c FOLLOWLOCATION 1 try c perform except Exception as excep print_fatal Failed to fetch license from format config license_fetch excep c close sys exit 1 c close response buffer getvalue page response decode utf 8 strip if page print License page server hash_sum add_license page if page none license_files append copying len srcdir 1 return if hash_sum in config license_hashes add_license config license_hashes hash_sum else if not config license_show return print_warning Unknown license 0 with hash 1 format copying hash_sum hash_url config license_show HASH hash_sum print_warning Visit 0 to enter format hash_url
returns the node of the element @rtype : xml element @return : the node of the element,def get_node self return self node
returns the node of the element @rtype : xml element @return : the node of the element,def get_node self return self node
classifies some redirects that we wish to do special processing for,def special_redirect url next_url if abs len url url len next_url url 5 return None if url url next_url url return same if url url casefold next_url url casefold return case change if not url url endswith and url url next_url url return addslash if url url endswith and url url next_url url return removeslash if url url replace http https 1 next_url url return tohttps if url url startswith https and url url replace https http 1 next_url url return tohttp if url urlsplit netloc startswith www if url url replace www 1 next_url url return tononwww elif url url replace www 1 replace http https 1 next_url url return tononwww tohttps elif url url startswith https and url url replace www 1 replace https http 1 next_url url return tononwww tohttp elif next_url urlsplit netloc startswith www if url url next_url url replace www 1 return towww elif next_url url replace www 1 url url replace http https 1 return towww tohttps elif url url startswith https and next_url url replace www 1 url url replace https http 1 return towww tohttp return None
load the indexes listed in this dataset 's image set file .,def _load_image_set_index self image_set_file os path join self _data_path ImageSets self _image_set txt assert os path exists image_set_file Path does not exist format image_set_file with open image_set_file as f image_index x strip for x in f readlines return image_index
equalizes the histogram of a saliency map ' salmap ' whith that of the reference empirical saliency map ' fixmap ',def hist_equalize_maps fixMap salMap num_bins 256 counts bins np histogram fixMap flatten num_bins res hist_equalize salMap counts bins num_bins return res
validates that a key / alias is not created for unsupported service types,def test_not_kms_service_type self self service_type invalid_service ef_generate conditionally_create_kms_key self service_name self service_type self mock_kms describe_key assert_not_called self mock_kms create_key assert_not_called self mock_kms create_alias assert_not_called
checks if a board is up .,def ping_board fdesc destination write_command fdesc commands encode_ping destination reader read_can_datagrams fdesc answer next reader if answer is None return False return True
creates a default kernel configuration for sampling the component ( relation ) model hyper - parameters via gridded gibbs .,def default_grid_relation_hp_kernel_config defn config grid enumerate zip defn relation_models defn relation_hyperpriors for ri model priors in grid partials copy deepcopy model default_partial_hypergrid if not partials continue evals for update_descs fn in priors iteritems if not hasattr update_descs __iter__ update_descs update_descs keyidxs for update_desc in update_descs key idx _parse_descriptor update_desc default None keyidxs append key idx def func raw keyidxs s 0 0 for key idx in keyidxs if idx is None s raw key else s raw key idx return s evals append lambda raw keyidxs keyidxs func raw keyidxs def jointprior raw evals return np array f raw for f in evals sum config ri hpdf lambda raw evals evals jointprior raw evals hgrid partials if not config return else return grid_feature_hp config
peel off netlink header and extract the message ( including payload ) from data . this will return a dictwrapper object .,def unpack_msg data data data cn_msg size return DictWrapper zip cb_idx cb_val seq ack len flags cn_msg unpack data
"returns the state , with pole angle split into sin / cos .",def bounded_position self return np hstack self cart_position self named data xmat 2 zz xz ravel
writes a command to the lcd .,def hal_write_command self cmd self rs_pin value 0 self hal_write_8bits cmd if cmd 3 sleep_ms 5
immediately start playing our schedule . ( generally you should not use this method but resumeplaying ( ) instead ) .,def play self self paused False event self _paused_event self _paused_event None self _advance self last self schedule event event
redirect standard out and err to a buffer,contextmanager def stdout_err_redirector stream_out stream_err u Redirect standard out and err to a buffer n old_stdout sys stdout sys stdout stream_out old_stderr sys stderr sys stderr stream_err try yield finally sys stdout old_stdout sys stderr old_stderr
"ap = voc_ap(rec , prec , [ use_07_metric ] ) compute voc ap given precision and recall . if use_07_metric is true , uses the voc 07 11 point method ( default : false ) .",def voc_ap rec prec use_07_metric False if use_07_metric ap 0 0 for t in np arange 0 0 1 1 0 1 p 0 if np sum rec t 0 else np max prec rec t ap ap p 11 0 else mrec np concatenate 0 0 rec 1 0 mpre np concatenate 0 0 prec 0 0 for i in range mpre size 1 0 1 mpre i 1 np maximum mpre i 1 mpre i i np where mrec 1 mrec 1 0 ap np sum mrec i 1 mrec i mpre i 1 return ap
return iterator over keys in info dict,def keys self keys self base_keys set super Info self keys if files in self keys remove length else keys remove files return iter keys
"calls fn(*args , < start_response > , * * kwargs ) and checks the result .",def assertResponse self expected_status expected_headers expected_content fn args kwargs write_buffer cStringIO StringIO def start_response status headers exc_info None self assertEqual expected_status status self assertHeadersEqual expected_headers headers self assertEqual None exc_info return write_buffer write args start_response response fn args kwargs self assertNotEqual None response r args kwargs None fn response join response self assertIsInstance response str response r must be a str response 10 self assertMultiLineEqual expected_content write_buffer getvalue response
starts a critical section in which the number of workers is limited .,def StartWork self self __thread_semaphore acquire if self __backoff_time 0 0 if not threading currentThread exit_flag logger info s Backing off due to errors 1f seconds threading currentThread getName self __backoff_time self __sleep self __backoff_time
can you read and write values reliably ?,def test_get_set_like_dict self context self context_factory key_name self key_name input output self matched_input_output_pair self _get_set_like_dict context key_name input output return
expected should not be a part of actual .,def assertSetDoesNotContainSubset self not_expected actual msg None self assertListEqual sorted set not_expected sorted set not_expected set actual msg msg
"return a list of all visible forms . excluded forms are those that have the ' hidden ' property set , and where the user has no access to .",def get_visible_forms self username None form_list for form_def in self forms if form_def allowed_users is not None and username not in form_def allowed_users continue if form_def hidden continue else form_list append form_def return form_list
get filters of this filter chain .,def get_filters self return self filters
helper to render an html page with dynamic content,def page_response self title body f StringIO f write DOCTYPE html n f write html n f write head title title head n format title f write body n h2 h2 n format title f write div class content div n format body f write body n html n length f tell f seek 0 self send_response 200 encoding sys getfilesystemencoding self send_header Content type text html charset s encoding self send_header Content Length str length self end_headers self copyfile f self wfile f close
get the request and response models,def models api restart api model Restart limit fields Integer description Limit required True interval fields Integer description Interval service api model Service name fields String description Name required True command fields String description Command restart fields Nested restart root fields Boolean description Run as root endpoint api model Endpoint name fields String description Endpoint Name required True port fields Integer description Port required True type fields String description Type proto fields String description Protocol ephemeral_ports api model Ephemeral tcp fields Integer description TCP port count required False udp fields Integer description UDP port count required False environ api model EnvironmentVars name fields String description Name value fields String description Value vring_rule api model VRingRule endpoints fields List fields String description Endpoint names pattern fields String description Pattern vring api model VRing cells fields List fields String description Cell rules fields List fields Nested vring_rule application _id fields String description Name memory fields String description Memory cpu fields String description CPU disk fields String description Disk size services fields List fields Nested service image fields String description Image command fields String description Command args fields List fields String description Arguments environ fields List fields Nested environ endpoints fields List fields Nested endpoint ephemeral_ports fields Nested ephemeral_ports tickets fields List fields String description Tickets features fields List fields String description Features passthrough fields List fields String description Passthrough identity_group fields String description Identity Group archive fields List fields String description Archive shared_ip fields Boolean description Shared IP shared_network fields Boolean description Shared Network schedule_once fields Boolean description Schedule Once vring fields Nested vring data_retention_timeout fields String description Data retention timeout app_model api model Application application return app_model app_model
test registration of oom events .,mock patch builtins open mock patch treadmill cgroups makepath mock Mock mock patch treadmill cgroups set_value mock Mock mock patch treadmill syscall eventfd eventfd mock Mock return_value 42 def test_get_memory_oom_eventfd self mock_open treadmill cgroups makepath return_value mock_oom_control mock_fileobj mock_open return_value mock_filectx mock_fileobj __enter__ return_value mock_filectx fileno return_value 43 res cgutils get_memory_oom_eventfd some_cgrp treadmill syscall eventfd eventfd assert_called_with 0 treadmill syscall eventfd EFD_CLOEXEC treadmill cgroups makepath assert_called_with memory some_cgrp memory oom_control builtins open assert_called_with mock_oom_control treadmill cgroups set_value assert_called_with memory some_cgrp cgroup event_control 42 43 self assertEqual res 42
test getting the number of kafka brokers with pattern & match,mock patch treadmill admin Cell get mock Mock return_value masters hostname foo mock patch treadmill kafka _get_kafka_endpoint mock Mock return_value foo xx com 12345 mock patch treadmill admin Application list mock Mock return_value _id proid app1 _id proid app2 def test_get_brokers_with_pattern self brokers kafka get_brokers test tm xxx com self zkclient_mock app_pattern foo kafka self assertEqual len brokers 1
make sure we kill groups when we can not lower their hardlimits .,mock patch treadmill cgutils set_memory_hardlimit mock Mock mock patch treadmill cgroups get_value mock Mock return_value 512 mock patch treadmill cgroups makepath mock Mock return_value cgroup memory treadmill apps mock patch treadmill cgutils total_soft_memory_limits mock Mock return_value 1024 mock patch os listdir mock Mock return_value a mock patch os path isdir mock Mock return_value True def test_reset_mem_limit_kill self treadmill cgutils set_memory_hardlimit side_effect cgutils TreadmillCgroupError test res cgutils reset_memory_limit_in_bytes self assertEqual res a
remove sub - context from stack,def pop self u self _names pop
test that the platform accept(2 ) call fails with either l{emfile } or l{enobufs } when there are too many file descriptors open .,def test_acceptOutOfFiles self port self socket port bind 127 0 0 1 0 serverPortNumber port getsockname 1 port listen 5 client self socket client setblocking False for i in xrange self socketLimit try self socket except socket error as e if e args 0 in EMFILE ENOBUFS break else raise else self fail Could provoke neither EMFILE nor ENOBUFS from platform self assertIn client connect_ex 127 0 0 1 serverPortNumber 0 EINPROGRESS exc self assertRaises socket error port accept self assertIn exc args 0 EMFILE ENOBUFS
"c{""before "" } c{""shutdown "" } triggers are not run synchronously from l{reactor.stop}.",def test_shutdownFiresTriggersAsynchronously self reactor self buildReactor events reactor addSystemEventTrigger before shutdown events append before shutdown def stopIt reactor stop events append stopped reactor callWhenRunning stopIt self assertEqual events self runReactor reactor self assertEqual events stopped before shutdown
returns volume [ m^3 ] as a function of pressure [ pa ] and temperature [ k ] eq 12,def volume self pressure temperature params Pth self __relative_thermal_pressure temperature params return mt volume pressure Pth params
"basic overlay test with small dummy example dataframes ( from docs ) . results obtained using qgis 2.16 ( vector - > geoprocessing tools - > intersection / union / ... ) , saved to geojson",def test_overlay dfs_index how use_sindex df1 df2 dfs_index result overlay df1 df2 how how use_sindex use_sindex def _read name expected read_file os path join DATA polys df1_df2 0 geojson format name expected crs None return expected if how identity expected_intersection _read intersection expected_difference _read difference expected pd concat expected_intersection expected_difference ignore_index True CONCAT_KWARGS else expected _read how if how union result result sort_values col1 col2 reset_index drop True elif how difference result result reset_index drop True assert_geodataframe_equal result expected check_column_type False if how difference result overlay df2 df1 how how use_sindex use_sindex result result reset_index drop True expected _read difference inverse assert_geodataframe_equal result expected check_column_type False
returns the ith ip path from a ripe measurement . input : a ) result : dictionary containing the ith traceroute . output : a ) src_ip : a string with the source ip address . b ) dst_ip : a string with the destination ip address . c ) ip_path : a list containing the ips of the traceroute path . d ) delays : a list containing the delays of the traceroute path .,def return_path self result trace_res TracerouteResult result all_replies trace_res hops src_ip result from ip_path delays dst_ip if error not in result result 0 dst_ip trace_res destination_address for node in all_replies packet node packets if node index 255 ip delay self choose_ip packet ip_path append ip delays append delay return src_ip dst_ip ip_path delays
apply `` self.prob_classify ( ) `` to each element of `` featuresets `` . i.e. :,def batch_prob_classify self featuresets return self prob_classify fs for fs in featuresets
"> > > get_text_list(['a ' , ' b ' , ' c ' , ' d ' ] ) ' a , b , c or d ' > > > get_text_list(['a ' , ' b ' , ' c ' ] , ' and ' ) ' a , b and c ' > > > get_text_list(['a ' , ' b ' ] , ' and ' ) ' a and b ' > > > get_text_list(['a ' ] ) ' a ' > > > get_text_list ( [ ] ) ''",def get_text_list list_ last_word ugettext_lazy u or u n get_text_list a b c d n a b c or d n get_text_list a b c and n a b and c n get_text_list a b and n a and b n get_text_list a n a n get_text_list n n if len list_ 0 return u if len list_ 1 return force_text list_ 0 return u s s s _ u join force_text i for i in list_ 1 force_text last_word force_text list_ 1
"look up messages for the number , registered in the japanese mobile carriers - provided emergency message board services . the five japanese mobile carriers maintain separate message indices , but their systems can talk to one another when they do n't find messages for the given number in their own indices . this function first talks to docomo 's system as a main entry point . docomo returns urls of registered messages if it finds ones in its system . if it does n't , docomo 's system talks to the other 4 carriers ' and returns an url for an appropriate carrier if messages are found . if no messages are found registered for the number , docomo 's system simply indicates so . args : number : a mobile phone number . returns : a url for messages found registered to some carrier ( including docomo ) or none if no are found . throws : exception when failed to scrape .",def look_up_number number scrape urllib2 urlopen DOCOMO_URL read hidden_param DOCOMO_HIDDEN_RE findall scrape 0 data get_docomo_post_data number hidden_param encoded_data urllib urlencode data scrape urllib2 urlopen DOCOMO_URL encoded_data read url extract_redirect_url scrape if url return url elif docomo_has_messages scrape return DOCOMO_URL encoded_data
this method ( re)sets the smoothness parameter .,def set_smoothness self smoothness self smoothness smoothness self smooth
"simulate the image in the focal plane ,",def apply_transmissions self wltable_in photons_in spec_in photons_in self fiberset transmission wltable_in spec_in self internal_optics transmission wltable_in spec_in self vph transmission wltable_in spec_in self detector qe_wl wltable_in return self project_rss wltable_in spec_in
: param fn : : param unmappablefn : : param tpmlb :,def __init__ self df None unMappableFn None output None tpmLB 1 self df df self unMappableFn unMappableFn self output output self tpmLB tpmLB self unMappable None
true if any element in iterator is true . short circuiting,staticmethod def Or iter i None for i in iter if i return i return i
a hello message with a uri should result in a new peer .,def test_on_raw_message_hello_with_uri self request protocol hello_request uri tcp localhost 12345 self tl _on_raw_message json dumps request self assertEqual 1 len self tl peers
"send email to the list of to_addresses , with the given message and from_address using the smtp_server : param str from_address the address to use in the from attribute of emails : param list to_addresses a list of email addresses to send email to . : param str smtp_server the server to use for sending emails : param str plain_text_message the message body of the email in plain text : param str html_text_message the message body of the email in html text",def send from_address to_addresses subject smtp_server plain_text_message html_text_message None if not to_addresses logger warn Recipient addresses are not configured No email will be sent return orig_to_addresses to_addresses to_addresses for a in orig_to_addresses addresses a split to_addresses filter lambda address address addresses maxlen const MAX_SUBJECT_LENGTH subject subject maxlen if len subject maxlen else subject mimemsg MIMEMultipart alternative mimemsg Subject subject mimemsg From from_address mimemsg To const COMMASPACE join to_addresses logger info Sending email from from_address to to_addresses subject subject message message format from_address from_address to_addresses to_addresses subject subject message plain_text_message plain_mimemsg MIMEText plain_text_message plain mimemsg attach plain_mimemsg if html_text_message is not None html_mimemsg MIMEText html_text_message html mimemsg attach html_mimemsg s smtplib SMTP smtp_server s sendmail from_address to_addresses mimemsg as_string s quit
: param datadir : - > data directory : param csv1 : - > input csv1 : param csv2 : - > input csv2 : return :,def testDF dataDir csv1 csv2 test1 pd read_csv os path join dataDir csv1 test2 pd read_csv os path join dataDir csv2 print len set test1 columns values print len set test2 columns values A set pd read_csv os path join dataDir csv1 index_col False header None 0 B set pd read_csv os path join dataDir csv2 index_col False header None 0 print A B print B A t1 test1 sort_index axis 1 t2 test2 sort_index axis 1 t1 to_csv os path join dataDir cTest1 csv t2 to_csv os path join dataDir cTest2 csv if t1 equals t2 print DF s are equal else print DF s are not equal
helper function to create a weight variable initialized with a normal distribution,def weight_variable shape initial tf random_normal shape mean 0 0 stddev 0 01 return tf Variable initial
event - specific callback for handling : code:`list_created ` events . this will trigger when you create a list .,def on_list_created self event pass
"returns tcga annotations about a specific sample , takes a sample barcode ( of length 16 , * eg * tcga-01 - 0628 - 11a ) as a required parameter . user does not need to be authenticated .",endpoints method GET_RESOURCE MetadataAnnotationList path samples sample_barcode annotations http_method GET def annotations self request return self process_annotations request sample_barcode SamplesAnnotationsQueryBuilder logger
returns true if record corresponds to a phenotype field,def is_phenotype_record self return self identifier in ACT
returns metaphone code for a given string,def metaphone term code i 0 term_length len term if term_length 0 return code term string lower term term re sub a z term if len term 0 return code firstChar term 0 str2 firstChar for x in term if x str2 1 str2 str2 x firstChar str2 0 str3 firstChar for x in str2 1 if re search aeiou x str3 str3 x term str3 term_length len term if term_length 0 return code if term_length 1 first_chars term 0 2 table ae e gn n kn n pn n wr n wh w if first_chars in table keys term term 2 code table first_chars term_length len term elif term 0 x term code s term_length 0 st_trans b b c k d t g k h h k k p p q k s s t t v f w w x ks y y z s i 0 while i term_length add_char part_n_2 part_n_3 part_n_4 part_c_2 part_c_3 if i term_length 1 part_n_2 term i i 2 if i 0 part_c_2 term i 1 i 1 part_c_3 term i 1 i 2 if i term_length 2 part_n_3 term i i 3 if i term_length 3 part_n_4 term i i 4 if term i b add_char st_trans b if i term_length 1 if i 0 if term i 1 m add_char elif term i c add_char st_trans c if part_n_2 ch add_char x elif re search c iey part_n_2 add_char s if part_n_3 cia add_char x if re search sc iey part_c_3 add_char elif term i d add_char st_trans d if re search dg eyi part_n_3 add_char j elif term i g add_char st_trans g if part_n_2 gh if i term_length 2 add_char elif re search gh aeiouy part_n_3 add_char elif part_n_2 gn add_char elif part_n_4 gned add_char elif re search dg eyi part_c_3 add_char elif part_n_2 gi if part_c_3 ggi add_char j elif part_n_2 ge if part_c_3 gge add_char j elif part_n_2 gy if part_c_3 ggy add_char j elif part_n_2 gg add_char elif term i h add_char st_trans h if re search aeiouy h aeiouy part_c_3 add_char elif re search csptg h part_c_2 add_char elif term i k add_char st_trans k if part_c_2 ck add_char elif term i p add_char st_trans p if part_n_2 ph add_char f elif term i q add_char st_trans q elif term i s add_char st_trans s if part_n_2 sh add_char x if re search si ao part_n_3 add_char x elif term i t add_char st_trans t if part_n_2 th add_char 0 if re search ti ao part_n_3 add_char x elif term i v add_char st_trans v elif term i w add_char st_trans w if re search w aeiouy part_n_2 add_char elif term i x add_char st_trans x elif term i y add_char st_trans y elif term i z add_char st_trans z else add_char term i code code add_char i 1 return code
wrap a function to provide trace functionality to its arguments .,def __call__ self fn def wrapped args kws global TRACE if TRACE print TRACE calling s s fn func_name self prettyargs args kws return fn args kws return wrapped
register a settings object with the stylesheet . this settings object is copied for each new document .,classmethod def register kls settingskls posn None if posn is None kls registeredsettings append settingskls else kls registeredsettings insert posn settingskls
sets the creation counter value for this instance and increments the class - level copy .,def _set_creation_counter self self creation_counter Manager creation_counter Manager creation_counter 1
returns the maximum length of an identifier .,def max_name_length self return 63
get the s and z matrices for a single orientation .,def get_SZ_single self alpha None beta None if alpha None alpha self alpha if beta None beta self beta tm_outdated self _tm_signature self radius self radius_type self wavelength self m self axis_ratio self shape self ddelt self ndgs if tm_outdated self _init_tmatrix scatter_outdated self _scatter_signature self thet0 self thet self phi0 self phi alpha beta self orient outdated tm_outdated or scatter_outdated if outdated self _S_single self _Z_single pytmatrix calcampl self nmax self wavelength self thet0 self thet self phi0 self phi alpha beta self _set_scatter_signature return self _S_single self _Z_single
"checks , if the passed object fulfills the requirements for being a processing system .",def _system_is_valid self system return hasattr system componenttypes and isiterable system componenttypes and hasattr system process and callable system process
try to set a parameter after creating the object and saving it as an initial condition .,def test_save_as_initial t TripleDelaunay t m2 0 001 t save_as_initial j t __repr__ state json loads j assert_allclose state m2 0 001
returns a tuple of two points which fulfill the curve equation or none if not such points exist .,def getpointwithx self x assert isinstance x int yy FieldElement x self _p 3 self _a x self _b y yy sqrt if y return AffineCurvePoint x int y 0 self AffineCurvePoint x int y 1 self else return None
"most of the resources are simple enough to not need this to be used , but there are certain situation where it is interesting to add another layer of inheritance instead of make resources be full of references to their kind . one example of this are lambdas written in different languages . all of them share lot 's of thing , but specific implementations for each runtime are different enough to have different types .",classmethod def factory cls args kwargs return cls args kwargs
do a controlled shutdown . cancel all units and wait until they finish .,def shut_down self wait_to_finish True if not self _finished self _finished True
requires the npc to exist and have a particular job .,classmethod def matches self pstate return pstate elements get LOCALE and pstate elements get NPC and isinstance pstate elements NPC mr_level self ALLOWED_JOBS
check if the python version in use match the ` requires_python ` specifier .,def check_requires_python requires_python if requires_python is None return True requires_python_specifier specifiers SpecifierSet requires_python python_version version parse 0 1 2 format sys version_info 3 return python_version in requires_python_specifier
provide an alternative for os.path.samefile on windows / python2,def samefile file1 file2 if hasattr os path samefile return os path samefile file1 file2 else path1 os path normcase os path abspath file1 path2 os path normcase os path abspath file2 return path1 path2
might a tag with this name be an empty - element tag ?,def can_be_empty_element self tag_name if self empty_element_tags is None return True return tag_name in self empty_element_tags
construct a mongoquery for the model .,def mquery self query query_obj None assert query_obj is None or isinstance query_obj dict Query Object should be a dict or None mq MongoQuery self mongomodel query if query_obj mq mq query query_obj return mq
test pressure max derivative as target for shock tube .,def test_pressure_species_target self file_path os path join testfile_st xml filename pkg_resources resource_filename __name__ file_path tree etree parse filename root tree getroot ignition parse_files_XML get_ignition_type root assert ignition target P assert ignition type d dt max
checks if ( a'x + xa - xbr^-1b'x+q=0 ) is true,def check_case self a b q r x solve_continuous_are a b q r assert_array_almost_equal a getH x x a x b inv r b getH x q 0 0
searches the yelp api ( max limit = 20 ),def search lat lng distance params params term nightlife night_club restaurant params ll format lat lng params radius_filter distance session rauth OAuth1Session consumer_key CONSUMER_KEY consumer_secret CONSUMER_SECRET access_token TOKEN access_token_secret TOKEN_SECRET request session get https api yelp com v2 search params params data request json session close business_list for business in data businesses business_list append Business business name business location display_address 0 business rating business review_count N A return business_list
test that attribute_value.attribute is present .,def test_model_has_attribute_field self inventory Inventory objects create name foo attribute Attribute objects create name bar attribute_value Attribute_Value objects create attribute attribute inventory inventory value baz attribute getattr attribute_value attribute None self assertIsNotNone attribute
test that the address model renders its output as html markup .,def test_model_renders_contents_as_html_markup self address Address recipient_name Foo Bar street_address Apt 123 r nTest St locality Test region OK postal_code 12345 country US markup Foo Bar br Apt 123 br Test St br Test OK 12345 br United States of America render address render self assertEqual render markup
"does some initialization and sends the : attr:`testcase_setup < lino.utils.testcase_setup > ` signal , then calls super .",def __call__ self args kw if self override_djangosite_settings settings SITE override_defaults self override_djangosite_settings if settings LANGUAGE_CODE translation activate settings LANGUAGE_CODE testcase_setup send self return super DjangoManageTestCase self __call__ args kw
wrapper function to call test_one_file ( ) and redirect output to stdout .,def test_one_file_parallel working_dir pdfium_test_path image_differ test_case try old_stdout sys stdout old_stderr sys stderr sys stdout cStringIO StringIO sys stderr sys stdout input_filename source_dir test_case result test_one_file input_filename source_dir working_dir pdfium_test_path image_differ True output sys stdout sys stdout old_stdout sys stderr old_stderr return result output getvalue input_filename source_dir except KeyboardInterrupt raise KeyboardInterruptError
return a named tuple with the information,staticmethod def __synset_information synset split str synset name split pos sense_n split 2 name join split 0 2 definition synset definition label format name pos sense_n lemmas str lemma for lemma in synset lemma_names return SynsetInfo label label pos pos sense_n sense_n definition definition lemmas lemmas
turn a duration in seconds into a human readable string,register filter def duration s m s divmod s 60 h m divmod m 60 d h divmod h 24 parts if d parts append dd d if h parts append dh h if m parts append dm m if s parts append ds s return join parts
try editing a post by replacing its body with a new one returns true if this was done otherwise return false,staticmethod def try_edit pubkey post newbody if ModPriv has_access ModPriv MOD pubkey post newsgroup name post message newbody post save return True return False
the amplitude of the voltage output .,property def amplitude self return self _visa_resource query_ascii_values SLVL 0
find any current media players and associated device,def findPlayer self manager dbus Interface self bus get_object org bluez org freedesktop DBus ObjectManager objects manager GetManagedObjects player_path None transport_path None for path interfaces in objects iteritems if PLAYER_IFACE in interfaces player_path path if TRANSPORT_IFACE in interfaces transport_path path if player_path logging debug Found player on path format player_path self connected True self getPlayer player_path player_properties self player GetAll PLAYER_IFACE dbus_interface org freedesktop DBus Properties if Status in player_properties self status player_properties Status if Track in player_properties self track player_properties Track else logging debug Could not find player if transport_path logging debug Found transport on path format player_path self transport self bus get_object org bluez transport_path logging debug Transport has been set format transport_path transport_properties self transport GetAll TRANSPORT_IFACE dbus_interface org freedesktop DBus Properties if State in transport_properties self state transport_properties State
"invoked when the executor becomes "" disconnected "" from the slave ( e.g. , the slave is being restarted due to an upgrade ) .",def disconnected self driver
create a docker credentials file . docker username and password are used to create a ` { file_name } ` with ` .docker / config.json ` containing the credentials .,def create_docker_credentials_file username password file_name docker tar gz import base64 auth_hash base64 b64encode format username password encode decode config_json auths https index docker io v1 auth auth_hash config_json_filename config json with open config_json_filename w as f json dump config_json f indent 4 try try import tarfile with tarfile open file_name w gz as tar tar add config_json_filename arcname docker config json tar close except Exception as e print Failed to create a docker credentils file format e raise e finally os remove config_json_filename
setup celery to use non blocking producer,def setup_nonblocking_producer celery_app None io_loop None on_ready None result_cls AsyncResult limit 1 producer_cls NonBlockingTaskProducer callback None if on_ready is not None assert callback is None you may only supply either on_ready or callback callback on_ready celery_app celery_app or celery current_app io_loop io_loop or ioloop IOLoop instance producer_cls app celery_app producer_cls conn_pool ConnectionPool limit io_loop producer_cls result_cls result_cls if celery_app conf BROKER_URL and celery_app conf BROKER_URL startswith amqp celery app amqp AMQP producer_cls producer_cls def connect broker_url celery_app connection as_uri include_password True options celery_app conf get CELERYT_PIKA_OPTIONS producer_cls conn_pool connect broker_url options options callback callback io_loop add_callback connect
handle a post request from the client and sends response back .,def do_POST self if grade in self path and self _send_graded_result status_code 200 status_message LTI consumer edX responded with XML content br self server grade_data TC answer content self _create_content status_message self send_response 200 content elif lti2_outcome in self path and self _send_lti2_outcome status_code 200 status_message LTI consumer edX responded with HTTP br format self server grade_data status_code content self _create_content status_message self send_response 200 content elif lti2_delete in self path and self _send_lti2_delete status_code 200 status_message LTI consumer edX responded with HTTP br format self server grade_data status_code content self _create_content status_message self send_response 200 content elif self _is_correct_lti_request params k v for k v in self post_dict items if k oauth_signature if self _check_oauth_signature params self post_dict get oauth_signature status_message This is LTI tool Success if lis_outcome_service_url in self post_dict self server grade_data callback_url self post_dict get lis_outcome_service_url replace https http sourcedId self post_dict get lis_result_sourcedid submit_url format self server server_address content self _create_content status_message submit_url self send_response 200 content else content self _create_content Wrong LTI signature self send_response 200 content else content self _create_content Invalid request URL self send_response 500 content
tests that financialaidfactory.create ( ) will create a profile for the user field if a user is not specified,def test_financial_aid_factory_create self assert FinancialAid objects count 0 assert User objects count 0 assert Profile objects count 0 FinancialAidFactory create assert FinancialAid objects count 1 assert User objects count 1 assert Profile objects count 1
tests generate_financial_aid_email ( ) with status reset .,def test_generate_financial_aid_email_reset self self financial_aid status FinancialAidStatus RESET self financial_aid save email_dict generate_financial_aid_email self financial_aid assert email_dict subject FINANCIAL_AID_RESET_SUBJECT format program_name self financial_aid tier_program program title assert FINANCIAL_AID_DOCUMENTS_RESET_MESSAGE in email_dict body
test that a typical no - show result from perason does not result in any errors,def test_exam_read_no_shows self test_file_path exams pearson test_resources noshow dat format settings BASE_DIR reader EXAMReader with open test_file_path r as test_file results reader read test_file assert len results 1 0
email office on new user sign up .,receiver user_signed_up def email_admin_on_signup request user kwargs body New User Signed Up Please go to the admin page to approve their account If you do not approve their account and they are not using a whitelisted domain they will be unable to access apostello body body format str user from site_config models import SiteConfiguration to_ SiteConfiguration get_solo office_email if to_ send_async_mail apostello New User body to_
receive next portion of incoming datastream and store it write it to temporary file . used internally .,def ReceiveHandler self conn stanza sid seq data stanza getTagAttr data sid stanza getTagAttr data seq stanza getTagData data self DEBUG ReceiveHandler called sid s seq s sid seq info try seq int seq data decodestring data except Exception seq data err None if not sid in self _streams keys err ERR_ITEM_NOT_FOUND else stream self _streams sid if not data err ERR_BAD_REQUEST elif seq stream seq err ERR_UNEXPECTED_REQUEST else self DEBUG Successfull receive sid s s s bytes sid stream fp tell len data ok stream seq 1 stream fp write data if err self DEBUG Error on receive s err error conn send Error Iq to stanza getFrom frm stanza getTo payload Node NS_IBB close err reply 0
"given three points of an arc , find the center , radius , normal , and angle .",def arc_center points is_2D points three_dimensionalize points return_2D True edge_direction np diff points axis 0 edge_midpoints edge_direction 0 5 points 0 2 plane_normal unitize np cross edge_direction 1 vector_edge unitize edge_direction vector_perpendicular unitize np cross vector_edge plane_normal intersects center line_line edge_midpoints vector_perpendicular if not intersects raise ValueError Segments do not intersect radius euclidean points 0 center vector unitize points center angle np arccos np clip np dot vector 0 2 1 0 1 0 large_arc abs angle tol zero and np dot edge_direction 0 0 if large_arc angle np pi 2 angle angles np arctan2 vector 0 2 T 1 np pi 2 angles_sorted np sort angles 0 2 reverse angles_sorted 0 angles 1 angles_sorted 1 angles_sorted angles_sorted 1 int not reverse 2 result center center 3 is_2D radius radius normal plane_normal span angle angles angles_sorted return result
return boolean indicating whether this extension is available,def glInitCompressed3DcTextureAMD from OpenGL import extensions return extensions hasGLExtension _EXTENSION_NAME
return boolean indicating whether this extension is available,def glInitConvolutionEXT from OpenGL import extensions return extensions hasGLExtension _EXTENSION_NAME
check if obj is string .,def is_string_like obj try obj except TypeError ValueError return False return True
return a new graph that contains only the edges that exist in all graphs .,def intersection_all graphs graphs iter graphs R next graphs for H in graphs R nx intersection R H return R
set the value of c_ctl_lpfh_rbb<7:0 >,C_CTL_LPFH_RBB setter def C_CTL_LPFH_RBB self value if not 0 value 255 raise ValueError Value must be 0 255 self _writeReg LPF0 C_CTL_LPFH_RBB 7 0 value
"function aotf_wav(ch , wl ) // sets aotf channel ch wavelength to wl variable ch , wl nvar aotfwl0,aotfwl1,aotfwl2 string nm wl = ( wl>690 ? 690 : wl ) wl = ( wl<450 ? 450 : wl ) sprintf nm,""dds w % u % 3.1f"",ch , wl if ( ( ch>=0)&&(ch<8 ) ) aotf_write(nm ) aotf_read ( )",def set_wavelength self channel wavelength assert int channel 0 and int channel 7 Channel index in range 0 7 assert float wavelength 450 0 and float wavelength 690 0 Channel wavelength in range 450 0 690 0 command dds w 0 1 1f format channel wavelength response self query command print AOTF set_wavelength response return
start the program when run from cli,def run arg get_cli_args ipv4 requests get http 169 254 169 254 latest meta data public ipv4 text ipv6 get_ipv6 conn53 boto3 client route53 upd53 conn53 get_zone_hosted arg domain upd53 get_records upd53 get_a arg record upd53 update_a arg record ipv4 upd53 get_aaaa arg record upd53 update_aaaa arg record ipv6 print DNSLOG arg record updated to ipv4 print DNSLOG arg record updated to ipv6 return
test if the add new note view works .,def test_notes_manage_note_id self c Client c login username admin password test response c get reverse notes manage note id args self note id self failUnlessEqual response status_code 200
delegates logging to the fsmcontext logger,def handle_exception self exception debug_mode self error 500 logger logging if self fsm logger self fsm logger logger exception FSMHandler caught Exception if debug_mode import traceback sys cgi lines join traceback format_exception sys exc_info self response clear self response out write pre s pre cgi escape lines quote True
inter - rater reliability cohen 's kappa coefficient,def cohen_kappa cursor obsid1 obsid2 interval selected_subjects include_modifiers def subj_behav_modif cursor obsid subject time include_modifiers current behaviors for observation obsId at time Args cursor sqlite3 cursor cursor to aggregated events db obsid str id of observation subject str name of subject time Decimal time include_modifiers bool True include modifiers False do not Returns list list of lists subject behavior modifiers s rows cursor execute SELECT behavior modifiers FROM aggregated_events WHERE observation AND subject AND type STATE AND BETWEEN start AND STOP obsid subject float currentTime fetchall for row in rows if include_modifiers s append subject row 0 row 1 else s append subject row 0 rows cursor execute SELECT behavior modifiers FROM aggregated_events WHERE observation AND subject AND type POINT AND abs start obsid subject float currentTime float interval 2 fetchall for row in rows if include_modifiers s append subject row 0 row 1 else s append subject row 0 return s first_event cursor execute SELECT min start FROM aggregated_events WHERE observation in AND subject in format join selected_subjects obsid1 obsid2 fetchone 0 if first_event is None logging debug An observation has no recorded events or format obsid1 obsid2 return 100 An observation has no recorded events format obsid1 obsid2 logging debug first_event format first_event last_event cursor execute SELECT max stop FROM aggregated_events WHERE observation in AND subject in format join selected_subjects obsid1 obsid2 fetchone 0 logging debug last_event format last_event nb_events1 cursor execute SELECT COUNT FROM aggregated_events WHERE observation AND subject in format join selected_subjects obsid1 fetchone 0 nb_events2 cursor execute SELECT COUNT FROM aggregated_events WHERE observation AND subject in format join selected_subjects obsid2 fetchone 0 total_states currentTime Decimal str first_event while currentTime last_event for obsid in obsid1 obsid2 for subject in selected_subjects s subj_behav_modif cursor obsid subject currentTime include_modifiers if s not in total_states total_states append s logging debug format obsid subject currentTime s currentTime interval total_states sorted total_states logging debug total_states len format total_states len total_states contingency_table np zeros len total_states len total_states currentTime Decimal str first_event while currentTime last_event for subject in selected_subjects s1 subj_behav_modif cursor obsid1 subject currentTime include_modifiers s2 subj_behav_modif cursor obsid2 subject currentTime include_modifiers logging debug currentTime s1 s2 format currentTime s1 s2 try contingency_table total_states index s1 total_states index s2 1 except return 100 Error with contingency table currentTime interval logging debug contingency_table n format contingency_table template Observation obsid1 number of events nb_events1 Observation obsid2 number of events nb_events2 0f K K 3f cols_sums contingency_table sum axis 0 rows_sums contingency_table sum axis 1 overall_total contingency_table sum logging debug overall_total format overall_total agreements sum contingency_table diagonal logging debug agreements format agreements sum_ef 0 for idx in range len total_states sum_ef rows_sums idx cols_sums idx overall_total logging debug sum_ef format sum_ef if not overall_total sum_ef K 1 else try K round agreements sum_ef overall_total sum_ef 3 except K nan out template format obsid1 obsid1 obsid2 obsid2 nb_events1 nb_events1 nb_events2 nb_events2 K K return K out
is there such a thing as too much logging ?,def _log self code self response status_code reason self response reason response_json to_json self response begin code reason self endpoint begin end code reason self endpoint end transaction s s s s log debug 100 format transaction begin messages Request endpoint s self endpoint url Request time s self response elapsed Request parameters s self params Request payload s self request_payload Request headers s self headers Response headers s self response headers Response payload s response_json Response cookies s self response cookies Request full URL s self url for message in messages log debug message indent 4 if settings EXPANDED_LOG_STYLE else None log debug dumps response_json ensure_ascii False indent indent log debug 100 format transaction end
open ssh session with host and execute command .,def _run_ssh_cmd self host cmd try sshclient ssh Client host self usr self pwd key_filename self key timeout self timeout return sshclient exec_longrun_command cmd except Exception LOG exception Failure on ssh run cmd self fail s command failed cmd
call link ( ) with the names of configuration values that should always be the same to link them together,def link self names u Call link with the names of configuration values that should n always be the same to link them together n link _link names self for n in names self _properties n link
returns an empty list if the requested data does n't exist,def getlist self key try return dict __getitem__ self key except KeyError return
get column names for assay - specific result fields .,def get_result_names self from_tid False tids names for field in self get_results name field name strip if name in names warnings warn Duplicated field in AID format name self get_aid tids field tid name names append name if from_tid return tids else return names
"replace each real _ * function with the corresponding function from either trans_real or trans_null ( e.g. real_gettext is replaced with trans_real.gettext or trans_null.gettext ) . this function is run once , the first time any i18n method is called . it replaces all the i18n methods at once at that time .",def delayed_loader args kwargs import traceback from django conf import settings if settings USE_I18N import trans_real as trans else import trans_null as trans caller traceback extract_stack limit 2 0 2 g globals for name in __all__ if hasattr trans name g real_ s name getattr trans name return g real_ s caller args kwargs
remove the authenticated user 's id from the request .,def logout request try del request session SESSION_KEY except KeyError pass try del request session BACKEND_SESSION_KEY except KeyError pass if hasattr request user from django contrib auth models import AnonymousUser request user AnonymousUser
returns the map of known problems with the installed_apps .,def get_app_errors self self _populate return self app_errors
returns true if this boundfield 's widget is hidden .,def _is_hidden self return self field widget is_hidden
remove rorp information from dictionary if seen all links,def del_rorp rorp if not rorp isreg or rorp getnumlinks 2 return rp_inode_key get_inode_key rorp val _inode_index get rp_inode_key if not val return index remaining dest_key digest val if remaining 1 del _inode_index rp_inode_key return 1 else _inode_index rp_inode_key index remaining 1 dest_key digest return 0
force arrays in stubborn scientific notation into a few digits .,def rr obj decimals 4 print np vectorize 4g __mod__ r obj decimals decimals
adds the images to the menu & sets the current item in the menu,def add_text_to_menu self names for name in names self menu addItem name self set_current_index
remove the json recorded movement file,def remove_move_record self move_name return os remove record format move_name
get cover image url from provided lines,def get_image_url self lines p img src u PREVIEW_URL c p u a alt for v in lines i v find c if i 1 s v i len c v find a return u s return None
set gui on - top flag,def inFocus self self _dispatch inFocus
reads crystal structure from espresso input,def read_structure filename from numpy import dot array from quantities import bohr_radius as a0 angstrom Ry from crystal import Structure from import error from import Namelist from card import read_cards namelists Namelist namelists read filename cards read_cards filename if atomic_positions not in set u name for u in cards raise error RuntimeError Card ATOMIC_POSITIONS is missing from input positions u for u in cards if u name atomic_positions 0 if cell_parameters not in set u name for u in cards cell_parameters None if namelists system ibrav 0 raise error RuntimeError Card CELL_PARAMETERS is missing else cell_parameters u for u in cards if u name cell_parameters 0 cell scale read_cell_and_scale namelists system cell_parameters result Structure result cell cell result scale scale for line in positions value rstrip lstrip split n line line split result add_atom array line 1 4 dtype float64 line 0 if positions subtitle bohr factor float a0 rescale result scale for atom in result atom pos factor elif positions subtitle angstrom factor float angstrom rescale result scale for atom in result atom pos factor elif positions subtitle crystal for atom in result atom pos dot result cell atom pos elif positions subtitle crystal_sg raise error RuntimeError Reading symmetric atomic positions is not implemented if atomic_forces in set u name for u in cards atomic_forces u for u in cards if u name atomic_forces 0 if atomic_forces value is None raise error RuntimeError Atomic forces card is empty lines atomic_forces value rstrip lstrip split n if len lines len result raise error RuntimeError Number forces and number of atoms do not match for atom force in zip result lines atom force array force rstrip lstrip split 1 4 dtype float64 Ry a0 return result
dataframe constructor to open xbt edf ascii format .,def from_edf fname below_water False lon None lat None f read_file fname header names for k line in enumerate f readlines line line strip if line startswith Serial Number serial line strip split 1 strip elif line startswith Latitude if not lat try hemisphere line 1 lat line strip hemisphere split 1 strip lat np float_ lat split if hemisphere S lat lat 0 lat 1 60 0 elif hemisphere N lat lat 0 lat 1 60 0 except IndexError ValueError as e msg Ill formed or not present latitude in the header msg Try specifying one with the keyword lat raise ValueError s n s msg e elif line startswith Longitude if not lon try hemisphere line 1 lon line strip hemisphere split 1 strip lon np float_ lon split if hemisphere W lon lon 0 lon 1 60 0 elif hemisphere E lon lon 0 lon 1 60 0 except IndexError ValueError as e msg Ill formed or not present Longitude in the header msg Try specifying one with the keyword lon raise ValueError s n s msg e else header append line if line startswith Field col unit l strip lower for l in line split names append unit split 0 if line Data skiprows k 1 break f seek 0 cast pd read_table f header None index_col None names names skiprows skiprows delim_whitespace True f close cast set_index depth drop True inplace True cast index name Depth m name basename fname 1 if below_water cast remove_above_water cast return CTD cast longitude float lon latitude float lat serial serial name name header header
connect a controlflownode properly to the next_node .,def _connect_control_flow_node control_flow_node next_node for last in control_flow_node last_nodes if isinstance next_node ControlFlowNode last connect next_node test elif isinstance next_node AssignmentCallNode call_node next_node call_node inner_most_call_node _get_inner_most_function_call call_node last connect inner_most_call_node else last connect next_node
check if the format of the hotkey is correct or not,def _IsAsianHotkeyFormatIncorrect text pos char GetHotkey text if char found _asianHotkeyRE search text if not found return True return False
read a z88 disp file and extract the nodes and elements z88 displacment output file is z88o2.txt works with z88os14,def read_z88_disp z88_disp_input nodes mode_disp mode_results results z88_disp_file pyopen z88_disp_input r for no line in enumerate z88_disp_file lno no 1 linelist line split if lno 6 node_no int linelist 0 mode_disp_x float linelist 1 mode_disp_y float linelist 2 if len linelist 3 mode_disp_z float linelist 3 else mode_disp_z 0 0 mode_disp node_no FreeCAD Vector mode_disp_x mode_disp_y mode_disp_z nodes node_no node_no mode_results disp mode_disp results append mode_results if Debug for r in results 0 disp print r results 0 disp r z88_disp_file close return Nodes nodes Results results
: type nums : list[int ] : rtype : int,def firstMissingPositive self nums ls len nums index 0 while index ls if nums index 0 or nums index ls or nums nums index 1 nums index index 1 else pos nums index 1 nums index nums pos nums pos nums index res 0 while res ls and nums res res 1 res 1 return res 1
set the frequencies in the map .,frequencies setter def frequencies self freq self _frequencies freq
returns all the passwords in the vault .,def get_all_pass self r_dte DTE_random return i self dte decode_pw s if self machine_pass_set i 0 else i r_dte decode_pw s for i s in enumerate self S
patch a single review request 's diff using rbt patch .,def patch self review_request_id u patch_command RB_MAIN u patch patch_command extend build_rbtools_cmd_argv self options if self options edit patch_command append u c else patch_command append u C patch_command append six text_type review_request_id rc output execute patch_command ignore_errors True return_error_code True if rc raise CommandError u Failed to execute rbt patch n s output
converts unicode code point to hex string .,def _UStr v if v 0 or v _RUNE_MAX raise InputError invalid Unicode value s v return 0x 04X v
convert a windows path to a cygwin path .,def _get_cygwin_path self path Convert a Windows path to a cygwin path The cygpath utility insists on converting paths that it thinks are Cygwin root paths to what it thinks the correct roots are So paths such as C slave webkit release uild hird_party cygwin in are converted to plain usr bin To avoid this we do the conversion manually The path is expected to be an absolute path on any drive drive_regexp re compile a z re IGNORECASE def lower_drive matchobj return cygdrive s matchobj group 1 lower path drive_regexp sub lower_drive path return path replace
build lexer instance . arguments are passed to lexer.__init _ _ ( ) .,def getLexer self args kwargs if self grammarType lexer self lexerModule self __load_module self grammarName cls getattr self lexerModule self grammarName else self lexerModule self __load_module self grammarName Lexer cls getattr self lexerModule self grammarName Lexer cls self lexerClass cls lexer cls args kwargs return lexer
retrieve a pinned object from the object store .,def get_pinned_object pinned_id from ray local_scheduler import ObjectID if threading current_thread getName MainThread placeholder queue Queue _fetch_requests put placeholder pinned_id print Requesting main thread to fetch pinned object pinned_id return placeholder get return _from_pinnable ray get ObjectID base64 b64decode pinned_id len PINNED_OBJECT_PREFIX
checkpoints the state of this trial .,def checkpoint self to_object_store False obj None path None if to_object_store obj self runner save_to_object remote else path ray get self runner save remote self _checkpoint_path path self _checkpoint_obj obj if self verbose print Saved checkpoint for to format self path or obj return path or obj
sets the directory where screenshots are saved .,def set_screenshot_directory self path path self _norm_path path if not os path isdir path raise RuntimeError Directory s does not exist path old self _screenshot_dir self _given_screenshot_dir path return old
runs command and verifies its success .,def check_call args stdin None env None log debug run s s args format env if env else subprocess check_call args args stdin stdin env env
"whenever we raise any event , we also raise an update , so we extend the implementation in eventmixin .",def raiseEvent self event args kw rv EventMixin raiseEvent self event args kw if type event is not Update EventMixin raiseEvent self Update event return rv
take screenshots of all the pages in sitemap .,def screenshots self if not os path exists Sitemap screenshot_dir os makedirs Sitemap screenshot_dir cookies_list for key value in self cookies items cookies_list append key value urls for url in self sitemap keys if not self skipscreenshot or self skipscreenshot not in url urls append url self sitemap url image os path join Sitemap screenshot_dir url pretty png screenshot Screenshot path Sitemap screenshot_dir screenshot screenshot urls cookies_list
return true if the object is an instance method .,def ismethod object return isinstance object types MethodType
integrate a system of ordinary differential equations .,def odeint func y0 t args Dfun None col_deriv 0 full_output 0 ml None mu None rtol None atol None tcrit None h0 0 0 hmax 0 0 hmin 0 0 ixpr 0 mxstep 0 mxhnil 0 mxordn 12 mxords 5 printmessg 0 if ml is None ml 1 if mu is None mu 1 t copy t y0 copy y0 output _odepack odeint func y0 t args Dfun col_deriv ml mu full_output rtol atol tcrit h0 hmax hmin ixpr mxstep mxhnil mxordn mxords if output 1 0 warning_msg _msgs output 1 Run with full_output 1 to get quantitative information warnings warn warning_msg ODEintWarning elif printmessg warning_msg _msgs output 1 warnings warn warning_msg ODEintWarning if full_output output 1 message _msgs output 1 output output 1 if len output 1 return output 0 else return output
instantiate a layer from a config dictionary .,def deserialize config custom_objects None from import models globs globals globs Model models Model globs Sequential models Sequential return deserialize_keras_object config module_objects globs custom_objects custom_objects printable_module_name layer
"returns true if the geometry properly contains the other , else false",delegated def contains_properly self other return bool self impl prepared_contains_properly self other
instantiates scalarsplugin via tensorboard core .,def __init__ self context self _logdir context logdir self _multiplexer context multiplexer self _plugin_name_to_instance context plugin_name_to_instance
reads the value of a variable .,def read_variable_op resource dtype name None result _op_def_lib apply_op ReadVariableOp resource resource dtype dtype name name return result
solves the continuous lyapunov equation : math:`ax + xa^h = q ` .,def solve_lyapunov a q return solve_sylvester a a conj transpose q
"this method provides a basic reverse jmespath implementation that lets you go from a jmespath - like string to a possibly deeply nested object . the `` params `` are mutated in - place , so subsequent calls can modify the same element by its index .",def build_param_structure params target value index None pos params parts target split for i part in enumerate parts result INDEX_RE search part if result if result group 1 if result group 1 part part 3 else index int result group 1 part part len str index else index None part part 2 if part not in pos or not isinstance pos part list pos part if index is None index len pos part while len pos part index pos part append if i len parts 1 pos part index value else pos pos part index else if part not in pos pos part if i len parts 1 pos part value else pos pos part
"same as : py : func:`~pil.imagecolor.getrgb ` , but converts the rgb value to a greyscale value if the mode is not color or a palette image . if the string can not be parsed , this function raises a : py : exc:`valueerror ` exception .",def getcolor color mode color alpha getrgb color 255 if len color 4 color alpha color 0 3 color 3 if Image getmodebase mode L r g b color color r 299 g 587 b 114 1000 if mode 1 A return color alpha elif mode 1 A return color alpha return color
get pretty printed object prototype of schema .,util positional 2 def _prettyPrintSchema self schema seen None dent 0 if seen is None seen return _SchemaToStruct schema seen dent dent to_str self _prettyPrintByName
x must match expected type must match expected shape,def __call__ self x u n x n Must match expected type n Must match expected shape n return self predict x
concentration parameter associated with a ` 0 ` outcome .,property def concentration0 self return self bijector concentration0
"returns a copy of row i of the matrix , as a ( 1 x n ) csr matrix ( row vector ) .",def getrow self i return self _get_submatrix i slice None tocsr
reconstruct input ` x ` from a its normalized version .,def _inv_z self z with ops name_scope reconstruct values z return z self scale self loc
multi - dimensional fourier shift filter .,def fourier_shift input shift n 1 axis 1 output None input numpy asarray input output return_value _get_output_fourier_complex output input axis _ni_support _check_axis axis input ndim shifts _ni_support _normalize_sequence shift input ndim shifts numpy asarray shifts dtype numpy float64 if not shifts flags contiguous shifts shifts copy _nd_image fourier_shift input shifts n axis output return return_value
"return a ( minx , miny , maxx , maxy ) bounding box .",def bounds geometry if bbox in geometry return tuple geometry bbox geom geometry get geometry or geometry return _bounds geom
check if the object is a sequence of objects . string types are not included as sequences here .,def is_sequence obj try iter obj len obj return not isinstance obj string_and_binary_types except TypeError AttributeError return False
read all messages from the queue and persist them to file - like object . messages are written to the file and the ' sep ' string is written in between messages . messages are deleted from the queue after being written to the file . returns the number of messages saved .,def save_to_file self fp sep n n 0 m self read while m n 1 fp write m get_body if sep fp write sep self delete_message m m self read return n
pull the data from the various hosts .,def run self self logger info starting blocking stats monitoring self hostKey sleepTime self mmsAgent collectionInterval 2 1 if sleepTime 1 sleepTime 1 monitorConn None passes 0 while not self mmsAgent done and self running try time sleep sleepTime passes passes 1 if passes 60 0 monitorConn self mmsAgent closeDbConnection self hostKey monitorConn if not monitorConn monitorConn self mmsAgent getDbConnection self hostKey if not self _collectBlockingStats passes monitorConn monitorConn self mmsAgent closeDbConnection self hostKey monitorConn except Exception as e monitorConn self mmsAgent closeDbConnection self hostKey monitorConn self logger error Problem collecting blocking data from self hostKey exception traceback format_exc e self logger info stopping blocking stats monitoring self hostKey self mmsAgent closeDbConnection self hostKey monitorConn
test when there is no config,def test_no_config self self assertEqual scitokens utils config get cache_location None
resnet-101 model of [ 1 ] . see resnet_v1 ( ) for arg and return description .,def resnet_v1_101 inputs num_classes None is_training True global_pool True output_stride None reuse None scope resnet_v1_101 blocks resnet_utils Block block1 bottleneck 256 64 1 2 256 64 2 resnet_utils Block block2 bottleneck 512 128 1 3 512 128 2 resnet_utils Block block3 bottleneck 1024 256 1 22 1024 256 2 resnet_utils Block block4 bottleneck 2048 512 1 3 return resnet_v1 inputs blocks num_classes is_training global_pool global_pool output_stride output_stride include_root_block True reuse reuse scope scope
return the name of the sensor .,property def name self return self _name
loaders for the ampds release 2013 dataset .,def AMPds_r2013 filename ids precision denoised False verbose True timestamp_col TimeStamp agg_meter_col WHE unmetered_col UNE if verbose print Loading AMPds R1 dataset at s filename df pandas read_csv filename if verbose print tSetting timestamp column s as index timestamp_col df df set_index timestamp_col if verbose print tModfity data with precision f then convert to int precision for col in list df df col df col precision df col df col astype int cols ids if unmetered_col in cols cols remove unmetered_col if verbose print tNoise will modelled as s unmetered_col if verbose print tKeeping only columns s str cols df df agg_meter_col cols if denoised if verbose print tDenoising aggregate meter column s agg_meter_col df agg_meter_col df cols sum axis 1 if verbose print tCalculating unmetered column s unmetered_col df unmetered_col df agg_meter_col df cols sum axis 1 df loc df unmetered_col 0 0 return df
change class for obj . use wisely .,def instance obj cls ptr PyObject from_address id obj ptr ob_refcnt 1 ptr ob_type ctypes pointer PyObject from_address id cls return obj
determine the default availability zone .,def get_zone options if not options zone result fetch os path join GOOGLE_INSTANCE_METADATA_URL zone google True if result ok options zone os path basename result content else options zone us central1 f return options zone
: type comp_name : str : type queue : zoom.agent.entities.unique_queue.uniquequeue : type work_dict : dict,def __init__ self comp_name queue work_dict self _operate ThreadSafeObject True self _thread Thread target self _run name work_manager args self _operate queue work_dict self _thread daemon True self _log logging getLogger sent 0 wm format comp_name
this method can cause deadlocks ! tryget is safer,def get self id if self doCache if self cullCount self cullFrequency self cullCount 0 self cull else self cullCount self cullCount 1 try return self cache id except KeyError pass self lock acquire try val self cache id except KeyError pass else self lock release return val try val self expiredCache id except KeyError return None else del self expiredCache id if val is None return None self cache id val self lock release return val else try val self expiredCache id if val is not None return val except KeyError pass self lock acquire try val self expiredCache id except KeyError return None else if val is None del self expiredCache id return None self lock release return val
"generates a latin square layout for the pilot experiment . assumes 4 subjects , 2 data sources , 2 splits per source , and 2 ui conditions",def make_pilot_layout user_to_layout user_to_layout 0 0 0 0 1 0 0 0 1 1 1 1 1 user_to_layout 1 1 0 1 0 1 1 1 1 0 0 0 0 user_to_layout 2 1 1 0 0 1 0 1 0 1 0 0 1 user_to_layout 3 1 1 1 0 1 1 0 0 0 1 0 0 return user_to_layout
return `` true `` if this : class:`.templatelookup ` is capable of returning a : class:`.template ` object for the given `` uri `` .,def has_template self uri try self get_template uri return True except exceptions TemplateLookupException return False
construct the query criteria service .,def __init__ self assert isinstance self queryIndexer IQueryIndexer Invalid IQueryIndexer s self queryIndexer self _locales code Locale parse code for code in locale_identifiers
"perform rapid / more - sensitive acquisition based on a prior estimate of the receiver 's position , velocity and time .",def warm_start signal t_prior r_prior v_prior ephem settings n_codes_integrate 8 pred whatsup ephem r_prior t_prior pred_dopp ephemeris pred_dopplers pred ephem r_prior v_prior t_prior if settings acqSanityCheck notup whatsdown ephem r_prior t_prior else notup wiz_file os path join settings cacheDir fftw_wisdom if not os path isfile wiz_file if not os path isdir settings cacheDir os makedirs settings cacheDir if os path isfile etc fftw wisdom shutil copy etc fftw wisdom wiz_file a acquisition Acquisition signal settings samplingFreq settings IF settings samplingFreq gps code_period n_codes_integrate n_codes_integrate wisdom_file wiz_file acq_results a acquisition threshold settings acqThreshold prns pred notup doppler_priors pred_dopp 0 for p in notup doppler_search settings rxFreqTol gps l1 show_progress True multi True nacq_results acq_results len pred acq_results acq_results len pred nacq_acqed ar for ar in nacq_results if ar status A if len nacq_acqed 0 print ALERT d of d PRNs acquired despite being well below the horizon len nacq_acqed len notup for ar in nacq_acqed print ar print Maybe there s heavy jamming prior orbit is badly wrong or thresholds need to be adjusted if settings abortIfInsane print Aborting this sample set return acquisition print_scores acq_results pred pred_dopp acqed a for a in acq_results if a status A return acqed
"handles the case where the arguments to then are values , not functions or promises .",def test_3_2_6_4_fulfilled p1 Promise p1 do_resolve 10 p2 p1 then 5 assert 10 p1 get p2 _wait assert p2 is_fulfilled assert 10 p2 get
traverse from source go up parents .,def _traverse_parent_objs self goobj_child child_id goobj_child id self seen_cids add child_id self godag go2obj child_id goobj_child for parent_obj in goobj_child parents parent_id parent_obj id self godag p_from_cs parent_id add child_id if parent_id not in self seen_cids self _traverse_parent_objs parent_obj
return high go ids that are actually used to group current set of go ids .,def get_hdrgos self return set self hdrgo2usrgos keys union self hdrgo_is_usrgo
fix logits to be scalar ( true / false ) rather than two class .,def fix_logits kind logits logits_rank logits get_shape ndims if kind sequence and logits_rank 2 logits get_shape merge_with None 2 logits logits 0 elif logits_rank 1 raise ValueError logits has bad rank r logits_rank return logits
add an html row for each csv column .,def add_table_row self key value new_row self d createElement tr self add_element new_row td key self add_element new_row td value return new_row
a wrapper for views that check specific constance settings . only used for site_is_configured below . the test should be a callable that takes the user object and returns true if the user passes .,def constance_check test_func next_url None redirect_field_name REDIRECT_FIELD_NAME def decorator view_func wraps view_func assigned available_attrs view_func def _wrapped_view request args kwargs if test_func return view_func request args kwargs path request build_absolute_uri resolved_setup_url resolve_url next_url or settings CONSTANCE_SETUP_URL setup_scheme setup_netloc urlparse resolved_setup_url 2 current_scheme current_netloc urlparse path 2 if not setup_scheme or setup_scheme current_scheme and not setup_netloc or setup_netloc current_netloc path request get_full_path from django contrib auth views import redirect_to_login return redirect_to_login path resolved_setup_url redirect_field_name return _wrapped_view return decorator
"get a tiddler from the store , returning a populated tiddler object . `` tiddler.creator `` and `` tiddler.created `` are based on the modifier and modified of the first revision of a tiddler .",def tiddler_get self tiddler raise StoreMethodNotImplemented this store does not handle getting tiddlers
"sends an update to github . returns true on success or false otherwise . state should be one of ' pending ' , ' success ' , ' error ' , or ' failure ' .",def update self state message details_url logger info STATUS format self _context_label state message if details_url logger info STATUS URL format details_url if not WORKSPACE in os environ return True if os environ get GITHUB_DISABLE return True if not os environ get GITHUB_COMMIT_STATUS_URL or os environ get BUILD_URL return True request self _build_request state message details_url response self _send_request request if response status 200 or response status 300 logger error Got response to update request format response status logger error Request logger error pprint pformat request logger error Response logger error pprint pformat response read return logger info Updated GitHub PR with status format request path
"restore saved net , global step , and epsilons or create checkpoint directory for later storage .",def restore_vars saver sess game alg_type max_local_steps alg alg_type format _ str max_local_steps _steps if alg_type q else checkpoint_dir checkpoints game alg check_or_create_checkpoint_dir checkpoint_dir path tf train latest_checkpoint checkpoint_dir if path is None sess run tf initialize_all_variables return 0 else saver restore sess path global_step int path path rfind 1 return global_step
computes deformation gradients from displacement data .,def strain t x d sd network_prior_model network_prior_params network_noise_model network_noise_params station_noise_model station_noise_params out_t out_x rate covariance t np asarray t dtype float x np asarray x dtype float d np array d dtype float sd np array sd dtype float diff np array 0 0 0 t_grid x0_grid np meshgrid t x 0 indexing ij t_grid x1_grid np meshgrid t x 1 indexing ij z np array t_grid ravel x0_grid ravel x1_grid ravel T t_grid x0_grid np meshgrid out_t out_x 0 indexing ij t_grid x1_grid np meshgrid out_t out_x 1 indexing ij out_z np array t_grid ravel x0_grid ravel x1_grid ravel T prior_gp composite network_prior_model network_prior_params gpnetwork CONSTRUCTORS noise_gp composite network_noise_model network_noise_params gpnetwork CONSTRUCTORS sta_gp composite station_noise_model station_noise_params gpstation CONSTRUCTORS mask np isinf sd z d sd z mask ravel d mask sd mask sta_sigma sta_p station_sigma_and_p sta_gp t mask obs_sigma _as_covariance sd sta_sigma _as_sparse_or_array sta_sigma obs_sigma net_sigma noise_gp _covariance z z diff diff net_p noise_gp _basis z diff noise_sigma _as_sparse_or_array sta_sigma net_sigma noise_p np hstack sta_p net_p del sta_sigma net_sigma obs_sigma sta_p net_p post_gp prior_gp condition z d sigma noise_sigma p noise_p if rate dudx_gp post_gp differentiate 1 1 0 dudy_gp post_gp differentiate 1 0 1 else dudx_gp post_gp differentiate 0 1 0 dudy_gp post_gp differentiate 0 0 1 if covariance dudx dudx_gp mean out_z cdudx dudx_gp covariance out_z out_z sdudx np sqrt np diag cdudx dudy dudy_gp mean out_z cdudy dudy_gp covariance out_z out_z sdudy np sqrt np diag cdudy dudx dudx reshape out_t shape 0 out_x shape 0 sdudx sdudx reshape out_t shape 0 out_x shape 0 cdudx cdudx reshape out_t shape 0 out_x shape 0 out_t shape 0 out_x shape 0 dudy dudy reshape out_t shape 0 out_x shape 0 sdudy sdudy reshape out_t shape 0 out_x shape 0 cdudy cdudy reshape out_t shape 0 out_x shape 0 out_t shape 0 out_x shape 0 out dudx sdudx cdudx dudy sdudy cdudy else dudx sdudx dudx_gp meansd out_z chunk_size 1000 dudy sdudy dudy_gp meansd out_z chunk_size 1000 dudx dudx reshape out_t shape 0 out_x shape 0 sdudx sdudx reshape out_t shape 0 out_x shape 0 dudy dudy reshape out_t shape 0 out_x shape 0 sdudy sdudy reshape out_t shape 0 out_x shape 0 out dudx sdudx dudy sdudy return out
return a new mismatch object replacing specified fields with new values,def _replace _self kwds result _self _make map kwds pop actual expected value _self if kwds raise ValueError Got unexpected field names r kwds keys return result
add pos tags to input text e.g. ' car#noun is#verb blue#adj . ',def add_pos text tokens _spacy text return join t orth_ t pos_ for t in tokens
creates a copy of this instance .,since 1 4 0 def copy self extra None if extra is None extra dict that Params copy self extra stages stage copy extra for stage in that getStages return that setStages stages
create a time - stetched segment .,def __init__ self track comp_location start orig_duration new_duration Segment __init__ self track comp_location start new_duration self orig_duration int orig_duration self samplerate
return the name of the module which this app was defined within . this can be considered a unique identifier with the project .,property def name self return self __module__ split 2
"_ receive_node_destroy(self , node_id ) - > none",def cb_receive_node_destroy self node_id return super VerseSession self cb_receive_node_destroy node_id
calculate cds phase and add to the cds exons,def add_CDS_phase strand cds cds_region cds_flag 0 if strand for cdspos in cds if cds_flag 0 cdspos cdspos 0 cdspos 1 0 diff cdspos 1 cdspos 0 1 3 else xy 0 if diff 0 cdspos cdspos 0 cdspos 1 0 elif diff 1 cdspos cdspos 0 cdspos 1 2 xy 2 elif diff 2 cdspos cdspos 0 cdspos 1 1 xy 1 diff cdspos 1 cdspos 0 1 xy 3 cds_region append cdspos cds_flag 1 elif strand cds reverse for cdspos in cds if cds_flag 0 cdspos cdspos 0 cdspos 1 0 diff cdspos 1 cdspos 0 1 3 else xy 0 if diff 0 cdspos cdspos 0 cdspos 1 0 elif diff 1 cdspos cdspos 0 cdspos 1 2 xy 2 elif diff 2 cdspos cdspos 0 cdspos 1 1 xy 1 diff cdspos 1 cdspos 0 1 xy 3 cds_region append cdspos cds_flag 1 cds_region reverse return cds_region
all assignments to names go through this function .,def visit_Name self node store_as_param False kwargs if store_as_param or node ctx param self symbols declare_parameter node name elif node ctx store self symbols store node name elif node ctx load self symbols load node name
used to download big file .,def big_file_iterator filename chunk_size 512 with open filename rb as f while True content f read chunk_size if content yield content else break
parse command - line arguments . note that the input and output directories are positional arguments,def parse_cmdline args usage usage prog options input_directory output_directory parser OptionParser usage parser add_option l minlen dest minlen action store default 1000 help Minimum length of sequence parser add_option s filesuffix dest suffix action store default _restricted help Suffix to indicate the file was processed parser add_option v verbose dest verbose action store_true default False help Give verbose output return parser parse_args
op handler for regular tick op,def tick_operation self op if self target is None self irrelevant return if self count 0 self count int self target mass if not self character location velocity is_valid or self character location velocity square_mag 1 or self character location velocity square_mag 10 self rate 0 self progress 0 return self next_tick 1 75 old_rate self rate self rate 1 0 1 75 self progress 0 01 if old_rate 0 1 return self next_tick 1 75 surface self target terrain get_surface self character location coordinates if surface is not 2 return self next_tick 1 75 res Oplist chunk_loc Location self character location parent chunk_loc velocity Vector3D chunk_loc coordinates self character location coordinates create Operation create Entity name grass type grass location chunk_loc to self target res append create res append self next_tick 1 75 return res
sets the learning rate to the initial lr decayed by 10 every 30 epochs,def adjust_learning_rate optimizer epoch lr_steps decay 0 1 sum epoch np array lr_steps lr args lr decay decay args weight_decay for param_group in optimizer param_groups param_group lr lr param_group lr_mult param_group weight_decay decay param_group decay_mult
we 'll setup the network to have 3 nodes that all mine with different parameters . but first we need to use one node to create a lot of small low priority outputs which we will use to generate our transactions .,def setup_network self self nodes self nodes append start_node 0 self options tmpdir maxorphantx 1000 relaypriority 0 whitelist 127 0 0 1 print This test is time consuming please be patient print Splitting inputs to small size so we can generate low priority tx s self txouts self txouts2 split_inputs self nodes 0 self nodes 0 listunspent 0 self txouts True while len self nodes 0 getrawmempool 0 self nodes 0 generate 1 reps 0 while reps 5 while len self txouts 0 split_inputs self nodes 0 self txouts self txouts2 while len self nodes 0 getrawmempool 0 self nodes 0 generate 1 while len self txouts2 0 split_inputs self nodes 0 self txouts2 self txouts while len self nodes 0 getrawmempool 0 self nodes 0 generate 1 reps 1 print Finished splitting self nodes append start_node 1 self options tmpdir blockprioritysize 1500 blockmaxsize 17000 maxorphantx 1000 relaypriority 0 debug estimatefee connect_nodes self nodes 1 0 node2args blockprioritysize 0 blockmaxsize 8000 maxorphantx 1000 relaypriority 0 self nodes append start_node 2 self options tmpdir node2args connect_nodes self nodes 0 2 connect_nodes self nodes 2 1 self is_network_split False self sync_all
"if a function calls another one , call this method to insert it into the tree at the appropriate place . @return : a reference to the newly created child node .",def calls self func calltime child CallTree func calltime self self _children append child return child
"initialize simulation , populations , and connections .",def initialize self t0 0 0 self connection_distribution_collection ConnectionDistributionCollection self t t0 for p in self population_list p simulation self for c in self connection_list c simulation self for p in self population_list p initialize for c in self connection_list c initialize
split a string into two parts at the input index .,def chunk data index return data index data index
return a set of permission strings the user ` user_obj ` has from the groups they belong .,def get_group_permissions self user_obj obj None return self _get_permissions user_obj obj group
"deserialize a stream or a string . return an iterator that yields `` ( obj , m2m_relation_dict ) `` , where `` obj `` is an instantiated -- but * unsaved * -- object , and `` m2m_relation_dict `` is a dictionary of `` { m2m_field_name : list_of_related_objects } `` .",def deserialize format stream_or_string options d get_deserializer format return d stream_or_string options
iso 8601 year number matching the iso week number ( w ),def o self return self data isocalendar 0
""" makes sure app version meta is always updated . helps maintain method_info and future proof version structures .",def update_app_version self other_app if self other_app version_num other_app track version self app_creation_datetime other_app app_creation_datetime if inclusions in self method_info self method_info inclusions other_app method_info inclusions self track version version_num return self
handler for when the envisalink wishes to send us a keypad update .,def handle_keypad_update self code data raise NotImplementedError
"checks if a string is "" * * * * self "" or contains conn.name .",def is_self conn target if re search self format re escape conn nick target re I return True else return False
"if the configuration file does not exist , `` noconfiguration `` is raised .",def test_no_config self self config _default_file improbable_chickens self assertRaises NoConfiguration self config read_and_parse
edit metadata of a server image .,def ex_edit_image self kwargs image kwargs image public kwargs public params id image id isPublic str public lower if ex_description in kwargs params description kwargs ex_description if name in kwargs params friendlyName kwargs name object self connection request api grid image edit params params object return self _to_image object list 0
get a list of all objects defined * somewhere * in a package .,def getRLModules global rl_modules if rl_modules is None rl_modules for _ name _ in walk_packages_ex cond rl_module rl_modules append name return rl_modules
test the execution of a generic wind farm,def test_execution self gwf TestWindFarm self fill_up gwf gwf run
"this method should get all the files on the api using getcollection , then clean them to what we need for the application : return : list of cleaned json results",def cleanCollection self raise NotImplementedError
opens the log file for writing .,def _OpenLogFile self log_dir os path dirname self _temp_log_file_path if not os path exists log_dir os makedirs log_dir return open self _temp_log_file_path w
enumerate the token search space for pattern matching : param c : : return :,def _get_search_func self c u n Enumerate the token search space for pattern matching n param c n return n if self search u sentence return c get_parent __dict__ self attrib elif self search u between return get_text_between c strip split elif self search u left span c 0 if c 0 char_start c 1 char_start else c 1 return get_left_tokens span window self window attrib self attrib elif self search u right span c 0 if c 0 char_start c 1 char_start else c 1 return get_right_tokens span window self window attrib self attrib
"given a dataset , returns list of arrays of coordinates of the events in the analysis dimensions",def to_analysis_dimensions self d return utils _events_to_analysis_dimensions d self config analysis_space
converts an exception to an api error response .,def to_json_error e exc_info if isinstance e Http404 e kbapi NotFoundError e message elif isinstance e ValueError e kbapi BadRequestError str e elif isinstance e NoTokenError e kbapi NotFoundError e message if isinstance e kbapi Error code e __class__ __name__ http_code e HTTP_CODE message e Message else code ServerError http_code 500 message An internal error occurred s str e result error code code message message if settings DEBUG result error traceback join traceback format_exception exc_info return result http_code
"if the user attempts to access this frontend endpoint but is already logged in , redirect to the specified uri .",def hide_if_logged_in redirect_uri def decorator func wraps func def decorated_view args kwargs if current_user is_authenticated return redirect redirect_uri return func args kwargs return decorated_view return decorator
use this api to remove an l{iservice } from an l{iservicecollection}.,def disownServiceParent
"this fixture provides the gcloud test driver . it is not normally installable , since it lacks a setup.py",pytest fixture scope session def gcloud_driver_module request cache_key live_auth driver_zip driver_zip_data request config cache get cache_key None if driver_zip_data is None url https github com GoogleCloudPlatform cloudsdk test driver archive master zip driver_zip_data requests get url content request config cache set cache_key base64 b64encode driver_zip_data else driver_zip_data base64 b64decode driver_zip_data extract_path tempfile mkdtemp with zipfile ZipFile cStringIO StringIO driver_zip_data as driver_zip driver_zip extractall path extract_path os rename os path join extract_path cloudsdk test driver master os path join extract_path cloudsdk_test_driver sys path append extract_path driver_module importlib import_module cloudsdk_test_driver driver yield driver_module sys path pop shutil rmtree extract_path
called to return the list of groups to automatically add / remove this connection to / from .,def connection_groups self kwargs print adding to connection group lobby return lobby
send reminder in two weeks interal .,def test_send_reminder self modified_at timezone now timedelta days 16 self create_page_with_version modified modified_at self create_reminder interval choices INTERVAL_2_WEEKS page self page self reminder sent_at modified_at self reminder save management call_command send_reminders stdout self stdout verbosity 3 command_output self stdout getvalue strip self assertEqual command_output Email for is sent to format self reminder content_object self reminder user email
return if a key can be used in the sha-256 signature .,def is_valid_key key return key not in merchantSig sig and not key startswith ignore
return the string name of a key event . will raise a valueerror error if its invalid .,def EventToString event return str
"parse each line of the specified data file , assuming a "" | "" delimiter . key is item_id , converts each rating to a float .",def parseVectorOnItem line line line split return line 1 line 0 float line 2
test handling of bad inputs into get inclusion proof .,def test_tree_inclusion_proof_bad_indices self tree in_memory_merkle_tree InMemoryMerkleTree TEST_VECTOR_DATA n tree tree_size self assertRaises ValueError tree get_inclusion_proof 0 n 3 self assertRaises ValueError tree get_inclusion_proof n 3 n 1
appends analytics tracking to urls found within the plain text .,def replace_urls_text text params for url in re findall PAT_URL text text text replace url append_tracking url params return tex
taken from regressiontests / syndication / tests.py .,def assertChildNodes self elem expected actual set n nodeName for n in elem childNodes expected set expected self assertEqual actual expected
recursively crawl starting from * start_url*. returns a set of urls that were found .,def producer start_url pool eventlet GreenPool seen set q eventlet Queue q put start_url while not q empty or pool running 0 url eventlet with_timeout 0 1 q get timeout_value if url not in seen and eventlet net in url seen add url pool spawn_n fetch url q return seen
l{lockfile.readlink } raises l{oserror } with c{errno } set to l{enoent } when an attempt is made to read a symlink which does not exist .,def test_readlinkENOENT self name self mktemp exc self assertRaises OSError lockfile readlink name self assertEqual exc errno errno ENOENT
loading an app with no models from under the top - level egg package generates no error,def test_egg4 self egg_name s omelet egg self egg_dir sys path append egg_name models load_app omelet app_no_models self failUnless models is None
increment the number of shells currently open for the given user .,def increment_count self self num_shells 1
return an iterable of two - tuples of each lower - case header name and the last value for that header .,def iteritems self for k v in self _headers getAllRawHeaders yield k lower v 1
hook for rendering a template if final revalidation failed .,def render_revalidation_failure self request step form return self render form request step
retrieve a list of all names for entities that i contain .,def listNames self request return self listStaticNames
return a documentation string describing the use of the given method .,def xmlrpc_methodHelp self method method self _xmlrpc_parent _getFunction method return getattr method help None or getattr method __doc__ None or
"given a model class , returns a dict of { field_name : field_triple } defs .",def get_model_fields model m2m False field_defs SortedDict inherited_fields for base in model __bases__ if base models Model and issubclass base models Model if not base _meta abstract inherited_fields update get_model_fields base source model _meta local_fields if m2m source model _meta local_many_to_many for field in source if can_ignore field continue if hasattr field south_field_triple if NOISY print Nativing field s field name field_defs field name field south_field_triple elif can_introspect field field_class field __class__ __module__ field __class__ __name__ args kwargs introspector field field_defs field name field_class args kwargs else if NOISY print Nodefing field s field name field_defs field name None if model _meta order_with_respect_to field_defs _order django db models fields IntegerField default 0 return field_defs
"computes rouge - l score given a set of reference and candidate sentences for the dataset invoked by evaluate_captions.py : param hypo_for_image : dict : candidate / test sentences with "" image name "" key and "" tokenized sentences "" as values : param ref_for_image : dict : reference ms - coco sentences with "" image name "" key and "" tokenized sentences "" as values : returns : average_score : float ( mean rouge - l score computed by averaging scores for all the images )",def compute_score self gts res assert sorted gts keys sorted res keys imgIds sorted gts keys score for id in imgIds hypo res id ref gts id score append self calc_score hypo ref assert type hypo is list assert len hypo 1 assert type ref is list assert len ref 1 average_score np mean np array score return average_score np array score
all concrete classes with a storage format can copy .,pytest mark parametrize class_ classes def test_consort___deepcopy___01 class_ if _storage_format_specification not in dir class_ or _get_format_specification not in dir class_ return if inspect isabstract class_ return if class_ in _classes_to_fix return instance_one class_ instance_two copy deepcopy instance_one instance_one_format format instance_one storage instance_two_format format instance_two storage if not issubclass class_ abjad Container assert instance_one_format instance_two_format
constructs an audio - rate local in .,classmethod def ar cls channel_count 1 default 0 import supriya synthdefs calculation_rate supriya synthdefs CalculationRate AUDIO ugen cls _new_expanded calculation_rate calculation_rate channel_count channel_count default default return ugen
gets ` keycode ` input of keystate .,property def keycode self index self _ordered_input_names index keycode return self _inputs index
gets ` rect ` input of inrect .,property def rect self index self _ordered_input_names index rect return self _inputs index
gets ` source ` input of integrator .,property def source self index self _ordered_input_names index source return self _inputs index
gets ` center_pos ` input of tgrains .,property def center_pos self index self _ordered_input_names index center_pos return self _inputs index
gets ` whtype ` input of onsets .,property def whtype self index self _ordered_input_names index whtype return self _inputs index
write all the results from google to an xml file,def write_everything_from_yahoo_to_xml country cities outfile weather xml weather_reports pywapi get_everything_from_yahoo country cities xml_output Element Weather for city report in weather_reports items try xml_city Element town xml_name Element name xml_name text city xml_city append xml_name xml_temperature Element temperature temp_c report wind chill temp_unit report units temperature temp_cond join temp_c temp_unit xml_temperature text temp_cond xml_city append xml_temperature xml_humidity Element humidity xml_humidity text report atmosphere humidity xml_city append xml_humidity xml_condition Element condition xml_condition text report condition text xml_city append xml_condition xml_wind Element wind beaufort pywapi wind_beaufort_scale report wind speed direction pywapi wind_direction report wind direction wind_cond join beaufort direction xml_wind text wind_cond xml_city append xml_wind xml_output append xml_city except KeyError pass ElementTree xml_output write outfile UTF 8
entry point function for the ansible role manager .,def main os environ COLUMNS 100 parser argparse ArgumentParser prog sys argv 0 subparsers parser add_subparsers commands_dir os path join os path dirname __file__ commands for module in os listdir commands_dir if module __init__ py or module 3 py continue command_mod __import__ arm commands s module 3 locals globals object 1 Assumes that each command defines a BaseCommand which inherits from arm commands Command for command_name command_class in find_subclasses command_mod Command command_parser subparsers add_parser command_name help command_class help command command_class command_parser command_parser set_defaults func command run args parser parse_args sys argv 1 try args func args except RouteException as e print nError fetch s n e exit 1 except CommandException as e print nError command s n e exit 1 exit 0
set the global bmc_power_policy_method to either ' old ' or ' new ' .,def set_power_policy_method power_policy_setup int BuiltIn get_variable_value power_policy_setup default 0 bmc_power_policy_method BuiltIn get_variable_value bmc_power_policy_method default 0 gp dpvar power_policy_setup if power_policy_setup return gp dpvar bmc_power_policy_method 1 if bmc_power_policy_method status ret_values grk run_key_u New Get Power Policy ignore 1 if status PASS bmc_power_policy_method New else bmc_power_policy_method Old gp qpvar bmc_power_policy_method if bmc_power_policy_method Old BuiltIn set_global_variable RESTORE_LAST_STATE RESTORE_LAST_STATE BuiltIn set_global_variable ALWAYS_POWER_ON ALWAYS_POWER_ON BuiltIn set_global_variable ALWAYS_POWER_OFF ALWAYS_POWER_OFF BuiltIn set_global_variable bmc_power_policy_method bmc_power_policy_method BuiltIn set_global_variable power_policy_setup 1
covers creating a secret without an expiration .,testcase attr positive def test_secret_create_defaults_no_expiration self secret self barbicanclient secrets create secret_create_defaults_data secret expiration None secret_ref self cleanup add_entity secret self assertIsNotNone secret_ref
search for quads from a mosaic that are inside the specified bounding box . will yield all quads if no bounding box is specified .,def get_quads self mosaic bbox None if bbox is None xmin ymin xmax ymax mosaic bbox bbox max 180 xmin max 85 ymin min 180 xmax min 85 ymax url mosaic _links quads url url format lx bbox 0 ly bbox 1 ux bbox 2 uy bbox 3 return self _get url models MosaicQuads get_body
"iterates over a labelled query stream and generates a feature file with the columns : < query_num>,<answer_id>,<fea_0>,<fea_1>, ... ,<fea_n>,<relevance_label > : param rnr_debug_helpers.queries . labelledquerystream in_query_stream : : param file outfile : where the feature file contents will be written to : param str collection_id : the rnr solr collection to use for finding search results : param str cluster_id : the rnr solr cluster i d to use for finding search results : param int or none num_rows : the number of search results that will be retrieved for each query . defaults to 30 similar to rnr web ui / tooling : param configparser config : a config loaded with the credentials to use",def generate_rnr_features in_query_stream outfile collection_id cluster_id num_rows 30 config load_config rnr_cluster RetrieveAndRankProxy solr_cluster_id cluster_id config config writer csv writer outfile stats defaultdict int is_first_row True for qid query in enumerate in_query_stream labels_for_relevant_answer_ids _parse_correct_answer_ids_from_query query _collect_stats stats labels_for_relevant_answer_ids LOGGER debug Getting feature vectors for query s query get_qid rnr_search_results rnr_cluster get_fcselect_features query_text query get_qid collection_id collection_id generate_header is_first_row num_results_to_return num_rows if len rnr_search_results 0 stats num_queries_with_zero_rnr_results 1 else if is_first_row writer writerow _QID_COLUMN_NAME rnr_search_results pop 0 _GT_COLUMN_NAME is_first_row False stats num_queries_with_atleast_one_search_result 1 stats num_search_results_retrieved len rnr_search_results num_possible_correct num_correct_answers_in_search_results _print_feature_vectors_and_check_for_correct_answers writer rnr_search_results d qid 1 labels_for_relevant_answer_ids if num_possible_correct num_correct_answers_in_search_results stats num_queries_where_at_least_correct_answer_didnt_appear_in_rnr 1 stats num_correct_in_search_result num_correct_answers_in_search_results if stats num_queries 100 0 LOGGER info Processed d queries from input file stats num_queries _average_stats_across_collection stats LOGGER info Finished processing d queries from input file stats num_queries return stats
"compute the spectrogram for a real signal . the parameters follow the naming convention of matplotlib.mlab.specgram args : samples ( 1d array ) : input audio signal fft_length ( int ) : number of elements in fft window sample_rate ( scalar ) : sample rate hop_length ( int ) : hop length ( relative offset between neighboring fft windows ) . returns : x ( 2d array ) : spectrogram [ frequency x time ] freq ( 1d array ) : frequency of each row in x note : this is a truncating computation e.g. if fft_length=10 , hop_length=5 and the signal has 23 elements , then the last 3 elements will be truncated .",def spectrogram samples fft_length 256 sample_rate 2 hop_length 128 assert not np iscomplexobj samples Must not pass in complex numbers window np hanning fft_length None window_norm np sum window 2 scale window_norm sample_rate trunc len samples fft_length hop_length x samples len samples trunc nshape fft_length len x fft_length hop_length 1 nstrides x strides 0 x strides 0 hop_length x as_strided x shape nshape strides nstrides assert np all x 1 samples hop_length hop_length fft_length x np fft rfft x window axis 0 x np absolute x 2 x 1 1 2 0 scale x 0 1 scale freqs float sample_rate fft_length np arange x shape 0 return x freqs
collect the elements in an prdd and concatenate the partition .,def collect self def append_frames frame_a frame_b return frame_a append frame_b return self _custom_rdd_reduce append_frames
"return the visibility from a name : public , protected , private or special",def get_visibility name if SPECIAL match name visibility special elif PRIVATE match name visibility private elif PROTECTED match name visibility protected else visibility public return visibility
return an unicode string containing all the message 's headers,def headers self values for header in self message keys values append u s s header self get header return n join values
run a block permutation test .,def blocked_sampled_test observed_values unit_assignments test_stat alpha 0 01 iterations 10000 s datetime now Tobs test_stat observed_values unit_assignments print Tobs Tobs under 0 for i in range 0 iterations permuted_assignments get_perm unit_assignments Tpi test_stat observed_values permuted_assignments if round Tobs 10 round Tpi 10 under 1 e datetime now print Time for running permutation test str e s print nConfidence Interval of p value proportion_confint under iterations alpha beta return 1 0 under 1 0 iterations
"kill the process . if group = true , all sub - processes will also be killed .",def kill self group True self kill_called True if mswindows if group and self _job winprocess TerminateJobObject self _job 127 else winprocess TerminateProcess self _handle 127 self returncode 127 else if group try os killpg self pid signal SIGKILL except pass else os kill self pid signal SIGKILL self returncode 9
given a relative file path this ought to find an absolute file path .,def find self path all False raise NotImplementedError subclasses of BaseFinder must provide a find method
"most session backends do n't need to override this method , but we do , because instead of generating a random string , we want to actually generate a secure url - safe base64-encoded string of data as our session key .",def _get_session_key self session_cache getattr self _session_cache return signing dumps session_cache compress True salt django contrib sessions backends signed_cookies serializer self serializer
called to handle a manytomanyfield .,def handle_m2m_field self obj field raise NotImplementedError subclasses of Serializer must provide an handle_m2m_field method
was this model really renamed ?,def ask_rename_model self old_model_state new_model_state u msg u Did you rename the s s model to s y N return self _boolean_input msg old_model_state app_label old_model_state name new_model_state name False
makes an aware datetime.datetime naive in a given time zone .,def make_naive value timezone None if timezone is None timezone get_current_timezone value value astimezone timezone if hasattr timezone normalize value timezone normalize value return value replace tzinfo None
cast the data in a tag as a specific type,def cast_as self cast_type return obj Object cast_type offset self RealDataOffset vm self obj_vm
return the blobs to be used for the next minibatch .,def _get_next_minibatch self if cfg TRAIN USE_PREFETCH return self _blob_queue get else db_inds self _get_next_minibatch_inds minibatch_db self _roidb i for i in db_inds return get_minibatch minibatch_db self _num_classes
"wa configuration can come from various sources of increasing priority , as well as being specified in a generic and specific manner ( e.g `` device_config `` and `` nexus10 `` respectivly ) . wa has two rules for the priority of configuration :",def _merge_using_priority_specificity self specific_name generic_name merged_config is_final True ms MergeState ms generic_name generic_name ms specific_name specific_name ms generic_config copy self plugin_configs generic_name ms specific_config copy self plugin_configs specific_name ms cfg_points self get_plugin_parameters specific_name sources self sources merged_config name specific_name for source in sources try update_config_from_source merged_config source ms except ConfigError as e raise ConfigError Error in n t format source str e merged_config name specific_name for cfg_point in ms cfg_points values cfg_point validate merged_config check_mandatory is_final
patch resource response returns resource and 200 .,testcases fragile def test_patch_resource_response self user models User first Sally last Smith password password username SallySmith1 self session add user blog_post models Post title This Is A Title content This is the content self session add blog_post self session commit payload data type posts id blog_post id attributes title This is a new title relationships author data type users id user id response models serializer patch_resource self session payload posts blog_post id expected data id 1 attributes content u This is the content title u This is a new title type posts relationships comments links related posts 1 comments self posts 1 relationships comments author links related posts 1 author self posts 1 relationships author included jsonapi version 1 0 meta sqlalchemy_jsonapi_version __version__ actual response data self assertEqual expected actual self assertEqual 200 response status_code
check that a user can be updated using a put method,def test_user_update self endpoint reverse api user detail kwargs pk self user pk response self client get endpoint self assertEqual response status_code status HTTP_200_OK content username self user username first_name self user first_name last_name self user last_name profile biography This is a test bio organization NASA response self client put endpoint content format json self assertEqual response status_code status HTTP_200_OK user User objects get pk self user pk self assertEqual user profile organization NASA
http get handler for the tlarsen users page .,def get self self response headers Content Type text plain self response write Wassup it s Justin
removes the contenttype objects that have not the ' gallery_visible ' attribute set to true .,def _filter_choices self filtered_choices for choice in self choices try if choice 0 filtered_choices append choice continue ctype ContentType objects get pk int choice 0 model_class ctype model_class if model_class gallery_visible filtered_choices append choice except pass self choices filtered_choices
smoke test for string representation .,def test_str self stop factories StopFactory year 2013 self assertEqual str stop Stop s agency s in 2013 stop pk stop agency_description
control the state of the digital output . ( is_output must be true ),state setter def state self value self set_output value
tests whether simple upsert works correctly when the conflicting field is a foreign key specified as an object .,def test_on_conflict_update_foreign_key_by_object other_model get_fake_model model get_fake_model other models OneToOneField other_model on_delete models CASCADE data models CharField max_length 255 other_obj other_model objects create obj1 model objects on_conflict other ConflictAction UPDATE insert_and_get other other_obj data some data assert obj1 other other_obj assert obj1 data some data obj1 refresh_from_db assert obj1 other other_obj assert obj1 data some data with pytest raises ValueError model objects on_conflict other ConflictAction UPDATE insert_and_get other obj1 obj2 model objects on_conflict other ConflictAction UPDATE insert_and_get other other_obj data different data assert obj2 other other_obj assert obj2 data different data obj1 refresh_from_db obj2 refresh_from_db assert obj1 id obj2 id assert obj1 other other_obj assert obj2 other other_obj assert obj1 data different data assert obj2 data different data
delay the import of the records,def _import_record self record_id kwargs import_record delay self session self model _name self backend_record id record_id kwargs
main solution function : param cipher : the cipher,def solve self cipher N cipher turn 0 while N 1 turn 1 if N N 1 0 N 2 else num 1 while num N num 1 num 1 N num if turn 1 0 return Richard else return Louise
create a 40 digit hex number to be used as a job id string . ( similar to sha1 ),def create_unique_job_id return hashlib sha1 hex _RAND_POOL getrandbits 160 hexdigest
find the loader for the specified module .,def find_loader name path None try loader sys modules name __loader__ if loader is None raise ValueError __loader__ is None format name else return loader except KeyError pass return _bootstrap _find_module name path
to implement . check if extracted configuration can be parsed .,def is_parsable self content return True
in case of post make sure we return the access - control - allow origin regardless of returning data,def post_detail self request kwargs response super CorsResourceBase self post_list request kwargs return self add_cors_headers response True
"if the output file exists , delete it and start over .",def setup self if os path exists __OUTPUT__ os remove __OUTPUT__
add a ' --no - save ' option to a parser,def add_no_save_option parser add_arg parser no save action store_true dest no_save default False help Don t save parameter changes to the auto_process info file return parser
find and delete the message described by message_id .,def DeleteMessage self message_criteria _LOG debug s Deleting messsage s self _user_email message_criteria for gmail_label found_indices in self _found_indices iteritems if not found_indices continue self _SelectLabel gmail_label for message_index in found_indices self _imap_query uid COPY message_index Gmail self _LOCALIZED_TRASH_LABEL self _imap_query expunge _LOG debug s s messages purged from s self _user_email found_indices gmail_label gmail_label Gmail self _LOCALIZED_TRASH_LABEL self _SelectLabel gmail_label messages_found 0 search_query self _SEARCH_MESSAGE_ID message_criteria unused_type data self _imap_query uid SEARCH None search_query for found_index in data 0 split messages_found 1 self _imap_query uid STORE found_index FLAGS Deleted self _imap_query expunge _LOG debug s Message has been purged from Gmail self _user_email _LOG debug s Total message s purged s self _user_email messages_found return messages_found 0
datafile : definition | datafile definition,def p_datafile1 p if len p 2 p 0 p 1 else p 0 p 1 p 2
asks user for a question returning true / false answed,def decision question if sys version_info 0 3 if raw_input n s Y n question in y Y return True elif input n s Y n question in y Y return True return False
"check if a condition is met by all documents in a list , where a condition can also be a sequence ( e.g. list ) .",def all self cond if callable cond def _cmp value return is_sequence value and all cond e for e in value else def _cmp value return is_sequence value and all e in value for e in cond return self _generate_test lambda value _cmp value all tuple self _path freeze cond
optional . a string with the location of your hook . used to add extra dictionary values specific for your app into id_token .,property def OIDC_IDTOKEN_PROCESSING_HOOK self return oidc_provider lib utils common default_idtoken_processing_hook
prompts the user to login if necessary and returns the user token suitable for use with the spotipy . spotify constructor,def prompt_for_user_token username scope None client_id None client_secret None redirect_uri None if not client_id client_id os getenv SPOTIPY_CLIENT_ID if not client_secret client_secret os getenv SPOTIPY_CLIENT_SECRET if not redirect_uri redirect_uri os getenv SPOTIPY_REDIRECT_URI if not client_id print You need to set your Spotify API credentials You can do this by setting environment variables like so export SPOTIPY_CLIENT_ID your spotify client id export SPOTIPY_CLIENT_SECRET your spotify client secret export SPOTIPY_REDIRECT_URI your app redirect url Get your credentials at https developer spotify com my applications raise spotipy SpotifyException 550 1 no credentials set sp_oauth oauth2 SpotifyOAuth client_id client_secret redirect_uri scope scope cache_path cache username token_info sp_oauth get_cached_token if not token_info print User authentication requires interaction with your web browser Once you enter your credentials and give authorization you will be redirected to a url Paste that url you were directed to to complete the authorization auth_url sp_oauth get_authorize_url try webbrowser open auth_url print Opened s in your browser auth_url except print Please navigate here s auth_url print print try response raw_input Enter the URL you were redirected to except NameError response input Enter the URL you were redirected to print print code sp_oauth parse_response_code response token_info sp_oauth get_access_token code if token_info return token_info access_token else return None
test ._parse_port_mapping ( ) fails on > 4 parts,def test_parse_port_mapping_udp self mapping 53 53 udp self assertEqual self transformer _parse_port_mapping mapping host_port 53 container_port 53 protocol udp
"walk the index gathering inode , dir entry , and file nodes .",def index ubifs lnum offset inodes chdr extract common_hdr ubifs lnum offset if chdr node_type UBIFS_IDX_NODE idxn extract idx_node ubifs lnum offset UBIFS_COMMON_HDR_SZ for branch in idxn branches index ubifs branch lnum branch offs inodes elif chdr node_type UBIFS_INO_NODE inon extract ino_node ubifs lnum offset UBIFS_COMMON_HDR_SZ ino_num inon key ino_num if not ino_num in inodes inodes ino_num inodes ino_num ino inon elif chdr node_type UBIFS_DATA_NODE datn extract data_node ubifs lnum offset UBIFS_COMMON_HDR_SZ chdr len ino_num datn key ino_num if not ino_num in inodes inodes ino_num if not data in inodes ino_num inodes ino_num data inodes ino_num data append datn elif chdr node_type UBIFS_DENT_NODE dn extract dent_node ubifs lnum offset UBIFS_COMMON_HDR_SZ ino_num dn key ino_num if not ino_num in inodes inodes ino_num if not dent in inodes ino_num inodes ino_num dent inodes ino_num dent append dn
set new path to vmx_file .,def set_path_to_vmx_file self path_to_vmx_file self path path_to_vmx_file
"return the subtasks that comprise this task if the task is to be modelled as a sequence of subtasks . if the task does not require or does not prefer such modelling , it should just return none .",def subtasks self return None
validates that the input can be compiled as a regular expression .,def clean self value value super RegexpExpressionFormField self clean value import re try re compile value except Exception as error raise ValidationError error return value
read terminal status line : clear to send,property def cts self if not self is_open raise portNotOpenError if self logger self logger info returning dummy for cts return True
the time at which this check will be run .,abc abstractproperty def time_to_run self return
"reshape inputs from [ time_length , batch_size , ... ] to [ time_length * batch_size , ... ] .",def reshape_batched_inputs self all_obs all_actions internal_policy_states policy_logits batch_size tf shape all_obs 0 1 time_length tf shape all_obs 0 0 reshaped_obs for obs obs_dim obs_type in zip all_obs self env_spec obs_dims_and_types if self env_spec is_discrete obs_type reshaped_obs append tf reshape obs time_length batch_size elif self env_spec is_box obs_type reshaped_obs append tf reshape obs time_length batch_size obs_dim reshaped_prev_act reshaped_policy_logits for i act_dim act_type in enumerate self env_spec act_dims_and_types prev_act all_actions i if self env_spec is_discrete act_type reshaped_prev_act append tf reshape prev_act time_length batch_size elif self env_spec is_box act_type reshaped_prev_act append tf reshape prev_act time_length batch_size act_dim reshaped_policy_logits append tf reshape policy_logits i time_length batch_size 1 reshaped_internal_policy_states tf reshape internal_policy_states time_length batch_size self internal_policy_dim time_step float self input_time_step tf expand_dims tf to_float tf range time_length batch_size batch_size 1 return time_step reshaped_obs reshaped_prev_act reshaped_internal_policy_states reshaped_policy_logits
": param no_prereqs_means : if an instance of this model has no prereqs , what should happen ? true - > make the object available false - > the object is unavailable ( and would have to be made available through some other mechanism ) i use this for badges , which must be granted manually if they have no prerequisites .",def __init__ self no_prereqs_means False self no_prereqs_means no_prereqs_means super PrereqQuerySet self __init__
used in order to make floats a consistent length for unit tests - it 's ok to shorten them because with 8 decimal places we should be able to test if the code is functioning correctly . beyond that the small specifics probably are n't super important : param original : the original number : param places : the number of decimal places to shorten it to ( obeys rounding rules ) : return : new number with specified number of decimal places,def shorten_float original places 8 if original is None or numpy isnan original return None format_str 0 six text_type places f return float format_str format original
"combine the path fragments with path_prefix as a base , and return the new full path",def p path_fragments return os path join PATH_PREFIX path_fragments
this gets called with the function we wish to wrap,def __call__ self func from compute import get_image_path assert callable func if self jobname is None self jobname func __name__ assert func __name__ wrapper utils args_from func wraps True inject_kwargs wait True def wrapper args kwargs Wraps a python function so that it will be executed remotely using a compute engine Note At runtime this documentation should be replaced with that of the wrapped function f func wait kwargs get wait True if wait and not self pkg force_remote return f args kwargs if self is_imethod f args _bind_instance_method f args python_call bpy PythonCall f args kwargs engine utils if_not_none self pkg engine mdt compute get_engine job bpy PythonJob engine engine image self pkg get_docker_image_path command python_call name self jobname sendsource self sendsource interpreter python persist_references self persist_refs submit False return run_job job wait wait _return_result True wrapper __name__ func __name__ wrapper __wrapped__ func return wrapper
gets the section from config file or raises an exception,def get_conf self varname try return self items varname except NoSectionError raise ConanException Invalid configuration missing s varname
get all the keys for the given key and class . this will be a single item array unless the key is all or similar : param key : : param clazz : : return :,classmethod def permission_keys cls key clazz return map lambda key s_ s key clazz __name__ lower cls _COMBOS get key key
runs all configured publishers via the django signals they depend upon . this is done in celery in order to support long running tasks launched from a client . peer tasks are run in parallel . dependent tasks are called after the tasks they depend on complete,app task base PostSaveTask def _post_save_publishing job config_entity user kwargs if not settings FOOTPRINT_INIT time sleep 10 bundle kwargs bundle if config_entity config_entity _feature_classes_created False FeatureClassCreator config_entity publishing_info get_publishing_info kwargs try transaction commit except Exception as e pass updated_kwargs merge remove_keys kwargs signal_path current_job bundle dict instance bundle instances user_id bundle user_id recurse True current_job job logger warn kwargs s updated_kwargs logger info Running handlers for signal signal_path for bundle format config_entity config_entity username user username signal_path publishing_info signal_path bundle unicode bundle resolve_module_attr publishing_info signal_path send sender config_entity __class__ if config_entity else bundle clazz updated_kwargs try transaction commit except Exception as e pass event postSavePublisherProportionCompleted logger info Sending message s for signal complete s to user s with s and proportion s event publishing_info signal_proportion_lookup_name user username unicode bundle publishing_info proportion if kwargs get update_setup_percent_complete for instance in bundle client_instances logger info Instance percent before s instance setup_percent_complete instance setup_percent_complete F setup_percent_complete 100 publishing_info proportion instance save logger info Instance percent after s instance setup_percent_complete send_message_to_client user id dict event event job_id str job hashid config_entity_id config_entity and config_entity id config_entity_class_name config_entity and config_entity __class__ __name__ publisher_name publishing_info publisher_name class_name bundle class_name_for_client ids bundle client_instance_ids keys bundle keys class_key bundle class_key proportion publishing_info proportion progress_description humanize publishing_info signal_path for dependent_signal_path in publishing_info dependent_signal_paths post_save_publishing dependent_signal_path config_entity user updated_kwargs job status Complete
create the file path editor window,def create self pass
"if using from within a plugin module 's `` initializeplugin `` or `` uninitializeplugin `` callback , pass along the mobject given to these functions .",def deregister cls plugin None pass
opens dialog box to select a folder params : none returns : path to folder / false,def openFolderDialog self lFp FBFolderPopup lFp Caption Select a folder self app FBApplication if not self sceneName Untitled lFp Path str self sceneName parent else lFp Path str schemaObj artRoot lRes lFp Execute if lRes return lFp Path else return False
save h5 file . set_name='data ',def save_h5 fname data compress 1 fast_compression 1 mkdir fname h5f h5py File fname mode w if compress h5set h5f create_dataset data data shape dtype data dtype compression gzip if fast_compression True else lzf else h5set h5f create_dataset data data shape dtype data dtype h5set data h5f close return 0
handle post requests to update an entity .,def post self user users get_current_user key_id self request get id parent_id self request get parent_id if parent_id and hasattr self model parent_model_name if parent_id crud_model NEW_ENTITY_ID return if issubclass self model ndb Model parent_key ndb Key self model parent_model_name long parent_id else parent_key db Key from_path self model parent_model_name long parent_id else parent_key None if key_id crud_model NEW_ENTITY_ID ex self _CreateNewEntity parent parent_key else ex self model get_by_id long key_id parent parent_key if not self IsAuthorized crud_model Actions UPDATE user ex self error 403 return ex UpdateFromJsonDict json loads self request body if hasattr ex last_updated_by ex last_updated_by user email if hasattr self postEntity ans self postEntity ex json loads self request body else key ex put ans self _GetJsonDict ex ans id key id self response headers Content Type text json self response out write JSON_PREFIX json dumps ans default JsonPrinter
delete /description / id : delete an existing item,def delete self id
function for creating device tables .,DEVICES route devices hostname def index hostname lookup Lookup CONFIG device_object Device hostname CONFIG lookup port_table device_object ports system_table device_object system return render_template device html hostname hostname port_table port_table system_table system_table
a utility function for decoding json strings from unicode,def _decode_dict data rv for key value in data iteritems if isinstance key unicode key key encode utf 8 if isinstance value unicode value value encode utf 8 elif isinstance value list value _decode_list value elif isinstance value dict value _decode_dict value rv key value return rv
remove the contents of the given directory .,def rmDirectoryContents dir for root dirs files in os walk dir topdown False for name in files os remove os path join root name for name in dirs os rmdir os path join root name
return the django aggregation function this module uses for the aggregated graph views .,def get_aggregate_function self return self aggregate_function
deletes the person from the client .,def delete self params email self email_address response self _delete clients s people json self client_id params params
generator to read a file piece by piece .,def get_binary_iterator self CHUNK_SIZE 1024 file_object open self path while True data file_object read CHUNK_SIZE if not data break yield data file_object close
"even when a callback method is not supplied to the xbeebase constructor , it must be properly initalized as a threading . thread object",def test_thread_always_initialized self self assertFalse self base is_alive
insert the volume market cap data .,def insertMarketCapVolume data return _insertMarketCap data tables trade_volume_usd
determines whether this list contains all of the items in specified collection or not .,def contains_all self items check_not_none items Items can t be None data_items for item in items check_not_none item item can t be None data_items append self _to_data item return self _encode_invoke list_contains_all_codec values data_items
frame a signal into overlapping frames .,def framesig sig frame_len frame_step winfunc lambda x numpy ones x stride_trick True slen len sig frame_len int round_half_up frame_len frame_step int round_half_up frame_step if slen frame_len numframes 1 else numframes 1 int math ceil 1 0 slen frame_len frame_step padlen int numframes 1 frame_step frame_len zeros numpy zeros padlen slen padsignal numpy concatenate sig zeros if stride_trick win winfunc frame_len frames rolling_window padsignal window frame_len step frame_step else indices numpy tile numpy arange 0 frame_len numframes 1 numpy tile numpy arange 0 numframes frame_step frame_step frame_len 1 T indices numpy array indices dtype numpy int32 frames padsignal indices win numpy tile winfunc frame_len numframes 1 return frames win
continue hashing of a message by consuming the next chunk of data .,def update self data if self _is_squeezing raise TypeError You cannot call update after the first read expect_byte_string data result _raw_keccak_lib keccak_absorb self _state get data c_size_t len data if result raise ValueError Error d while updating SHAKE128 state result return self
obtain 1 sentence summaries from wikipedia for corresponding wikipedia page for ' node_title ' node_title : title to be used for wikipedia query node_dir : directory containing content for given node ( wiki_summary_file will be written here ) wiki_summary_file : directory containing the node directories,def write_wiki_summary node_title node_dir wiki_ep http en wikipedia org w api php urlparams action query redirects prop extracts exintro explaintext exsectionformat plain exsentences 1 format xml titles s urllib quote_plus node_title rquest urllib2 Request wiki_ep urlparams xmlresp parseXML urllib2 urlopen rquest extxt xmlresp getElementsByTagName extract if len extxt summary extxt 0 firstChild wholeText replace n else summary temp tag os path split node_dir content_path _ os path split temp wiki_summary_file formats wiki_summary_file content_path tag with open wiki_summary_file w as wikif wikif write summary encode utf 8
check if the application can connect to the default cached and read / write some dummy data .,def check_cache_default dummy str uuid uuid4 key healthcheck s dummy cache set key dummy timeout 5 cached_value cache get key return cached_value dummy
sets the attached storage of a cv to this store,def set_cache_store self cv if self has_cache cv cv set_cache_store self cache_store cv else raise RuntimeWarning Your object is not stored in s yet and hence a store for the cache cannot be attached Save your CV first and retry self storage
return the clientquery api key from teamspeak config directory .,def get_api_key u clientquery_ini os path join get_config_location u clientquery ini if not os path isfile clientquery_ini Logger info u ClientQuery Could not find clientquery ini Assuming no api key return None try config ConfigParser RawConfigParser allow_no_value True config read clientquery_ini api_key config get u General u api_key return api_key except Exception as ex Logger error u ClientQuery get_api_key format ex return None
calculate mean of absorption coefficients .,def mean_alpha alphas surfaces Calculate mean of absorption coefficients param alphas Absorption coefficients math alpha param surfaces Surfaces math S return np average alphas axis 0 weights surfaces
loads config dict from environmental variables ( if set ) :,def load_environment_config mapper access_key AWS_ACCESS_KEY secret_key AWS_SECRET_ACCESS_KEY associate_tag AWS_ASSOCIATE_TAG locale AWS_LOCALE return dict key os environ get val for key val in mapper items if val in os environ
wrap the given get_response callable in exception - to - response conversion .,def convert_exception_to_response get_response u n Wrap the given get_response callable in exception to response conversion n n All exceptions will be converted All known 4xx exceptions Http404 n PermissionDenied MultiPartParserError SuspiciousOperation will be n converted to the appropriate response and all other exceptions will be n converted to 500 responses n n This decorator is automatically applied to all middleware to ensure that n no middleware leaks an exception and that the next middleware in the stack n can rely on getting a response instead of an exception n wraps get_response assigned available_attrs get_response def inner request try response get_response request except Exception as exc response response_for_exception request exc return response return inner
returns a dictionary to use as extra context if either `` self.description_template `` or `` self.item_template `` are used .,def get_context_data self kwargs u n Returns a dictionary to use as extra context if either n self description_template or self item_template are used n n Default implementation preserves the old behavior n of using obj item site current_site as the context n return u obj kwargs get u item u site kwargs get u site
create a suitable context from a plain dict and optionally an httprequest .,def make_context context request None kwargs if request is None context Context context kwargs else original_context context context RequestContext request kwargs if original_context context push original_context return context
post factory from a context . io message ( with body ) .,staticmethod def from_cio_message message subject message subject m_from message addresses from author m_from name if name in m_from else Anonymous body message body 0 content body body body rfind date datetime datetime fromtimestamp message date eastern pytz timezone US Eastern date eastern localize date date date datetime timedelta hours 4 date date year date month date day return Post subject author body date
consumes the next token which must match expectation .,def consume self expected_token token self next if token expected_token raise ValueError Expect s but got s at offset d expected_token token self index
"removes all nodes that are not accessible from the root , i.e. that have no dependant top - level nodes .",def remove_orphans self pre_nodes self _graph number_of_nodes self _graph self _graph subgraph nx dfs_postorder_nodes self _graph self ROOT_NODE_LABEL logging info Removed d orphaned nodes pre_nodes self _graph number_of_nodes
"this hook is called by the serializer instance , prior to the validation call being made .",def set_context self serializer_field u n This hook is called by the serializer instance n prior to the validation call being made n self field_name serializer_field source_attrs 1 self instance getattr serializer_field parent u instance None
print the ranges as an array of type named name .,def PrintRanges type name ranges print static s s type name for lo hi in ranges print t d d lo hi print
copy filename to newname along with stats : arguments : filename - filename path to be copied along with stats newname - new file name or path to which the file and stats has to be moved : returns : true if successful otherwise false,def copy2 self filename newname wdesc copy filename to newname along with stats pNote wdesc status file_Utils copy2 filename newname pStep Copying contents with stats of r to r format filename newname file_Utils log_result copy2 status return status
build the resnn model . args : page_batch : sequences returned from inputs_train ( ) or inputs_eval . returns : logits .,def resnn self sequences target_expanded tf expand_dims sequences 2 BottleneckBlock namedtuple BottleneckBlock num_layers num_filters bottleneck_size blocks BottleneckBlock 3 64 32 BottleneckBlock 6 128 64 BottleneckBlock 3 256 128 with tf variable_scope conv_layer1 net convolution2d target_expanded 64 7 1 stride 2 1 activation_fn self activation normalizer_fn batch_norm normalizer_params decay self norm_decay net tf nn max_pool net 1 3 1 1 strides 1 2 1 1 padding SAME with tf variable_scope conv_layer2 net convolution2d net blocks 0 num_filters 1 1 padding VALID activation_fn self activation normalizer_fn batch_norm normalizer_params decay self norm_decay for block_i block in enumerate blocks for layer_i in range block num_layers name block_ d layer_ d block_i layer_i with tf variable_scope name conv_in conv convolution2d net block bottleneck_size 1 1 padding VALID activation_fn self activation normalizer_fn batch_norm normalizer_params decay self norm_decay with tf variable_scope name conv_bottleneck conv convolution2d conv block bottleneck_size 3 1 padding SAME activation_fn self activation normalizer_fn batch_norm normalizer_params decay self norm_decay with tf variable_scope name conv_out conv convolution2d conv block num_filters 1 1 padding VALID activation_fn self activation normalizer_fn batch_norm normalizer_params decay self norm_decay net conv net try next_block blocks block_i 1 with tf variable_scope block_ d conv_upscale block_i net convolution2d net next_block num_filters 1 1 activation_fn self activation normalizer_fn batch_norm normalizer_params decay self norm_decay except IndexError pass net_shape net get_shape as_list net tf nn avg_pool net ksize 1 net_shape 1 net_shape 2 1 strides 1 1 1 1 padding VALID net_shape net get_shape as_list softmax_len net_shape 1 net_shape 2 net_shape 3 net tf reshape net 1 softmax_len with tf variable_scope softmax_linear WW tf get_variable WW shape softmax_len self num_cats initializer tf contrib layers xavier_initializer b self _variable_on_cpu b self num_cats tf constant_initializer value 0 1 softmax_linear tf nn xw_plus_b net WW b name scores return softmax_linear
tests ' samba - tool drs showrepl ' command output should be like : < site - name>/<domain - name > dsa options : < hex - options > dsa object guid : < dsa - object - guid > dsa invocationid : < dsa - invocationid > < inbound - connections - list > < outbound - connections - list > < kcc - objects > ... todo : perhaps we should check at least for dsa 's objectgudi and invocationid,def test_samba_tool_showrepl self out self check_output samba tool drs showrepl s s self dc1 self cmdline_creds self assertTrue DSA Options in out self assertTrue DSA object GUID in out self assertTrue DSA invocationId in out
"return a list of len(max_indexes ) indexes computed from the seed , such that 0 < = indexes[i ] < max_indexes[i ] . also return what remains from the seed .",def list_of_indexes_from_seed seed max_indexes indexes for i in range len max_indexes r seed max_indexes i seed seed r max_indexes i indexes append r return indexes seed
manifold intrinsic dimension estimator returns both global intrinsic dimensionality and local intrinsic dimensionality,def mide X n_neighbors None verbose 0 if n_neighbors is None k_min k_max get_k_range X n_neighbors k_min k_max 2 neigh NearestNeighbors fit X dist nbrs neigh kneighbors n_neighbors n_neighbors return_distance True local_dims lmse X nbrs verbose verbose if verbose visualize_graph X nbrs local_dims np array local_dims X_dims np concatenate X local_dims reshape 1 1 axis 1 b np mean dist 1 5 kde KernelDensity kernel epanechnikov bandwidth b fit X_dims for i in range len local_dims Xi np concatenate np repeat X i reshape 1 1 len np unique local_dims axis 0 np unique local_dims reshape 1 1 axis 1 kde_scores kde score_samples Xi local_dims i Xi np argmax kde_scores 1 if verbose 2 print local_dims intr_dim int round np mean local_dims 0 return intr_dim local_dims
fetch the tarball of anime titles,def com_net_anidb_fetch_titles_file self if common_file com_file_modification_timestamp cache anidb_titles gz time time 86400 common_network mk_network_fetch_from_url http anidb net api anime titles xml gz cache anidb_titles gz return True return False
verify value of radio button | arguments | usage | ( m)andatory / ( o)ptional | | locator | element i d | m | | actual | expected value | m |,def verify_radio_button self locator expected actual WHITE_LIB verify_radio_button locator verify_value expected actual
initializes a new instance of : see : localizedvaluedescriptor .,def __init__ self field self field field
"when initialized , it copies the class defaults ; then takes a copy of the attributes of the parent if any . all the work is done in init - styles should cost little to use at runtime .",def __init__ self name parent None kw assert name not in self defaults Class Defaults may not contain a name attribute assert parent not in self defaults Class Defaults may not contain a parent attribute if parent assert parent __class__ self __class__ Parent style s must have same class as new style s parent __class__ __name__ self __class__ __name__ self name name self parent parent self __dict__ update self defaults self refresh self _setKwds kw
remove the column and then resize .,def RemoveColumn self args kwargs result super AutoColumnWidthMixin self RemoveColumn args kwargs self DoResize return result
convert json files to intents objects and insert to mongodb : return :,intents route import methods POST def import_intents if file not in request files abort 400 No file part json_file request files file all_intents import_json json_file return build_response build_json num_intents_created len all_intents
check if a user already exists with this name,def unique_username form field user User query filter User name field data first if user is not None raise ValidationError There is already a user with this name
test stdout is captured in logs when capture - output argument is set .,def test_output_logging self logstash self run_logstash try environment LOGSTASH_SERVER logstash server_address 0 LOGSTASH_PORT str logstash server_address 1 LOGSTASH_PROTO udp COVERAGE_PROCESS_START coveragerc config get_config arguments capture output events PROCESS_LOG self run_supervisor environment config try expected version 1 channel stdout eventname PROCESS_LOG_STDOUT groupname messages level INFO logger_name supervisor message Test 0 n path logstash_notifier __init__ py processname messages tags type logstash received self messages clear_buffer True wait_for 1 self assertEqual received expected finally self shutdown_supervisor finally self shutdown_logstash
makes predictions by running the forward pass over all of the layers .,def predict wb_struct inputs graphs curr_inputs inputs for i layer in enumerate layers wb wb_struct layer 0 _ 1 format i layer curr_inputs layer forward_pass wb curr_inputs graphs return curr_inputs
create headers for the request . parameters method ( str ) http method ( e.g. ' post ' ) . auth_session ( session ) the session object containing oauth 2.0 credentials . returns headers ( dict ) dictionary of access headers to attach to request . raises lyftillegalstate ( apierror ) raised if headers are invalid .,def _build_headers self method auth_session u Create headers for the request n Parameters n method str n HTTP method e g POST n auth_session Session n The Session object containing OAuth 2 0 credentials n Returns n headers dict n Dictionary of access headers to attach to request n Raises n LyftIllegalState ApiError n Raised if headers are invalid n token_type auth_session token_type token auth_session oauth2credential access_token if not self _authorization_headers_valid token_type token message u Invalid token_type or token raise LyftIllegalState message headers u Authorization u join token_type token if method in http BODY_METHODS headers update http DEFAULT_CONTENT_HEADERS return headers
delete a user 's account .,admin route user int user_id _delete login_required def delete_user user_id if current_user id user_id flash You cannot delete your own account Please ask another administrator to do this error else user User query filter_by id user_id first db session delete user db session commit flash Successfully deleted user s user full_name success return redirect url_for admin registered_users
converts the thermocouple byte values to a decimal value .,staticmethod def _thermocouple_temp_from_bytes byte0 byte1 byte2 temp_bytes byte2 127 16 byte1 8 byte0 temp_bytes temp_bytes 5 if byte2 128 temp_bytes 2 MAX31856 MAX31856_CONST_THERM_BITS 1 temp_c temp_bytes MAX31856 MAX31856_CONST_THERM_LSB return temp_c
"draws a 3d axis - aligned bounding box with lower corner a and upper corner b. if lighting is true , sends gl normal vectors . if filled = true , draws it solidly . otherwise , only the wireframe is drawn .",def box a 0 0 0 b 1 1 1 lighting True filled True glNormal3f 0 0 1 quad a 0 a 1 a 2 a 0 b 1 a 2 b 0 b 1 a 2 b 0 a 1 a 2 False filled glNormal3f 0 0 1 quad a 0 a 1 b 2 b 0 a 1 b 2 b 0 b 1 b 2 a 0 b 1 b 2 False filled glNormal3f 1 0 0 quad a 0 a 1 a 2 a 0 a 1 b 2 a 0 b 1 b 2 a 0 b 1 a 2 False filled glNormal3f 1 0 0 quad b 0 a 1 a 2 b 0 b 1 a 2 b 0 b 1 b 2 b 0 a 1 b 2 False filled glNormal3f 0 1 0 quad a 0 a 1 a 2 b 0 a 1 a 2 b 0 a 1 b 2 a 0 a 1 b 2 False filled glNormal3f 0 1 0 quad a 0 b 1 a 2 a 0 b 1 b 2 b 0 b 1 b 2 b 0 b 1 a 2 False filled
gets the html diff from the daisydiff server and returns it as a table row,def daisydiff field1 field2 service_url DAISYDIFF_URL params urlencode field1 field1 field2 field2 headers Content type application x www form urlencoded Accept text html split_url urlparse urlsplit service_url conn httplib HTTPConnection split_url netloc conn request POST split_url path params headers response conn getresponse if not response status 200 raise ServiceUnavailableError Service responded with status i s response status response reason data response read conn close row extract_table_row data row attributes class htmldiff return row toxml
the `` --all `` parameter will send notifications to all users .,def test_all_parameter self call_command report_mailing all self assertEqual len mail outbox 1 self assertListEqual mail outbox 0 to self user email self staff_user email self admin_user email
create a link in the closure tree .,def _closure_createlink self linkparents self _closure_model objects filter child__pk self _closure_parent_pk values parent depth linkchildren self _closure_model objects filter parent__pk self pk values child depth newlinks self _closure_model parent_id p parent child_id c child depth p depth c depth 1 for p in linkparents for c in linkchildren self _closure_model objects bulk_create newlinks
setup things to be run when tests are started .,def setup_method self method self hass get_test_home_assistant self rs cmd_rs CommandCover self hass foo command_open command_close command_stop command_state None
set up the zamg sensor platform .,def setup_platform hass config add_devices discovery_info None station_id config get CONF_STATION_ID or closest_station config get CONF_LATITUDE config get CONF_LONGITUDE hass config config_dir if station_id not in zamg_stations hass config config_dir _LOGGER error Configured ZAMG s s is not a known station CONF_STATION_ID station_id return False probe ZamgData station_id station_id logger _LOGGER try probe update except ValueError as err _LOGGER error Received error from ZAMG s err return False add_devices ZamgWeather probe config get CONF_NAME True
"set volume level , range 0 .. 1 .",def set_volume_level self volume self _volume volume
return the unit of measurement the value is expressed in .,property def unit_of_measurement self return self _units
return the unit the value is expressed in .,property def unit_of_measurement self return self _unit_of_measurement
return true if the binary sensor is on .,property def is_on self return self _state
initialize the ecobee data object .,def __init__ self config_file from pyecobee import Ecobee self ecobee Ecobee config_file
stop everything that was started .,def teardown_method self self hass stop
return the lower bound temperature we try to reach .,property def target_temperature_low self if self is_away_mode_on or self _mode STATE_ECO and self _eco_temperature 0 return self _eco_temperature 0 if self _mode STATE_HEAT_COOL return self _target_temperature 0 else return None
return the title of current playing media .,property def media_title self return self _media_title
retrieve auth tokens from the router .,def _get_auth_tokens self _LOGGER info Retrieving auth tokens url http cgi bin luci stok login form login format self host referer http webpages login html format self host response requests post url params operation login username self username password self password headers referer referer try self stok response json get data get stok _LOGGER info self stok regex_result re search sysauth response headers set cookie self sysauth regex_result group 1 _LOGGER info self sysauth return True except ValueError _LOGGER error Couldn t fetch auth tokens return False
turn the media player on .,def turn_on self self _receiver on True self _volume self _receiver volume 100 1
volume level of the media player ( 0 .. 1 ) .,property def volume_level self if self _volume is not None return self _volume 100 else return None
"example : opting out for 50 symbol - long , [ a - z][a - z][0 - 9 ] string would yield log_2((26 + 26 + 50)^50 ) ~= 334 bit strength .",def generate_random_string length using_digits False using_ascii_letters False using_punctuation False if not using_sysrandom return None symbols if using_digits symbols string digits if using_ascii_letters symbols string ascii_letters if using_punctuation symbols string punctuation replace replace replace return join random choice symbols for _ in range length
compute the softmax function for each row of the input x.,def softmax x orig_shape x shape if len x shape 1 c np max x axis 1 reshape 1 1 return np exp x c np sum np exp x c axis 1 reshape 1 1 else return np exp x np sum np exp x assert x shape orig_shape return x
package node aims to package a ( present working node ) for a user into a container . this assumes that the node is a single partition .,def package_node root None name None if name is None name platform node if root is None root tmpdir tempfile mkdtemp image s s tgz tmpdir name print Preparing to package root s into s root name cmd tar one file system czvSf image root exclude image output run_command cmd return image
a view function to handle the overall processing of batch requests .,csrf_exempt require_http_methods POST def handle_batch_requests request args kwargs batch_start_time datetime now try wsgi_requests get_wsgi_requests request except BadBatchRequest as brx return HttpResponseBadRequest content brx message response execute_requests wsgi_requests resp HttpResponse content json dumps response content_type application json if _settings ADD_DURATION_HEADER resp __setitem__ _settings DURATION_HEADER_NAME str datetime now batch_start_time seconds return resp
this test shows a very simple line model with test_loss .,def test_end_to_end self training_input training_output 1 0 2 0 3 0 4 0 2 8 5 1 7 2 8 7 test_input test_output 5 0 6 0 7 0 8 0 11 13 15 17 random_seed set_random_seed 1234 def test_line x m variable_scope get_variable w shape initializer init_ops truncated_normal_initializer b variable_scope get_variable b shape initializer init_ops truncated_normal_initializer return x m b line_template template make_template line test_line train_prediction line_template training_input test_prediction line_template test_input train_loss math_ops reduce_mean math_ops square train_prediction training_output test_loss math_ops reduce_mean math_ops square test_prediction test_output optimizer gradient_descent GradientDescentOptimizer 0 1 train_op optimizer minimize train_loss with session Session as sess sess run variables global_variables_initializer initial_test_loss sess run test_loss sess run train_op final_test_loss sess run test_loss self assertLess final_test_loss initial_test_loss
create a context manager that binds the names in values .,def __init__ self names if not isinstance names dict names vars names self names names
returns the variable scope object created by this template .,property def variable_scope self return self _variable_scope
return the label of a selected result .,def get_selected_result_label self result return self get_result_label result
excepts any thing that might happen in the signals and raises a validation error in order to send back the right status code .,def perform_create self serializer try long_url serializer validated_data long_url document _ Document objects get_or_create long_url long_url serializer instance document annotate _ Annotation objects get_or_create user self request user document document except CorpusException as e raise ValidationError str e
add command - line arguments to the program .,def add_all_args parser parser add_argument output_path type str required True help GCS path to write the output to add_args parser
formats the log_record to display each item on a new line to increase readability,staticmethod def format_return log_record ret_list for key value in log_record items ret_list append s s n key value return join ret_list
return whether current date has a scheduled fixture .,def get_fixture self state False for leagueid league in data leagues get_leagues if self event len league fixtures events 1 if data date get_date_for_event league fixtures events self event state True return state
clear list of cards for season .,def clear_cards self self cards clear
"get a bunch of layers and concatenate them together into one . this is useful if you have a map with layers for , say , every year named stuff_2014 , stuff_2013 , stuff_2012 . etc .",def getMultiple self layers where 1 1 fields srid 4326 layer_name_field None features for layer in layers get_fields fields or self enumerate_layer_fields layer this_layer self get layer where get_fields False srid get features if layer_name_field descriptor self get_descriptor_for_layer layer layer_name descriptor get name for feature in this_layer feature properties layer_name_field layer_name features this_layer return type FeatureCollection features features
read data from source and target files and put into buckets .,def read_data source_path target_path max_size None data_set for _ in _buckets with tf gfile GFile source_path mode r as source_file with tf gfile GFile target_path mode r as target_file source target source_file readline target_file readline counter 0 while source and target and not max_size or counter max_size counter 1 if counter 100000 0 print reading data line d counter sys stdout flush source_ids int x for x in source split target_ids int x for x in target split for bucket_id source_size target_size in enumerate _buckets if len source_ids source_size and len target_ids target_size data_set bucket_id append source_ids target_ids break source target source_file readline target_file readline return data_set
legacy function - just in case someone is still using the old name,def remove_www_and_dev hostname return remove_www hostname
"a trial with possible outcomes where each outcome has equal probability , how many outcomes correspond to an event that has probability",def gpas return 4 0 30 3 0 40 2 0 20 1 0 10 100
returns a string representation of the object .,def __str__ self tripcode if self public tripcode str self public if self secure tripcode str self secure if not self solved return self url self name format tripcode self self solutions if self public and self public solved solutions self public key if self secure and self secure solved solutions self secure key return self url self name format solutions tripcode self self
"input : - s : a list of vectors , as instances of your vec class - a : a list of vectors , each of which are in s , with len(a ) < len(s ) - z : an instance of vec such that a+[z ] is linearly independent output : a vector w in s but not in a such that span s = span ( { z } u s - { w } ) example : > > > s = [ list2vec(v ) for v in [ [ 0,0,5,3],[2,0,1,3],[0,0,1,0],[1,2,3,4 ] ] ] > > > a = [ list2vec(v ) for v in [ [ 0,0,5,3],[2,0,1,3 ] ] ] > > > z = list2vec([0,2,1,1 ] ) > > > exchange(s , a , z ) = = vec({0 , 1 , 2 , 3},{0 : 0 , 1 : 0 , 2 : 1 , 3 : 0 } ) true",def exchange S A z solns for i v in enumerate S if is_superfluous S solns z i solns append v for soln in solns if soln not in A return soln return None
sends the command to stop doing a horizontal patrol : return :,def stop_horiz_patrol self self command 29
"same as above , but for simple signed transactions",def makeTransactionSimple network args return wrapTransaction network transactionUtil makeSimpleSigned args
an intelligent method to get real ip address .,def get_ip_from_request request x_forwarded_for request META get HTTP_X_FORWARDED_FOR if x_forwarded_for ip x_forwarded_for split 0 else ip request META get REMOTE_ADDR return ip
return latest datetime and dict of field names and values .,def fetch_last self fetch_metrics latest data datetime fromtimestamp 0 utc for series in Series filter self measured_object name__in fetch_metrics point Stats latest series id data series name point mean latest max latest point dt return latest data
"input : list of vertices representing the roadmap output : list of all polygon2ds representing lots , list of all polygon2ds representing blocks list of all polygon2ds which are too large to be lots polygon2d representing the road - network",def main vertex_list None singleton Singleton polygons if vertex_list is None from procedural_city_generation additional_stuff import pickletools vertex_list pickletools reconstruct singleton input_name print Reconstructing of data structure finished import os import procedural_city_generation path os path dirname procedural_city_generation __file__ with open path temp singleton input_name _heightmap txt r as f border int x for x in f read split _ 2 if x is not print Extracting Polygon2Ds from procedural_city_generation polygons import construct_polygons polylist construct_polygons getPolygon2Ds vertex_list print Polygon2Ds extracted from procedural_city_generation polygons getLots import getLots as getLots s vertices len vertex_list polygons getLots polylist vertex_list print Lots found sorted if singleton plotbool print Plotting if gui is None import matplotlib pyplot as plt for g in polygons g selfplot plt plt plt show else i 0 for g in polygons g selfplot plt gui i 1 if i singleton plot_counter 0 gui update gui update import pickle with open os path dirname procedural_city_generation __file__ temp singleton input_name _polygons txt wb as f import sys if sys version 0 2 s pickle dumps polygons f write s else pickle dump polygons f return 0
test that the finder can deal with a missing branch .,with_httmock mocked_urls def test_finder_missing_branch self finder OpenTSDBFinder http localhost 4242 api v1 3 with self assertRaises ValueError nodes list finder find_nodes query FindQuery None None
returns a driver instance for a user with the appropriate authentication credentials set .,def _get_user_driver self auth_credentials driver super _get_user_driver auth_credentials driver list_nodes return driver
get the latest known global position of the robot .,def get_latest_global_position self return self _lat self _lon self _dir_to_north
set password for the username of the service,def set_password self service username password service self _safe_string service username self _safe_string username password self _safe_string password attrs GnomeKeyring Attribute list_new GnomeKeyring Attribute list_append_string attrs username username GnomeKeyring Attribute list_append_string attrs service service GnomeKeyring Attribute list_append_string attrs application python keyring result GnomeKeyring item_create_sync self KEYRING_NAME GnomeKeyring ItemType NETWORK_PASSWORD Password for s on s username service attrs password True 0 if result GnomeKeyring Result CANCELLED raise PasswordSetError Cancelled by user elif result GnomeKeyring Result OK raise PasswordSetError result value_name
"searches for solution to f(x ) = y in ( lb , ub ) , where f is a monotone decreasing function",def find_root f y lb ub tol 1e 06 a b lb ub fa fb f a f b if fa y and fb y while fb y b fb b b a f b b a elif fa y and fb y while fa y a fa a b a f a b a try max_iter int np ceil np log tol np log b a np log 0 5 except OverflowError warnings warn root finding failed returning np nan return np nan for _ in range max_iter try c fc a b 2 f a b 2 if fc y a c elif fc y b c except OverflowError warnings warn root finding failed returning np nan return np nan return c
run tests that do n't require http,task def test_fast print Running Fast Tests sh python run_tests py test_pattern test_math_ py sh python run_tests py test_pattern test_ helper py sh python run_tests py test_pattern test_ parser py sh python run_tests py test_pattern test_ manipulator py sh python run_tests py test_pattern test_ api py sh python run_tests py test_pattern test_event py sh python run_tests py test_pattern test_match_cleanup py sh python run_tests py test_pattern test_event_group_by_week py sh python run_tests py test_pattern test_event_team_repairer py sh python run_tests py test_pattern test_event_team_updater py sh python run_tests py test_pattern test_event_get_short_name py
create a normalizedbool instance with a normalized value .,def __init__ self value try super NormalizedBool self __init__ type self normalize value except ValueError as e raise type e repr value
clean [ targets ] clean ( remove ) the specified targets and their dependencies . ' c ' is a synonym .,def do_clean self argv return self do_build build clean argv 1
find all unique twitter screen names in the database,property def all_screen_names self return set ContactDetail objects filter contact_type twitter values_list value flat True
ping implemented to check service availability .,def Ping self request _ return inventory_pb2 PingReply data request data
string representation . returns : str : json string .,def __repr__ self return self _json
get a file name that can be used for creating a stash file,def get_file_name self source_name re sub a zA Z_0 9 _ str self source_name stash_file make_splunkhome_path var spool splunk source_name _ str time time _ str random randrange 0 65535 1 self file_extension return stash_file
main run function for processing chip - seq fastq data . pipeline aligns the fastq files to the genome using bwa . macs 2 is then used for peak calling to identify transcription factor binding sites within the genome .,def run self input_files metadata output_files output_files_generated output_metadata logger info PROCESS CHIPSEQ DEFINED OUTPUT output_files bam if genome_public in input_files align_input_files remap input_files genome genome_public loc loc index index_public align_input_file_meta remap metadata genome genome_public loc loc index index_public else align_input_files remap input_files genome loc index align_input_file_meta remap metadata genome loc index if fastq2 in input_files align_input_files fastq2 input_files fastq2 align_input_file_meta fastq2 metadata fastq2 logger progress BWA Aligner status RUNNING bwa bwaAlignerTool self configuration bwa_files bwa_meta bwa run align_input_files align_input_file_meta output output_files bam logger progress BWA Aligner status DONE try output_files_generated bam bwa_files bam output_metadata bam bwa_meta bam tool_name output_metadata bam meta_data tool output_metadata bam meta_data tool_description tool_name output_metadata bam meta_data tool process_chipseq except KeyError logger fatal BWA aligner failed if bg_loc in input_files if genome_public in input_files align_input_files_bg remap input_files genome genome_public index index_public loc bg_loc align_input_file_meta_bg remap metadata genome genome_public index index_public loc bg_loc else align_input_files_bg remap input_files genome index loc bg_loc align_input_file_meta_bg remap metadata genome index loc bg_loc if fastq2 in input_files align_input_files_bg fastq2 input_files fastq2_bg align_input_file_meta_bg fastq2 metadata fastq2_bg logger progress BWA Aligner Background status RUNNING bwa_bg_files bwa_bg_meta bwa run align_input_files_bg align_input_file_meta_bg output output_files bam_bg logger progress BWA Aligner Background status DONE try output_files_generated bam_bg bwa_bg_files bam_bg output_metadata bam_bg bwa_bg_meta bam_bg tool_name output_metadata bam_bg meta_data tool output_metadata bam_bg meta_data tool_description tool_name output_metadata bam_bg meta_data tool process_chipseq except KeyError logger fatal Background BWA aligner failed b3f biobambam self configuration logger progress BioBamBam status RUNNING b3f_files b3f_meta b3f run input bwa_files bam input bwa_meta bam output output_files filtered logger progress BioBamBam status DONE try output_files_generated filtered b3f_files bam output_metadata filtered b3f_meta bam tool_name output_metadata filtered meta_data tool output_metadata filtered meta_data tool_description tool_name output_metadata filtered meta_data tool process_chipseq except KeyError logger fatal BioBamBam filtering failed if bg_loc in input_files logger progress BioBamBam Background status RUNNING b3f_bg_files b3f_bg_meta b3f run input bwa_bg_files bam input bwa_bg_meta bam output output_files filtered_bg logger progress BioBamBam Background status DONE try output_files_generated filtered_bg b3f_bg_files bam output_metadata filtered_bg b3f_bg_meta bam tool_name output_metadata filtered_bg meta_data tool output_metadata filtered_bg meta_data tool_description tool_name output_metadata filtered_bg meta_data tool process_chipseq except KeyError logger fatal Background BioBamBam filtering failed macs_caller macs2 self configuration macs_inputs bam output_files_generated filtered macs_metadt bam output_metadata filtered if bg_loc in input_files macs_inputs bam_bg output_files_generated filtered_bg macs_metadt bam_bg output_metadata filtered_bg logger progress MACS2 status RUNNING m_results_files m_results_meta macs_caller run macs_inputs macs_metadt remap output_files narrow_peak summits broad_peak gapped_peak logger progress MACS2 status DONE if not m_results_meta logger fatal MACS2 peak calling failed if narrow_peak in m_results_meta output_files_generated narrow_peak m_results_files narrow_peak output_metadata narrow_peak m_results_meta narrow_peak tool_name output_metadata narrow_peak meta_data tool output_metadata narrow_peak meta_data tool_description tool_name output_metadata narrow_peak meta_data tool process_chipseq if summits in m_results_meta output_files_generated summits m_results_files summits output_metadata summits m_results_meta summits tool_name output_metadata summits meta_data tool output_metadata summits meta_data tool_description tool_name output_metadata summits meta_data tool process_chipseq if broad_peak in m_results_meta output_files_generated broad_peak m_results_files broad_peak output_metadata broad_peak m_results_meta broad_peak tool_name output_metadata broad_peak meta_data tool output_metadata broad_peak meta_data tool_description tool_name output_metadata broad_peak meta_data tool process_chipseq if gapped_peak in m_results_meta output_files_generated gapped_peak m_results_files gapped_peak output_metadata gapped_peak m_results_meta gapped_peak tool_name output_metadata gapped_peak meta_data tool output_metadata gapped_peak meta_data tool_description tool_name output_metadata gapped_peak meta_data tool process_chipseq return output_files_generated output_metadata
increments the action instance for the given user and the current day .,def increment_now self user day now date return self increment_date user day
create snippet string for a list of keyword arguments .,def keyword_arguments self attributes section template name type optional description the default is default which default_description if len attributes 0 return for attr in attributes section template format name self _generate_field name attr name type self _generate_field type attr type description self _generate_field description default self _generate_field default attr default default_description self _generate_field default_description return section
"resultformat : # { ' contact name ' : { ' numbers ' : [ ' 123 ' , ' 456 ' ] , ' imageurl ' : ' http ... ' , ' imagebmp ' : ' imagepath ' } , ... }",abstractmethod def getPhonebook self pbid None pass
returns the mean vector of a collection of vectors . : type vectors : list of iterables,def Mean vectors assert isinstance vectors 0 collections Iterable return Multiply reduce lambda x y Add x y vectors 1 0 len vectors
"check grafana db for existant dashboards , panel i d 's and return them for next iteration .",def check_prev_metadata self pass
mix color with the checkered color .,def checkered_color color background checkered RGBA color checkered apply_alpha background return checkered get_rgb
evaluates a kernel on held out data input : - x - a matrix ( data_points x dimensions ) of input locations - y - a matrix ( data_points x 1 ) of output values - xtest - held out x data - ytest - held out y data - best_scored_kernel - a scored kernel object to be evaluated on the held out data - ... return : - a dictionary of results from the matlab script containing : - loglik - an array of log likelihoods of test data - predictions - an array of mean predictions for the held out data - actuals - ytest - model - i 'm not sure fixme - timestamp - a time stamp of some sort,def make_predictions X y Xtest ytest best_scored_kernel local_computation False max_jobs 500 verbose True zero_mean False random_seed 0 if X ndim 1 X X nax if y ndim 1 y y nax ndata y shape 0 data_file cblparallel create_temp_file mat scipy io savemat data_file X X y y Xtest Xtest ytest ytest if not local_computation if verbose print Moving data file to fear cblparallel copy_to_remote data_file parameters datafile data_file split 1 writefile output_file s gpml_path cblparallel gpml_path local_computation kernel_family best_scored_kernel k_opt gpml_kernel_expression kernel_params s join str p for p in best_scored_kernel k_opt param_vector noise str best_scored_kernel noise iters str 30 seed str random_seed if zero_mean code gpml PREDICT_AND_SAVE_CODE_ZERO_MEAN parameters else code gpml PREDICT_AND_SAVE_CODE parameters code re sub code if local_computation temp_results_file cblparallel run_batch_locally code language matlab max_cpu 1 1 max_mem 1 1 verbose verbose 0 else temp_results_file cblparallel run_batch_on_fear code language matlab max_jobs max_jobs verbose verbose 0 results scipy io loadmat temp_results_file cblparallel remove_temp_file temp_results_file local_computation cblparallel remove_temp_file data_file local_computation return results
deserialize a date object from its proper iso-8601 representation .,def _parse_date_value value return arrow get value YYYY MM DD date
return authentication class based on plugin name,def get_auth_plugin plugin_name for authclass in BaseAuthPlugin __subclasses__ if authclass plugin_name plugin_name return authclass raise errors NotSupportedError Authentication plugin 0 is not supported format plugin_name
this returns a string value for a battery level,def batteryLevel level l empty try v float level except v 0 if v 5 l empty elif v 20 l low elif v 90 l medium elif v 100 l high else l full return l
get mac address from domain xml .,def get_mac_address conn domain_name domain conn lookupByName domain_name domain_xml domain XMLDesc domain_tree etree fromstring domain_xml devices domain_tree find devices interfaces devices iterfind interface for interface in interfaces source interface find source if source is None or source get network vagrant private dhcp continue mac_element interface find mac mac_address mac_element get address return mac_address raise NoPrivateDHCPInterfaceException
"the pool was just created , so it must always be possible to destroy it .",def testExecution self managed_objects ObjectManager Methods GetManagedObjects self _proxy pool1 _ next pools managed_objects Name self _POOLNAME blockdevs1 blockdevs managed_objects Pool pool1 self assertEqual frozenset MOBlockDev b Devnode for _ b in blockdevs1 frozenset d for d in self _devices result rc _ Manager Methods DestroyPool self _proxy pool pool1 managed_objects ObjectManager Methods GetManagedObjects self _proxy blockdevs2 blockdevs managed_objects Pool pool1 pool2 next pools managed_objects Name self _POOLNAME None self assertEqual rc StratisdErrors OK self assertIsNone pool2 self assertTrue result self assertEqual len list blockdevs2 0
randomly permute the training roidb .,def _shuffle_roidb_inds self self _perm np random permutation np arange len self _roidb self _cur 0
test with missing html_url on pull_request dict,def test_is_valid_pull_request_missing_html_url self with self assertRaises BadRequest data self valid_request copy data pull_request is_valid_pull_request data
return true if this page list contains more than one page .,def paginated self u return len self 1
add transform expressed in tool coordinate,def add_pose_tool self trans acc 0 01 vel 0 01 wait True command movel threshold None pose self get_pose return self set_pose pose trans acc vel wait wait command command threshold threshold
gets the number of digital outputs this device has,def getNumOutputs self if self ptr return cphidgets InterfaceKit_getNumOutputs self ptr else return 0
"warp the target to the invoker 's current position , and rotation .",magicWord category CATEGORY_COMMUNITY_MANAGER def warp invoker spellbook getInvoker target spellbook getTarget if invoker doId target doId return You can t warp yourself target setPosHpr invoker getPos invoker getHpr
test that the decoder is in sync with the backend,def test_monitored_event_fetched_from_backend self self _create_deposit_event decoder Decoder block_number 0 self assertEqual decoder monitored_events count 1 LogDeposit is been monitored
"this method takes an initial allocation of prices across events , and an identical length list of allocation tuples . it applies the rule specified by this discount , allocates the discount across the listed items , and returns both the price and the allocation",def applyAndAllocate self allocatedPrices tieredTuples payAtDoor False initial_net_price sum x for x in allocatedPrices if self discountType self DiscountType flatPrice applicable_price self getFlatPrice payAtDoor or 0 this_price applicable_price sum x 0 event getBasePrice payAtDoor payAtDoor x 1 if x 1 1 else x 0 price for x in tieredTuples this_allocated_prices x this_price initial_net_price for x in allocatedPrices elif self discountType self DiscountType dollarDiscount this_price initial_net_price self dollarDiscount this_allocated_prices x this_price initial_net_price for x in allocatedPrices elif self discountType DiscountCombo DiscountType percentDiscount if self percentUniversallyApplied this_price initial_net_price 1 max min self percentDiscount or 0 100 0 100 this_allocated_prices x this_price initial_net_price for x in allocatedPrices else this_price 0 this_allocated_prices for idx val in enumerate tieredTuples this_val allocatedPrices idx 1 val 1 1 max min self percentDiscount or 0 100 0 100 allocatedPrices idx val 1 this_allocated_prices append this_val this_price this_val else raise KeyError _ Invalid discount type if this_price initial_net_price this_price max this_price 0 return self DiscountInfo self this_price initial_net_price this_price this_allocated_prices
this function counts the number of opening / closing blocks for a given opening / closing type and adjusts the current depth for that block based on the difference,def _count_jinja2_blocks token cur_depth open_token close_token num_open token count open_token num_close token count close_token if num_open num_close cur_depth num_open num_close if cur_depth 0 cur_depth 0 return cur_depth
fetch a file from remote to local,def fetch_file self in_path out_path pass
just runs some example code .,def main helper print_title Output actor help cv CrossValidate cv config setup Classifier classname weka classifiers trees J48 cv print_help
parses methods from the given discovery document .,def parse_methods root methods None if methods is None methods for method in six itervalues root get methods id_ method id methods id_ method for resource in six itervalues root get resources parse_methods resource methods return methods
"convert a ( pandas ) dataframe to a great_expectations dataset , with ( optional ) expectations_config",def _convert_to_dataset_class df dataset_class expectations_config None if expectations_config is not None df __class__ dataset_class df _initialize_expectations expectations_config else try df dataset_class df except raise NotImplementedError read_csv requires a Dataset class that can be instantiated from a Pandas DataFrame return df
does a right tree - rotation around node x.,def _right_rotate x y x left x set_left y right if x parent if x x parent left x parent set_left y else x parent set_right y else y parent None y save y set_right x
delete mappings that matches neutron_port_id .,def delete_switchport_binding context neutron_port_id segmentation_id session context session with session begin subtransactions True if neutron_port_id session query nuage_models NuageSwitchportBinding filter_by neutron_port_id neutron_port_id segmentation_id segmentation_id delete
"reads a pandas data frame , with time index labelled package_name(/path1/path2 .. , filename",def pd_readcsv filename date_index_name DATETIME ans pd read_csv filename ans index ans date_index_name values del ans date_index_name ans index name None return ans
ensure that the build directory is present .,def check_build if not os path isdir build_dir try os makedirs build_dir except OSError as exc if exc errno errno EEXIST pass else raise
"verifies the starlog has all the required fields , and any hashes and signatures match up .",def star_log star_log_json if not isinstance star_log_json hash basestring raise Exception hash is not a string if not isinstance star_log_json version int raise Exception version is not an integer if not isinstance star_log_json previous_hash basestring raise Exception previous_hash is not a string if not isinstance star_log_json difficulty int raise Exception difficulty is not an integer if not isinstance star_log_json nonce int raise Exception nonce is not an integer if not isinstance star_log_json time int raise Exception time is not an integer if util get_time star_log_json time raise Exception time is greater than the current time if not isinstance star_log_json events_hash basestring raise Exception events_hash is not a string if star_log_json events is None raise Exception events is missing if star_log_json meta_hash is None raise Exception meta_hash is missing field_is_sha256 star_log_json hash hash field_is_sha256 star_log_json previous_hash previous_hash field_is_sha256 star_log_json events_hash events_hash field_is_sha256 star_log_json meta_hash meta_hash sha256 star_log_json hash util concat_star_log_header star_log_json log_header sha256 star_log_json meta_hash star_log_json meta meta if not star_log_json events_hash util hash_events star_log_json events raise Exception events_hash does not match actual hash difficulty star_log_json difficulty star_log_json hash events star_log_json events
installs the gcs boto plugin on the vm .,def _Install vm vm Install pip vm RemoteCommand sudo pip install ignore installed gcs oauth2 boto plugin
installs the fio package on the vm .,def _Install vm for p in build_tools python pip python_dev vm Install p vm RemoteCommand sudo pip install pandas numpy vm RemoteCommand git clone 0 1 format GIT_REPO FIO_DIR vm RemoteCommand cd 0 git checkout 1 format FIO_DIR GIT_TAG vm RemoteCommand cd 0 configure make format FIO_DIR if flags FLAGS fio_hist_log vm PushDataFile FIO_HIST_LOG_PARSER_PATCH vm RemoteCommand cp log_parser_path log_parser patch log_parser patch format log_parser_path FIO_HIST_LOG_PARSER_PATH log_parser FIO_HIST_LOG_PARSER patch FIO_HIST_LOG_PARSER_PATCH
runs spec cpu2017 on the target vm .,def Run benchmark_spec vm benchmark_spec vms 0 speccpu Run vm ulimit s 130000 runcpu join FLAGS spec17_subset log_files set for test in FLAGS spec17_subset if test in LOG_FILENAME log_files add LOG_FILENAME test elif test in INTSPEED_SUITE log_files add LOG_FILENAME intspeed elif test in INTRATE_SUITE log_files add LOG_FILENAME intrate elif test in FPSPEED_SUITE log_files add LOG_FILENAME fpspeed elif test in FPRATE_SUITE log_files add LOG_FILENAME fprate return speccpu ParseOutput vm log_files False None
runs the stencil2d benchmark . gpu clock speeds must be set already .,def Run benchmark_spec vms benchmark_spec vms num_gpus benchmark_spec num_gpus master_vm vms 0 num_iterations FLAGS stencil2d_iterations problem_sizes FLAGS stencil2d_problem_sizes num_processes len vms num_gpus metadata metadata update cuda_toolkit GetMetadata master_vm metadata benchmark_version BENCHMARK_VERSION metadata num_iterations num_iterations metadata num_nodes len vms metadata num_processes num_processes results for problem_size in problem_sizes results extend _RunSingleIteration master_vm problem_size num_processes num_iterations metadata return results
return a list with the important info for each item .,def get_info self return self info_from_entry entry for entry in self get_entries
"args : * * kwargs : if kwargs contains ` volatile ` , always create an instance of the passed class whenever the state is entered . the instance is assigned to a model attribute which can be passed with the kwargs keyword ` hook ` . if hook is not passed , the instance will be assigned to the ' attribute ' scope . if ` volatile ` is not passed , an empty object will be assigned to the model 's hook .",def __init__ self args kwargs self volatile_cls kwargs pop volatile VolatileObject self volatile_hook kwargs pop hook scope super Volatile self __init__ args kwargs self initialized True
serialise links to ranges in a single external worbook,def write_external_link links root Element s externalLink SHEET_MAIN_NS book SubElement root s externalBook SHEET_MAIN_NS s id REL_NS rId1 external_ranges SubElement book s definedNames SHEET_MAIN_NS for l in links external_ranges append Element s definedName SHEET_MAIN_NS dict l return root
tests that a 404 response with a non - json response will throw an notfoundexception,def test_create_not_found self client Factory create_client_from_session self session response_body read_resource not_found html request_body create_request def receive_post uri request_headers body return Response 404 response_body content type text html self mock_connection post side_effect receive_post with self assertRaises NotFoundException as exception client merchant merchantId payments create request_body self assertIsNotNone exception exception cause self assertIsInstance exception exception cause ResponseException self assertIn response_body str exception exception cause
log the representation of the responses received .,def handleProxiedResponse self response request controls log msg Request 02x r format id self request log msg Response 02x r format id self response return defer succeed response
add post filter by type : type operator : filteroperator,def add_pf_type self data operator FilterOperator EQ post_filter PostFilterObject post_filter set_description post filter by type 0 1 format operator name data post_filter set_method filter_type post_filter set_filter data post_filter set_operator operator self add_post_filter post_filter
run st 's ' expand_tabs ' command when saving a file .,def on_pre_save self view if view settings get convert_tabspaces_on_save 1 if view settings get translate_tabs_to_spaces 1 view run_command expand_tabs else view run_command unexpand_tabs
returns the list of all entity types in the specified agent .,def ListEntityTypes self request context context set_code grpc StatusCode UNIMPLEMENTED context set_details Method not implemented raise NotImplementedError Method not implemented
"build mini - batch tensors from a list of ( image , caption ) tuples . args : data : list of ( image , caption ) tuple . - image : torch tensor of shape ( 3 , 256 , 256 ) . - caption : torch tensor of shape ( ? ) ; variable length .",def collate_fn data data sort key lambda x len x 1 reverse True images captions ids img_ids zip data images torch stack images 0 lengths len cap for cap in captions targets torch zeros len captions max lengths long for i cap in enumerate captions end lengths i targets i end cap end return images targets lengths ids
display a simple message box and wait until the user presses enter .,def message_dialog title u text u ok_text u Ok style None async_ False u n Display a simple message box and wait until the user presses enter n dialog Dialog title title body Label text text dont_extend_height True buttons Button text ok_text handler _return_none with_background True return _run_dialog dialog style async_ async_
get the full list of defconfigs appropriate for this tree .,def scan_configs names for n in glob glob arch arm configs fm sm 0 9 _defconfig names os path basename n 10 n for n in glob glob arch arm configs qsd _defconfig names os path basename n 10 n for n in glob glob arch arm configs apq _defconfig names os path basename n 10 n return names
order - order of the dsa generator used in the signature secexp - secure exponent ( private key ) in numeric form hash_func - reference to the same hash function used for generating hash data - hash in binary form of the signing data,def generate_k order secexp hash_func data qlen bit_length order holen hash_func digest_size rolen qlen 7 8 bx number_to_string secexp order bits2octets data order v b x01 holen k b x00 holen k hmac new k v b x00 bx hash_func digest v hmac new k v hash_func digest k hmac new k v b x01 bx hash_func digest v hmac new k v hash_func digest while True t b while len t rolen v hmac new k v hash_func digest t v secret bits2int t qlen if secret 1 and secret order return secret k hmac new k v b x00 hash_func digest v hmac new k v hash_func digest
inits a symbolfileparser to read symbol records from |input_stream| and write the processed output to |output_stream| .,def __init__ self input_stream output_stream ignored_prefixes None path_handler os path self unique_files self duplicate_files self input_stream input_stream self output_stream output_stream self ignored_prefixes ignored_prefixes or self path_handler path_handler
"return a point cloud , an nx3 array , made by projecting the kinect depth map through intrinsic / extrinsic calibration matrices parameters : depth - comes directly from the kinect u , v - are image coordinates , same size as depth ( default is the original image ) returns : xyz - 3d world coordinates in meters ( nx3 ) uv - image coordinates for the rgb image ( nx3 )",def depth2xyzuv depth u None v None if u is None or v is None u v np mgrid 480 640 C np vstack u flatten v flatten depth flatten 0 u flatten 1 X Y Z W np dot xyz_matrix C X Y Z X W Y W Z W xyz np vstack X Y Z transpose xyz xyz Z 0 U V _ W np dot np dot uv_matrix xyz_matrix C U V U W V W uv np vstack U V transpose uv uv Z 0 return xyz uv
returns a routing header string for the given request parameters .,def to_routing_header params return urlencode params
gets a single monitored resource descriptor . this method does not require a stackdriver account .,def GetMonitoredResourceDescriptor self request context context set_code grpc StatusCode UNIMPLEMENTED context set_details Method not implemented raise NotImplementedError Method not implemented
api call : test for the existence of the metric via a get request,def exists self client None client self _require_client client try client metrics_api metric_get self project self name except NotFound return False else return True
api call : test for the existence of the variable via a get request,def exists self client None client self _require_client client try query_params fields name client _connection api_request method GET path self path query_params query_params return True except NotFound return False
sets a bucket 's default kms key .,def enable_default_kms_key bucket_name kms_key_name storage_client storage Client bucket storage_client get_bucket bucket_name bucket default_kms_key_name kms_key_name bucket patch print Set default KMS key for bucket to format bucket name bucket default_kms_key_name
classifies content categories of the text in a google cloud storage file .,def classify_file gcs_uri client language LanguageServiceClient document types Document gcs_content_uri gcs_uri type enums Document Type PLAIN_TEXT categories client classify_text document categories for category in categories print u 20 print u 16 format name category name print u 16 format confidence category confidence
"loads the train , test , and validation sets",def load_parsed_data print loading parsed dataset inputs_train np load parsed_data inputs_train npy targets_train np load parsed_data targets_train npy inputs_valid np load parsed_data inputs_valid npy targets_valid np load parsed_data targets_valid npy inputs_test np load parsed_data inputs_test npy targets_test np load parsed_data targets_test npy print loaded parsed dataset return inputs_train targets_train inputs_valid targets_valid inputs_test targets_test
configures settings for manage.py and for run_tests.py .,def configure_settings if not settings configured test_db os environ get DB sqlite if test_db sqlite db_config ENGINE django db backends sqlite3 elif test_db postgres db_config ENGINE django db backends postgresql_psycopg2 USER postgres NAME localized_recurrence else raise RuntimeError Unsupported test DB 0 format test_db settings configure TEST_RUNNER django_nose NoseTestSuiteRunner NOSE_ARGS nocapture nologcapture verbosity 1 MIDDLEWARE_CLASSES DATABASES default db_config INSTALLED_APPS django contrib auth django contrib contenttypes django contrib sessions django contrib admin localized_recurrence localized_recurrence tests DEBUG False
intercept all tables used inside a codeblock .,contextlib contextmanager def intercept self tables global INTERCEPTOR_TLS INTERCEPTOR_TLS tables self tables try yield finally tables update INTERCEPTOR_TLS tables del INTERCEPTOR_TLS tables
runs cmd and writes the output to both stdout and logfile .,def TeeCmd cmd logfile fail_hard True proc subprocess Popen cmd bufsize 1 shell sys platform win32 stdin open os devnull stdout subprocess PIPE stderr subprocess STDOUT for line in iter proc stdout readline Tee line logfile if proc poll is not None break exit_code proc wait if exit_code 0 and fail_hard print Failed cmd sys exit 1
adds the following xml snippet to an xml element : < key > pfm_targets</key > < array > < string > user - managed</string > < /array >,def _AddTargets self parent policy array self _AddKeyValuePair parent pfm_targets array if self CanBeRecommended policy self AddElement array string user if self CanBeMandatory policy self AddElement array string user managed
definition : struct | union | interface | enum | const,def p_definition self p p 0 p 1
read a text file with id names .,def read_id_list id_list_path with open id_list_path r as f stripped_lines x strip for x in f non_empty_lines x for x in stripped_lines if x return non_empty_lines
basictypename : identifier | associated identifier | handletype,def p_basictypename self p if len p 2 p 0 p 1 else p 0 asso p 2
creates a user with a terribly long username,def setUp self long_username join str i for i in range 100 self user User objects create_user test s long_username s example com long_username testpassword
called by the executor with the exception if there is an error calling ` run_job ` .,def _run_job_error self job_id exc traceback None super GeventExecutor self _run_job_error job_id exc traceback traceback self cleanup_jobs_instances job_id
append the given images to the named initramfs . raises ioerror if the files ca n't be read / written .,def initramfs_append_images initramfs images with open initramfs ab as outfd for i in images with open i rb as infd copyfileobj infd outfd
returns true if server is not the user 's current used in setup of constraints .,staticmethod def _is_migration user server return server user current_server
"example : > > > list(getgaps(0 , 20 , [ ( 15,3 ) , ( 6,2 ) , ( 6,2 ) , ( 1,2 ) , ( 2,3 ) , ( 11,2 ) , ( 9,5 ) ] ) ) [ ( 0 , 1 ) , ( 5 , 1 ) , ( 8 , 1 ) , ( 14 , 1 ) , ( 18 , 2 ) ]",def getgaps start length blocks blocks sorted blocks key lambda b b 0 end start length for s l in blocks if s start yield start s start start s if s l start start s l if start end yield start end start
allows the user to add a sample to the sum aggregation data the value of the sample is then added to the current sum data,def add_sample self value self _sum_data value
test for the function parse_dates .,def test_parse_dates self from_date 2017 01 01 to_date 2018 01 01 job_kwargs from_date from_date to_date to_date parse_dates job_kwargs from_date 2017 01 41 job_kwargs from_date from_date to_date to_date with pytest raises ValueError parse_dates job_kwargs
compute the distance between each test point in x and each training point in self . x_train using a single loop over the test data .,def compute_distances_one_loop self X num_test X shape 0 num_train self X_train shape 0 dists np zeros num_test num_train for i in xrange num_test square_value np square X i self X_train dists i np sqrt square_value sum axis 1 return dists
instantiate the element finder class .,def setUp self self browser mock Mock self finder ElementFinder
the message formatted and dumped .,def raw_message self return json dumps self message
returns json for audit loop state .,def get self state AuditLogLoop get_state_entity self response content_type application json def datetime_handler x if isinstance x datetime datetime return x isoformat raise TypeError Unknown type self response write json dumps state default datetime_handler
create and return a new instance .,def new_instance self instance_id expect_ready_request False def instance_config_getter runtime_config self _runtime_config_getter runtime_config instance_id str instance_id return runtime_config proxy http_runtime HttpRuntimeProxy _RUNTIME_ARGS instance_config_getter self _module_configuration env dict os environ PYTHONHASHSEED random start_process_flavor http_runtime START_PROCESS_REVERSE return instance Instance self request_data instance_id proxy self max_concurrent_requests self max_background_threads expect_ready_request
like run_wsgi_app ( ) but does n't add wsgi middleware .,def run_bare_wsgi_app application env dict os environ env wsgi input sys stdin env wsgi errors sys stderr env wsgi version 1 0 env wsgi run_once True env wsgi url_scheme wsgiref util guess_scheme env env wsgi multithread False env wsgi multiprocess False result application env _start_response try if result is not None for data in result sys stdout write data finally if hasattr result close result close
"clean the given html . specifically , do the following : * convert < b > and < i > to < strong > and < em>. * encode all ampersands correctly . * remove all "" target "" attributes from < a > tags . * remove extraneous html , such as presentational tags that open and immediately close and < br clear=""all"">. * convert hard - coded bullets into html unordered lists . * remove stuff like "" < p>&nbsp;&nbsp;</p > "" , but only if it 's at the bottom of the text .",def clean_html text from google appengine _internal django utils text import normalize_newlines text normalize_newlines force_unicode text text re sub s b s 1strong text text re sub s i s 1em text text fix_ampersands text text link_target_attribute_re sub 1 text text html_gunk_re sub text def replace_p_tags match s match group replace p li for d in DOTS s s replace p s d li return u ul n s n ul s text hard_coded_bullets_re sub replace_p_tags text text trailing_empty_content_re sub text return text
"a decorator that allows a function to be called with one or more lazy arguments . if none of the args are lazy , the function is evaluated immediately , otherwise a _ _ proxy _ _ is returned that will evaluate the function when needed .",def allow_lazy func resultclasses def wrapper args kwargs for arg in list args kwargs values if isinstance arg Promise break else return func args kwargs return lazy func resultclasses args kwargs return wraps func wrapper
"inserts 1 char into generated , satisfying required if not already .",def _InsertAndEnsureSatisfaction generated required all_candidates if set generated isdisjoint required _InsertInto generated required else _InsertInto generated all_candidates
check if a command is registered for a given notification,def hasCommand self notificationName return self controller hasCommand notificationName
not implemented for this module . raises exception .,def update self unimportant raise NotImplementedError
save the education section of the document .,def save self section document graphics if graphics document self get_education_graphics section document else document self get_education section document return document
"return { ' false_positives ' : false_positives , ' true_positives':true_positives , ' not_detected ' : not_detected , ' silence_not_detected ' : silence_not_detected } each elements correspond to a list of tuple , first item of tuple is equal to detection second item equal to expectation ( i.e annotation )",def compute_tp_fp df df_expected timestamps_1 df timestamp_start timestamp_end to_records timestamps_2 df_expected timestamp_start timestamp_end to_records overlaps_index find_overlap timestamps_1 timestamps_2 index_expected_found zip overlaps_index 1 index_df_found zip overlaps_index 0 overlap_values df iloc x df_expected iloc y for x y in overlaps_index false_positives x y for x y in overlap_values if x class_predicted y class_expected true_positives x y for x y in overlap_values if x class_predicted y class_expected not_detected None df_expected iloc index for index in df_expected index if index not in index_expected_found silence_not_detected df iloc index None for index in df index if index not in index_df_found return false_positives false_positives true_positives true_positives not_detected not_detected silence_not_detected silence_not_detected
get a list of the user 's smartsheet contacts .,def list_contacts self page_size None page None include_all None _op fresh_operation list_contacts _op method GET _op path contacts _op query_params pageSize page_size _op query_params page page _op query_params includeAll include_all expected IndexResult Contact prepped_request self _base prepare_request _op response self _base request prepped_request expected _op return response
retrieves the body of the email from s3 .,def body self if self _body is None log debug Downloading message body from s3 format self s3_bucket self message_id s3 boto3 client s3 obj s3 get_object Bucket self s3_bucket Key self message_id self _body obj Body read decode utf 8 return self _body
add projection properties to the given datatstore . query proto message .,def add_projection query_proto projection for p in projection proto query_proto projection add proto property name p
"carries out the inverse of the above method which is required when going from search api url parameters to frontend url parameters . where group_request_filters takes request_filters as a multidict , this method takes request_filters as a tuple of tuple pairs ( ( param_name , param_value ) , ... )",def ungroup_request_filters request_filters content_builder filter_query for key value in request_filters if is_radio_type content_builder key if in value for value in value split filter_query append key value else filter_query append key value else filter_query append key value return tuple filter_query
tries to set the hugepages to the nr_full value and returns the max possible value set .,staticmethod def set_max_hugepages nr_full memory set_num_huge_pages nr_full return memory get_num_huge_pages
the : class:`collections.deque ` to which expired items are added .,property def out_deque self expired k v for k v in self _tracking items if self get k is None for k v in expired items del self _tracking k self _out_deque append v return self _out_deque
test fetching of rubygems artifact .,pytest mark parametrize name version expected_digest permutation 0 1 7 e715cccaccb8e2d1450fbdda85bbe84963a32e9bf612db278cbb3d6781267638 def test_fetch_rubygems_specific self tmpdir rubygems name version expected_digest digest path IndianaJones fetch_artifact rubygems artifact name version version target_dir str tmpdir assert digest expected_digest path Path path assert path name gem format name version assert path exists
"loads mr polarity data from files , splits the data into words and generates labels . returns split sentences and labels .",def load_data_and_labels positive_examples list open data word_embeddings rt polarity pos encoding ISO 8859 1 readlines positive_examples s strip for s in positive_examples negative_examples list open data word_embeddings rt polarity neg encoding ISO 8859 1 readlines negative_examples s strip for s in negative_examples x_text positive_examples negative_examples x_text clean_str sent for sent in x_text x_text s split for s in x_text positive_labels 0 1 for _ in positive_examples negative_labels 1 0 for _ in negative_examples y np concatenate positive_labels negative_labels 0 return x_text y
returns classes based on directories in train directory,def set_classes_from_train_dir d config train_dir config classes sorted o for o in os listdir d if os path isdir os path join d o
"args : vis ( numpy.ndarray ) : complex visibilities . 1d array , shape : ` ( n_vis , ) ` . uvw_lambda ( numpy.ndarray ) : uvw - coordinates of visibilities . units are multiples of wavelength . 2d array of `` np.float_ `` , shape : `` ( n_vis , 3 ) `` . assumed ordering is u , v , w i.e. `` u , v , w = uvw[idx ] `` image_size ( astropy.units.quantity ) : width of the image in pixels . e.g. `` 1024 * u.pixel `` . nb we assume the pixel `` [ image_size//2,image_size//2 ] `` corresponds to the origin in uv - space . cell_size ( astropy.units.quantity ) : angular - width of a synthesized pixel in the image to be created , e.g. `` 3.5 * u.arcsecond `` . kernel_func ( callable ) : callable object , ( e.g. : class:`.conv_funcs . pillbox ` , ) that returns a convolution co - efficient for a given distance in pixel - widths . kernel_support ( int ) : defines the ' radius ' of the bounding box within which convolution takes place . ` box width in pixels = 2*support+1 ` . ( the central pixel is the one nearest to the uv co - ordinates . ) ( this is sometimes known as the ' half - support ' ) kernel_exact ( bool ) : calculate exact kernel - values for every uv - sample . kernel_oversampling ( int ) : controls kernel - generation if `` exact==false `` . larger values give a finer - sampled set of pre - cached kernels . raise_bounds ( bool ) : raise an exception if any of the uv kernel_oversampling ( int ) : ( or none ) . controls kernel - generation , see : func:`fastimgproto.gridder.gridder.convolve_to_grid ` for details . progress_bar ( tqdm.tqdm ) : [ optional ] progressbar to update .",def image_visibilities vis vis_weights uvw_lambda image_size cell_size kernel_func kernel_support kernel_exact True kernel_oversampling 0 progress_bar None image_size image_size to u pix image_size_int int image_size value if image_size_int image_size value raise ValueError Please supply an integer valued image size grid_pixel_width_lambda 1 0 cell_size to u rad image_size uvw_in_pixels uvw_lambda grid_pixel_width_lambda value uv_in_pixels uvw_in_pixels 2 vis_grid sample_grid convolve_to_grid kernel_func support kernel_support image_size image_size_int uv uv_in_pixels vis vis vis_weights vis_weights exact kernel_exact oversampling kernel_oversampling progress_bar progress_bar image fft_to_image_plane vis_grid beam fft_to_image_plane sample_grid total_sample_weight sample_grid sum if total_sample_weight 0 renormalization_factor image_size_int image_size_int total_sample_weight beam renormalization_factor image renormalization_factor return image beam
"adds to the "" used "" metric for the given quota .",def tally self name value value value or 0 if used not in self usages name self usages name used 0 self usages name used int value self update_available name
tests if all declared macosx versions in meta / main.yml are supported in ansible galaxy,def main argv print Checking meta main yml for unsupported platform versions print meta open meta main yml obj yaml safe_load meta meta close platforms obj galaxy_info platforms macos filter lambda x x name MacOSX platforms declared_versions set macos 0 versions url https galaxy ansible com api v1 platforms name MacOSX r requests get url json_obj json loads r text allowed_versions set map lambda x str x release json_obj results print ALLOWED list allowed_versions print print DECLARED list declared_versions print if declared_versions issubset allowed_versions print All MacOS platform versions are supported in Ansible Galaxy sys exit 0 msg Error meta main yml lists MacOSX versions that are currently msg unsupported by Ansible Galaxy Attempts to import this role msg into Ansible Galaxy will fail n n msg Bad versions str list declared_versions allowed_versions msg n sys __stderr__ write msg sys exit 1
"returns the list of pages . for example if the current page is 8:- [ 1 , ... , 7 , 8 , 9 , ... , 16 ]",def get_page_list page_size result_size current_page pages last_page int math ceil float result_size float page_size pages append 1 if current_page 2 1 pages append if current_page 1 1 pages append current_page 1 if current_page 1 and current_page last_page pages append current_page if result_size current_page page_size pages append current_page 1 if result_size current_page 2 page_size pages append if result_size current_page 1 page_size pages append last_page return pages
test the create function with runtime properties,def test_operation_create_from_runtime_properties self _ctx self get_mock_ctx current_ctx set _ctx _ctx instance runtime_properties resource_config self _resource_config self addCleanup os remove self _file_path operation_output operation_task create self common_asserts operation_output
preparing the whole execution environment for this capua instance . note that a single memory array can be shared between multiple capua environment .,def __init__ self ma None mioc None name System if ma is None self ma MemoryArray else self ma ma if mioc is None self mioc MemoryIOController self ma testOnly False else self mioc mioc self ifu InstructionFetchUnit self ma self eu ExecutionUnit self mioc self ifu name
returns true if the key is in the cache and has not expired .,def has_key self key version None u n Returns True if the key is in the cache and has not expired n return self get key version version is not None
add all of the data points for a fpm - pool,def add_datapoints self stats self add_derive_value Connections Accepted connections stats get accepted conn 0 self add_gauge_value Connections Pending connections stats get listen queue 0 max_val stats get max listen queue 0 self add_gauge_value Socket Queue connections stats get listen queue len 0 self add_gauge_value Processes Active processes stats get active processes 0 max_val stats get max processes 0 self add_gauge_value Processes Idle processes stats get idle processes 0 self add_derive_value Process Limit Reached processes stats get max children reached 0 self add_derive_value Slow Requests requests stats get slow requests 0
retrieve a list of named geojson layer tiles from a tilestache config .,def get_tiles names config coord unknown_layers set names set config layers keys if unknown_layers raise KnownUnknown s get_tiles didn t recognize s when trying to load s __name__ join unknown_layers join names layers config layers name for name in names mimes bodies zip getTile layer coord json for layer in layers bad_mimes name mime for mime name in zip mimes names if not mime endswith json if bad_mimes raise KnownUnknown s get_tiles encountered a non JSON mime type in s sub layer s __name__ bad_mimes 0 geojsons map json loads bodies bad_types name topo type for topo name in zip geojsons names if topo type FeatureCollection if bad_types raise KnownUnknown s get_tiles encountered a non FeatureCollection type in s sub layer s __name__ bad_types 0 return geojsons
checks to make sure that requisite data files are available .,def verify_environment if not os path isdir DATA_DIR raise EnvironmentError In order to run system tests test data must exist in system_tests data See CONTRIBUTING rst for details
returns a list of headers fields to sign .,def get_headers_from_signature self signature match self SIGNATURE_HEADERS_RE search signature if not match return date headers_string match group 1 return headers_string split
"once trained , this method is called and expected to return a predicted behavior for the given observation .",def predict self observation i observation 3 prediction self clf predict i return prediction
add a subscription to the list of data subscriptions .,def addSubscription self subType callbackObj limit False filters self dataSubscriptions append commandType subType callback callbackObj limit limit
"> > > perm2('123 ' ) [ ' 123 ' , ' 132 ' , ' 213 ' , ' 231 ' , ' 312 ' , ' 321 ' ]",def perm2 str1 from itertools import permutations return join p for p in permutations str1
"originalloansubsidycost is required for loans ( i.e. , when assistancetype = 07 or 08 ) .",def test_failure database det_award DetachedAwardFinancialAssistanceFactory assistance_type 07 original_loan_subsidy_cost None det_award_2 DetachedAwardFinancialAssistanceFactory assistance_type 08 original_loan_subsidy_cost None errors number_of_errors _FILE database models det_award det_award_2 assert errors 2
"make a ` suds ` client , accounting for ? wsdl suffixes , failing to import appropriate schemas , and http auth",def new_client service_type config service_config service_type wsdl_url config get wsdl options url wsdl_url if wsdl_url endswith wsdl options location wsdl_url len wsdl parsed_wsdl urlparse wsdl_url import_fix doctor Import http schemas xmlsoap org soap encoding import_fix filter add format parsed_wsdl scheme parsed_wsdl netloc options doctor doctor ImportDoctor import_fix options plugins ControlFilter ZeroDateFilter if config get username and config get password options transport HttpAuthenticated username config username password config password timeout 300 return Client options
initialize event - listener error .,def __init__ self cause if hasattr cause args and cause args Error __init__ self cause args else Error __init__ self str cause self cause cause
wrapper for sklearn sample covariance estimator,def _scm X return empirical_covariance X T
python 3 implementation of execfile .,def _execfile filename globals locals None mode rb with open filename mode as stream script stream read if sys version_info 2 2 7 or sys version_info 2 3 0 and sys version_info 2 3 2 script script replace r n n script script replace r n if locals is None locals globals code compile script filename exec exec code in globals locals
return true if mode is from a socket .,def S_ISSOCK mode return S_IFMT mode S_IFSOCK
internal helper . removes a ( possibly still pending ) call from a bucket . it is * not * an error of the bucket is gone ( e.g. the call has already happened ) .,def _remove_call self real_time call try delayed_call calls self _buckets real_time except KeyError return calls remove call if not calls del self _buckets real_time delayed_call cancel
creates a win32 unnamed event .,def _create_event u n Creates a Win32 unnamed Event n n http msdn microsoft com en us library windows desktop ms682396 v vs 85 aspx n return windll kernel32 CreateEventA pointer SECURITY_ATTRIBUTES BOOL True BOOL False None
same as a & = b.,def iand a b a b return a
a method for fetching project and sample records from samplesheet and checking for registered samples in db,def check_for_registered_project_and_sample seqrun_info dbconfig samplesheet_file SampleSheet csv try msg new_seqrun_info dict dbparams read_dbconf_json dbconfig base BaseAdaptor dbparams base start_session sa SampleAdaptor session base session pa ProjectAdaptor session base session for seqrun_name seqrun_path in seqrun_info items samplesheet os path join seqrun_path samplesheet_file samplesheet_data SampleSheet infile samplesheet reject_seqrun False for row in samplesheet_data _data sample_id row Sample_ID project_id row Sample_Project record_exists sa check_project_and_sample project_igf_id project_id sample_igf_id sample_id if not record_exists reject_seqrun True if msg msg missing sample 0 and project 1 for run 2 format sample_id project_id seqrun_name else msg 0 n missing sample 1 and project 2 for run 3 format msg sample_id project_id seqrun_name project_authority_exists pa check_data_authority_for_project project_igf_id project_id if not project_authority_exists reject_seqrun True if msg msg missing user info for project 0 for run 1 format project_id seqrun_name else msg 0 n missing user info for project 1 for run 2 format msg project_id seqrun_name if not reject_seqrun new_seqrun_info update seqrun_name seqrun_path base close_session return new_seqrun_info msg except raise
"because ndk - r8e uses gcc4.6 as default . gcc4.6 does n't support c++11 . so we should select gcc4.7 when using ndk - r8e . but gcc4.7 is removed in ndk - r9 , so we should determine whether gcc4.7 exist . conclution : ndk - r8e - > use gcc4.7 ndk - r9 - > use gcc4.8",def select_toolchain_version ndk_root check_environment_variables if os path isdir os path join ndk_root toolchains arm linux androideabi 4 8 os environ NDK_TOOLCHAIN_VERSION 4 8 print The Selected NDK toolchain version was 4 8 elif os path isdir os path join ndk_root toolchains arm linux androideabi 4 7 os environ NDK_TOOLCHAIN_VERSION 4 7 print The Selected NDK toolchain version was 4 7 else print Couldn t find the gcc toolchain exit 1
create additional layer of nodes to our original stock price tree,def __new_stock_price_tree__ self self STs np array self S0 self u self d self S0 self S0 self d self u for i in range self N prev_branches self STs 1 st np concatenate prev_branches self u prev_branches 1 self d self STs append st
"converts a yang style range to a list of range lists > > > cvtrange(""1 .. 5 | 10 .. 20 "" ) [ [ 1 , 5 ] , [ 10 , 20 ] ] > > > cvtrange(""1 .. 5 "" ) [ [ 1 , 5 ] ] > > > cvtrange(""1 | 2 | 3 .. max "" ) [ [ 1 ] , [ 2 ] , [ 3,""max "" ] ]",def cvtRange s typ int if typ int or typ uint or typ uint32 or typ int32 or typ decimal64 or typ int64 or typ uint64 cvter int if s is None return None ranges x strip split for x in re findall s ret for r in ranges rang for elem in r if elem max rang append max elif elem min rang append min else rang append cvter elem ret append rang return ret
process api calls . @param call : api call object @param process : process object,def handle_event self call category funcname message None None None for row in call arguments if row name Subcategory category row value if row name FunctionName funcname row value if row name Message message row value self anomalies append dict category category funcname funcname message message
"the function returns the variable that is passed in , so all types work",def linear x return x
test restriction of source space to source sourceestimate,testing requires_testing_data def test_restrict_forward_to_stc start 0 stop 5 n_times stop start 1 sfreq 10 0 t_start 0 123 fwd read_forward_solution fname_meeg force_fixed True fwd pick_types_forward fwd meg True vertno fwd src 0 vertno 0 15 fwd src 1 vertno 0 5 stc_data np ones len vertno 0 len vertno 1 n_times stc SourceEstimate stc_data vertno tmin t_start tstep 1 0 sfreq fwd_out restrict_forward_to_stc fwd stc assert_true isinstance fwd_out Forward assert_equal fwd_out sol ncol 20 assert_equal fwd_out src 0 nuse 15 assert_equal fwd_out src 1 nuse 5 assert_equal fwd_out src 0 vertno fwd src 0 vertno 0 15 assert_equal fwd_out src 1 vertno fwd src 1 vertno 0 5 fwd read_forward_solution fname_meeg force_fixed False fwd pick_types_forward fwd meg True vertno fwd src 0 vertno 0 15 fwd src 1 vertno 0 5 stc_data np ones len vertno 0 len vertno 1 n_times stc SourceEstimate stc_data vertno tmin t_start tstep 1 0 sfreq fwd_out restrict_forward_to_stc fwd stc assert_equal fwd_out sol ncol 60 assert_equal fwd_out src 0 nuse 15 assert_equal fwd_out src 1 nuse 5 assert_equal fwd_out src 0 vertno fwd src 0 vertno 0 15 assert_equal fwd_out src 1 vertno fwd src 1 vertno 0 5
draw the output of the catalysis problem .,def plot_catalysis_output fig_name Y y load_dimensionless_catalysis_data t np array 0 0 1 0 6 1 0 3 1 0 2 2 0 3 5 0 6 1 0 colors b r g k m linestyles markerstyles o v s D p legend False title None shape t shape 0 Y shape 1 t shape 0 y y reshape shape Y_m np percentile Y 50 axis 0 reshape shape Y_p05 np percentile Y 5 axis 0 reshape shape Y_p95 np percentile Y 95 axis 0 reshape shape Y_p05 Y_p05 0 0 0 0 import matplotlib pyplot as plt fig plt figure ax fig add_subplot 111 for i in xrange 5 ax plot t Y_m i colors i linestyles i linewidth 2 markersize 5 0 ax fill_between t Y_p05 i Y_p95 i color colors i alpha 0 5 for i in xrange 5 ax plot t y i colors i markerstyles i markersize 10 ax set_xlabel Time tau fontsize 26 ax set_ylabel Concentration fontsize 26 ax set_title title fontsize 26 plt setp ax get_xticklabels fontsize 26 plt setp ax get_yticklabels fontsize 26 if legend leg plt legend operatorname NO _3 operatorname NO _2 operatorname N _2 operatorname N _2 operatorname O operatorname NH _3 loc best plt setp leg get_texts fontsize 26 ax set_ylim 0 0 1 5 plt tight_layout print Writing fig_name plt savefig fig_name
"convenience function that will load a fasta from the filestore and return the local path to it . this works with the pyfasta module to load all of the required files . : param job : current job . : param fasta_file_ids : list of filestore file id for the fasta , gdx , and flat file . : param prefix : local file path prefix : param upper : force all entries to upper case : return : open pyfasta fasta record pointing to the file .",def load_fasta_from_filestore job fasta_file_ids prefix genome upper False fasta_local_path fasta format prefix fasta_file_id gdx_file_id flat_file_id fasta_file_ids job fileStore readGlobalFile fasta_file_id fasta_local_path job fileStore readGlobalFile gdx_file_id fasta gdx format prefix job fileStore readGlobalFile flat_file_id fasta flat format prefix return bio get_sequence_dict fasta_local_path upper upper
"grammar : textual_clause - > textual_attribute textual_operator textual_value | textual_attribute "" between "" textual_value "" to "" textual_value",def parse_textual_clause self attribute self parse_textual_attribute if self accept between value1 self parse_textual_value self expect to value2 self parse_textual_value return BetweenClause attribute value1 value2 else operator self parse_textual_operator value self parse_textual_value return TextualClause attribute operator value
cleans up task batcher and all children .,def CleanUp self children BatchTask query ancestor self key iter keys_only True ndb delete_multi children self key delete
: param src : the actual source proxy,def __init__ self src self src src
determines which of the three possible formats for custom - plotting is used and returns a list of customplotinfo - objects : param rawdata : a string that contains the raw data,def readCustomPlotInfo rawData useName None info try data FoamStringParser rawData duplicateCheck True duplicateFail True for k d in iteritems data data info append CustomPlotInfo d name k except PyFoamParserError for i l in enumerate rawData split n if len l 0 name useName if i 0 and name None name _ d i info append CustomPlotInfo l name name return info
"dill.dump of object to a namedtemporaryfile . loads with "" dill.temp.load "" . returns the filehandle .",def dump object kwds import dill as pickle import tempfile file tempfile NamedTemporaryFile kwds pickle dump object file file flush return file
formula for computing the current backoff,def get_backoff_time self if self _observed_errors 1 return 0 backoff_value self backoff_factor 2 self _observed_errors 1 return min self BACKOFF_MAX backoff_value
concentration parameter associated with a ` 1 ` outcome .,property def concentration1 self return self _concentration1
returns the class predictions for the given test data .,def predict self x kwargs kwargs self filter_sk_params Sequential predict_classes kwargs classes self model predict_classes x kwargs return self classes_ classes
determine whether the argument is a servable ' classify ' signaturedef .,def _is_valid_classification_signature signature_def if signature_def method_name signature_constants CLASSIFY_METHOD_NAME return False if set signature_def inputs keys set signature_constants CLASSIFY_INPUTS return False if signature_def inputs signature_constants CLASSIFY_INPUTS dtype types_pb2 DT_STRING return False allowed_outputs set signature_constants CLASSIFY_OUTPUT_CLASSES signature_constants CLASSIFY_OUTPUT_SCORES if not signature_def outputs keys return False if set signature_def outputs keys allowed_outputs return False if signature_constants CLASSIFY_OUTPUT_CLASSES in signature_def outputs and signature_def outputs signature_constants CLASSIFY_OUTPUT_CLASSES dtype types_pb2 DT_STRING return False if signature_constants CLASSIFY_OUTPUT_SCORES in signature_def outputs and signature_def outputs signature_constants CLASSIFY_OUTPUT_SCORES dtype types_pb2 DT_FLOAT return False return True
"parse index . always return a tuple of the form ( row , col ) . where row / col is a integer , slice , or array of integers .",def _unpack_index self index from base import spmatrix if isinstance index spmatrix np ndarray and index ndim 2 and index dtype kind b return index nonzero index self _check_ellipsis index if isinstance index tuple if len index 2 row col index elif len index 1 row col index 0 slice None else raise IndexError invalid number of indices else row col index slice None row col self _check_boolean row col return row col
restrict the features to those in support using feature selection .,def restrict self support indices False if not indices support np where support 0 names self feature_names_ new_vocab for i in support new_vocab names i len new_vocab self vocabulary_ new_vocab self feature_names_ f for f i in sorted six iteritems new_vocab key itemgetter 1 return self
"given a valid region name , return a : class:`boto.sdb.connection . sdbconnection ` .",def connect_to_region region_name kw_params for region in regions if region name region_name return region connect kw_params return None
"( ? : \,)|(?:""\,"")|(?:'\ , ' )",def t_COMMA t return t
map the values passed in smtp headers to api - ready 2-item tuples present in headers_map,def _map_smtp_headers_to_api_parameters self email_message u n Map the values passed in SMTP headers to API ready n 2 item tuples present in HEADERS_MAP n n header values must be a single string or list or tuple of strings n n return 2 item tuples of the form api_name api_values n api_data for smtp_key api_transformer in six iteritems self _headers_map data_to_transform email_message extra_headers pop smtp_key None if data_to_transform is not None if isinstance data_to_transform list tuple for data in data_to_transform api_data append api_transformer 0 api_transformer 1 data elif isinstance data_to_transform dict for data in six iteritems data_to_transform api_data append api_transformer data else api_data append api_transformer 0 api_transformer 1 data_to_transform return api_data
main method for testing tool for creating a sample scitoken .,def main with open sample_ecdsa_keypair pem r as file_pointer serialized_pair file_pointer read loaded_public_key serialization load_pem_public_key serialized_pair backend default_backend serialized_public loaded_public_key public_bytes encoding serialization Encoding PEM format serialization PublicFormat SubjectPublicKeyInfo print My public key n serialized_public loaded_private_key serialization load_pem_private_key serialized_pair password None backend default_backend serialized_private loaded_private_key private_bytes encoding serialization Encoding PEM format serialization PrivateFormat PKCS8 encryption_algorithm serialization NoEncryption print My private key n serialized_private public_jwk private_jwk child_private_key gen_jwk print Instance JWK keypair public_jwk private_jwk token_encoded jwt encode read ligo serialized_private algorithm ES256 headers x5u https vo example com JWS cwk public_jwk signature token_encoded split 1 flattened flattened payload jwt decode token_encoded verify False flattened protected jwt get_unverified_header token_encoded flattened signature token_encoded split 1 print My encoded token n token_encoded print Plain text token n flattened header jwt get_unverified_header token_encoded print Non validated header n header token_decoded jwt decode token_encoded serialized_public algorithm ES256 print Validated token n token_decoded pwt payload token_decoded protected header signature signature serialized_child_private child_private_key private_bytes encoding serialization Encoding PEM format serialization PrivateFormat PKCS8 encryption_algorithm serialization NoEncryption child_token_encoded jwt encode read ligo brian serialized_child_private algorithm ES256 headers pwt pwt flattened flattened payload jwt decode child_token_encoded verify False flattened protected jwt get_unverified_header child_token_encoded flattened signature child_token_encoded split 1 flattened key private_jwk print Child token encoded n child_token_encoded print Child token with key n child_token_encoded base64 urlsafe_b64encode json dumps private_jwk print Child token headers n jwt get_unverified_header child_token_encoded print Child token flattened n flattened
creates a variant of the cifarnet model .,def cifarnet images num_classes 10 is_training False dropout_keep_prob 0 5 prediction_fn slim softmax scope CifarNet end_points with tf variable_scope scope CifarNet images num_classes net slim conv2d images 64 5 5 scope conv1 end_points conv1 net net slim max_pool2d net 2 2 2 scope pool1 end_points pool1 net net tf nn lrn net 4 bias 1 0 alpha 0 001 9 0 beta 0 75 name norm1 net slim conv2d net 64 5 5 scope conv2 end_points conv2 net net tf nn lrn net 4 bias 1 0 alpha 0 001 9 0 beta 0 75 name norm2 net slim max_pool2d net 2 2 2 scope pool2 end_points pool2 net net slim flatten net end_points Flatten net net slim fully_connected net 384 scope fc3 end_points fc3 net net slim dropout net dropout_keep_prob is_training is_training scope dropout3 net slim fully_connected net 192 scope fc4 end_points fc4 net logits slim fully_connected net num_classes biases_initializer tf zeros_initializer weights_initializer trunc_normal 1 192 0 weights_regularizer None activation_fn None scope logits end_points Logits logits end_points Predictions prediction_fn logits scope Predictions return logits end_points
computes the -log10 of kolmogorov - smirnov p - value of position distribution .,requires_positions def ks_significance fg_pos bg_pos None p ks_pvalue fg_pos max fg_pos if p 0 return np log10 p else return np inf
compute the entropy of the gamma distribution .,def negentropy self E_ln_lambda None E_lambda None E_beta None E_ln_beta None Compute the entropy of the gamma distribution param E_ln_lambda If given use this in place of expectation wrt alpha and beta param E_lambda If given use this in place of expectation wrt alpha and beta param E_ln_beta If given use this in place of expectation wrt alpha and beta param E_beta If given use this in place of expectation wrt alpha and beta return E ln p lambda lpha eta if E_ln_lambda is None E_ln_lambda self expected_log_lambda if E_lambda is None E_lambda self expected_lambda if E_ln_beta is None E_ln_beta np log self beta np ones_like E_ln_lambda if E_beta is None E_beta self beta np ones_like E_lambda alpha self alpha np ones_like E_ln_lambda H alpha E_ln_beta H gammaln alpha H alpha 1 0 E_ln_lambda H E_beta E_lambda return H
[ artist ] - displays the current user 's playcount for [ artist ] . you must have your username saved .,hook command plays def getuserartistplaycount event bot text nick api_key bot config get api_keys get lastfm if not api_key return error no api key set user get_account nick if not user event notice_doc return artist_info getartistinfo api_key text user if error in artist_info return No such artist if userplaycount not in artist_info artist stats return has never listened to format format_user user text playcount artist_info artist stats userplaycount out has plays format format_user user int playcount text return out
creates an operation that posts data to the given path when executed .,classmethod def new_post_operation cls title data path kwargs return http_agent HttpPostOperation title title data data path path kwargs
: type comp_name : str : type proc_client : zoom.agent.client.process_client.processclient : type interval : int or float : type operational : bool : type parent : str or none,def __init__ self comp_name proc_client interval operational False parent None SimplePredicate __init__ self comp_name operational operational parent parent self _log logging getLogger sent 0 pred process format comp_name self _proc_client proc_client if proc_client self process_client_lock proc_client process_client_lock else self process_client_lock Lock self interval interval self _operate ThreadSafeObject True self _thread Thread target self _run_loop name str self self _thread daemon True self _started False
test field formats that are not valid elementnum elements .,def test_not_valid self test_fields a 4x b z c 1 d 9S e f for field in test_fields with self subTest field out ElementNum valid field self assertFalse out
save font in version 1 format,def save1 self filename self compile self bitmap save os path splitext filename 0 pbm PNG fp open os path splitext filename 0 pil wb fp write PILfont n fp write d n self ysize fp write DATA n for id in range 256 m self metrics id if not m puti16 fp 0 10 else puti16 fp m 0 m 1 m 2 fp close
"set ( source , metric ) to value",staticmethod def SetVarz source metric value VarzReceiver VARZ_DATA metric VerifySource source value
"like repr ( ) , but nicer for debugging here .",def nice_repr v if isinstance v types ClassType type return v __module__ v __name__ elif isinstance v types FunctionType if __name__ in v func_globals if getattr sys modules v func_globals __name__ v func_name None is v return s s v func_globals __name__ v func_name return repr v elif isinstance v types MethodType return s s of s nice_repr v im_class v im_func func_name nice_repr v im_self else return repr v
replaces the last element returned by next or previous with the specified element .,def set self element if self _lastIndex 0 raise JavaError IllegalStateException set self _lst self _lastIndex element
"wait for fn(*a , * * kw ) to return true .",def retry timeout fn a kw step 0 2 waited 0 while waited timeout ret fn a kw if ret return ret time sleep step waited step if step waited 30 step 2 raise RetryTimeoutError
check that the ' pruned ' assc . has not been changed .,def _chk_no_change self g2gos rm_gos assert self gene2gos_orig g2gos assert not rm_gos
"return go ids , sections / gos , or none .",def internal_get_goids_or_sections self if self goids_fin chk_goids self goids_fin read_goids return goids self goids_fin else sections_2d for section_name in self sections_seen if section_name in self section2goids goids self section2goids get section_name chk_goids goids GO IDs IN SECTION S format S section_name sections_2d append section_name goids return sections sections_2d
compute the embedding for each of the conjectures .,def conjecture_embedding self conjectures with tf variable_scope conjecture_embedding return self make_embedding conjectures
downloads blobs to a target directory .,def download_files op blobref_list target_dir all_blobs set blobref_list found_blobs set def start_out blobref blob_path os path join target_dir blobref return open blob_path wb def end_out blobref blob_file found_blobs add blobref blob_file close op get_blobs blobref_list start_out start_out end_out end_out missing_blobs all_blobs found_blobs if missing_blobs print sys stderr Missing blobrefs s join missing_blobs return 1 else return 0
initialize fio path and version .,def initialize self fio subprocess Popen which fio stdout subprocess PIPE stderr subprocess PIPE stdout fio communicate 0 if fio returncode 0 logging error Error command which fio returned an error code raise RuntimeError which fio command error self __fioPath stdout rstrip n fio subprocess Popen fio version stdout subprocess PIPE self __fioVersion fio communicate 0
"create a `` json `` dictionary representing a tiddler , as described by : py : func:`_tiddler_dict ` plus the `` text `` of the tiddler .",def tiddler_as self tiddler query self environ get tiddlyweb query fat 1 render 0 try fat int query get fat fat 0 render int query get render render 0 except ValueError pass tiddler_dict self _tiddler_dict tiddler fat fat render render return simplejson dumps tiddler_dict
show double resolution on some fonts,def show_pil_double self im size self _init_size im size size 0 size 1 2 new_im im resize size convert RGB for y in range size 1 2 for x in range size 0 1 pix new_im getpixel x y 2 pixl new_im getpixel x y 2 1 print colors bg rgb pixl colors fg rgb pix u u2580 sep end print colors reset sep print colors reset
from zacharybears.com / using - python - to - translate - latlon - locations - to - pixels - on - a - geotiff/.,def lat_lon_to_pixel raster_dataset location ds raster_dataset gt ds GetGeoTransform srs osr SpatialReference srs ImportFromWkt ds GetProjection srs_lat_lon srs CloneGeogCS ct osr CoordinateTransformation srs_lat_lon srs new_location None None new_location 1 new_location 0 holder ct TransformPoint location 1 location 0 x new_location 1 gt 0 gt 1 y new_location 0 gt 3 gt 5 return int x int y
"return arrays ( x , y ) for the empirical cdf curve of sample ` s ` .",def get_ecdf s offset 0 5 return np sort s np arange offset s size offset 1 0 s size
applies unit length normalization on a vector .,def transform self vector sc SparkContext _active_spark_context assert sc is not None SparkContext should be initialized first if isinstance vector RDD vector vector map _convert_to_vector else vector _convert_to_vector vector return callMLlibFunc normalizeVector self p vector
> > > _ opentypeos2weightclassformatter(-20 ) 0 > > > _ opentypeos2weightclassformatter(0 ) 0 > > > _ opentypeos2weightclassformatter(50.4 ) 50 > > > _ opentypeos2weightclassformatter(90.6 ) 91 > > > _ opentypeos2weightclassformatter(120 ) 120,def _openTypeOS2WeightClassFormatter value value _roundNumber value if value 0 value 0 return value
this route / function is called when we want to remove all the references between one calendar openerp and one google calendar,http route google_calendar remove_references type json auth user def remove_references self model kw status NOP if model calendar event gc_obj request registry google calendar if gc_obj remove_references request cr request uid context kw get local_context status OK else status KO return status status
get a specific response by index,def __getitem__ self idx return self responses idx
populates context with a list of bibtex publications .,def add_publications generator if PUBLICATIONS_SRC not in generator settings return try from StringIO import StringIO except ImportError from io import StringIO try from pybtex database input bibtex import Parser from pybtex database output bibtex import Writer from pybtex database import BibliographyData PybtexError from pybtex backends import html from pybtex style formatting import plain except ImportError logger warn pelican_bibtex failed to load dependency pybtex return refs_file generator settings PUBLICATIONS_SRC try bibdata_all Parser parse_file refs_file except PybtexError as e logger warn pelican_bibtex failed to parse file s s refs_file str e return publications plain_style plain Style html_backend html Backend formatted_entries plain_style format_entries bibdata_all entries values for formatted_entry in formatted_entries key formatted_entry key entry bibdata_all entries key year entry fields get year pdf entry fields get pdf None slides entry fields get slides None poster entry fields get poster None bib_buf StringIO bibdata_this BibliographyData entries key entry Writer write_stream bibdata_this bib_buf text formatted_entry text render html_backend publications append key year text bib_buf getvalue pdf slides poster generator context publications publications
moves a note to a new location if its contents are modified .,def update if not bool int vim eval exists b pad_modified return modified bool int vim eval b pad_modified can_rename bool int vim eval g pad rename_files if modified and can_rename _id PadInfo vim current buffer id old_path expanduser vim current buffer name fs filter isfile glob expanduser join dirname vim current buffer name _id if old_path not in fs if fs new_path expanduser join get_save_dir _id else exts map lambda i 0 if i else i 1 map lambda i splitext i 1 fs new_path join expanduser join get_save_dir _id str int max exts 1 new_path new_path vim eval g pad default_file_extension vim command bw move old_path new_path
show knobs to start running the commands .,def index request menu_name request REQUEST get mname group_name request REQUEST get gname actions _get_actions menu_name group_name logname _get_logname menu_name group_name file_contents if os path exists logname with open logname r as lp fcntl flock lp fcntl LOCK_SH file_contents lp read fcntl flock lp fcntl LOCK_UN return render request execute _group html menu_name menu_name group_name group_name actions actions log_contents file_contents
creates the section of the graph which reads the input data .,def get_input_data_tensors reader data_pattern batch_size num_readers 1 with tf name_scope input files gfile Glob data_pattern if not files raise IOError Unable to find input files data_pattern data_pattern logging info number of input files str len files filename_queue tf train string_input_producer files num_epochs 1 shuffle False examples_and_labels reader prepare_reader filename_queue for _ in range num_readers video_id_batch video_batch unused_labels num_frames_batch tf train batch_join examples_and_labels batch_size batch_size allow_smaller_final_batch True enqueue_many True return video_id_batch video_batch num_frames_batch
"get the json data , and either create new entries or update existing : return :",def polling_locations_import_from_master_server request state_code import_results structured_json process_request_from_master request Loading Polling Locations from We Vote Master servers POLLING_LOCATIONS_SYNC_URL key WE_VOTE_API_KEY state state_code if import_results success results filter_polling_locations_structured_json_for_local_duplicates structured_json filtered_structured_json results structured_json duplicates_removed results duplicates_removed import_results polling_locations_import_from_structured_json filtered_structured_json import_results duplicates_removed duplicates_removed return import_results
project a value in this scale 's domain to a target range .,def project self value range_min range_max raise NotImplementedError
converts all newlines in a piece of plain text to html line breaks ( `` + < br / > `` ) .,register filter is_safe True needs_autoescape True stringfilter def linebreaksasciidocbr value autoescape None autoescape autoescape and not isinstance value SafeData value normalize_newlines value if autoescape value escape value return mark_safe value replace n nbsp br
returns true if the call failed .,def Failed self raise NotImplementedError
move instance : translate and rotate instance,def __MoveInstance self structureGeometry self __MoveTowerInstance self __MoveStiffeningGirderInstance self __MoveGirderRigidarmInstance structureGeometry self __MoveCableInstance self __MoveSuspenderInstance structureGeometry
initialize the data model and respective structures .,def __init__ self topo alignm model None if type alignm alignment phylipFriendlyAlignment raise TypeError libpll interfacing needs phylipFriendlyAlignment if not model if hasattr alignm _pllmodel self model alignm _pllmodel else self model partitionModel alignm self model createSimpleModel alignm _pllmodel self model alignm paths pll self model getFileName else self model model modf self model getFileName self instance new alignm getPhylip topo toUnrootedNewick modf
return whether or not this instance references the specified table .,def references_table self table return False
"create a coordinate sequence , set x , y , [ z ] , and create point",classmethod def _create_point cls ndim coords if not ndim return capi create_point None if ndim 2 or ndim 3 raise TypeError Invalid point dimension s ndim cs capi create_cs c_uint 1 c_uint ndim i iter coords capi cs_setx cs 0 next i capi cs_sety cs 0 next i if ndim 3 capi cs_setz cs 0 next i return capi create_point cs
"return url - safe , hmac / sha1 signed base64 compressed json string . if key is none , use settings . secret_key instead .",def dumps obj key None salt django core signing serializer JSONSerializer compress False data serializer dumps obj is_compressed False if compress compressed zlib compress data if len compressed len data 1 data compressed is_compressed True base64d b64_encode data decode if is_compressed base64d base64d return TimestampSigner key salt salt sign base64d
return the last modified time ( as a datetime ) of the file specified by name . the datetime will be timezone - aware if use_tz = true .,def get_modified_time self name raise NotImplementedError subclasses of Storage must provide a get_modified_time method
emit metrics from a hbase regionserver .,def emit self current_time int time time metrics self poll for context metric_name value in metrics if any c in EXCLUDED_CONTEXTS for c in context continue if any c regions for c in context if EMIT_REGION self emit_region_metric context current_time metric_name value else self emit_metric context current_time metric_name value
returns a visualization manager that can be reused in tests : param api_key_auth_client : fixture that provides a valid apikeyauthclient object : return : datamanager instance,pytest fixture scope module def visualization_manager api_key_auth_client return VisualizationManager api_key_auth_client
frange ' end ' property is int and read only,def test_property_end self end self f1 end self assertEqual end None end self f2 end self assertIsInstance end int self assertEqual end 1 end self f3 end self assertIsInstance end int self assertEqual end 1 end self f4 end self assertIsInstance end int self assertEqual end 5 end self f5 end self assertIsInstance end int self assertEqual end 10 end self f6 end self assertIsInstance end int self assertEqual end 19 end self f7 end self assertIsInstance end int self assertEqual end 19
-- gets the current time in .beats ( swatch internet time ) .,hook command autohelp False def beats text if text lower wut return Instead of hours and minutes the mean solar day is divided up into 1000 parts called beats Each beat lasts 1 minute and 26 4 seconds Times are notated as a 3 digit number out of 1000 after midnight So 248 would indicate a time 248 beats after midnight representing 248 1000 of a day just over 5 hours and 57 minutes There are no timezones elif text lower guide return 1 day 1000 beats 1 hour 41 666 beats 1 min 0 6944 beats 1 second 0 01157 beats t time gmtime h m s t tm_hour t tm_min t tm_sec utc 3600 h 60 m s bmt utc 3600 beat bmt 86 4 if beat 1000 beat 1000 return Swatch Internet Time 06 2f beat
this method handles synchronous calls which are generally fast information retrieval requests and thus return ' quickly ' .,def _sync_request self command kwargs kwargs command command result self request self driver path params kwargs command command lower response if command not in result object raise MalformedResponseError Unknown response format body result body driver self driver result result object command return result
raise servicefailure ( ) if the bagit zip archive file fails any of the following checks : - is a valid zip file . - the tag and manifest files are correctly formatted . - contains all the files listed in the manifests . - the file checksums match the manifests .,def validate_bagit_file bagit_path assert zipfile is_zipfile bagit_path bagit_zip zipfile ZipFile bagit_path manifest_info_list _get_manifest_info_list bagit_zip _validate_checksums bagit_zip manifest_info_list return True
encodes input using ascii - hex coding .,def _AsciiHexEncode input if isUnicode input input input encode utf 8 output getBytesIO output write binascii b2a_hex input output write return output getvalue
extended configure method for a balance of station cost assembly for coupling models to get a full wind plant balance of station cost estimate . it replaces the base balance of station cost aggregator component with an extended version which contains the full balance of station variable tree .,def configure_extended_bos assembly configure_base_bos assembly assembly replace bos ExtendedBOSCostAggregator assembly connect bos bos_breakdown bos_breakdown
": param models : a list of model object : param trends : a list of computed simulation trends : param statuses : the model statuses for which make the plot . default [ "" infected "" ] .",def __init__ self models trends statuses Infected super self __class__ self __init__ models trends statuses self ylabel Nodes self title Diffusion Trend
wait for browser to come up .,def _WaitForBrowserToComeUp self try timeout self browser_options browser_startup_timeout util WaitFor self HasBrowserFinishedLaunching timeout timeout except exceptions TimeoutException exceptions ProcessGoneException as e if not self IsBrowserRunning raise exceptions BrowserGoneException self browser e raise exceptions BrowserConnectionGoneException self browser e
return field position by its asn.1 type .,def getPositionByType self tagSet try return self __tagToPosMap tagSet except KeyError raise error PyAsn1Error Type s not found tagSet
"set an automatic reply for the account . args : message ( str ) : the message to be sent in replies . if external_message is provided this is the message sent to internal recipients status ( outlookaccount . autoreplystatus ) : whether the auto - reply should be always enabled , scheduled , or disabled . you can use : class:`autoreplystatus < pyoutlook.core.main . outlookaccount . autoreplystatus > ` to provide the value . defaults to always_enabled . start ( datetime ) : if status is set to scheduled , this is when the replies will start being sent . end ( datetime ) : if status is set to scheduled , this is when the replies will stop being sent . external_message ( str ) : if provided , this message will be sent to external recipients . audience ( outlookaccount . autoreplyaudience ) : whether replies should be sent to everyone , contacts only , or internal recipients only . you can use : class:`autoreplyaudience < pyoutlook.core.main . outlookaccount . autoreplyaudience > ` to provide the value .",def set_auto_reply self message status AutoReplyStatus ALWAYS_ENABLED start None end None external_message None audience AutoReplyAudience ALL start_is_none start is None end_is_none end is None if not start_is_none and end_is_none or start_is_none and not end_is_none raise ValueError Start and End not must both either be None or datetimes start_is_datetime isinstance start datetime end_is_datetime isinstance end datetime if not start_is_datetime and not start_is_none or not end_is_datetime and not end_is_none raise ValueError Start and End must both either be None or datetimes request_data dict Status status ExternalAudience audience if external_message is None external_message message request_data update InternalReplyMessage message ExternalReplyMessage external_message if not start_is_none and not end_is_none request_data update ScheduledStartDateTime dict DateTime str start request_data update ScheduledEndDateTime dict DateTime str end data odata context https outlook office com api v2 0 metadata Me MailboxSettings AutomaticRepliesSetting request_data requests patch https outlook office com api v2 0 me MailboxSettings headers self _headers data json dumps data self _auto_reply message
this test verifies that a ` packet ` definition can be created with default values for a particular field .,def test_pkt_create_packet_with_default_field_value self class two_int_field_packet models Packet int_field models IntField default_val 12 int_field_signed models IntField signed True default_val 12 p two_int_field_packet self assertEqual p int_field 12 self assertEqual p int_field_signed 12
test whether two open file objects reference the same file,def sameopenfile fp1 fp2 s1 os fstat fp1 s2 os fstat fp2 return samestat s1 s2
checks that the brainmodel matches the expected conte69 surface coordinates,def check_Conte69 brain_model assert isinstance brain_model axis BrainModel structures list brain_model iter_structures assert len structures 2 assert structures 0 0 CIFTI_STRUCTURE_CORTEX_LEFT assert structures 0 2 is_surface all assert structures 1 0 CIFTI_STRUCTURE_CORTEX_RIGHT assert structures 1 2 is_surface all assert brain_model voxel 1 all assert brain_model arr 5 vertex np arange 5 all assert structures 0 2 vertex 1 32491 assert structures 1 2 vertex 0 0 assert structures 1 2 vertex 1 32491
: param tuning_parameters : a preset class instance with all the running paramaters : type tuning_parameters : preset,def __init__ self tuning_parameters ExplorationPolicy __init__ self tuning_parameters self keep_probability tuning_parameters exploration initial_keep_probability self final_keep_probability tuning_parameters exploration final_keep_probability self keep_probability_decay_delta tuning_parameters exploration initial_keep_probability tuning_parameters exploration final_keep_probability float tuning_parameters exploration keep_probability_decay_steps self action_space_size tuning_parameters env action_space_size self network tuning_parameters network self epsilon 0
advection of particles using adadptive runge - kutta 4/5 integration .,def AdvectionRK45 particle fieldset time dt tol 1e 09 c 1 0 4 0 3 0 8 0 12 0 13 0 1 0 1 0 2 0 A 1 0 4 0 0 0 0 0 0 0 0 0 3 0 32 0 9 0 32 0 0 0 0 0 0 0 1932 0 2197 0 7200 0 2197 0 7296 0 2197 0 0 0 0 0 439 0 216 0 8 0 3680 0 513 0 845 0 4104 0 0 0 8 0 27 0 2 0 3544 0 2565 0 1859 0 4104 0 11 0 40 0 b4 25 0 216 0 0 0 1408 0 2565 0 2197 0 4104 0 1 0 5 0 b5 16 0 135 0 0 0 6656 0 12825 0 28561 0 56430 0 9 0 50 0 2 0 55 0 u1 v1 fieldset UV time particle lon particle lat particle depth lon1 lat1 particle lon u1 A 0 0 dt particle lat v1 A 0 0 dt u2 v2 fieldset UV time c 0 dt lon1 lat1 particle depth lon2 lat2 particle lon u1 A 1 0 u2 A 1 1 dt particle lat v1 A 1 0 v2 A 1 1 dt u3 v3 fieldset UV time c 1 dt lon2 lat2 particle depth lon3 lat3 particle lon u1 A 2 0 u2 A 2 1 u3 A 2 2 dt particle lat v1 A 2 0 v2 A 2 1 v3 A 2 2 dt u4 v4 fieldset UV time c 2 dt lon3 lat3 particle depth lon4 lat4 particle lon u1 A 3 0 u2 A 3 1 u3 A 3 2 u4 A 3 3 dt particle lat v1 A 3 0 v2 A 3 1 v3 A 3 2 v4 A 3 3 dt u5 v5 fieldset UV time c 3 dt lon4 lat4 particle depth lon5 lat5 particle lon u1 A 4 0 u2 A 4 1 u3 A 4 2 u4 A 4 3 u5 A 4 4 dt particle lat v1 A 4 0 v2 A 4 1 v3 A 4 2 v4 A 4 3 v5 A 4 4 dt u6 v6 fieldset UV time c 4 dt lon5 lat5 particle depth lon_4th particle lon u1 b4 0 u2 b4 1 u3 b4 2 u4 b4 3 u5 b4 4 dt lat_4th particle lat v1 b4 0 v2 b4 1 v3 b4 2 v4 b4 3 v5 b4 4 dt lon_5th particle lon u1 b5 0 u2 b5 1 u3 b5 2 u4 b5 3 u5 b5 4 u6 b5 5 dt lat_5th particle lat v1 b5 0 v2 b5 1 v3 b5 2 v4 b5 3 v5 b5 4 v6 b5 5 dt kappa math sqrt math pow lon_5th lon_4th 2 math pow lat_5th lat_4th 2 if kappa math fabs dt tol 0 particle lon lon_4th particle lat lat_4th if kappa math fabs dt tol 0 10 particle dt 2 else particle dt 2 return ErrorCode Repeat
convert a tuple or struct_time representing a time as returned by gmtime ( ) or localtime ( ) to a 24-character string of the following form :,def asctime t None if t is None t time localtime s s s 2s s DAYNAMES t tm_wday MONTHNAMES t tm_mon t tm_mday time strftime H M S Y t return s
returns the i d of this ecu type,def get_type_id self return SimpleECU
initialization function of the plugin system .,def init sys path append path abspath settings plugin_path if settings is_sim req_type sim else req_type gui for fname in glob path join settings plugin_path py p check_plugin fname if p and p plugin_type req_type plugin_descriptions p plugin_name upper p for pname in settings enabled_plugins success load pname upper print success 1
"force the given input to only use ` str ` instead of ` bytes ` or ` unicode ` . this works even if the input is a dict , list ,",staticmethod def _byteify input if isinstance input dict return _Auxiliary _byteify key _Auxiliary _byteify value for key value in input items elif isinstance input list return _Auxiliary _byteify element for element in input elif _Constants _PYTHON_3 and isinstance input str return str input encode ascii replace decode ascii elif not _Constants _PYTHON_3 and isinstance input unicode return str input encode ascii replace decode ascii else return input
destroy the window : return : none,def _close self self destroy
"if the client wants ansi , replace the tokens with ansi sequences -- otherwise , simply strip them out .",def colorize text ansi True if ansi text text replace x00 for token code in _ANSI_CODES text text replace token code text text replace x00 else text strip_caret_codes text return text
randomly flips bits in the population matrix .,def fast_mutation self entities p self bit_mutate_rate self entity_mutate_rate if self fast_rng is None r self rng choice size entities shape p 1 p p else r self fast_rng uniform size entities shape r r p non_zero_indices r nonzero to_be_changed entities non_zero_indices changed_to 1 to_be_changed entities T set_subtensor to_be_changed changed_to return entities
highly parameterized correlation matrix of variables given by the columns of one or two dataframes .,def correlation_matrix df_x_path df_y_path None x_cols None y_cols None x_dict None y_dict None x_normalize False y_normalize False correction fdr_bh entries None er 0 05 output pearson save_as None xlabel_rotation vertical bp_style True if bp_style behaviopy_style if xlabel_rotation vertical ha left else ha center df pd read_csv df_x_path index_col 0 if not x_cols x_cols list df columns if df_y_path dfy pd read_csv df_y_path index_col 0 if not y_cols y_cols list dfy columns df pd concat df dfy axis 1 if entries df df loc entries if x_normalize df x_cols df x_cols apply lambda x x x mean if y_normalize df y_cols df y_cols apply lambda x x x mean if output pearsonr dfc df corr cmap cm PiYG cbar_label Pearson s r elif output slope dfc df corr df std values df std values np newaxis cmap cm PiYG cbar_label Slope elif output p n len df dfc df corr dfc dfc applymap lambda x p_from_r x n cmap cm BuPu_r cbar_label p value uncorrected elif output p_corrected n len df dfc df corr dfc dfc applymap lambda x p_from_r x n dfc_corrected multipletests dfc as_matrix flatten er correction 1 reshape np shape dfc dfc pd DataFrame dfc_corrected dfc index dfc columns cmap cm BuPu_r if fdr in correction cbar_label p value FDR corrected format str er else cbar_label p value FWER corrected format str er dfc dfc loc y_cols dfc dfc x_cols fig ax plt subplots if output not in p p_corrected im ax matshow dfc norm MidpointNormalize midpoint 0 0 cmap cmap else im ax matshow dfc norm MidpointNormalize midpoint 0 05 cmap cmap if x_dict plt xticks range len x_cols failsafe_apply_dict x_cols x_dict rotation xlabel_rotation ha ha else plt xticks range len x_cols x_cols rotation xlabel_rotation ha ha if y_dict plt yticks range len y_cols failsafe_apply_dict y_cols y_dict else plt yticks range len y_cols y_cols ax grid False ax tick_params axis both which both bottom off top off length 0 divider make_axes_locatable ax cax divider append_axes right size 5 pad 0 05 cbar fig colorbar im cax cax label cbar_label if save_as plt savefig save_as dpi 300 transparent True return dfc
"used in the predict phase , after training . override",def predict self test_data kwargs pass
return true if a record matches the type of variant being investigated,def relevant rec vtype ignorechroms rel rec is_snp and vtype SNV or rec is_sv and vtype SV or rec is_indel and vtype INDEL return rel and ignorechroms is None or rec CHROM not in ignorechroms
function appends open admin port to list .,def add_vulnerable_port self port self ports append port
just a short alias for python 's ' print ' .,def magic_p self parameter_s exec print parameter_s in self shell user_ns
greedy matching : type s : str : type t : str : rtype : bool,def isSubsequence self s t i 0 j 0 while i len s and j len t if t j s i j 1 else i 1 j 1 return i len s
"since majority elements appears more than ceil(n / k ) times , there are at most 2 majority number",def majorityNumber self nums k cnt defaultdict int for num in nums if num in cnt cnt num 1 elif len cnt k 1 cnt num 1 else for key in cnt keys cnt key 1 if cnt key 0 del cnt key for key in cnt keys if len filter lambda x x key nums len nums k return key raise Exception
get semantic annotations ( i.e. entity links ) from a text .,def annotate address text confidence 0 0 support 0 spotter Default disambiguator Default filters None headers None payload confidence confidence support support text text spotter spotter disambiguator disambiguator pydict _post_request address payload filters headers if Resources not in pydict raise SpotlightException No Resources found in spotlight response s pydict return _dict_cleanup resource for resource in pydict Resources
least - recently - used cache decorator .,def lru_cache maxsize 100 typed False def decorating_function user_function cache dict stats 0 0 HITS MISSES 0 1 make_key _make_key cache_get cache get _len len lock RLock root root root root None None nonlocal_root root PREV NEXT KEY RESULT 0 1 2 3 if maxsize 0 def wrapper args kwds result user_function args kwds stats MISSES 1 return result elif maxsize is None def wrapper args kwds key make_key args kwds typed result cache_get key root if result is not root stats HITS 1 return result result user_function args kwds cache key result stats MISSES 1 return result else def wrapper args kwds key make_key args kwds typed if kwds or typed else args with lock link cache_get key if link is not None root nonlocal_root link_prev link_next key result link link_prev NEXT link_next link_next PREV link_prev last root PREV last NEXT root PREV link link PREV last link NEXT root stats HITS 1 return result result user_function args kwds with lock root nonlocal_root if key in cache pass elif _len cache maxsize oldroot root oldroot KEY key oldroot RESULT result root nonlocal_root 0 oldroot NEXT oldkey root KEY root KEY root RESULT None del cache oldkey cache key oldroot else last root PREV link last root key result last NEXT root PREV cache key link stats MISSES 1 return result def cache_info Report cache statistics with lock return _CacheInfo stats HITS stats MISSES maxsize len cache def cache_clear Clear the cache and cache statistics with lock cache clear root nonlocal_root 0 root root root None None stats 0 0 wrapper __wrapped__ user_function wrapper cache_info cache_info wrapper cache_clear cache_clear return update_wrapper wrapper user_function return decorating_function
decode and return the source string .,def read self return self decode self source
: type s : str : rtype : int,def lengthOfLongestSubstring self s if s None return None if s return if len s 1 return s maxlens maxlens append 1 for i in range 1 len s print print i str i print longest substring without repetition s i maxlens i 1 i p s i maxlens i 1 i find s i print p str p if p 1 maxlens append maxlens i 1 1 continue else maxlens append i p print maxlens str maxlens max maxlens 0 for i in range len maxlens if max maxlens i max maxlens i return max
make a basic mixing proportion histogram .,def plot_heatmap mpm cm plt cm viridis xlabel Sources ylabel Sinks title Mixing Proportions as Fraction fig plt figure ax fig add_subplot 1 1 1 sns heatmap mpm vmin 0 vmax 1 0 cmap cm annot True linewidths 0 5 ax ax ax set_xlabel xlabel ax set_ylabel ylabel ax set_title title return fig ax
": param query : a grounded query : param interfaces : interfaces to allow access : param privacy : a privacy specification : either a blanket number or a dict . if none , all information is public ( though limited to the named interfaces ) if a number , all queries must be authorized with a privacy score lower than or equal to the number if a dict , queries having the specified scope must authorize with a privacy score lower than or equal to the corresponding value . the lowest privacy score is 0 , so a negative number means authorization is not possible . only keys in the list of known scopes are retained",def __init__ self query interfaces allowed_interfaces privacy None self _query query if isinstance interfaces str interfaces interfaces self _interfaces tuple k for k in interfaces if k in allowed_interfaces if isinstance privacy dict self _scopes PrivacyDeclaration from_dict privacy else self _scopes PrivacyDeclaration privacy
this function finds the rvas to keservicedescriptortable and keservicedescriptortableshadow in the nt module .,def find_tables start_addr vm service_tables try import distorm3 use_distorm True except ImportError use_distorm False function_size 120 if use_distorm data vm zread start_addr function_size for op in distorm3 DecomposeGenerator start_addr data distorm3 Decode64Bits if op flowControl FC_RET break if op mnemonic CMP and op size 9 and op operands 0 dispSize 32 and op operands 0 value 0 service_tables append op operands 0 disp elif op mnemonic LEA and op size 7 and op operands 1 dispSize 32 and op operands 1 disp 0 service_tables append op operands 1 disp else vm profile add_types _INSTRUCTION 9 opcode 0 String dict length 4 disp 4 int value 8 unsigned char ops_list K x83 xbc H x83 xbc J x83 xbc H x8d x8b for i in range function_size op obj Object _INSTRUCTION offset start_addr i vm vm if op value 0 for s in ops_list if op opcode v startswith s service_tables append op disp return service_tables
selects a template based on the current backend,def get_template backend func templates join backend _ func md join default_ func md return tenv get_or_select_template templates name
replace endogenous equations from the allequations dict .,def RebuildEquations self new_endo x 0 self AllEquations x 0 for x in self Endogenous self Endogenous new_endo
map names from translated rbh 's to original query and database names .,def backmap_names results_df q_names d_names results_df pd merge results_df q_names left_on q_name right_on new_name results_df q_name results_df old_name del results_df old_name results_df pd merge results_df d_names left_on s_name right_on new_name results_df s_name results_df old_name del results_df old_name del results_df new_name_x del results_df new_name_y return results_df
compares current web2py 's version with the latest stable web2py version .,def check_new_version myversion version_URL try from urllib import urlopen version urlopen version_URL read pversion parse_version version pmyversion parse_version myversion except Exception as e import traceback print traceback format_exc return 1 myversion if pversion 3 pversion 6 pmyversion 3 pmyversion 6 return True version else return False version
decorator turning a function into a task webhook .,def task_webhook fun u Decorator turning a function into a task webhook n n If an exception is raised within the function the decorated n function catches this and returns an error JSON response otherwise n it returns the result as a JSON response n n n Example n n code block python n n task_webhook n def add request n x int request GET x n y int request GET y n return x y n n def view request n response add request n print response content n n Gives n n status success retval 100 n n wraps fun def _inner args kwargs try retval fun args kwargs except Exception as exc response u status u failure u reason safe_repr exc else response u status u success u retval retval return JsonResponse response return _inner
write the examples and labels and write to file,def writelines self examples labels idx None linelen 60 if idx is None idx list range len labels fp open self filename w for ix in idx fp write d label d n ix round labels ix for lineidx in range 0 len examples ix linelen fp write examples ix lineidx lineidx linelen n fp close
return greyscale local autolevel of an image .,def autolevel_percentile image selem out None mask None shift_x False shift_y False p0 0 p1 1 return _apply percentile_cy _autolevel image selem out out mask mask shift_x shift_x shift_y shift_y p0 p0 p1 p1
"examples of pdbref chains entries to be parsed : a=65 - 119 = > { ' a':[65,119 ] } a / c / e / g=64 - 121 = > { ' a':[64,121 ] , ' b':[64,121 ] , ' c':[64,121 ] , ' d':[64,121 ] } a=458 - 778 , b=764 - 778 = > { ' a':[458,778],'b':[764,778 ] }",def parse_uniprot_pdbref_chains chains_span_str comma_sep chains_span_str split chains_span for s in comma_sep span s split 1 begin int span split 0 end int span split 1 chainids s split 0 strip split for c in chainids chains_span c begin end return chains_span
initialise each node 's children - essentially build the tree .,def _init_children self parent for dir_name in self get_children_paths parent full_path child Node name dir_name parent parent parent children append child self _init_children child
paint event handler . reads the turtle reports and draws graphics accordingly .,def on_paint self e None turtle_reports dumpqueue dump_queue self turtle_queue dc wx GCDC wx MemoryDC self bitmap for turtle_report in turtle_reports if turtle_report pen_down is True dc SetPen turtle_report give_pen dc DrawLinePoint from_my_pos self turtle pos from_my_pos turtle_report pos if turtle_report clear is True brush wx Brush black dc SetBackground brush dc Clear self turtle turtle_report del dc if len turtle_reports 0 self Refresh dc wx PaintDC self widget_size Vector self GetSize top_left_corner BITMAP_SIZE widget_size 2 0 dc DrawBitmap self bitmap top_left_corner if self turtle visible new_pos top_left_corner from_my_pos self turtle pos draw_bitmap_to_dc_rotated dc self TURTLE_IMAGE from_my_angle self turtle orientation new_pos dc Destroy
get a yaxis keyed by name . returns a newly generted twinx if it does n't exist,def get_yax self name def make_patch_spines_invisible ax ax set_frame_on True ax patch set_visible False for sp in list ax spines values sp set_visible False size len self yaxes if name not in self yaxes ax self ax twinx self yaxes name ax ax spines right set_position outward 50 size make_patch_spines_invisible ax ax spines right set_visible True ax set_ylabel name self set_formatter return self yaxes name
args : num_states ( int ) [ optional ] : number of states in the random mdp . num_rand_trans ( int ) [ optional ] : number of possible next states .,def __init__ self num_states 5 num_rand_trans 5 gamma 0 99 MDP __init__ self RandomMDP ACTIONS self _transition_func self _reward_func init_state RandomState 1 gamma gamma self num_rand_trans num_rand_trans self num_states num_states self _reward_s_a random choice range self num_states random choice RandomMDP ACTIONS self _transitions defaultdict lambda defaultdict str
stop running the event loop . every callback already scheduled will still run . this simply informs run_forever to stop looping after a complete iteration .,def stop self self _stopping True
game events contain the combat log as well as ' chase_hero ' events which could be interesting,def parse_game_event self ge if ge name dota_combatlog if ge keys type 4 try source self dp combat_log_names get ge keys sourcename unknown target self dp combat_log_names get ge keys targetname unknown target_illusion ge keys targetillusion timestamp ge keys timestamp if target startswith npc_dota_hero and not target_illusion self kills append target target source source timestamp timestamp tick self tick elif source startswith npc_dota_hero self heroes source creep_kill target timestamp except KeyError Sometimes we get combat logs for things we dont have in combat_log_names My theory is that the server sends us incremental updates to the string table using CSVCMsg_UpdateStringTable but I m not sure how to parse that pass
tests that sql query parameters for generic relations are properly grouped when or is used .,def test_q_object_or self note_contact Contact objects create org_contact Contact objects create Note objects create note note content_object note_contact org Organization objects create name org name org contacts add org_contact qs Contact objects filter Q notes__note__icontains other note Q organizations__name__icontains org name self assertTrue org_contact in qs qs Contact objects filter Q organizations__name__icontains org name Q notes__note__icontains other note self assertTrue org_contact in qs
ensures @xframe_options_deny properly sets the x - frame - options header .,def test_deny_decorator self xframe_options_deny def a_view request return HttpResponse r a_view HttpRequest self assertEqual r X Frame Options DENY
produces a prediction using the encapsulated model .,abc abstractmethod def _underlying_predict self x pass
compute a weight update for the current batch .,def compute_update self printing False raise NotImplementedError
sets up context for the request,api_blueprint before_request def context_setup g user users get_current_user g domain address parse g user email hostname g base_report_query EmailReport domain_query g domain
"takes an xml string and an identifier , creates a record in exist - db .",def write_to_exist xml xml_id con httplib HTTP earkdev ait ac at con putrequest PUT exist apps eark nlp s xml_id con putheader Content Type application xml clen len xml con putheader Content Length clen con putheader Authorization Basic s base64 b64encode nlp user earknlp con endheaders con send xml errcode errmsg headers con getreply if errcode in 200 201 return errcode else return errcode
verify that build_schema marks the aggregation_key field as not_analyzed .,def test_build_schema_handles_aggregation_key self backend self get_backend index haystack connections backend connection_alias get_unified_index fields index all_searchfields mapping backend build_schema fields 1 assert mapping get aggregation_key assert mapping aggregation_key index not_analyzed assert analyzer not in mapping aggregation_key
verify the xml data produced by the endpoint conforms to the dtd file .,def test_dtd_with_valid_data self response self client get self affiliate_url assert response status_code 200 filename abspath join dirname dirname __file__ affiliate_window_product_feed 1 4 dtd dtd etree DTD open filename root etree XML response content assert dtd validate root
draw the animation onto the screen .,def draw self if self active cur_img self images self img_ptr self draw_rect cur_img get_rect move self pos self screen blit cur_img self draw_rect
print help for arguments parsed by parse_common_args ( ) .,classmethod def common_usage cls print l level Turn on log level where level is one of DEBUG INFO WARNING ERROR CRITICAL
installs an actual big - ip as the object 's bigip attribute,def install_bigip self request request addfinalizer self nuke_bigip_config cx self _big_ip_connect args cx hostname cx username cx password self bigip ManagementRoot port cx port args
initialize a mcversion object by a dict parsed from < version>.json,def __init__ self d self id d id self assets d get assets self jar d get jar self id self type d get type self main_class d get mainClass self minecraft_arguments d get minecraftArguments if self minecraft_arguments is not None if self minecraft_arguments find versionType Forge 1 self type Forge self is_forge True else self is_forge False self minecraft_arguments Template self minecraft_arguments self libraries self extract for obj in d get libraries lib MCLibrary obj if lib allow self libraries append lib if lib exclude self extract append lib self inherits_from d get inheritsFrom
learning ( see the ` explauto introduction < about.html>`_ _ for more detail ) :,def perceive self s_ context None s self sensory_primitive s_ self emit perception s if context is None self sensorimotor_model update self m s self interest_model update np hstack self m self s np hstack self m s elif self context_mode mode mdmsds m self m len self m 2 dm self m len self m 2 ds s len s 2 s s len s 2 ds_g self s len self s 2 self sensorimotor_model update np hstack m dm np hstack s ds self interest_model update np hstack m dm context ds_g np hstack m dm s ds elif self context_mode mode mcs s s len context s_g self s len context self sensorimotor_model update self m np hstack context s self interest_model update np hstack self m context s_g np hstack self m context s self t 1
test the client pulsarexchange abstraction with an in - memory connection .,skip_unless_module kombu timed 15 def test_amqp manager1_exchange amqp_exchange PulsarExchange TEST_CONNECTION manager_test manager3_exchange amqp_exchange PulsarExchange TEST_CONNECTION manager3_test manager2_exchange amqp_exchange PulsarExchange TEST_CONNECTION manager2_test thread1 TestThread manager_test manager1_exchange thread2 TestThread manager2_test manager2_exchange thread3 TestThread manager3_test manager3_exchange thread1 start thread2 start thread3 start manager1_exchange publish manager_test u cow1 manager2_exchange publish manager2_test u cow2 manager3_exchange publish manager3_test u cow3 time sleep 0 1 thread1 wait_for_message u cow1 thread2 wait_for_message u cow2 thread3 wait_for_message u cow3
proximal operator for enforcing non - negativity ( indicator function over the set x > = 0 ),curry def nonneg x0 rho return np maximum x0 0
returns bounds of the given tile in latutude / longitude using wgs84 datum,def TileLatLonBounds self tx ty zoom bounds self TileBounds tx ty zoom minLat minLon self MetersToLatLon bounds 0 bounds 1 maxLat maxLon self MetersToLatLon bounds 2 bounds 3 return minLat minLon maxLat maxLon
process a line of output from the task returns true if the output was able to be processed,def process_output self line raise NotImplementedError
"creates a semi - deep copy of this function wrapper . the returned function wrapper clone contains copies of all parameters , so they can be modified at will .",def clone self func Function self function_name self return_value copy param for param in self parameters docstring self docstring custom_name self custom_name func _module self _module func wrapper_base_name self wrapper_base_name func wrapper_actual_name self wrapper_actual_name func throw list self throw func custodians_and_wards list self custodians_and_wards return func
retrieve a field or raise an error .,def get_required_field name verbose_name None try return flask request form name except KeyError verbose_name verbose_name or name raise errors ValidationError s is a required field verbose_name
draw .glyphs paths onto a pen .,def to_ufo_paths self ufo_glyph layer u pen ufo_glyph getPointPen for path in layer paths nodes list path nodes for node in nodes self to_ufo_node_user_data ufo_glyph node pen beginPath if not nodes pen endPath continue if not path closed node nodes pop 0 assert node type u line u Open path starts with off curve points pen addPoint tuple node position segmentType u move else nodes insert 0 nodes pop for node in nodes node_type _to_ufo_node_type node type pen addPoint tuple node position segmentType node_type smooth node smooth pen endPath
go to first column but stay in current row ( syntactic sugar ) : return :,def returntofirst self self __current_col__ 0
return base directories that contains all the themes .,def get_theme_base_dirs_from_settings theme_dirs None theme_base_dirs if theme_dirs theme_base_dirs extend Path theme_dir for theme_dir in theme_dirs return theme_base_dirs
"a course testing all of the conversion mechanisms : * some inheritable settings * sequences w/ draft and live intermixed children to ensure all get to the draft but only the live ones get to published . some are only draft , some are both , some are only live . * about , static_tab , and conditional documents",def _create_course self super TestMigration self _create_course split False chapter1_name uuid uuid4 hex self _create_item chapter chapter1_name display_name Chapter 1 course runid split False chap2_loc self old_course_key make_usage_key chapter uuid uuid4 hex self _create_item chap2_loc block_type chap2_loc block_id display_name Chapter 2 course runid split False live_vert_name uuid uuid4 hex self _create_item vertical live_vert_name display_name Live vertical chapter chapter1_name draft False split False self create_random_units False self old_course_key make_usage_key vertical live_vert_name both_vert_loc self old_course_key make_usage_key vertical uuid uuid4 hex self _create_item both_vert_loc block_type both_vert_loc block_id display_name Both vertical chapter chapter1_name draft False split False self create_random_units False both_vert_loc draft_both self draft_mongo get_item both_vert_loc draft_both display_name Both vertical renamed self draft_mongo update_item draft_both self user_id self create_random_units True both_vert_loc draft_vert_loc self old_course_key make_usage_key vertical uuid uuid4 hex self _create_item draft_vert_loc block_type draft_vert_loc block_id display_name Draft vertical chapter chapter1_name draft True split False self create_random_units True draft_vert_loc draft_vert_loc self old_course_key make_usage_key vertical uuid uuid4 hex self _create_item draft_vert_loc block_type draft_vert_loc block_id display_name Draft vertical2 chapter chapter1_name draft True split False self create_random_units True draft_vert_loc live_vert_loc self old_course_key make_usage_key vertical uuid uuid4 hex self _create_item live_vert_loc block_type live_vert_loc block_id display_name Live vertical end chapter chapter1_name draft False split False self create_random_units False live_vert_loc indirect1_loc self old_course_key make_usage_key discussion uuid uuid4 hex indirect2_loc self old_course_key make_usage_key html uuid uuid4 hex conditional_loc self old_course_key make_usage_key conditional uuid uuid4 hex self _create_item conditional_loc block_type conditional_loc block_id show_tag_list indirect1_loc indirect2_loc sources_list live_vert_loc xml_attributes completed True chap2_loc block_type chap2_loc block_id draft False split False self _create_item indirect1_loc block_type indirect1_loc block_id data display_name conditional show 1 conditional_loc block_type conditional_loc block_id draft False split False self _create_item indirect2_loc block_type indirect2_loc block_id data display_name conditional show 2 conditional_loc block_type conditional_loc block_id draft False split False self create_random_units False conditional_loc self _create_item static_tab uuid uuid4 hex data display_name Tab uno None None draft False split False self _create_item about overview data p test p None None draft False split False self _create_item course_info updates data ol li h2 Sep 22 h2 p test p li ol None None draft False split False
verifies course goal success message appears .,def is_course_goal_success_message_shown self return self q css success message present
capture any messages that have been recorded,def info self message args if args output message args else output message if not output startswith self messages append unicode output
"consume the score_reset signal defined in the submissions api , and convert it to a problem_weighted_score_changed signal indicating that the score has been set to 0/0 . converts the unicode keys for user , course and item into the standard representation for the problem_weighted_score_changed signal .",receiver score_reset def submissions_score_reset_handler sender kwargs course_id kwargs course_id usage_id kwargs item_id user user_by_anonymous_id kwargs anonymous_user_id if user is None return PROBLEM_WEIGHTED_SCORE_CHANGED send sender None weighted_earned 0 weighted_possible 0 user_id user id anonymous_user_id kwargs anonymous_user_id course_id course_id usage_id usage_id modified kwargs created_at score_deleted True score_db_table ScoreDatabaseTableEnum submissions
create a shell expansion of passed in parameter and iteratively remove them . must only expand to directories .,def _rm_glob self path for path in glob glob path shutil rmtree path
"when given some ` data ` and an rsa private key , decrypt the data",def rsa_decrypt data rsa_priv_key_bytes if isinstance data text_type data data encode utf 8 if isinstance rsa_priv_key_bytes text_type rsa_priv_key_bytes rsa_priv_key_bytes encode utf 8 if rsa_priv_key_bytes startswith key serialization load_pem_private_key rsa_priv_key_bytes password None backend default_backend else key serialization load_der_private_key rsa_priv_key_bytes password None backend default_backend return key decrypt data OAEP MGF1 SHA1 SHA1 label None
look for a user partition with a matching i d in the course 's partitions . note that this method can return an inactive user partition .,def get_user_partition self user_partition_id return _get_partition_from_id self course_partitions user_partition_id
"if the definition data is invalid xml , export it wrapped in an "" error "" tag . if it is valid , export without the wrapper .",def export_to_xml self resource_fs try xml etree fromstring self contents return etree tostring xml encoding unicode except etree XMLSyntaxError root etree Element error root text self contents err_node etree SubElement root error_msg err_node text self error_msg return etree tostring root encoding unicode
tests that the disconnect context manager errors when given an invalid signal .,def test_disconnect_manager_bad_arg self with self assertRaises ValueError with disconnect_submissions_signal_receiver PROBLEM_RAW_SCORE_CHANGED pass
dump all of the fuzzers currently loadable,def list_fuzzers msg Currently loaded fuzzers try load importlib import_module src fuzzers modules list pkgutil iter_modules load __path__ for mod in modules dp mod 0 find_module mod 1 load_module mod 1 for e in dir dp x getattr dp e if isclass x and e Fuzzer and issubclass x src core fuzzer Fuzzer msg s s x name mod 1 except Exception as e msg Failed to list modules s e ERROR
"find a noncovered zero and prime it . if there is no starred zero in the row containing this primed zero , go to step 5 . otherwise , cover this row and uncover the column containing the starred zero . continue in this manner until there are no uncovered zeros left . save the smallest uncovered value and go to step 6 .",def _step4 state C state C 0 astype np int covered_C C state row_uncovered np newaxis covered_C astype state col_uncovered dtype np int copy False n state C shape 0 m state C shape 1 while True row col np unravel_index np argmax covered_C n m if covered_C row col 0 return _step6 else state marked row col 2 star_col np argmax state marked row 1 if not state marked row star_col 1 state Z0_r row state Z0_c col return _step5 else col star_col state row_uncovered row False state col_uncovered col True covered_C col C col astype state row_uncovered dtype np int copy False covered_C row 0
much simpler this one is . just move it .,def Vertical_Motor_Step stepper3 dz speed dir3 sign dz dz abs dz for i in range 0 int dz stepper3 move dir3 1000000 0 speed return 0
the method is called from the hardware_tree module when a tree item is clicked on . it passes the tree structure and the necessary list of nodes to arrive to the selected item from the tree root,def add_new_widget_to_panel self nodes self __logger debug Add new widget to panel self __hw_table_panel add_new_widget nodes self __hw_tree_struct
replace http:// strings ( texts ) with html links .,def autolink doc clean autolink doc return doc
tests the login lock trying to login a lot of times more than failure limit,def test_failure_limit_many self u Tests the login lock trying to login a lot of times more n than failure limit n for _ in range 1 settings AXES_FAILURE_LIMIT response self _login self assertContains response self LOGIN_FORM_KEY for _ in range random randrange 1 settings AXES_FAILURE_LIMIT response self _login self assertContains response self LOCKED_MESSAGE status_code 403
save data as a csv file .,def save_csv X y path if sparse issparse X X X todense np savetxt path np hstack y reshape 1 1 X delimiter
setup the cloud resource before delegation and register a cleanup callback .,def setup self super OpenNebulaCloudProvider self setup if not self _use_static_config self _setup_dynamic
validates the appliance exists by id or name . return the appliance id .,def get_appliance oneandone_conn appliance full_object False for _appliance in oneandone_conn list_appliances q IMAGE if appliance in _appliance id _appliance name if full_object return _appliance return _appliance id
builds a kwargs dict which may contain the optional registryid .,def build_kwargs registry_id if not registry_id return dict else return dict registryId registry_id
loads the candidate configuration into the network device,abstractmethod def edit_config self candidate check_mode False replace None pass
main entry point for module execution,def main argument_spec dict http dict aliases enable_http type bool http_port dict type int https dict aliases enable_https type bool https_port dict type int sandbox dict aliases enable_sandbox type bool state dict default present choices started stopped present absent argument_spec update nxos_argument_spec module AnsibleModule argument_spec argument_spec supports_check_mode True warnings list check_args module warnings result changed False warnings warnings want map_params_to_obj module have map_config_to_obj module commands map_obj_to_commands want have module result commands commands if commands if not module check_mode load_config module commands result changed True module exit_json result
fail if new fresh image is too dissimilar from the baseline image,def assert_screenshot self file_path element_or_selector None threshold 0 exclude None element self _find_element element_or_selector self _create_dir self baseline_dir baseline_image os path join self baseline_dir s png file_path if isinstance file_path basestring else Image open file_path convert RGB if self save_baseline return self get_screenshot_as_image element exclude exclude save baseline_image self _create_dir self output_dir fresh_image self get_screenshot_as_image element exclude exclude fresh_image_file os path join self output_dir s png file_path fresh_image save fresh_image_file if not self save_baseline and not isinstance file_path basestring and not os path exists baseline_image raise IOError The baseline screenshot s does not exist You might want to re run this test in baseline saving mode baseline_image if isinstance baseline_image basestring try try self engine assertSameFiles fresh_image_file baseline_image threshold except AssertionError as err msg err message if hasattr err message else err args 0 if err args else args err args 1 if len err args 1 else raise ImageMismatchException msg baseline_image fresh_image_file args finally if self cleanup_on_success os remove fresh_image_file else diff ImageDiff fresh_image baseline_image distance abs diff get_distance if distance threshold pytest fail Fail New screenshot did not match the baseline by a distance of 2f distance
"combines this gene with the other , basically averaging the two parameter sets and using self.input_size and other.output_size .",def combine self other gene_data deepcopy self data gene_data 1 other data 1 for i in range 2 len gene_data gene_data i gene_data i other data i 2 if roundable i gene_data i int round gene_data i return Gene gene_data 0 gene_data 1 gene_data
"specify `` collect `` operators , it 's possible to use it multiple times",def collect self pairs kwargs if len pairs 2 0 raise ValueError Arguments should be pairs variable name and expression into kwargs get into self collect_expr append pairs into return self
a helper method used to select two parents from the population using a tournament selection algorithm .,def _selectParents self return self _tournament_selection self _tournament_selection
check whether anchor and offset yield a valid position .,def validate self anchor sentinel offset sentinel if anchor is sentinel anchor self anchor if offset is sentinel offset self offset if offset 0 raise CDSPositionError Offset may not be 0 For no offset use None if not anchor and anchor 0 and not offset raise CDSPositionError At least one of pos or offset must be defined if anchor and anchor 0 raise CDSPositionError CDS anchor may not be negative return True
"given an mdp and a utility function u , determine the best policy , as a mapping from state to action . ( equation 17.4 )",def best_policy mdp U pi for s in mdp states pi s argmax mdp actions s lambda a expected_utility a s U mdp return pi
validate that a directory exists and optionally create it .,def validate_dir_exists config section create_dir True path_is_file False dir_path config section if path_is_file dir_path os path dirname dir_path if dir_path dir_path os curdir if not os path isdir dir_path if not create_dir raise ConfigException 0 is not a directory format dir_path section try os makedirs dir_path except OSError raise ConfigException Could not create directory 0 format dir_path section
mark as bad to avoid reconnects but also to remember for a while .,def mark_bad self self bad True
will send each digit in the ' digits ' sequentially . would send nothing if there is non - dtmf digit .,def send_dtmf self digits u Will send each digit in the digits sequentially Would n send nothing if there is non DTMF digit return self _interface SendDTMF digits
get the placements and return a dict with the keys being the edge numbers where to do the insertions and the values being a dict of nodes to insert at that point and their distances .,def get_placements data distmeasure posn data fields index edge_num if distmeasure not in data fields sys stderr write Crap We do not have in our possible fields n format distmeasure data fields sys exit 1 distn data fields index distmeasure placements for pl in data placements multiplier if n in pl sys stderr write Crap not sure what to do because I ve never seen an example You should be able to figure out from what I did with nm sys exit 1 if nm in pl for i in pl nm multiplier i 0 replace _ i 1 for p in pl p edge_num p posn distance p distn if edge_num not in placements placements edge_num for thisid in multiplier placements edge_num thisid multiplier thisid distance 1 0 return placements
return true if the host is python 3 .,def is_py3 return tuple python_version short True 3 0
"create a directory if it does not already exist , else nothing is done and no error is return",def create_dir_if_not_exist path if not os path exists path os makedirs path
"type : : ( int , int ) - > int return : : return module inverse of a * x = 1 ( mod m )",def modinv a m if gcd a m is not 1 raise Exception Not coprime _ x y exgcd a m return m x m m
": return : r , w",def get_status self return len self _read_buff len self _write_buff
determine if the point is at least the minimumdistance away from other points .,def getIsPointAway minimumDistance point spongeCircles for otherSpongeCircle in spongeCircles if abs otherSpongeCircle center point minimumDistance return False return True
determine if the loop is intersecting or is within the other loop .,def getIsIntersectingWithinLoop loop otherLoop outsetLoop if euclidean isLoopIntersectingLoop loop otherLoop return True return euclidean isPathInsideLoop otherLoop loop euclidean isPathInsideLoop otherLoop outsetLoop
"set the default settings , execute title & settings filename .",def __init__ self skeinforge_profile addListsToCraftTypeRepository skeinforge_application skeinforge_plugins craft_plugins wipe html self self fileNameInput settings FileNameInput getFromFileName fabmetheus_interpret getGNUTranslatorGcodeFileTypeTuples Open File for Wipe self self openWikiManualHelpPage settings HelpPage getOpenFromAbsolute http www bitsfrombytes com wiki index php title Skeinforge_Wipe self activateWipe settings BooleanSetting getFromValue Activate Wipe self False settings LabelSeparator getFromRepository self settings LabelDisplay getFromName Location Arrival self self locationArrivalX settings FloatSpin getFromValue 100 0 Location Arrival X mm self 100 0 70 0 self locationArrivalY settings FloatSpin getFromValue 100 0 Location Arrival Y mm self 100 0 50 0 self locationArrivalZ settings FloatSpin getFromValue 100 0 Location Arrival Z mm self 100 0 50 0 settings LabelSeparator getFromRepository self settings LabelDisplay getFromName Location Departure self self locationDepartureX settings FloatSpin getFromValue 100 0 Location Departure X mm self 100 0 70 0 self locationDepartureY settings FloatSpin getFromValue 100 0 Location Departure Y mm self 100 0 40 0 self locationDepartureZ settings FloatSpin getFromValue 100 0 Location Departure Z mm self 100 0 50 0 settings LabelSeparator getFromRepository self settings LabelDisplay getFromName Location Wipe self self locationWipeX settings FloatSpin getFromValue 100 0 Location Wipe X mm self 100 0 70 0 self locationWipeY settings FloatSpin getFromValue 100 0 Location Wipe Y mm self 100 0 70 0 self locationWipeZ settings FloatSpin getFromValue 100 0 Location Wipe Z mm self 100 0 50 0 settings LabelSeparator getFromRepository self self wipePeriod settings IntSpin getFromValue 1 Wipe Period layers self 5 3 self executeTitle Wipe
add the wipe travel gcode .,def addWipeTravel self splitLine location gcodec getLocationFromSplitLine self oldLocation splitLine self highestZ max self highestZ location z if not self shouldWipe return self shouldWipe False if self extruderActive self distanceFeedRate addLine M103 if self oldLocation None self addHop self oldLocation self locationArrival self distanceFeedRate addLine self getLinearMoveWithFeedRate self travelFeedRatePerMinute self locationArrival self distanceFeedRate addLine self getLinearMoveWithFeedRate self travelFeedRatePerMinute self locationWipe self distanceFeedRate addLine self getLinearMoveWithFeedRate self travelFeedRatePerMinute self locationDeparture self addHop self locationDeparture location if self extruderActive self distanceFeedRate addLine M101
creates a sampledetails object based on a vanadium sample which is found in the advanced config of an instrument . : param config_dict : the advanced config dictionary of the instrument for the vanadium sample : return : a sample details object which holds properties used in sample corrections,def create_vanadium_sample_details_obj config_dict height_key cylinder_sample_height radius_key cylinder_sample_radius pos_key cylinder_position formula_key chemical_formula number_density_key number_density e_msg The following key was not found in the advanced configuration for sample correction height common dictionary_key_helper dictionary config_dict key height_key exception_msg e_msg height_key radius common dictionary_key_helper dictionary config_dict key radius_key exception_msg e_msg radius_key pos common dictionary_key_helper dictionary config_dict key pos_key exception_msg e_msg pos_key formula common dictionary_key_helper dictionary config_dict key formula_key exception_msg e_msg formula_key number_density common dictionary_key_helper dictionary config_dict key number_density_key throws False vanadium_sample_details sample_details SampleDetails height height radius radius center pos shape cylinder vanadium_sample_details set_material chemical_formula formula number_density number_density return vanadium_sample_details
"test a transmission calculation using tosca , graphite , 002 .",def test_indirect_transmission_tosca_graphite_002 self instrument TOSCA analyser graphite reflection 002 formula H2 O density 0 1 thickness 0 1 ws IndirectTransmission Instrument instrument Analyser analyser Reflection reflection ChemicalFormula formula DensityType Number Density Density density Thickness thickness ref_result 5 5137 0 680081 2 58187 53 5069 56 0888 0 1 0 1 0 566834 0 429298 values ws column 1 np testing assert_array_almost_equal values ref_result decimal 4
averages the median bin widths of the input workspace .,def PyExec self inputWs self getProperty self _PROP_INPUT_WS value roundingMode self getProperty roundinghelper PROP_NAME_ROUNDING_MODE value xs inputWs extractX dxs numpy diff xs medians numpy median dxs axis 1 binWidth numpy mean medians binWidth roundinghelper round binWidth roundingMode self setProperty self _PROP_BIN_WIDTH numpy abs binWidth
converts the stored data to a displayable text . override this function if you need data types other than str in your table .,def _dataToText self row col value return str value
test simple run with sample and can workspace and number density for both,def test_mass_density_for_sample_can self corrected fact IndirectFlatPlateAbsorption SampleWorkspace self _red_ws SampleChemicalFormula H2 O SampleDensityType Number Density SampleDensity 0 5 CanWorkspace self _can_ws CanChemicalFormula V CanDensityType Number Density CanDensity 0 5 UseCanCorrections True Events 200 self assertEqual fact size 2 self _test_workspaces corrected fact
data of the cell : param index : index of the cell : param role : role of the cell : return : data of the cell,def data self index role if Qt DisplayRole role or Qt EditRole role return self _getCellText index row index column return None
test to ensure cal file can not be used on a different instrument other than osiris,def test_reduction_with_cal_file_iris_fail self self assertRaises RuntimeError ISISIndirectDiffractionReduction InputFiles IRS26176 RAW Instrument IRIS Mode diffspec CalFile osi_041_RES10 cal OutputWorkspace wks SpectraRange 105 112
determine the number of states from a set of discrete trajectories,def number_of_states dtrajs nmax 0 for dtraj in dtrajs nmax max nmax np max dtraj return nmax 1
import the named python module(s ) add return the leaf .,def importmod modname return __import__ modname fromlist __should_not_exist
"calculate the percentage drop related to the "" worst "" drawdown seen .",def calculate_max_drawdown_pct self drawdown_series pd Series self drawdowns equity_series pd Series self equity bottom_index drawdown_series idxmax try top_index equity_series bottom_index idxmax pct equity_series ix top_index equity_series ix bottom_index equity_series ix top_index 100 return round pct 4 except ValueError return np nan
returns true if the notification is older than the specified timeout value .,def is_expired self return datetime datetime now self _when self _timeout
compute r200 ( in kpc ) for a given redshift and mass ( m200 ),def r200 self mass redshift msun 1 99e 33 cm2pc 3 086e 18 Delta 200 0 r200cube 3 0 10 mass msun 4 0 np pi self cosmo critical_density redshift value Delta r200 r200cube 1 0 3 cm2pc 1000 0 return r200
calculates the membershib degree of x in set a returns a(x ),def membership A x a b c d A assert b a and c b and d c if x a or x d return 0 0 elif x a and x b return x a float b a elif x b and x c return 1 0 else return d x float d c
"given the gff hits with overlapping ranges , determine if one has a score far exceeding the others and return that one , else return none",def score_filter hits score_multiplier 2 print Searching for hit with score times better n format score_multiplier scores int x 0 5 for x in hits max_score max scores for s in scores if s max_score if s score_multiplier max_score print No top score found return None return scores index max_score
"wait until `` op(function(*args ) , value ) `` is true or until timeout expires",def WaitUntil timeout retry_interval func value True op operator eq args start time time func_val func args while not op func_val value time_left timeout time time start if time_left 0 time sleep min retry_interval time_left func_val func args else err TimeoutError timed out err function_value func_val raise err return func_val
convenience function for counting unique rows in a numpy.ndarray,def unique_row_count arr _ counts unique arr view dtype void arr dtype itemsize arr shape 1 return_counts True return counts
method reprocesses the node and all its dependants and parent nodes,thread_safe def reprocess_tree_node self tree_node tx_context None if not tx_context tx_context collections defaultdict dict if tree_node parent is None return tx_context if tree_node timeperiod in tx_context tree_node process_name return tx_context if tree_node job_record is_embryo pass else state_machine_name context process_context tree_node process_name state_machine_name state_machine self state_machines state_machine_name state_machine reprocess_job tree_node job_record tx_context tree_node process_name tree_node timeperiod tree_node self reprocess_tree_node tree_node parent tx_context dependant_nodes self _find_dependant_tree_nodes tree_node for node in dependant_nodes self reprocess_tree_node node tx_context return tx_context
run the event loop to receive requests and notifications from nvim .,def run self request_cb notification_cb self _request_cb request_cb self _notification_cb notification_cb self _msgpack_stream run self _on_message self _request_cb None self _notification_cb None
print a timestamp to blender console .,def print_timestamp label None output Timestamp str time time if label is not None output output label print_console PROFILE output
release the lock for writing .,def write_out self self rwOK acquire try ident _get_ident if not self writer raise ValueError write_out invoked without an active writer if self writer ident raise ValueError write_out called by non writer self write_depth 1 if self write_depth 0 return self writer 0 self nw self nw 1 if self nw self writeOK notify else self readOK notifyAll finally self rwOK release
"@param region -- options are ' all ' ( equalize the entire image ) , ' bbox ' ( equalize just the portion of the image within the bounding box ) , and ' mask ' ( equalize just the portion of the image within the mask ) . @param mode -- * * deprecated * * alias for ' region ' . @param cutoff -- number of pixels to clip from each end of the histogram before rescaling it .",def __init__ self region all mode None cutoff 0 BaseFilter __init__ self if mode is not None region mode if region not in all bbox mask raise RuntimeError Not a supported region options are all bbox and mask if type cutoff int or cutoff 0 raise RuntimeError cutoff must be a positive integer self region region self cutoff cutoff
return package names sorted in the order as they should be imported due to dependence relations between packages .,def _get_sorted_names self depend_dict for name info_module in self info_modules items depend_dict name getattr info_module depends package_names for name in depend_dict keys if not depend_dict name package_names append name del depend_dict name while depend_dict for name lst in depend_dict items new_lst n for n in lst if n in depend_dict if not new_lst package_names append name del depend_dict name else depend_dict name new_lst return package_names
evaluates an expression such as $ bandwidth > 500,def asmrp_comp_expression self rules self logger debug self indent Expression getting a operand self indent a self asmrp_operand rules self indent self indent 1 rules isCharElseNext if rules sym in return a operator rules sym rules next if rules sym operator rules nextChar self logger debug self indent Expression operator s operator self logger debug self indent Expression getting b operand self indent b self asmrp_operand rules self indent self indent 1 self logger debug self indent Expression s s s a operator b if operator return a b if operator return a b if operator return a b if operator return a b if operator return a b
run the mainloop for exactly one iteration .,def RunOnce self timeout None r w os pipe try os write w x self ioloop add_handler r lambda fd events self ioloop stop self ioloop READ self Start timeout finally os close r os close w self ioloop remove_handler r
build up a course tree with an html control,def build_course self self global_staff UserFactory is_staff True self course CourseFactory create org Elasticsearch course ES101 run test_run display_name Elasticsearch test course self section ItemFactory create parent self course category chapter display_name Test Section self subsection ItemFactory create parent self section category sequential display_name Test Subsection self vertical ItemFactory create parent self subsection category vertical display_name Test Unit self html ItemFactory create parent self vertical category html display_name Test Html control 1 self html ItemFactory create parent self vertical category html display_name Test Html control 2
make sure that the page is accessible .,def test_page_existence self self asset_page visit
' serialize ' to a json - serializable representation .,def to_json self return id self id name self name version Group VERSION
extract rendered xblock component html content .,def xblock_component_html_content self index 0 element self q css edx notes wrapper content format self xblock_component_selector if element first return element attrs innerHTML index strip else return self q css self xblock_component_selector attrs innerHTML index strip
test for calling get_preview_html . ensures data - usage - id is correctly set and asides are correctly excluded because they are not enabled .,XBlockAside register_temp_plugin AsideTestType test_aside def test_preview_no_asides self course CourseFactory create default_store ModuleStoreEnum Type split html ItemFactory create parent_location course location category html data data html foobar html config StudioConfig current config enabled False config save request RequestFactory get dummy url request user UserFactory request session context reorderable_items set read_only True html get_preview_fragment request html context content self assertNotRegexpMatches html data block type test_aside self assertNotRegexpMatches html Aside rendered
"returns the role that the user is masquerading as , or none if no masquerade is in effect .",def get_masquerade_role user course_key course_masquerade get_course_masquerade user course_key return course_masquerade role if course_masquerade else None
helper method to remove a parameter from the lti launch and call the view,def launch_with_missing_parameter self missing_param request build_launch_request del request POST missing_param return views lti_launch request None None
tests that staff can not add entries,def test_add_permission self self assertFalse self creator_admin has_add_permission self request
"create a text message using a template , message body and context .",staticmethod def _render format_string message_body context if user_id in context and course_id in context message_body substitute_keywords_with_data message_body context result format_string format context message_body_tag COURSE_EMAIL_MESSAGE_BODY_TAG format result result replace message_body_tag message_body 1 return wrap_message result
check that the signature from the credit provider is valid .,def _validate_signature parameters provider_id secret_key get_shared_secret_key provider_id if secret_key is None log error u Could not retrieve secret key for credit provider with ID s Since no key has been configured we cannot validate requests from the credit provider provider_id return HttpResponseForbidden Credit provider credentials have not been configured if signature parameters secret_key parameters signature log warning u Request from credit provider with ID s had an invalid signature parameters signature return HttpResponseForbidden Invalid signature
check the example certificate status .,def _assert_cert_status self expected_statuses actual_status certs_api example_certificates_status self COURSE_KEY self assertEqual list expected_statuses actual_status
send an event message for publishing,def publish_events self events if self raw_only data evt as_dict raw payload for evt in events if evt as_dict get raw get payload else data event serialize for event in events self poster data
create a new cache and send events for changes from the old cache,def _poll_once self old_cache new_cache for entry_key in self _driver get_all_keys self _table_name entry_value self _driver get_key self _table_name entry_key if entry_value is None continue old_value old_cache pop entry_key None if old_value is None self _send_event create entry_key entry_value elif old_value entry_value self _send_event set entry_key entry_value new_cache entry_key entry_value for entry_key in old_cache self _send_event delete entry_key None return new_cache
transform a coma - separated list of host names into a list .,def parse_compute_hosts compute_hosts return filter None re split a zA Z0 9 _ compute_hosts
allocate an ip from the pool,def allocate self address_request return self backend_allocate address_request
add common cluster permission information to the context .,def common_permissions request user getattr request user None if user and user is_authenticated if user is_superuser return CLUSTER_ADMIN_PERMISSIONS perms user get_perms_any Cluster if admin in perms return CLUSTER_ADMIN_PERMISSIONS else create_vm create_vm in perms view_cluster any p in perms for p in CLUSTER_VIEW_PERMS return cluster_admin False create_vm create_vm view_cluster view_cluster return ANONYMOUS_PERMISSIONS
calculates coulomb forces and updates node data .,def _coulomb n1 n2 k r delta x2 x1 for x1 x2 in zip n1 velocity n2 velocity distance sqrt sum d 2 for d in delta if distance 0 1 delta uniform 0 1 0 2 for _ in repeat None 3 distance sqrt sum d 2 for d in delta if distance r force k distance 2 n1 force f force d for f d in zip n1 force delta n2 force f force d for f d in zip n2 force delta
sets the size of the scene .,def setSize self xSize ySize debugMsg Called Scene setSize self xSize xSize self ySize ySize return
install or upgrade setuptools and easyinstall,def main options _parse_args archive download_setuptools version options version download_base options download_base downloader_factory options downloader_factory return _install archive _build_install_args options
returns the list of all names in tree .,def traverse_tree t parent_name if parent_name full_node_name parent_name t name else full_node_name t name if t children is None result full_node_name else result full_node_name for i in t children result extend traverse_tree i full_node_name return result
determine if the simulator is using multiple parallel event queues,def _using_pdes root for obj in root descendants if not m5 proxy isproxy obj eventq_index and obj eventq_index root eventq_index return True return False
sums transactions into a total of remaining vacation days .,def sum_transactions transactions workdays_per_year 250 previous_date None rate 0 day_sum 0 for transaction in transactions date action value _parse_transaction_entry transaction if previous_date is None previous_date date elapsed workdays networkdays previous_date date stat_holidays 1 if action rate rate float value workdays_per_year elif action off elapsed 1 day_sum 1 day_sum rate elapsed if action days day_sum value previous_date date return day_sum
load the data and instantiate the correct data model,def load self fullfilename directory filename os path split fullfilename check_filename directory filename protein_ID ext os path splitext filename DataObject getattr core self type data DataObject ID protein_ID with open fullfilename rU as data_file data_reader csv reader data_file delimiter quotechar header data_reader next data labels header x_label header 0 y_labels header 1 data data x y_lbl for y_lbl in y_labels y y_lbl for y_lbl in y_labels for row in data_reader x_val float row pop 0 for phase y_val in zip y_labels row if y_val data data x phase append x_val data data y phase append float y_val return data
retrieve password from the given command,def oracle_eval command p subprocess Popen command shell True stdout subprocess PIPE stderr subprocess PIPE p wait if p returncode 0 return p stdout readline strip decode utf 8 else die Error retrieving password command returned error format command command error p stderr read strip
test that a prepboot bootloader shows up in the ks data .,patch pyanaconda dbus DBus get_proxy patch pyanaconda storage osinstall InstallerStorage bootloader_device new_callable PropertyMock patch pyanaconda storage osinstall InstallerStorage mountpoints new_callable PropertyMock def test_prepboot_bootloader_in_kickstart self mock_mountpoints mock_bootloader_device dbus bootloader_device_obj PartitionDevice test_partition_device bootloader_device_obj size Size 5 MiB bootloader_device_obj format formats get_format prepboot mock_bootloader_device return_value bootloader_device_obj mock_mountpoints values return_value prepboot_blivet_obj InstallerStorage makeVersion prepboot_blivet_obj update_ksdata self assertIn part prepboot str prepboot_blivet_obj ksdata
set if the firewall command was present in the input kickstart .,def set_firewall_seen self firewall_seen self _firewall_seen firewall_seen self firewall_seen_changed emit log debug Firewall command considered seen in kickstart s self _firewall_seen
url of an x.509 certificate .,property def escrowcert self return self _escrowcert
init a levelfilter : param levels : iterable of integers representing different logging levels : critical 50 error 40 warning 30 info 20 debug 10 notset 0,def __init__ self levels self _levels set levels
find the name of an exception,def get_exception_name node name node children 1 while not name type name name name children 0 return name value
transform fluxes into magnitudes including errorbars,def get_mag_and_err_from_flux flux err_flux zeropoint MAG_ZEROPOINT if np any flux 0 0 warnings warn Flux to magnitude conversion approached negative flux UserWarning mag zeropoint 2 5 np log10 flux err_mag err_flux flux 2 5 np log 10 0 return mag err_mag
check if the distance between old and new centroids is zero .,def _is_converged self centroids_old centroids distance 0 for i in range self K distance euclidean_distance centroids_old i centroids i return distance 0
decorator that converts python slicing to offset and limit,def offset_limit func u n Decorator that converts python slicing to offset and limit n def func_wrapper self start stop offset start limit stop start return func self offset limit return func_wrapper
"returns the summary of the template representing an rtsp message . ( meaningful , short , human - understandable description )",def getSummary self template return s s template status template reason
record update operation to log ; called also by _ wconfig,def _logupdate self src for k in src self _logset k src k
"false if the set is empty , true otherwise .",def __nonzero__ self try iter self next return True except StopIteration return False
seeds the random number generators in mxnet .,def seed seed_state if not isinstance seed_state int raise ValueError sd must be int seed_state ctypes c_int int seed_state check_call _LIB MXRandomSeed seed_state
a module - level function so that it can be spawn with multiprocessing .,def f x y 0 z 0 return x 2 y z
a function with a side effect in its arguments .,def count_and_append x len_x len x x append None return len_x
make sure a secret mount is mounted,def mount_present module url mount_url url v1 sys mounts module params mountpoint headers X Vault Token module params token data type module params type description module params description config default_lease_ttl str module params default_lease_ttl max_lease_ttl str module params max_lease_ttl data_json json dumps data mount_list get_mounts module url if module params mountpoint in mount_list module exit_json changed False data if module check_mode module exit_json changed True response info fetch_url module mount_url method POST headers headers data data_json if info status 204 and info status 200 module fail_json msg Unable to mount 0 s 1 s format module params mountpoint info msg module exit_json changed True data
wrapper for keras with pandas support derived from https://github.com/fchollet/keras/blob/master/keras/wrappers/scikit_learn.py,def __init__ self model_create default_classification_model tmp_model tmp model target None target_readable None included None excluded None id_map optimizer adam loss categorical_crossentropy train_batch_size 128 test_batch_size 128 nb_epoch 100 shuffle True show_accuracy False validation_split 0 validation_data None callbacks None verbose 0 super KerasClassifier self __init__ target target_readable included excluded id_map self target target self target_readable target_readable self id_map id_map self included included self excluded excluded if not self target_readable is None if self excluded is None self excluded self target_readable else self excluded append self target_readable self vectorizer None self model_create model_create self optimizer optimizer self loss loss self train_batch_size train_batch_size self test_batch_size test_batch_size self nb_epoch nb_epoch self shuffle shuffle self show_accuracy show_accuracy self validation_split validation_split self validation_data validation_data self callbacks if callbacks is None else callbacks self verbose verbose self tmp_model tmp_model self compiled_model_ None
"this method is used to initialise , i.e. , create an instance of the exphydrodistrmodel class .",def __init__ self p pet t npixels self model ExphydroModel p pet t for j in range npixels self timespan p shape 0 self qsimtmp numpy zeros self timespan self qsim numpy zeros self timespan
returns the root node of a parser tree . the returned node does n't have a parent node like all the other nodes / leaves .,def get_root_node self scope self while scope parent is not None scope scope parent return scope
"raise cartridge.shop.checkout.checkouterror(""error message "" ) if payment is unsuccessful .",def process request order_form order u n Raise cartridge shop checkout CheckoutError error message if n payment is unsuccessful n trans amount order total trans u amount amount if settings DEBUG trans u connection AUTH_NET_TEST else trans u connection AUTH_NET_LIVE trans u authorize_only False trans u configuration u x_login AUTH_NET_LOGIN u x_tran_key AUTH_NET_TRANS_KEY u x_version u 3 1 u x_relay_response u FALSE u x_test_request u FALSE u x_delim_data u TRUE u x_delim_char u u x_type u AUTH_CAPTURE u x_method u CC data order_form cleaned_data trans u custBillData u x_first_name data u billing_detail_first_name u x_last_name data u billing_detail_last_name u x_address data u billing_detail_street u x_city data u billing_detail_city u x_state data u billing_detail_state u x_zip data u billing_detail_postcode u x_country data u billing_detail_country u x_phone data u billing_detail_phone u x_email data u billing_detail_email trans u custShipData u x_ship_to_first_name data u shipping_detail_first_name u x_ship_to_last_name data u shipping_detail_last_name u x_ship_to_address data u shipping_detail_street u x_ship_to_city data u shipping_detail_city u x_ship_to_state data u shipping_detail_state u x_ship_to_zip data u shipping_detail_postcode u x_ship_to_country data u shipping_detail_country trans u transactionData u x_amount amount u x_card_num data u card_number u x_exp_date u month year format month data u card_expiry_month year data u card_expiry_year u x_card_code data u card_ccv u x_invoice_num str order id part1 urlencode trans u configuration u part2 u urlencode trans u custBillData part3 u urlencode trans u custShipData trans u postString part1 urlencode trans u transactionData part2 part3 request_args u url trans u connection u data trans u postString encode u utf 8 try all_results urlopen Request request_args read except URLError raise CheckoutError u Could not talk to authorize net payment gateway parsed_results all_results decode u utf 8 split trans u configuration u x_delim_char response_code parsed_results 0 success response_code u 1 if not success raise CheckoutError u Transaction declined parsed_results 2 return parsed_results 6
"assigns a permissions dict to the given model , much like django does with its dashboard app list .",register render_tag def set_model_permissions context token u n Assigns a permissions dict to the given model much like Django n does with its dashboard app list n n Used within the change list for pages to implement permission n checks for the navigation tree n model context token split_contents 1 opts model _meta perm_name opts app_label u s_ opts object_name lower request context u request setattr model u perms for perm_type in u add u change u delete model perms perm_type request user has_perm perm_name perm_type return u
return the value of a given property name .,def get_property_value self name props self get_properties if props and name in props return props name value
"must be implemented in child , this called if the _ _ init _ _ fails",def _raiseInitFailed self request raise NotImplemented Must be implemented in child
provide a test schema built from scratch using the schema classes .,def get_manually_created_schema schema sch Schema schema column_schemas fixed_bool_with_default sch ColumnSchema tf bool 1 sch FixedColumnRepresentation default_value False schema column_schemas fixed_bool_without_default sch ColumnSchema tf bool 5 sch FixedColumnRepresentation schema column_schemas fixed_int_with_default sch ColumnSchema tf int64 1 sch FixedColumnRepresentation default_value 0 schema column_schemas fixed_categorical_int_with_range sch ColumnSchema sch IntDomain tf int64 5 10 True 1 sch FixedColumnRepresentation 0 schema column_schemas fixed_categorical_int_with_vocab sch ColumnSchema sch IntDomain tf int64 vocabulary_file test_filename 1 sch FixedColumnRepresentation 0 schema column_schemas fixed_int_without_default sch ColumnSchema tf int64 5 sch FixedColumnRepresentation schema column_schemas fixed_float_with_default sch ColumnSchema tf float32 1 sch FixedColumnRepresentation default_value 0 0 schema column_schemas fixed_float_without_default sch ColumnSchema tf float32 5 sch FixedColumnRepresentation schema column_schemas fixed_string_with_default sch ColumnSchema tf string 1 sch FixedColumnRepresentation default_value default schema column_schemas fixed_string_without_default sch ColumnSchema tf string 5 sch FixedColumnRepresentation schema column_schemas 3d_fixed_int_without_default sch ColumnSchema tf int64 5 6 7 sch FixedColumnRepresentation schema column_schemas var_bool sch ColumnSchema tf bool None sch ListColumnRepresentation schema column_schemas var_int sch ColumnSchema tf int64 None sch ListColumnRepresentation schema column_schemas var_float sch ColumnSchema tf float32 None sch ListColumnRepresentation schema column_schemas var_string sch ColumnSchema tf string None sch ListColumnRepresentation schema column_schemas sparse_bool sch ColumnSchema tf bool 15 sch SparseColumnRepresentation sparse_bool_value sch SparseIndexField sparse_bool_index True schema column_schemas sparse_int sch ColumnSchema tf int64 150 sch SparseColumnRepresentation sparse_int_value sch SparseIndexField sparse_int_index False schema column_schemas sparse_float sch ColumnSchema tf float32 1500 sch SparseColumnRepresentation sparse_float_value sch SparseIndexField sparse_float_index False schema column_schemas sparse_string sch ColumnSchema tf string 15000 sch SparseColumnRepresentation sparse_string_value sch SparseIndexField sparse_string_index True return schema
helper function to parse graphdef 's nodes .,def parse_graph_nodes graph_def name_to_node for node_def in graph_def node name_to_node node_def name node_def return name_to_node
creates a stats accumulator and returns a handle to it .,def __init__ self stamp_token gradient_shape hessian_shape name None container None if name is not None name _PATTERN sub name with ops name_scope name StatsAccumulator as name if gradient_shape tensor_shape scalar and hessian_shape tensor_shape scalar self _is_scalar True self _resource_handle gen_stats_accumulator_ops stats_accumulator_scalar_resource_handle_op container name name name create_op gen_stats_accumulator_ops create_stats_accumulator_scalar self _resource_handle stamp_token is_initialized_op gen_stats_accumulator_ops stats_accumulator_scalar_is_initialized self _resource_handle else self _is_scalar False self _resource_handle gen_stats_accumulator_ops stats_accumulator_tensor_resource_handle_op container name name name create_op gen_stats_accumulator_ops create_stats_accumulator_tensor self _resource_handle stamp_token gradient_shape as_list hessian_shape as_list is_initialized_op gen_stats_accumulator_ops stats_accumulator_tensor_is_initialized self _resource_handle self _create_op create_op slice_spec saver_name self _resource_handle name stamp_token num_updates partition_ids feature_ids gradients hessians self serialize specs saver BaseSaverBuilder SaveSpec stamp_token slice_spec saver_name _stamp saver BaseSaverBuilder SaveSpec num_updates slice_spec saver_name _num_updates saver BaseSaverBuilder SaveSpec partition_ids slice_spec saver_name _partition_ids saver BaseSaverBuilder SaveSpec feature_ids slice_spec saver_name _feature_ids saver BaseSaverBuilder SaveSpec gradients slice_spec saver_name _gradients saver BaseSaverBuilder SaveSpec hessians slice_spec saver_name hessians super StatsAccumulator self __init__ self _resource_handle specs name resources register_resource self _resource_handle create_op is_initialized_op ops add_to_collection ops GraphKeys SAVEABLE_OBJECTS self
create a new ` modelaveragecustomgetter ` .,def __init__ self worker_device self _worker_device worker_device self _local_2_global
condition a tensor based on a one - hot tensor .,def condition_tensor_from_onehot tensor one_hot_labels embedding_size 256 _validate_onehot one_hot_labels conditioning _one_hot_to_embedding one_hot_labels embedding_size return condition_tensor tensor conditioning
annotate the placement onto the specified metagraph .,def export_placement self metagraph for node in metagraph graph_def node if node name in self important_op_names node device self get_node_by_name node name device
returns whether actual_tensor 's shape is expected_shape .,def _is_shape expected_shape actual_tensor actual_shape None with ops name_scope is_shape values actual_tensor as scope is_rank _is_rank array_ops size expected_shape actual_tensor if actual_shape is None actual_shape array_ops shape actual_tensor name actual shape_equal _all_equal ops convert_to_tensor expected_shape name expected actual_shape return math_ops logical_and is_rank shape_equal name scope
combine adversarial loss and main loss .,def combine_adversarial_loss gan_loss gan_model non_adversarial_loss weight_factor None gradient_ratio None gradient_ratio_epsilon 1e 06 scalar_summaries True gradient_summaries True combined_loss losses_impl combine_adversarial_loss non_adversarial_loss gan_loss generator_loss weight_factor gradient_ratio gradient_ratio_epsilon gan_model generator_variables scalar_summaries gradient_summaries return gan_loss _replace generator_loss combined_loss
resnet-101 model of [ 1 ] . see resnet_v1 ( ) for arg and return description .,def resnet_v1_101 inputs num_classes None is_training True global_pool True output_stride None reuse None scope resnet_v1_101 blocks resnet_v1_block block1 base_depth 64 num_units 3 stride 2 resnet_v1_block block2 base_depth 128 num_units 4 stride 2 resnet_v1_block block3 base_depth 256 num_units 23 stride 2 resnet_v1_block block4 base_depth 512 num_units 3 stride 1 return resnet_v1 inputs blocks num_classes is_training global_pool output_stride include_root_block True reuse reuse scope scope
"assert that all given keys are present in the given collection , dict , list or tuple",def assert_all_in self keys collection exp_to_raise AssertionError for key in keys if key not in collection raise exp_to_raise return True
terminate video test source specified by index : param index : the index of the video source to terminate use get_test_video for finding the index,def terminate_index_video self index u Terminate video test source specified by index n param index The index of the video source to terminate n Use get_test_video for finding the index n try testsrc self _running_tests_video int index except IndexError raise InvalidIndexError u No video source with index 0 use get_test_video to determine index format index except ValueError raise InvalidIndexError u Index should be a valid integer except TypeError raise InvalidIndexError u Index should be a valid integer self log debug u terminating video source with pattern s testsrc pattern testsrc end self _running_tests_video remove self _running_tests_video index
method for recording a benchmark directly .,def _global_report_benchmark name iters None cpu_time None wall_time None throughput None extras None if extras is not None if not isinstance extras dict raise TypeError extras must be a dict logging info Benchmark s iters d wall_time g cpu_time g throughput g name iters if iters is not None else 1 wall_time if wall_time is not None else 1 cpu_time if cpu_time is not None else 1 throughput if throughput is not None else 1 test_env os environ get TEST_REPORTER_TEST_ENV None if test_env is None return entries test_log_pb2 BenchmarkEntries entry entries entry add entry name name if iters is not None entry iters iters if cpu_time is not None entry cpu_time cpu_time if wall_time is not None entry wall_time wall_time if throughput is not None entry throughput throughput if extras is not None for k v in extras items if isinstance v numbers Number entry extras k double_value v else entry extras k string_value str v serialized_entry entries SerializeToString mangled_name name replace __ output_path s s test_env mangled_name if gfile Exists output_path raise IOError File already exists s output_path with gfile GFile output_path wb as out out write serialized_entry
tests that loss goes down with training .,def testLinearModel self def input_fn return age tf constant 1 language tf SparseTensor values english indices 0 0 shape 1 1 tf constant 1 language tf contrib layers sparse_column_with_hash_bucket language 100 age tf contrib layers real_valued_column age head head_lib _multi_class_head n_classes 2 classifier LinearEstimator head feature_columns age language classifier fit input_fn input_fn steps 1000 loss1 classifier evaluate input_fn input_fn steps 1 loss classifier fit input_fn input_fn steps 2000 loss2 classifier evaluate input_fn input_fn steps 1 loss self assertLess loss2 loss1 self assertLess loss2 0 01
"deprecated , please use baseestimator.export .",deprecated 2016 09 23 Please use BaseEstimator export def export_estimator estimator export_dir signature_fn None input_fn _default_input_fn default_batch_size 1 exports_to_keep None _export_estimator estimator estimator export_dir export_dir signature_fn signature_fn input_fn input_fn default_batch_size default_batch_size exports_to_keep exports_to_keep
ensure set_defaults writes values under .,def test_set_defaults_does_not_overwrite config Config config env develop config set_defaults env production assert config env develop
"writes all data of read tuples and returns a list of all advisors , or on failures an empty one",def writeDegreeTuples tpls res for degree year title school degrees in tpls tidx dbase writeThesis degree year title school if tidx is None print sys stderr Search Failed on writing thesis tidx continue for sID aID in degrees if not dbase writeDegree sID aID tidx print sys stderr Search Failed on writing degrees d d sID aID continue res append aID return res
"method which evaluates the mixed second derivative . it calls the method "" s_s_der "" to obtain it ; at a first glance can appear useless , but it has the capability to be independent from the second derivative , so for the user is useful ; one has to change only the method "" s_s_der "" to mantain independence .",def e_m_s_der self x y z None try assert len x len y m_s_der ExactSolution2D s_m_s_der x y z msg Evaluated mixed second derivative extra_msg n str m_s_der self log_msg msg info extra_msg self _m_s_der m_s_der except AssertionError msg MPI Abort called setting second derivative for self log_msg msg self _comm_w Abort 1
return a pydot graph from a networkx graph n.,def to_pydot N strict True try import pydot except ImportError raise ImportError to_pydot requires pydot http code google com p pydot if N is_directed graph_type digraph else graph_type graph strict N number_of_selfloops 0 and not N is_multigraph name N graph get name graph_defaults N graph get graph if name is None P pydot Dot graph_type graph_type strict strict graph_defaults else P pydot Dot s name graph_type graph_type strict strict graph_defaults try P set_node_defaults N graph node except KeyError pass try P set_edge_defaults N graph edge except KeyError pass for n nodedata in N nodes_iter data True str_nodedata dict k str v for k v in nodedata items p pydot Node str n str_nodedata P add_node p if N is_multigraph for u v key edgedata in N edges_iter data True keys True str_edgedata dict k str v for k v in edgedata items edge pydot Edge str u str v key str key str_edgedata P add_edge edge else for u v edgedata in N edges_iter data True str_edgedata dict k str v for k v in edgedata items edge pydot Edge str u str v str_edgedata P add_edge edge return P
testing whether the tunnelcommunity does not reload itself after unloading,blocking_call_on_reactor_thread inlineCallbacks def test_unload_receive self tunnel_community self session lm tunnel_community dispersy self session lm dispersy some_candidate Candidate 1 2 3 4 1234 False some_packet self create_valid_packet tunnel_community dispersy on_incoming_packets some_candidate some_packet self assertIn tunnel_community dispersy get_communities yield tunnel_community unload_community self assertNotIn tunnel_community dispersy get_communities for community in dispersy get_communities self assertNotIsInstance community HiddenTunnelCommunity dispersy on_incoming_packets some_candidate some_packet for community in dispersy get_communities self assertNotIsInstance community HiddenTunnelCommunity
testing whether the encoding of an error packet is correct,def test_encode_packet_error self encoded encode_packet opcode OPCODE_ERROR session_id 123 error_code 1 error_msg hi self assertEqual encoded 3 h self assertEqual encoded 2 i
return when the order is going to expire : rtype : timeout,property def timeout self return self _timeout
montage _ tv*.jpg -tile 8x8 -geometry 100x66 + 0 + 0 montage.jpg # grid of images not using : convert tv*.jpg -append sprite.jpg # single vertical line of images not using : convert tv*.jpg + append sprite.jpg # single horizontal line of images base the sprite size on the number of thumbs we need to make into a grid .,def makesprite outdir spritefile coords gridsize grid dx d gridsize gridsize cmd montage s tv jpg tile s geometry s s pipes quote outdir grid coords pipes quote spritefile doCmd cmd
"validate , build message and convert to string",def as_string self u self validate self make return self msg_root as_string
dat : an instance of data candidate_kernels : a list of kernel 's to choose from tr_proportion : proportion of sample to be used to choosing the best kernel reg : regularization parameter for the test power criterion,def perform_test self dat candidate_kernels None return_mmdtest False tr_proportion 0 2 reg 0 001 with util ContextTimer as t seed self seed p self p ds p get_datasource p_sample ds sample dat sample_size seed seed 77 xtr xte p_sample split_tr_te tr_proportion tr_proportion seed seed 18 ytr yte dat split_tr_te tr_proportion tr_proportion seed seed 12 tr_tst_data fdata TSTData xtr data ytr data te_tst_data fdata TSTData xte data yte data if candidate_kernels is None med util meddistance tr_tst_data stack_xy 1000 list_gwidth np hstack med 2 2 0 np linspace 4 4 10 list_gwidth sort candidate_kernels kernel KGauss gw2 for gw2 in list_gwidth alpha self alpha besti powers tst QuadMMDTest grid_search_kernel tr_tst_data candidate_kernels alpha reg reg best_ker candidate_kernels besti mmdtest tst QuadMMDTest best_ker self n_permute alpha alpha results mmdtest perform_test te_tst_data if return_mmdtest results mmdtest mmdtest results time_secs t secs return results
return the contents of the file at the given path as a unicode string .,def read_text_file self path with codecs open path r utf8 as f return f read
construct the poly symmetry plugin menu .,def _initializePlugin args if cmds about batch True return _try_delete_menu cmds menu _POLY_REORDER_MENU_ITEMS label Poly Reorder parent MayaWindow for item in _POLY_REORDER_MENU_ITEMS _addMenuItem item _addMenuItem _MenuItem Reload Menu _initializePlugin cmds menuSet riggingMenuSet addMenu _POLY_REORDER_MENU_NAME
revoke roles from users and/or groups for a project,def revoke_roles self users None groups None roles None if users is None users if isinstance users User users users if groups is None groups if isinstance groups Group groups groups if roles is None roles if isinstance roles Role roles roles for role in roles for user in users self _http delete self _url_resource_path self _id users user get_id roles role get_id for group in groups self _http delete self _url_resource_path self _id groups group get_id roles role get_id
"process the queue , possibly modifying it . may return a command .",def process queue command None last_temp _get_last_sample queue temp if last_temp and last_temp 1 MAX_TEMP LOG info shutting down since temperature of s exceeds maximum of s last_temp 1 MAX_TEMP queue status common timestamp shutdown CPU temp s max s last_temp 1 MAX_TEMP command exit 100 else queue status common timestamp ok return command
initialise an instance of a module makefile .,def __init__ self args kw if qt not in kw kw qt QtCore QtGui QtNetwork QtDeclarative QtNetworkModuleMakefile __init__ self args kw
creates a temporary directory and defines the tde path as temp_dir+view_or_table_name.tde,def _build_temp_tdepath self temp_dir_path tempfile mkdtemp _ __ extract_name get_db_components self _view_or_table_name file_name tde format extract_name self _tde_path os path join temp_dir_path file_name
polls with a pub_date in the future should not be displayed on the index page .,def test_index_view_with_a_future_poll self create_poll question Future poll days 30 response self client get reverse polls index self assertContains response No polls are available status_code 200 self assertQuerysetEqual response context latest_poll_list
returns length aligned to the align_to byte boundary,staticmethod def padded length return length Decoder __ALIGN_TO 1 Decoder __ALIGN_TO 1
"the activity , should be verified by the dispatch method .",property def activity self return self kwargs activity
handle syntax : no exception if too many slashes in handle .,def test_check_handle_syntax_two_slashes self check_handle_syntax foo bar foo
writes a 16-bit value to the specified register / address pair,def write16 self reg value try self bus write_word_data self address reg value if self debug print I2C Wrote 0x 02X to register pair 0x 02X 0x 02X value reg reg 1 except IOError as err erreur self errMsg i2cLogger debug Error writing a 16 bit value to the specified register address pair s erreur return self errMsg
set a flightgear property value .,def __setitem__ self key value self telnet set key value
traceback display a list of the tracebacks that have been captured from past exceptions .,def do_tracebacks self line print self stdout _tracebacks
calculate the batched kl divergence kl(g0 || g1 ) with g0 and g1 gamma .,kullback_leibler RegisterKL Gamma Gamma def _kl_gamma_gamma g0 g1 name None with ops name_scope name kl_gamma_gamma values g0 concentration g0 rate g1 concentration g1 rate return g0 concentration g1 concentration math_ops digamma g0 concentration math_ops lgamma g1 concentration math_ops lgamma g0 concentration g1 concentration math_ops log g0 rate g1 concentration math_ops log g1 rate g0 concentration g1 rate g0 rate 1 0
returns a new http client for an hdfs cluster using an hdfsconfig object,def get_hdfs_client_from_conf conf hostport conf get dfs namenode http address if hostport is None raise Exception dfs namenode http address not found in config host port hostport split return get_hdfs_client host host port port
returns string containing proxy details .,def get_proxy self return self _proxy
reseting the values for the latent layer,def reset_prior self nu 10 self reset_nus nu self reset_Sigma_theta self update_GMM
"quick access to pre - configured experimental configurations . input : * exp : string , name of the experiment to simulated output : * noise_uk_arcmin : float , level of noise in uk.arcmin * fwhm_arcmin : float , beam size ( fwhm ) in arcmin * lmin : int , minimum multipole for the reconstruction * lmax : int , maximum multipole for the reconstruction * folder_cache : string , where the data will be saved",def get_exp_configuration exp _test_ do_cori False do_edison False if os getenv NERSC_HOST cori do_cori True folder_cache os path join os getenv SCRATCH cache elif os getenv NERSC_HOST edison do_edison True folder_cache os path join os getenv SCRATCH cache else folder_cache cache if exp _test_ lmin 2 lmax 250 noise_uK_arcmin 1 0 fwhm_arcmin 1 0 TTcorr False elif exp Planck From Schmittfull et al 13 lmin 2 lmax 2500 noise_uK_arcmin 27 0 fwhm_arcmin 7 0 TTcorr False elif exp Core From Jojo article 1509 06770 150 GHz lmin 2 lmax 4000 noise_uK_arcmin 5 0 fwhm_arcmin 6 0 TTcorr False elif exp CMB S4 From Jojo article 1509 06770 150 GHz Comment I find the lmax a bit low however if we take into account that the main contribution at high ell is the point source contribution foregrounds etc it sounds somehow ok lmin 20 lmax 3000 noise_uK_arcmin 1 5 fwhm_arcmin 3 0 TTcorr False elif exp CMB S4_noisecorr Same as above but with a correlated noise component for the noise lmin 20 lmax 3000 noise_uK_arcmin 1 5 fwhm_arcmin 3 0 TTcorr 1000 return noise_uK_arcmin fwhm_arcmin lmin lmax TTcorr folder_cache
run the text as python code .,def run self info info object run return
parse a multiline with size as first elements and n points as rest,def parse_multiline line elems float x for x in line split count int elems pop 0 points while count 0 points append elems 0 3 elems elems 3 count 1 return points
e.g. ' 6:30pm ' or ' 5 am ',def get_human_time self obj return dateformat format obj starts_at fa replace
validate an entity by looking up the core schema for its type and overriding it with any project level overrides,def validate_entity entity schemata project None name local_schema get_project_specific_schema projects project schemata entity type entity type result validate entity local_schema return result
computes length of the longest palindromic substring centered on each char in the given string . the idea behind this algorithm is to reuse previously computed values whenever possible ( palindromes are symmetric ) .,def manacher string if type string is not str raise TypeError Manacher Algorithm only excepts strings not format str type string string_with_bounds join format string length len string_with_bounds P 0 length center right 0 for i in range 1 length 1 P i right i and min right i P 2 center i while string_with_bounds i 1 P i string_with_bounds i 1 P i P i 1 if i P i right center right i i P i maxLen centerIndex max n i for i n in enumerate P return string centerIndex maxLen 2 centerIndex maxLen 2
generator which yields all config variables of this app .,def get_config_variables yield ConfigVariable name assignments_poll_vote_values default_value auto input_type choice label Election method choices value auto display_name Automatic assign of method value votes display_name Always one option per candidate value yesnoabstain display_name Always Yes No Abstain per candidate value yesno display_name Always Yes No per candidate weight 410 group Elections subgroup Ballot and ballot papers yield ConfigVariable name assignments_poll_100_percent_base default_value YES_NO_ABSTAIN input_type choice label The 100 base of an election result consists of choices value YES_NO_ABSTAIN display_name Yes No Abstain per candidate value YES_NO display_name Yes No per candidate value VALID display_name All valid ballots value CAST display_name All casted ballots value DISABLED display_name Disabled no percents help_text For Yes No Abstain per candidate and Yes No per candidate the 100 base depends on the election method If there is only one option per candidate the sum of all votes of all candidates is 100 Otherwise for each candidate the sum of all votes is 100 weight 420 group Elections subgroup Ballot and ballot papers yield ConfigVariable name assignments_poll_default_majority_method default_value simple_majority input_type majorityMethod label Required majority help_text Default method to check whether a candidate has reached the required majority weight 425 group Elections subgroup Ballot and ballot papers yield ConfigVariable name assignments_add_candidates_to_list_of_speakers default_value True input_type boolean label Put all candidates on the list of speakers weight 428 group Elections subgroup Ballot and ballot papers yield ConfigVariable name assignments_pdf_ballot_papers_selection default_value CUSTOM_NUMBER input_type choice label Number of ballot papers selection choices value NUMBER_OF_DELEGATES display_name Number of all delegates value NUMBER_OF_ALL_PARTICIPANTS display_name Number of all participants value CUSTOM_NUMBER display_name Use the following custom number weight 430 group Elections subgroup Ballot and ballot papers yield ConfigVariable name assignments_pdf_ballot_papers_number default_value 8 input_type integer label Custom number of ballot papers weight 440 group Elections subgroup Ballot and ballot papers validators MinValueValidator 1 yield ConfigVariable name assignments_pdf_title default_value Elections label Title for PDF document all elections weight 460 group Elections subgroup PDF yield ConfigVariable name assignments_pdf_preamble default_value label Preamble text for PDF document all elections weight 470 group Elections subgroup PDF
returns file object . ' filename ' should be the fragment of the filepath below the collection test dir .,def collection_file_obj filename fp collection_source_path filename filename return codecs open fp mode r encoding utf 8
look up network port configuration . this tells us if a port in the host is bound to a port inside the container .,def getPortConfiguration self port protocol tcp info self inspect key format port protocol try return info NetworkSettings Ports key except return
provides a scope that changes to ` _ global_custom_objects ` can not escape .,def custom_object_scope args return CustomObjectScope args
test for specific scopes that the access token has been authenticated for before processing the request and eventual response .,def scope_required scopes def decorator view_func wraps view_func assigned available_attrs view_func def _wrapped_view request args kwargs from django http import HttpResponseBadRequest HttpResponseForbidden from exceptions base import InvalidRequest InsufficientScope from models import Scope from utils import request_error_header try if not hasattr request access_token raise CredentialsNotProvided access_token request access_token for scope_name in scopes try scope access_token scope for_short_name scope_name except Scope DoesNotExist raise ScopeNotEnough except InvalidRequest as e response HttpResponseBadRequest response WWW Authenticate request_error_header e return response except InsufficientScope as e response HttpResponseForbidden response WWW Authenticate request_error_header e return response return view_func request args kwargs return _wrapped_view if scopes and hasattr scopes 0 __call__ func scopes 0 scopes scopes 1 return decorator func return decorator
create new user group using multiple users attached to that group .,tier1 def test_positive_create_with_users self users entities User create for _ in range randint 3 5 user_group entities UserGroup user users create self assertEqual sorted user login for user in users sorted user read login for user in user_group user
power on a machine on rhev using apiv4,tier2 def test_positive_v4_wui_virtual_machines_can_be_powered_on session module_rhev4 vm_poweron session module_rhev4
verifies that appending filters with instance methods works .,def testAppend self multi_filter ee Filter eq foo 1 eq bar 2 eq baz 3 self assertEquals 3 multi_filter predicateCount
"emit ' class=""active "" ' if running in the specified language .",register simple_tag name active_if_lang def active_if_lang request language_code if language_code request LANGUAGE_CODE return class active else return
return a populated object object from dictionary datas,def create_from_name_and_dictionary self name datas if type not in datas str_type any else str_type str datas type lower if str_type not in ObjectRaw Types type ObjectRaw Types type else type ObjectRaw Types str_type if type is ObjectRaw Types object object ObjectObject if properties in datas object properties self create_dictionary_of_element_from_dictionary properties datas if patternProperties in datas object pattern_properties self create_dictionary_of_element_from_dictionary patternProperties datas if additionalProperties in datas if isinstance datas additionalProperties dict object additional_properties self create_from_name_and_dictionary additionalProperties datas additionalProperties elif not to_boolean datas additionalProperties object additional_properties None else raise ValueError AdditionalProperties doe not allow empty value yet elif type is ObjectRaw Types array object ObjectArray if items in datas object items self create_from_name_and_dictionary items datas items else object items ObjectObject if sample_count in datas object sample_count int datas sample_count elif type is ObjectRaw Types number object ObjectNumber elif type is ObjectRaw Types integer object ObjectInteger elif type is ObjectRaw Types string object ObjectString elif type is ObjectRaw Types boolean object ObjectBoolean if sample in datas object sample to_boolean datas sample elif type is ObjectRaw Types reference object ObjectReference if reference in datas object reference_name str datas reference elif type is ObjectRaw Types type object ObjectType object type_name str datas type elif type is ObjectRaw Types none object ObjectNone elif type is ObjectRaw Types dynamic object ObjectDynamic if items in datas object items self create_from_name_and_dictionary items datas items if sample in datas if isinstance datas sample dict object sample for k v in datas sample items object sample str k str v else raise ValueError A dictionnary is expected for dynamic s object in s name elif type is ObjectRaw Types const object ObjectConst if const_type in datas const_type str datas const_type if const_type not in ObjectConst Types raise ValueError Const type s unknwon const_type else const_type ObjectConst Types string object const_type const_type if value not in datas raise ValueError Missing const value object value datas value elif type is ObjectRaw Types enum object ObjectEnum if values not in datas or not isinstance datas values list raise ValueError Missing enum values object values str value for value in datas values if descriptions in datas and isinstance datas descriptions dict for value_name value_description in datas descriptions items value EnumValue value name value_name value description value_description object descriptions append value descriptions description name for description in object descriptions for value_name in x for x in object values if x not in descriptions value EnumValue value name value_name object descriptions append value else object ObjectRaw self set_common_datas object name datas if isinstance object Constraintable self set_constraints object datas object type type if optional in datas object optional to_boolean datas optional return object
pull out the transport metadata for each packet in the input_stream,def transport_meta_data self for item in self input_stream trans_data item packet data trans_type self _get_transport_type trans_data if trans_type and trans_data item transport data_utils make_dict trans_data item transport type trans_type item transport flags self _readable_flags item transport item transport data trans_data data yield item
make the difficult decisions in life .,command permission view use_shlex False def decide self mask target args options join args options for delimiter in DECIDE_DELIMITERS options options replace delimiter options options split options list filter None set option replace delimiter strip for delimiter in DECIDE_DELIMITERS for option in options if option not in DECIDE_DELIMITERS options remove delimiter strip for delimiter in DECIDE_DELIMITERS if delimiter strip in options self bot log debug Parsed options s options if not options return 0 I can t make a decision for you if you don t give me any choices V format mask nick options_length len options if options_length 1 options Yes Maybe No return 0 1 format mask nick random choice options
overrides the token eq to allow for magic : alias comparison for magic inputs . defaults to the super ( ) eq otherwise .,def __eq__ self other try return self magic other alias or super Output self __eq__ other except AttributeError return False
test node view with no / alias : return : none,def test_node_view_with_no_front self Node objects all delete create_front wrong slug assert_no_front self
... test that modelhawkesexpkernleastsq gradient is consistent with loss,def test_model_hawkes_least_sq_grad self for model in self model self model_list self assertLess check_grad model loss model grad self coeffs 1e 05 coeffs_min fmin_bfgs model loss self coeffs fprime model grad disp False self assertAlmostEqual norm model grad coeffs_min 0 0 delta 0 0001
figure for comparing the layer distributions on log pressure and linear pressure scales against the temperature vertical profile .,def show_atmosphere_structures model filename None import matplotlib pyplot as plt fig axs plt subplots ncols 3 nrows 2 figsize 19 11 fig subplots_adjust hspace 0 2 wspace 0 3 for i method in enumerate linear_pressure split_at_tropopause log_pressure axs 0 i set_title method plot_structure set_HASI_structure nlev model nlev method method logP True ax axs 0 i plot_structure set_HASI_structure nlev model nlev method method logP False ax axs 1 i if filename savefig filename
` < https://docs.exchange.coinbase.com/#time > ` _,def get_time self return self _get time
"returns instead of a ` match ` object only it 's value , also if we have only one match , return it instead of returning a list with one ` match `",def _unpack match_group unpacked match value for match in match_group if len unpacked 1 unpacked unpacked 0 return unpacked
open the url in the specified request .,def open self request raise Exception not implemented
! @brief performs image segmentation .,def process self image_source collect_dynamic False order_color 0 9995 order_object 0 999 self __order_color order_color self __order_object order_object data read_image image_source color_analyser self __analyse_colors data collect_dynamic if self __object_radius is None return syncsegm_analyser color_analyser None object_segment_analysers self __analyse_objects image_source color_analyser collect_dynamic return syncsegm_analyser color_analyser object_segment_analysers
return top of git tree where autotest is running from,def topdir d os path dirname os path realpath __file__ assert os path basename d pysim d os path dirname d assert os path basename d autotest d os path dirname d assert os path basename d Tools d os path dirname d return d
overidden - called when a charref ( & # xyz ) is parsed,def handle_charref self name self out_doc name
write the primary value to jout . reduces first dataseries .,def _write_primary self reduce_func self _qformat_get reduce LAST dseries self mdseries get_series 0 value dseries reduce reduce_func self jout item value
add a little down - arrow to start completion ( list all available tags ),def initDownButton self u add a little down arrow to start completion n list all available tags downIcon qtawesome icon u fa sort down self downButton QtGui QPushButton downIcon u self self downButton setStyleSheet u border 0px padding 0px self downButton setCursor QtCore Qt ArrowCursor self downButton setFocusPolicy QtCore Qt NoFocus self downButton clicked connect self onDownPressed frameWidth self style pixelMetric QtGui QStyle PM_DefaultFrameWidth buttonSize self downButton sizeHint self setStyleSheet u QLineEdit padding right dpx buttonSize width frameWidth self setMinimumSize max self minimumSizeHint width buttonSize width frameWidth 2 max self minimumSizeHint height buttonSize height frameWidth 2
"performs logic needed to determine if changing a retention_tag is valid , returns an error fit for displaying in widget",classmethod def update_product cls job product retentiontag job retention_tag if not retentiontag requires_product and product None return success False msg Current retention tag does not support a product vars cls _needs_tag 1 VALID_TAGS tag id tag tag for tag in RetentionTag list_by_requires_product if retentiontag requires_product and product None return success False msg Current retention tag requires a product vars cls _needs_tag 1 VALID_TAGS tag id tag tag for tag in RetentionTag list_by_requires_product False job product product return success True
converts a filesystem string to a path object .,def fromstr self string split_string string split os path sep for each in split_string if each continue self add each
you need to extend this constructor to add more journal export init step by using the parameters from kwargs,def __init__ self user_clbk _kwargs u you need to extend this constructor to add more journal export init n step by using the parameters from kwargs n self _user_clbk user_clbk
write zookeeper data to filesystem .,def _write_data self fpath data stat u Write Zookeeper data to filesystem n zksync_utils write_data fpath data stat last_modified raise_err True tmp_dir self tmp_dir
test the get_readonly_scheduler ( ) func .,mock patch u treadmill context GLOBAL mock Mock cell u test mock patch u treadmill context ZkContext conn mock Mock mock patch u treadmill scheduler loader Loader mock patch u treadmill scheduler zkbackend mock Mock def test_get_readonly_scheduler self loader_mock u now scheduler _CACHE_TIMEOUT 1 with mock patch u time time return_value now scheduler get_readonly_scheduler self assertTrue loader_mock called self assertEqual scheduler _LAST_CACHE_UPDATE now loader_mock reset_mock now now scheduler _CACHE_TIMEOUT 1 with mock patch u time time return_value now scheduler get_readonly_scheduler self assertTrue loader_mock called self assertEqual scheduler _LAST_CACHE_UPDATE now loader_mock reset_mock now now scheduler _CACHE_TIMEOUT 1 with mock patch u time time return_value now scheduler get_readonly_scheduler self assertFalse loader_mock called
get the number of apps in treadmill / apps,def app_cgrp_count u appcount 0 basepath cgroups makepath u memory u treadmill apps files os listdir basepath for appname in files fullpath os path join basepath appname if os path isdir fullpath appcount 1 return appcount
"raw data , a word at a time , big - endian",def pragmaWordbe ppt line result words readData line result append IR Node ppt WordBE words
"loads sar format logfile in ascii format ( sarxx ) . : return : `` true `` if loading and parsing of file went fine , `` false `` if it failed ( at any point )",def load_file self searchunks self _split_file if searchunks usage self _parse_file searchunks if CPU in usage return False self _sarinfo usage del usage return True else return False
"description : creates a most recent - oldest mosaic of the input dataset . if no clean mask is given , the ' cf_mask ' variable must be included in the input dataset , as it will be used to create a clean mask ----- inputs : dataset_in ( xarray . dataset ) - dataset retrieved from the data cube ; should contain coordinates : time , latitude , longitude variables : variables to be mosaicked if user does not provide a clean_mask , dataset_in must also include the cf_mask variable optional inputs : clean_mask ( nd numpy array with dtype boolean ) - true for values user considers clean ; if user does not provide a clean mask , one will be created using cfmask no_data ( int / float ) - no data pixel value ; default : -9999 output : dataset_out ( xarray . dataset ) - mosaicked data with coordinates : latitude , longitude variables : same as dataset_in",def create_mosaic dataset_in clean_mask None no_data 9999 if not clean_mask cfmask dataset_in cf_mask clean_mask utilities create_cfmask_clean_mask cfmask data_vars dataset_in data_vars mosaic collections OrderedDict for key in data_vars data data_vars key values masked np full data shape no_data masked clean_mask data clean_mask out np full masked shape 1 no_data for index in reversed range len clean_mask swap np reshape np in1d out reshape 1 no_data out shape out swap masked index swap mosaic key latitude longitude out latitude dataset_in latitude longitude dataset_in longitude dataset_out xr Dataset mosaic coords latitude latitude longitude longitude return dataset_out
global values to pass to templates,def resource_urls request url_parsed urlparse settings SEARCH_URL defaults dict APP_NAME __description__ APP_VERSION __version__ SITE_URL settings SITE_URL rstrip SEARCH_TYPE settings SEARCH_TYPE SEARCH_URL settings SEARCH_URL SEARCH_IP s s s url_parsed scheme url_parsed hostname url_parsed port return defaults
converts the short - hand nested dictionary structure into a series of triples .,def nested_to_triples nested parent_value None as_vars False id None triples if isinstance nested dict nested nested items if parent_value is None for k v in nested triples extend nested_to_triples v parent_value k as_vars as_vars else for predicate rest in nested if parent_value is None subject DONT_CARE else subject parent_value id DONT_CARE extra None if in subject subject extra subject split 0 subject split 1 for ex in extra attr val ex split assert attr in id Only id inline attribute supported exec s s attr val if in predicate predicate extra predicate split 0 predicate split 1 for ex in extra attr val ex split assert attr in id Only id inline attribute supported exec s s attr val if type rest in tuple list dict if as_vars object str uuid uuid4 else object str uuid uuid4 if as_vars triples append id subject predicate object else triples append id subject predicate object triples extend nested_to_triples rest parent_value object as_vars as_vars else if isinstance rest basestring and in rest rest extra rest split 0 rest split 1 for ex in extra attr val ex split assert attr in id Only id inline attribute supported exec s s attr val if as_vars triples append id subject predicate rest else triples append id subject predicate rest return triples
set the base url to be retrieved .,def set_url self url self base_url url self set_option pycurl URL self base_url
return the distribution that data is being compared against,property def distribution self return self _distribution
called for list + proxfn .,def __radd__ self other if type other list return other self else return NotImplemented
use ' h hitch --help ' to get help on these commands .,def hitch args hitch_maintenance args
called when the base address field is changed .,def _base_changed self cell path new_text col if len path 1 return try value int new_text 16 except ValueError LOGGER error Illegal address 0 format new_text return if new_text node self _model get_iter path name self _model get_value node AddrMapMdl NAME_COL fixed self _model get_value node AddrMapMdl FIXED_COL uvm self _model get_value node AddrMapMdl UVM_COL width STR2SIZE self _model get_value node AddrMapMdl WIDTH_COL self _prj set_address_map name value width fixed uvm self _model path AddrMapMdl BASE_COL new_text self _prj modified True
"to create a new key , we simply make sure that the modified flag is set so that the cookie is set on the client for the current request .",def create self self modified True
manually set exposed ports always override automatically exposed ports .,def test_portmapping ports telepresence cli PortMapping parse 1234 80 90 ports merge_automatic_ports 80 555 666 assert ports local_to_remote 1234 80 90 90 555 555 666 666 assert ports remote 80 90 555 666
make sure .jpeg synonym works in cli,def test_jpeg_synonym_cli self jpeg_filename self get_jpeg_filename self raw_text_filename self compare_cli_output jpeg_filename self get_expected_filename self raw_text_filename os remove jpeg_filename
"return a human - readable "" backtrace "" from the document root to the specified element .",def Backtrace self elt return _backtrace elt _getNode self dom _getNode
returns true if the passed category is the current category .,def _is_current_category request category id request path split 1 return str category id id
calculates the distance between two points on earth .,def _calculate_distance latlon1 latlon2 lat1 lon1 latlon1 lat2 lon2 latlon2 dlon lon2 lon1 dlat lat2 lat1 R 6371 a np sin dlat 2 2 np cos lat1 np cos lat2 np sin dlon 2 2 c 2 np pi R np arctan2 np sqrt a np sqrt 1 a 180 return c
returns the name of the primary key column for the given table,def get_primary_key_column self cursor table_name for column in self get_indexes cursor table_name items if column 1 primary_key return column 0 return None
opens a new window and jumps to declaration if possible,def _jump_to_in_window self filename line_number None column_number None transient False active_window self view window try if self view sel 0 self point self view sel clear self view sel add self point except AttributeError pass if isinstance filename int if filename 1 active_window focus_view self view self view show self point return filename line_number column_number self options filename flags self prepare_layout active_window transient filename active_window open_file s s s filename line_number or 0 column_number or 0 flags
move at specified velocity in meters / sec with absolute heading ( if already in guided mode ),def move_at_ned_vel self north 0 0 east 0 0 down 0 0 yaw 0 0 msg PprzMessage datalink GUIDED_SETPOINT_NED msg ac_id self ac_id msg flags 96 msg x north msg y east msg z down msg yaw yaw print move at vel NED s msg self _interface send_raw_datalink msg
adds response counts of various types,def get_for_inbox user if user is_anonymous return None flag_activity_types const TYPE_ACTIVITY_MARK_OFFENSIVE if askbot_settings ENABLE_CONTENT_MODERATION flag_activity_types const TYPE_ACTIVITY_MODERATED_NEW_POST const TYPE_ACTIVITY_MODERATED_POST_EDIT group_join_requests_count 0 if user is_administrator_or_moderator pending_memberships GroupMembership objects filter group__in user get_groups level GroupMembership PENDING group_join_requests_count pending_memberships count return re_count user new_response_count user seen_response_count flags_count user get_notifications flag_activity_types count group_join_requests_count group_join_requests_count
see what 's faster at int key lookup : dicts or lists .,def test_lists_vs_dicts list_time timeit item l 9000 l 0 10000 dict_time timeit item d 9000 d x 0 for x in range 10000 ok_ list_time dict_time s s list_time dict_time
get_requirements reads in requirements and versions from the lookup obtained with get_lookup,def get_requirements lookup None if lookup None lookup get_lookup install_requires for module in lookup INSTALL_REQUIRES module_name module 0 module_meta module 1 if exact_version in module_meta dependency s s module_name module_meta exact_version elif min_version in module_meta if module_meta min_version None dependency module_name else dependency s s module_name module_meta min_version install_requires append dependency return install_requires
check if file / folder is versioned .,def is_versioned target assert exists target s does not exist target git_tree get_git_tree target versioned False if git_tree is not None output gitopen status ignored porcelain target git_tree if not output startswith or output startswith versioned True return versioned
internal method to get the content of a node : param node : : param path : : return :,def nodeContent self node path ns http xml vidispine com schema vidispine try return node find 0 1 format ns path text except StandardError return None
grab an exclusive lock on the preserved libs registry .,def lock self if self _lock is not None raise AssertionError already locked self _lock lockfile self _filename
@param errcodes dictionary of error codes - > explainations,def __init__ self errcodes self errcodes errcodes return
autogenerated many - to - many inlines are displayed correctly ( # 13407 ),def test_many_to_many_inlines self response self client get test_admin admin admin_inlines author add self assertContains response h2 Author book relationships h2 self assertContains response Add another Author Book Relationship self assertContains response id id_Author_books TOTAL_FORMS
regression test for # 12550 : display_for_field should handle none value .,def test_null_display_for_field self display_value display_for_field None models CharField self assertEqual display_value EMPTY_CHANGELIST_VALUE display_value display_for_field None models CharField choices None test_none self assertEqual display_value test_none display_value display_for_field None models DateField self assertEqual display_value EMPTY_CHANGELIST_VALUE display_value display_for_field None models TimeField self assertEqual display_value EMPTY_CHANGELIST_VALUE display_value display_for_field None models NullBooleanField expected u img src simg admin icon unknown gif alt None settings ADMIN_MEDIA_PREFIX self assertEqual display_value expected display_value display_for_field None models DecimalField self assertEqual display_value EMPTY_CHANGELIST_VALUE display_value display_for_field None models FloatField self assertEqual display_value EMPTY_CHANGELIST_VALUE
regression for # 13095 : using base forms with widgets defined in meta should not raise errors .,def test_baseform_with_widgets_in_meta self widget forms Textarea class BaseForm forms ModelForm class Meta model Person widgets name widget Form modelform_factory Person form BaseForm self assertTrue Form base_fields name widget is widget
"search for all unused elements : return : list of dict items holding href , type and name",def search_unused return element_by_href_as_json fetch_entry_point search_unused
: return : a jsonapi compliant response object,def respond self dict_ self to_dict return make_response json dumps jsonapi_errors dict_ self status self headers
: return : the internal polygon defining the roi . : rtype : : class:`~numpy.ndarray `,property def polygon self return self _polygon
"500 error handler . templates : ` 500.html ` context : static_url path of static media ( e.g. "" media.example.org "" )",def server_error request template_name 500 html t loader get_template template_name return HttpResponseServerError t render Context STATIC_URL settings STATIC_URL
verifies percentiles when there are not latency values .,def testNoLatencies self percentiles cli CalculatePercentiles expected_percentiles 0 50 75 90 95 99 100 for actual expected in zip percentiles expected_percentiles self assertEqual actual 0 expected self assertTrue math isnan actual 1
"initialize the combobox , building the display column .",def __init__ self model None Gtk ComboBox __init__ self self set_model model cell Gtk CellRendererText self pack_start cell True self add_attribute cell text 0
method called when active person changes .,def active_changed self handle self update
return the column number of the note tab .,def on_get_n_columns self return len self fmap 1
return the tag name from the given tag handle .,def get_tag_name self tag_handle cached value self get_cached_value tag_handle TAG_NAME if not cached value self db get_tag_from_handle tag_handle get_name self set_cached_value tag_handle TAG_NAME value return value
update the list of tags in the tag filter .,def on_tags_changed self tag_list model Gtk ListStore str model append for tag_name in tag_list model append tag_name self tag set_model model self tag set_active 0
set the presence or absence of rigth border .,def set_right_border self val self right_border val
returns the time to live ( ttl ) in seconds,def get_ttl self return int from_bytes self data 36 38 byteorder big
"return config parser , or none if config file can not be found .",def get_config_parser self defaults if self config_parser is None config_file self get_config_file self config_parser ConfigParser ConfigParser defaults if os path exists config_file self config_parser read config_file if self config_parser is not None self config_parser defaults defaults return self config_parser
retrieves historical stock data for the provided symbol .,def get_historical_info symbol from_dt None to_dt None if from_dt is None or to_dt is None date_string else date_string a d b d c d d d e d f d g d ignore csv from_dt month 1 from_dt day from_dt year to_dt month 1 to_dt day to_dt year yql select from csv where url s and columns Date Open High Low Close Volume AdjClose HISTORICAL_URL symbol date_string response execute_yql_query yql results __validate_response response row del results 0 return results
key name for this attribute in json dictionary . defaults to the attribute name in the class it is bound to .,property def json_name self return self name if self _json_name is _default else self _json_name
can make a group not public,def test_03_change_group_not_public self dog self dog meowers self meowers self assertFalse dog uaccess owns_group meowers self assertFalse dog uaccess can_change_group meowers self assertTrue dog uaccess can_view_group meowers meowers gaccess public False meowers gaccess save self assertFalse meowers gaccess public self assertTrue meowers gaccess discoverable self assertTrue meowers gaccess shareable self assertFalse dog uaccess owns_group meowers self assertFalse dog uaccess can_change_group meowers self assertFalse dog uaccess can_view_group meowers self assertFalse self admin uaccess owns_group meowers self assertTrue self admin uaccess can_change_group meowers self assertTrue self admin uaccess can_view_group meowers
hook method executed once when the cmdloop ( ) method is called .,def preloop self pass
certain options support string values . we want clients to be able to pass python strings in but we need them to be quoted in the output . unfortunately some of those options also allow numbers so we type check the value before wrapping it in quotes .,def quote key value if key in quoted_options and isinstance value string_types return s value if key in quoted_bool_options and isinstance value bool return True true False false value return value
copy everything but the point data .,def header self points None points list points if points else return self _replace points points
factory method for a member representing all authenticated users .,staticmethod def authenticated_users return allAuthenticatedUsers
"all the arguments are lists returns a list of dictionaries ; each dictionary "" represent "" an attachment",def attach_list filepaths notes assert type filepaths in list tuple assert type notes in list tuple if len filepaths len notes die The number of filepath and notes must be the same attach_list for fname note in zip filepaths notes name os path basename fname assert os path exists fname mime mimetypes guess_type fname 0 if mime is not None and not in mime mime None attach_list append file fname name name mime mime note note return attach_list
"returns the jacobian of the pca model . in this case , simply the components of the model reshaped to have the standard jacobian shape :",property def jacobian self jacobian self components reshape self n_active_components 1 self template_instance n_dims return jacobian swapaxes 0 1
compute the windowed sum of the given arrays .,def windowed_sum_slow arrays span t None indices None tpowers 0 period None subtract_mid False span np asarray span dtype int if not np all span 0 raise ValueError span values must be positive arrays tuple map np asarray arrays N arrays 0 size if not all a shape N for a in arrays raise ValueError sizes of provided arrays must match t_input t if t is not None t np asarray t if t shape N raise ValueError shape of t must match shape of arrays else t np ones N tpowers tpowers np zeros len arrays if len tpowers len arrays raise ValueError tpowers must be broadcastable with number of arrays if period if t_input is None raise ValueError periodic requires t to be provided t t period if indices is None indices np arange N spans indices np broadcast_arrays span indices results for tpower array in zip tpowers arrays if period result sum array j N t j N j N period tpower for j in range i s 2 i s 2 s if not subtract_mid and j i for i s in np broadcast indices spans else result sum array j t j tpower for j in range max 0 i s 2 min N i s 2 s if not subtract_mid and j i for i s in np broadcast indices spans results append np asarray result return tuple results
increases the cursor by one if possible .,def next self if self cursor len self sols 1 self cursor self cursor 1 self show
"generates a url - safe token for the given user , action , time tuple .",_helpers positional 2 def generate_token key user_id action_id when None digester hmac new _helpers _to_bytes key encoding utf 8 digester update _helpers _to_bytes str user_id encoding utf 8 digester update DELIMITER digester update _helpers _to_bytes action_id encoding utf 8 digester update DELIMITER when _helpers _to_bytes str when or int time time encoding utf 8 digester update when digest digester digest token base64 urlsafe_b64encode digest DELIMITER when return token
update estimate using ' data ' as input,def update self particles u noise t particles 0 5 particles 25 0 particles 1 particles 2 8 math cos 1 2 t noise
return whether the provided ` item ` was contacted .,def __contains__ self item return item in self contacted
verify that getbalance / listtransactions return expected values .,def check self txid None amount None confirmations None balance self node getbalance self label 0 True assert_equal balance self expected_balance txs self node listtransactions self label 10000 0 True assert_equal len txs self expected_txs if txid is not None tx tx for tx in txs if tx txid txid assert_equal tx account self label assert_equal tx address self address address assert_equal tx amount amount assert_equal tx category receive assert_equal tx label self label assert_equal tx txid txid assert_equal tx confirmations confirmations assert_equal trusted not in tx True if self data Data priv assert_equal tx involvesWatchonly True else assert_equal involvesWatchonly not in tx True
write a list ( or any iterable ) of data bytes to the transport .,def writelines self list_of_data if not _PY34 list_of_data bytes data if isinstance data memoryview else data for data in list_of_data self write join list_of_data
return the base path for storing system files .,def resource_path type major bpy app version 0 minor bpy app version 1 return str
return interesting metrics for all cluster autoscaler functions .,def parse_metrics_file metrics_file summary with open metrics_file as metrics_file summary metrics json load metrics_file ca_metrics metrics ClusterAutoscalerMetrics total_sum ca_metrics cluster_autoscaler_function_duration_seconds_sum for sample in total_sum function function_name sample summary function CAMetric function summary function sum float metric_value sample count ca_metrics cluster_autoscaler_function_duration_seconds_count for sample in count function function_name sample summary function count int metric_value sample summary function avg summary function sum summary function count buckets ca_metrics cluster_autoscaler_function_duration_seconds_bucket for sample in buckets function function_name sample summary function buckets append float sample metric le int metric_value sample for value in summary values value upper_bound upper_bound value buckets return summary
return a filtering * function * that will let through those leaves that are good iobjects for @action and @for_item .,def iobjects_valid_for_action action for_item def valid_object leaf for_item _valid_object action valid_object for L in _get_leaf_members leaf for I in _get_leaf_members for_item if not _valid_object L for_item I return False return True types tuple action object_types def type_obj_check iobjs for i in iobjs if isinstance i types and valid_object i for_item for_item yield i def type_check itms for i in itms if isinstance i types yield i if hasattr action valid_object return type_obj_check else return type_check
assign parameters to object attributes .,def __init__ self xid None match None cookie None priority None reason None duration_sec None duration_nsec None idle_timeout None packet_count None byte_count None super __init__ xid self match match self cookie cookie self priority priority self reason reason self duration_sec duration_sec self duration_nsec duration_nsec self idle_timeout idle_timeout self packet_count packet_count self byte_count byte_count
remove element * key * from the dictionary . raises * keyerror * if * key * is not contained in the dictionary .,def remove self key u Remove element key from the dictionary Raises KeyError if key is not contained in the n dictionary n index self _get_item_index key if index is None raise KeyError u KeyError format key else self _discard index
return a tuple of the ions in the solution .,property def ions self return tuple self _contents keys
try loading each binding in turn,def init preferred os getenv QT_PREFERRED_BINDING verbose os getenv QT_VERBOSE is not None bindings _pyside2 _pyqt5 _pyside _pyqt4 if preferred if preferred None self __wrapper_version__ self __version__ return preferred preferred split os pathsep available PySide2 _pyside2 PyQt5 _pyqt5 PySide _pyside PyQt4 _pyqt4 try bindings available binding for binding in preferred except KeyError raise ImportError Available preferred Qt bindings n join preferred for binding in bindings _log Trying s binding __name__ verbose try binding binding except ImportError as e _log ImportError s e verbose continue else binding __shim__ self binding QtCompat self sys modules update __name__ binding __name__ QtWidgets binding QtWidgets return raise ImportError No Qt binding were found
returns a new pagelabel using options from a pdfrw object,classmethod def from_pdf cls pagenum opts return cls pagenum style stylecodes get opts S defaults style prefix opts P and opts P decode or defaults prefix firstpagenum opts St or defaults firstpagenum
release a job specified by ` job ` from batchcompute sevice .,def delete_job self job job_id self _get_id job res self _sa delete jobs job_id return ActionResponse res self _h
return array of parsed tokens in the expression,def parse expression result current for i in expression if i isdigit or i current i else if len current 0 result append current current if i in __operators__ or i in __parenthesis__ result append i else raise Exception invalid syntax i if len current 0 result append current return result
solve the discrete time lqr controller for a discrete time system .,def controller_lqr_discrete_time A B Q R X scipy linalg solve_discrete_are A B Q R K np dot np linalg inv np dot np dot B T X B R np dot np dot B T X A eigVals np linalg eigvals A np dot B K return K X eigVals
implementation of the generator to feed the event loop,def looper self for name endpoint topic msg in fedmsg tail_messages mute True yield topic dict msg
extracts contig information . : param contig : contig file : return : various information,def get_contig_txt_information contig BLASTP util NOT_AVAILABLE EVALUE util NOT_AVAILABLE IDENTITY util NOT_AVAILABLE SUBACCES util NOT_AVAILABLE SUBTIT util NOT_AVAILABLE SUBTAXID util NOT_AVAILABLE SUBID util NOT_AVAILABLE if os path isfile contig with open contig rb as f reader csv reader f delimiter t for row in reader BLASTP row 1 EVALUE row 10 IDENTITY row 2 SUBACCES row 12 SUBTIT row 13 SUBTAXID row 14 SUBID row 15 break return BLASTP EVALUE IDENTITY SUBACCES SUBTIT SUBTAXID SUBID
returns the number of bytes required to serialize a single varint using boundary value comparisons . ( unrolled loop optimization -wpierce ) uint64 must be unsigned .,def _VarUInt64ByteSizeNoTag uint64 if uint64 127 return 1 if uint64 16383 return 2 if uint64 2097151 return 3 if uint64 268435455 return 4 if uint64 34359738367 return 5 if uint64 4398046511103 return 6 if uint64 562949953421311 return 7 if uint64 72057594037927935 return 8 if uint64 9223372036854775807 return 9 if uint64 UINT64_MAX raise message EncodeError Value out of range d uint64 return 10
"move a workload , identified by agent_id , into quarantine",def quarantine_workload self agent_id self server_obj assign_group agent_id self target_group_id return
verifies the computed object behavior of the geometry constructor .,def testComputedGeometries self line ee Geometry LineString 1 2 3 4 bounds line bounds self assertTrue isinstance bounds ee Geometry self assertEquals ee ApiFunction lookup Geometry bounds bounds func self assertEquals line bounds args geometry self assertTrue hasattr bounds bounds
"a simple decorator that caches into memcache , using a simple key based on stringing args and kwargs . arguments to the method must be easily and consistently serializable using str ( .. ) otherwise the cache key will be inconsistent . : param prefix : a prefix for the key in memcache : type prefix : string : param timeout : number of seconds to cache the key for , default 60 seconds : type timeout : integer",def memoize prefix timeout 60 def decorator func functools wraps func def wrapper args kwargs def wrapped_func return func args kwargs key memoize_key prefix args kwargs return cache_get_or_set key wrapped_func timeout timeout return wrapper return decorator
test that function declarations happen in the right time .,def test_function_declaration_order self self run_script foo first function test foo second bar foo self assert_var_eq bar first self assert_var_eq foo second
test that duplicate files in a package are caught .,def test_duplicate_files err ErrorBundle err save_resource has_install_rdf True packagelayout test_layout_all err MockDupeXPI assert err failed
"draw text , reducing font size until it fits with a given max width and height .",def fit_text c text x y max_w max_h font_name Helvetica padding_w 4 5 padding_h 4 5 font_decrement 0 0625 max_w padding_w 2 0 max_h padding_h 2 0 x padding_w y padding_h font_size max_h while font_size 1 0 ps ParagraphStyle name text alignment TA_CENTER fontName font_name fontSize font_size leading font_size p Paragraph text ps actual_w actual_h p wrapOn c max_w max_h if actual_h max_h or actual_w max_w font_size font_decrement else y_pad max_h actual_h 2 p drawOn c x y y_pad return
using strip = true should n't result in malicious content .,def test_strip s scri script pt alert 1 scr script ipt eq_ pt gt alert 1 ipt gt clean s strip True s scri scri script pt pt alert 1 script eq_ pt gt pt gt alert 1 clean s strip True
return the greyscale image after the detection process,def returnGreyscaleMask self foreground_image return self BackgroundSubtractorMOG2 apply foreground_image
returns the toi of given team in given season across all games .,def get_team_toi season team return feather read_dataframe get_team_toi_filename season team_info team_as_str team True
drops all database and users created .,def drop_all self user_drop_lst joe_pass joe_pass user joe_nopass user amy_nopass user jill user jack user john user remote for user in user_drop_lst self drop_user user self server1 self drop_user user self server2 query DROP DATABASE util_test try self server1 exec_query query except UtilError pass try self server2 exec_query query except UtilError pass
open the ' url ' in the current desktop 's preferred file browser . if the optional ' desktop ' parameter is specified then attempt to use that particular desktop environment 's mechanisms to open the ' url ' instead of guessing or detecting which environment is being used .,def open url desktop None wait 0 desktop_in_use use_desktop desktop if desktop_in_use standard arg join os environ DESKTOP_LAUNCH commands mkarg url return _run arg 1 wait elif desktop_in_use Windows return os startfile url elif desktop_in_use KDE cmd kfmclient exec url elif desktop_in_use GNOME cmd gnome open url elif desktop_in_use XFCE cmd exo open url elif desktop_in_use Mac OS X cmd open url elif desktop_in_use X11 and os environ has_key BROWSER cmd os environ BROWSER url else raise OSError Desktop s not supported neither DESKTOP_LAUNCH nor os startfile could be used desktop_in_use return _run cmd 0 wait
computes the next chunk boundaries within ` buf ` .,def next_chunk_boundaries self buf prepend_bytes 0 return boundary for boundary _ in self next_chunk_boundaries_levels buf prepend_bytes
return an rpmpackage object for the file at location or none if the file is not an rpm .,def parse location infos info location include_desc True if TRACE logger_debug parse infos infos if not infos return name infos name try epoch infos epoch and int infos epoch or None except ValueError epoch None evr EVR version infos version or None release infos release or None epoch epoch to_string qualifiers os infos os if os and os linux qualifiers os os arch infos arch if arch qualifiers arch arch related_packages if infos source_rpm purl models PackageURL type rpm name name version evr qualifiers qualifiers to_string src_epoch src_name src_version src_release src_arch nevra from_name infos source_rpm src_evr EVR src_version src_release src_epoch to_string src_qualifiers if src_arch src_qualifiers arch src_arch src_purl models PackageURL type rpm name src_name version src_evr qualifiers src_qualifiers to_string if TRACE logger_debug parse source_rpm src_purl related_packages models PackageRelationship from_purl src_purl to_purl purl relationship source_of parties if infos distribution parties append models Party name infos distribution role distributor if infos vendor parties append models Party name infos vendor role vendor description join_texts infos summary infos description package RpmPackage name name version evr description description or None homepage_url infos url or None parties parties declared_licensing infos license or None related_packages related_packages return package
should parse an ok assertion with message,def test_parse_ok_with_message self assertion TapAssertion parse ok 284 I should be equal to me self assertIsNotNone assertion self assertEqual assertion num 284 self assertEqual assertion success True self assertEqual assertion parsed_indent self assertEqual assertion message I should be equal to me self assertEqual assertion expected None self assertEqual assertion got None self assertListEqual assertion stack
creates model comprised of 2 convolutional layers followed by dense layers,def make_model dense_layer_sizes nb_filters nb_conv nb_pool model Sequential model add Convolution2D nb_filters nb_conv nb_conv border_mode valid input_shape 1 img_rows img_cols model add Activation relu model add Convolution2D nb_filters nb_conv nb_conv model add Activation relu model add MaxPooling2D pool_size nb_pool nb_pool model add Dropout 0 25 model add Flatten for layer_size in dense_layer_sizes model add Dense layer_size model add Activation relu model add Dropout 0 5 model add Dense nb_classes model add Activation softmax model compile loss categorical_crossentropy optimizer adadelta metrics accuracy return model
returns a list of elbs associated with self.instance_id indirectly through its auto scaling group membership,def _get_auto_scaling_group_lbs self try asg connect_to_aws boto ec2 autoscale self region self aws_connect_params except boto exception NoAuthHandlerFound AnsibleAWSError as e self module fail_json msg str e asg_instances asg get_all_autoscaling_instances self instance_id if len asg_instances 1 self module fail_json msg Illegal state expected one auto scaling group instance if not asg_instances asg_elbs else asg_name asg_instances 0 group_name asgs asg get_all_groups asg_name if len asg_instances 1 self module fail_json msg Illegal state expected one auto scaling group asg_elbs asgs 0 load_balancers return asg_elbs
"find information about the current user , first trying ~/.smtrc , then the version control system",def get_user working_copy None u n Find information about the current user first trying smtrc then n the version control system n global_conf_file expanduser join u u smtrc if exists global_conf_file with open global_conf_file as fp config json load fp if u username in config return config u username if working_copy return working_copy get_username return u
: type initialcommands : list of string : param initialcommands : commands to run before giving the user a prompt ( they come from the pfainspector script 's arguments ) : type gadgets : list of titus.inspector.defs.gadget : param gadgets : gadgets to load at start - up,def __init__ self initialCommands gadgets self prompt PFA Inspector self dirStack self pfaFiles class LoadCommand Command def __init__ self mode self name load self syntax load file path as name self help read a PFA file into the current context possibly naming it n self syntax self mode mode def complete self established active words getcomplete established if len words 0 return pathcomplete established active elif len words 1 and as startswith active return as else return def action self args if len args 1 and args 0 parser Word help print self help elif len args 3 and isinstance args 0 parser FilePath and args 1 parser Word as and isinstance args 2 parser Word try data json load open args 0 text except IOError as err raise InspectorError err self mode pfaFiles args 2 text Model data else self syntaxError class RenameCommand Command def __init__ self mode self name rename self syntax rename name as name self help change the name of a PFA document n self syntax self mode mode def complete self established active words getcomplete established if len words 0 return sorted x for x in self mode pfaFiles keys if x startswith active elif len words 1 and as startswith active return as else return def action self args if len args 1 and args 0 parser Word help print self help elif len args 3 and isinstance args 0 parser Word and args 1 parser Word as and isinstance args 2 parser Word if args 0 text not in self mode pfaFiles raise InspectorError no PFA document named 0 in memory format args 0 text self mode pfaFiles args 2 text self mode pfaFiles args 0 text del self mode pfaFiles args 0 text else self syntaxError class DropCommand Command def __init__ self mode self name drop self syntax drop name self help delete a named PFA document from memory n self syntax self mode mode def complete self established active words getcomplete established if len words 0 return sorted x for x in self mode pfaFiles keys if x startswith active else return def action self args if len args 1 and args 0 parser Word help print self help elif len args 1 and isinstance args 0 parser Word if args 0 text not in self mode pfaFiles raise InspectorError no PFA document named 0 in memory format args 0 text del self mode pfaFiles args 0 text else self syntaxError class SaveCommand Command def __init__ self mode self name save self syntax save name to file path self help save a PFA document from the current context or a named document to a file self syntax self mode mode def complete self established active words getcomplete established if len words 0 return sorted x for x in self mode pfaFiles keys to if x startswith active elif len words 1 and to startswith active return to elif words 1 parser Word to return pathcomplete established active else return def action self args if len args 1 and args 0 parser Word help print self help elif len args 3 and isinstance args 0 parser Word and args 1 parser Word to and isinstance args 2 parser FilePath name args 0 text if name not in self mode pfaFiles raise InspectorError no PFA document named 0 in memory format name try json dump self mode pfaFiles name obj open args 2 text w except IOError as err raise InspectorError err else self syntaxError commands SimpleCommand pwd os getcwd 0 0 help print name of current working directory syntax pwd SimpleCommand cd lambda x switch os path isdir x lambda do self dirStack append os getcwd os chdir os path expanduser x None lambda exception InspectorError not a directory 1 1 pathcomplete help change the current working directory to the specified path syntax cd dir SimpleCommand back lambda maybe lambda os chdir self dirStack pop IndexError no directories on stack 0 0 help pop back to a previously visited directory syntax back SimpleCommand ls lambda args run ls args rstrip 0 None pathcomplete help list directory contents syntax same as command line ls including switches LoadCommand self SimpleCommand list lambda n join sorted x for x in self pfaFiles if len self pfaFiles 0 else None 0 0 help list the named PFA files in memory syntax list RenameCommand self DropCommand self SaveCommand self commands extend x self commandGroup for x in gadgets commands append SimpleCommand exit lambda sys exit 0 0 0 help exit the PFA Inspector also control D syntax exit self commandGroup CommandGroup None commands print Titus PFA Inspector version 0 nType help for a list of commands format titus version __version__ for initialCommand in initialCommands print initialCommand self action initialCommand super InspectorMode self __init__
adding accepts to a naked function : single positional param,def test_add_accepts_to_naked_function_1 def foo int_1 pass t time time for i in range 0 10000 accepts int foo return time time t
parses a mime - type into its component parts .,def parse_mime_type mime_type parts mime_type split params dict tuple s strip for s in param split 1 for param in parts 1 full_type parts 0 strip if full_type full_type type subtype full_type split return type strip subtype strip params
receiving the starttag of the root element results in stream start .,def test_receiveRoot self streamStarted def streamStartEvent rootelem streamStarted append None self xmlstream addObserver xmlstream STREAM_START_EVENT streamStartEvent self xmlstream connectionMade self xmlstream dataReceived root self assertEquals 1 len streamStarted
get the path to the programs menu .,def getProgramsMenuPath if not platform isWinNT return C Windows Start Menu Programs keyname SOFTWARE Microsoft Windows CurrentVersion Explorer Shell Folders hShellFolders win32api RegOpenKeyEx win32con HKEY_LOCAL_MACHINE keyname 0 win32con KEY_READ return win32api RegQueryValueEx hShellFolders Common Programs 0
test that c{suitevisit } visits stdlib unittest suites,def test_visitPyunitSuite self test TestTestVisitor test_visitPyunitSuite suite pyunit TestSuite test suiteVisit suite self visitor self assertEqual self visitor calls test
"zero as i d for autofield should raise exception in mysql , because mysql does not allow zero for automatic primary key .",skipIfDBFeature allows_primary_key_0 def test_zero_as_autoval self valid_country Country name Germany iso_two_letter DE invalid_country Country id 0 name Poland iso_two_letter PL with self assertRaises ValueError Country objects bulk_create valid_country invalid_country
"the username passed as `` remote_user `` is considered trusted . this method simply returns the `` user `` object with the given username , creating a new `` user `` object if `` create_unknown_user `` is `` true `` .",def authenticate self remote_user u n The username passed as remote_user is considered trusted This n method simply returns the User object with the given username n creating a new User object if create_unknown_user is True n n Returns None if create_unknown_user is False and a User n object with the given username is not found in the database n if not remote_user return user None username self clean_username remote_user UserModel get_user_model if self create_unknown_user user created UserModel objects get_or_create UserModel USERNAME_FIELD username if created user self configure_user user else try user UserModel objects get_by_natural_key username except UserModel DoesNotExist pass return user
"runwithpatches should run the given callable , passing in all arguments and keyword arguments , and return the return value of the callable .",def test_runWithPatchesDecoration self log def f a b c None log append a b c return foo result self monkeyPatcher runWithPatches f 1 2 c 10 self assertEquals foo result self assertEquals 1 2 10 log
removes a model from version control .,def unregister self model_class try registration_info self _registry pop model_class except KeyError raise RegistrationError r has not been registered with Reversion model_class else for field in registration_info file_fields field storage field storage wrapped_storage post_save disconnect self post_save_receiver model_class
cascade deletion works with foreignkey.to_field set to non - pk .,def test_to_field self apple Food objects create name apple eaten Eaten objects create food apple meal lunch apple delete self assertFalse Food objects exists self assertFalse Eaten objects exists
returns a dictionary where each key is associated with a list of values .,def dict_of_lists self r for key val in self items r setdefault key append val return r
"the string representation of a l{delayedcall } instance , as returned by c{str } , includes the unsigned i d of the instance , as well as its state , the function to be called , and the function arguments .",def test_str self def nothing pass dc DelayedCall 12 nothing 3 A 5 None None lambda 1 5 ids dc 200 def fakeID obj try return ids obj except TypeError KeyError return id obj self addCleanup setIDFunction setIDFunction fakeID self assertEquals str dc DelayedCall 0xc8 10 5s called 0 cancelled 0 nothing 3 A 5
return sorted list of integers - the old logs ' identifiers .,def listLogs self result for name in glob glob s self path try counter int name split 1 if counter result append counter except ValueError pass result sort return result
displays a menu of options for the user to choose from .,def PrintMenu self print Contacts Sample 1 List all of your contacts 2 Create a contact 3 Query contacts on updated time 4 Modify a contact 5 Delete a contact 6 List all of your contact groups 7 Query your groups on updated time 8 Exit
"similar to l{test_cancelconnecttcptimeout } , but for the case where the connection attempt fails .",def test_cancelConnectTCPFailedTimeout self def connect reactor cc d cc connectTCP example com 1234 host port factory timeout bindAddress reactor tcpClients pop return d factory return self _cancelConnectFailedTimeoutTest connect
"return a new virtualtree that copies files from the same locations as before , but with target locations modified by stripping off the leading directories .",def stripped self prefix return VirtualTree self sourcetree self targettree strip_prefix prefix
polling all vms for the status of execution guarantee to run once if the timeout is less than polling_interval,def polling_vms self timeout polling_interval None if not polling_interval polling_interval self config polling_interval retry_count max timeout polling_interval 1 retry cnt_succ cnt_failed 0 clist self client_dict copy samples perf_tool self client_dict values 0 perf_tool while retry retry_count and len clist time sleep polling_interval sample_count 0 while True try msg self message_queue popleft except IndexError sys exc_clear break payload eval msg data vm_name payload sender id cmd payload cmd if cmd READY instance self full_client_dict vm_name if instance up_flag continue else clist vm_name up_flag True clist pop vm_name cnt_succ cnt_succ 1 self agent_version payload data elif cmd REPORT sample_count sample_count 1 instance self client_dict vm_name self result vm_name instance perf_client_parser payload data samples append self result vm_name elif cmd DONE self result vm_name payload data clist pop vm_name if self result vm_name status LOG error s s vm_name self result vm_name stderr cnt_failed cnt_failed 1 else cnt_succ cnt_succ 1 elif cmd DONE_MC instance self client_dict vm_name try self result json loads payload data stdout except Exception LOG error payload data stderr clist elif cmd DEBUG LOG info s s vm_name payload data else LOG error s received invalid command s vm_name cmd log_msg VMs d Ready d Failed d Pending Retry d cnt_succ cnt_failed len clist retry if sample_count 0 log_msg d sample s received sample_count LOG info log_msg if sample_count 0 report perf_tool consolidate_samples samples len self client_dict self report seq self report seq 1 self report report report LOG info Periodical report s str self report samples retry retry 1 return cnt_succ cnt_failed len clist
create a security group to test data serialization .,def _create_fixtures self self security_group _secgroup_fixture secgroup_id ID1 tenant_id TENANT1 name test secgroup
int : channel number of openthread,property def channel self return int self _req channel 0
enter data mode ( for rx / tx operations ),def goToDataMode self if self _sermode SerialModem Mode DATA return True response self runAtCommand ATO r if response is not None if response 0 2 OK self _sermode SerialModem Mode DATA return True return False
this initializes a simtrack detector .,def __init__ self kinbody_path detection_frame world_frame service_namespace None import rospy import tf import tf transformations as transformations try rospy init_node simtrack_detector anonymous True except rospy exceptions ROSException pass if detection_frame is not None and world_frame is not None self listener tf TransformListener else self listener None if service_namespace is None service_namespace simtrack self detection_frame detection_frame self world_frame world_frame self service_namespace service_namespace self kinbody_path kinbody_path self kinbody_to_query_map fuze_bottle fuze_bottle_visual pop_tarts pop_tarts_visual self query_to_kinbody_map fuze_bottle_visual fuze_bottle pop_tarts_visual pop_tarts
"split node "" horizontally "" , by duplicating its content and splitting incoming and outgoing edges .",def split_node cfg n assert cfg degree_in n 2 assert cfg degree_out n 1 preds cfg pred n node_props cfg n node2_props copy deepcopy node_props n2 n split1 cfg add_node n2 node2_props cfg remove_edge preds 1 n cfg add_edge preds 1 n2 cfg add_edge n2 cfg succ n 0
take a migration lock to ensure no other migration are run concurrenly,def take_migration_lock source_replica_set destination_replica_set mig_dbs non_mig_dbs conn mysql_lib get_mysqlops_connections cursor conn cursor lock_identifier str uuid uuid4 log info Migration lock identifier is format lock_identifier log info Checking existing locks existing_lock check_migration_lock source_replica_set if not existing_lock existing_lock check_migration_lock destination_replica_set if existing_lock log error Lock is already held by format existing_lock log error You can abort this migration by running log error usr local bin mysql_utils clean_up_unfinished_migration py format existing_lock source_replica_set raise Exception Can not take migration lock params lock lock_identifier source_replica_set source_replica_set destination_replica_set destination_replica_set mig_dbs join mig_dbs non_mig_dbs join non_mig_dbs status STATUS_IMPORTING sql INSERT INTO mysqlops mysql_migration_locks SET lock_identifier lock s lock_active active created_at NOW released NULL source_replica_set source_replica_set s destination_replica_set destination_replica_set s mig_databases mig_dbs s non_mig_databases non_mig_dbs s status status s cursor execute sql params conn commit log info cursor _executed return lock_identifier
test parametrized scenario vertical example table has wrong format .,def test_wrong_vertical_examples_scenario testdir features testdir mkdir features feature features join test feature feature write_text textwrap dedent u n Scenario Outline Outlined with wrong vertical example table n Given there are start cucumbers n When I eat eat cucumbers n Then I should have left cucumbers n n Examples Vertical n start 12 2 n start 10 1 n left 7 1 n utf 8 ensure True with pytest raises exceptions FeatureError as exc scenario feature strpath Outlined with wrong vertical example table def wrongly_outlined pass assert exc value args 0 Scenario has not valid examples Example rows should contain unique parameters start appeared more than once
copies the current queue items .,def copy self copy self _queue copy result list while not copy empty result append copy get_nowait return result
returns the columns labels as a string to be written to the file,def labels self return self formatter format_header Results LINE_BREAK
"construct string to insert multiple records into sqlite3 database args : tablename : str , mandatory name of table in the database . records : set of records multiple : returns :",def insertfromdata tablename records multiple True if multiple lst records 0 else lst records s INSERT INTO str tablename VALUES s join len lst return s
creates a new review and publishes it .,webapi_login_required webapi_check_local_site webapi_response_errors DOES_NOT_EXIST INVALID_FORM_DATA NOT_LOGGED_IN PERMISSION_DENIED webapi_request_fields required u review_request_id u type int u description u The ID of the review request optional u ship_it u type bool u description u Whether or not to mark the review Ship It u body_top u type str u description u The review content above the comments u body_top_rich_text u type bool u description u Whether the body top should be formatted using Markdown u body_bottom u type str u description u The review content below the comments u body_bottom_rich_text u type bool u description u Whether the body bottom should be formatted using Markdown u diff_comments u type str u description u A JSON payload containing the diff comments def create self request review_request_id ship_it False body_top u body_top_rich_text False body_bottom u body_bottom_rich_text False diff_comments None args kwargs u try review_request resources review_request get_object request review_request_id review_request_id args kwargs except ObjectDoesNotExist return DOES_NOT_EXIST if not body_top body_top u if not body_bottom body_bottom u new_review Review objects create review_request review_request user request user body_top body_top body_top_rich_text body_top_rich_text body_bottom body_bottom body_bottom_rich_text body_bottom_rich_text ship_it ship_it if diff_comments try diff_comments json loads diff_comments for comment in diff_comments filediff FileDiff objects get pk comment u filediff_id diffset__history__review_request review_request if comment u issue_opened issue True issue_status BaseComment OPEN else issue False issue_status None new_review comments create filediff filediff interfilediff None text comment u text first_line comment u first_line num_lines comment u num_lines issue_opened issue issue_status issue_status rich_text comment u rich_text except KeyError return INVALID_FORM_DATA u fields u diff_comments u Diff comments were malformed except ObjectDoesNotExist return INVALID_FORM_DATA u fields u diff_comments u Invalid filediff_id new_review publish user request user return 201 self item_result_key new_review
returns a list of dependencies based on the specified manifest file . the returned dependencies will be made relative to |relative_path| and normalized . : raises ioerror : if the manifest could not be read .,def ReadDependencies manifest relative_path dependency_list with open manifest as f for line in f readlines dependency line partition 0 strip if dependency dependency os path normpath os path join relative_path dependency dependency_list append dependency return dependency_list
installs mock in place of the named member of the given obj .,def mock self obj member mock self _mocks setdefault obj collections OrderedDict setdefault member getattr obj member setattr obj member mock
starts the server in another thread .,def start self threading Thread target self serve_forever start
adds options related to instrumentation to |option_parser| .,def _AddInstrumentOptions option_parser _AddCommonOptions option_parser option_parser add_option source dirs help Space separated list of source directories source files should not be specified if source dirs is specified option_parser add_option source files help Space separated list of source files source dirs should not be specified if source files is specified option_parser add_option java sources file help File containing newline separated java paths option_parser add_option src root help Root of the src repository option_parser add_option emma jar help Path to emma jar option_parser add_option filter string default help Filter string consisting of a list of inclusion exclusion patterns separated with whitespace and or comma
computes average cpu usage over a time period for different process types .,def _SubtractCpuStats cpu_stats start_cpu_stats cpu_usage for process_type in cpu_stats assert process_type in start_cpu_stats Mismatching process types if not cpu_stats process_type or not start_cpu_stats process_type continue cpu_process_time cpu_stats process_type CpuProcessTime start_cpu_stats process_type CpuProcessTime total_time cpu_stats process_type TotalTime start_cpu_stats process_type TotalTime if total_time 0 total_time 2 32 100 0 assert total_time 0 and total_time 2 31 100 0 Expected total_time 0 was d total_time cpu_usage process_type float cpu_process_time total_time return cpu_usage
returns the json representation of the task as a dictionary .,def ToJsonDict self return action self _action action_params self _action_params backend_params self _backend_params
"runs the command if dry_run is false , otherwise just prints the command .",def _RunCommand cmd dry_run shell False echo_cmd True if echo_cmd print cmd if not dry_run return subprocess call cmd shell shell else return 0
skips / ignores the next asn.1 element,def step_over self self _tag self _header_length self _contents self _rest _parse_asn1_element self _rest
typedef : typedef extendedattributelistnocomments type identifier ' ; ',def p_Typedef self p p 0 self BuildNamed Typedef p 4 ListFromConcat p 2 p 3
scans a file for executable lines .,def ScanFile filename language if language python return PythonScanner Scan filename elif language in C C ObjC ObjC return CppScanner Scan filename return
read a file from dumptofile .,classmethod def ReadFromFile cls input_file seq cls None seq _seq sorted l strip for l in input_file readlines if l return seq
checks that the ' getelementbyid ' checker does n't flag |line| as a style error .,def ShouldPassGetElementByIdCheck self line self assertEqual self checker GetElementByIdCheck 1 line Should not be flagged as style error line
sets up the webpagereplay server if needed .,def SetupWpr device wpr_archive_path record network_condition_name out_log_path if wpr_archive_path or record or network_condition_name or out_log_path return device_setup RemoteWprHost device wpr_archive_path record network_condition_name out_log_path out_log_path return DummyWprHost
setup a route and a view for given action and clazz . the routes will have the follwoing following name and url :,def _setup_web_action config action clazz view_mapping name clazz __tablename__ action_name action name lower route_name get_action_routename clazz action_name route_url s s name action url log debug Adding WEB route s s route_name route_url config add_route route_name route_url factory get_resource_factory clazz settings config registry settings http_cache settings get security page_http_cache 0 view_func get_action_view view_mapping action_name name if view_func if action_name delete template confirm renderer default s mako template elif action_name download renderer None else template action_name renderer default s mako template config add_view view_func route_name route_name renderer renderer permission action permission or action_name http_cache int http_cache if action_name list action_name bundle route_name s s name action_name route_url s s name action_name view_func get_action_view view_mapping action_name name log debug Adding route s s route_name route_url config add_route route_name route_url factory get_resource_factory clazz config add_view view_func route_name route_name renderer default bundle mako permission list if action_name read action_name ownership route_name s s name action_name route_url s s id name action_name view_func get_action_view view_mapping action_name name log debug Adding route s s route_name route_url config add_route route_name route_url factory get_resource_factory clazz config add_view view_func route_name route_name renderer default update mako permission read
returns true if ` var ` is always equal to ` val ` .,def is_equal var val try v get_scalar_constant_value var return v val except NotScalarConstantError return False
this function checks if any of the bought servers are ready to be installed and installs plebnet on them . : param config : the configuration of this plebbot : type config : dict : param dna : the dna of this plebbot : type dna : dna : return : none : rtype : none,def install_available_servers config dna bought config get bought logger log install s bought install_available_servers for provider transaction_hash child_index in list bought if provider in cloudomate_controller get_vpn_providers return try provider_class cloudomate_controller get_vps_providers provider ip cloudomate_controller get_ip provider_class cloudomate_controller child_account child_index except Exception as e logger log str e s not ready yet str provider install_available_servers return if is_valid_ip ip if provider_class TUN_TAP_SETTINGS tun_success provider_class cloudomate_controller child_account child_index enable_tun_tap logger log Enabling s tun tap s provider tun_success if not cloudomate_controller save_info_vpn child_index logger log VPN not ready yet can t save ovpn config return logger log Installing child on s with ip s provider str ip account_settings cloudomate_controller child_account child_index rootpw account_settings get server root_password provider_class cloudomate_controller child_account child_index change_root_password rootpw time sleep 5 child_tree dna get_own_tree str child_index dna create_child_dna provider child_tree transaction_hash config save success _install_server ip rootpw child_index setup get_instance wallets_testnet config load config get installed append provider success if provider transaction_hash child_index in config get bought config get bought remove provider transaction_hash child_index config save else logger log Server not ready
hard link file from `` src `` to `` chroot / dst `` with optional label .,def link self src dst label None dst self _normalize dst self _tag dst label self _ensure_parent dst abs_src src abs_dst os path join self chroot dst safe_copy abs_src abs_dst overwrite False
lookup name in a namespace spanning sys.modules and _ _ main.dict _ _,def get_entity self name namespace sys modules copy namespace update __main__ __dict__ return eval name namespace
"takes a feature extraction function ( or its name ) and its parameters , and packs them into a tuple entry in the feature vector template .",def add_feature self fn fp self vec append fn fp
provides random initialization of clusters using dimension of train_data,def random_init self train_data centroids np zeros self n_clusters_ train_data shape 1 for c in range self n_clusters_ for f in range train_data shape 1 centroids c f random uniform min train_data f max train_data f return centroids
helper to fill in the potentially empty image_bbox field,shared_task def fill_in_bbox_task shape photo shape photo __class__ objects get id shape photo id image_bbox mask_complex_polygon image open_image photo image_orig vertices shape vertices triangles shape triangles bbox_only True save_obj_attr_image shape attr image_bbox img image_bbox format jpg save True
use logstalgia custom log format http://code.google.com/p/logstalgia/wiki/customlogformat,def _mk_custom_log self task module_args if task data is not None module_args s task module if invocation in task data if module_args in task data invocation args task data invocation module_args if len args 0 module_args s args replace 20 ts task timestamp replace tzinfo tzlocal log 0 1 2 3 4 format ts strftime self STRFTIME_FORMAT task hostname module_args task result return log
a batching transformation that omits the final small batch ( if present ) .,def batch_and_drop_remainder batch_size def _apply_fn dataset Function from Dataset to Dataset that applies the transformation tensor_batch_size ops convert_to_tensor batch_size dtype dtypes int64 name batch_size batched dataset batch tensor_batch_size flattened _RestructuredDataset batched tuple nest flatten batched output_types def _predicate xs Return True if this element is a full batch first_component xs 0 first_component_batch_size array_ops shape first_component out_type dtypes int64 0 return math_ops equal first_component_batch_size tensor_batch_size filtered flattened filter _predicate maybe_constant_batch_size tensor_util constant_value tensor_batch_size def _set_first_dimension shape return shape merge_with tensor_shape vector maybe_constant_batch_size concatenate shape 1 known_shapes nest map_structure _set_first_dimension batched output_shapes return _RestructuredDataset filtered batched output_types known_shapes return _apply_fn
retrieve the metagraph associated with the provided run .,def MetaGraph self run accumulator self _GetAccumulator run return accumulator MetaGraph
: param name : the name of product . : type name : str,def get_by_natural_key self name return self get name name
"call : func:`urllib2.urlopen ` , signing the request with flickr credentials .",def signed_urlopen url token_key token_secret kwargs auth oauthlib oauth1 Client appengine_config FLICKR_APP_KEY client_secret appengine_config FLICKR_APP_SECRET resource_owner_key token_key resource_owner_secret token_secret uri headers body auth sign url kwargs try return util urlopen urllib request Request uri body headers except BaseException as e util interpret_http_exception e raise
called before conversion process starts .,def pre_convert self original_book book raise NotImplementedError
validate pregnum in the respondent file .,def ValidatePregnum resp preg nsfg ReadFemPreg preg_map nsfg MakePregMap preg for index pregnum in resp pregnum iteritems caseid resp caseid index indices preg_map caseid if len indices pregnum print caseid len indices pregnum return False return True
m3u8 with ext audio but no options should not download additional streams : return :,def test_hls_ext_audio_all self master_url http mocked path master m3u8 expected http mocked path playlist m3u8 http mocked path en m3u8 http mocked path es m3u8 with requests_mock Mocker as mock mock get master_url text self playlist master_stream self run_streamlink master_url en es substreams master_stream video substreams result x url for x in substreams self assertEqual result expected
runs a single distributed benchmark .,def _RunBenchmark name yaml_file kubectl_util DeletePods name yaml_file kubectl_util CreatePods name yaml_file success kubectl_util WaitForCompletion name kubectl_util DeletePods name yaml_file return success
"downsample feature map with avg pooling , if filter size does n't match .",def downsample x filters strides axis 1 def pad_strides strides axis 1 Convert length 2 to length 4 strides Needed since tf layers Conv2D uses length 2 strides whereas operations such as tf nn avg_pool use length 4 strides Args strides length 2 list tuple strides for height and width axis integer specifying feature dimension according to data format Returns length 4 strides padded with 1 on batch and channel dimension assert len strides 2 if axis 1 return 1 1 strides 0 strides 1 return 1 strides 0 strides 1 1 assert len x shape 4 and axis 1 or axis 3 data_format NCHW if axis 1 else NHWC strides_ pad_strides strides axis axis if strides 0 1 x tf nn avg_pool x strides_ strides_ padding VALID data_format data_format in_filter x shape axis out_filter filters if in_filter out_filter pad_size out_filter in_filter 2 out_filter in_filter 2 if axis 1 x tf pad x 0 0 pad_size 0 0 0 0 else x tf pad x 0 0 0 0 0 0 pad_size return x 0 0
apply reversible block to inputs .,def call self h training True for block in self blocks h block h training training return h
test that a bn layer can be shared across different data streams .,def test_shared_batchnorm self with self test_session bn keras layers BatchNormalization x1 keras layers Input shape 10 _ bn x1 x2 keras layers Input shape 10 y2 bn x2 x np random normal loc 5 0 scale 10 0 size 2 10 model keras models Model x2 y2 model compile sgd mse model train_on_batch x x self assertEqual len bn updates 4 self assertEqual len model updates 2 self assertEqual len model get_updates_for x1 0 self assertEqual len model get_updates_for x2 2 x3 keras layers Input shape 10 y3 model x3 new_model keras models Model x3 y3 name new_model self assertEqual len new_model updates 2 self assertEqual len model updates 4 self assertEqual len new_model get_updates_for x3 2 new_model compile sgd mse new_model train_on_batch x x
create and clean up a directory hierarchy .,contextmanager def fakedirs path u os makedirs path try yield finally shutil rmtree path
determine a link to online source for a class / method / function,def _linkcode_resolve domain info package url_fmt revision if revision is None return if domain not in py pyx return if not info get module or not info get fullname return class_name info fullname split 0 if type class_name str class_name class_name encode utf 8 module __import__ info module fromlist class_name obj attrgetter info fullname module try fn inspect getsourcefile obj except Exception fn None if not fn try fn inspect getsourcefile sys modules obj __module__ except Exception fn None if not fn return fn os path relpath fn start os path dirname __import__ package __file__ try lineno inspect getsourcelines obj 1 except Exception lineno return url_fmt format revision revision package package path fn lineno lineno
predict new data by linear interpolation .,def predict self T return self transform T
build a small model that can be run partially in each step .,def BuildSplitableModel image array_ops zeros 2 6 6 3 kernel1 variable_scope get_variable DW 3 3 3 6 dtypes float32 initializer init_ops random_normal_initializer stddev 0 001 r1 nn_ops conv2d image kernel1 1 2 2 1 padding SAME kernel2 variable_scope get_variable DW2 2 3 3 6 dtypes float32 initializer init_ops random_normal_initializer stddev 0 001 r2 nn_ops conv2d image kernel2 1 2 2 1 padding SAME r3 r1 r2 return r1 r2 r3
convenience function to get a shape from a nodedef 's input string .,def tensor_shape_from_node_def_name graph input_name if not in input_name canonical_name input_name 0 else canonical_name input_name tensor graph get_tensor_by_name canonical_name shape tensor get_shape return shape
returns absolute path to the tethysapp directory .,def get_tethysapp_dir return os path join os path abspath os path dirname __file__ tethysapp
read a binary file containing the contents of the kernel 's .intlist section . this is an instance of a header created by include / linker / intlist.ld :,def read_intlist intlist_path intlist prefix endian_prefix intlist_header_fmt prefix IIIII intlist_entry_fmt prefix iiII with open intlist_path rb as fp intdata fp read header_sz struct calcsize intlist_header_fmt header struct unpack_from intlist_header_fmt intdata 0 intdata intdata header_sz debug str header intlist spurious_handler header 0 intlist sw_irq_handler header 1 intlist num_vectors header 2 intlist offset header 3 intlist num_isrs header 4 debug spurious handler s hex header 0 intlist interrupts i for i in struct iter_unpack intlist_entry_fmt intdata debug Configured interrupt routing debug handler irq flags param debug for irq in intlist interrupts debug 0 10 1 3 2 3 3 format hex irq 2 irq 0 irq 1 hex irq 3 return intlist
calculate the annual rate needed to equal an rate at frequency .,def effective_return rate 0 07 frequency 2 0 return np power 1 0 rate frequency frequency 1 0
floor divide each component of this vector3 .,def __ifloordiv__ self other self x other self y other self z other return self
widen the carving of a gcode file .,def writeOutput fileName fileName fabmetheus_interpret getFirstTranslatorFileNameUnmodified fileName if fileName skeinforge_craft writeChainTextWithNounMessage fileName widen
create statistics_manager rules . : param dpid : target dpid : type dpid : int : param peers : peer object array : type peers : list(peer ) : return : flow rules array,def create_rules_members self dpid peers rules enabled settings RULES_GENERATION_ENABLED ipv4 IPv4 ipv6 IPv6 icmpv6 ICMPv6 arp ARP for peer_dst in peers if peer_dst Egress is True if enabled Stats get ICMPv6 is True rule module Statistics_ICMPv6 rule icmpv6 create_stat dpid None peer_dst source None destination peer_dst idPeer rules append rule if enabled Stats get ARP is True rule module Statistics_ARP rule arp create_stat dpid None peer_dst source None destination peer_dst idPeer rules append rule for peer_src in peers if peer_src peer_dst if enabled Stats get IPv6 is True rule module Statistics_IPv6 rule ipv6 create_stat dpid peer_src peer_dst source peer_src idPeer destination peer_dst idPeer rules append rule if enabled Stats get IPv4 is True rule module Statistics_IPv4 rule ipv4 create_stat dpid peer_src peer_dst source peer_src idPeer destination peer_dst idPeer rules append rule rule module Miss table rule ipv4 create_miss_table dpid source None destination None rules append rule return rules
@param parent : the parent resource of this one .,def __init__ self parent store assert parent is not None DAVResource __init__ self principalCollections parent principalCollections self parent parent self store store
"install a reverse proxy for each of the other servers in the "" pod "" .",def installReverseProxies self maxClients for server in self _servers values if server thisServer continue installPool server id server uri maxClients
enumerate all calendars based on the directory record and/or calendars for this calendar home .,inlineCallbacks def listCalendars self txn exportService uid yield self getHomeUID exportService home yield txn calendarHomeWithUID uid True result if self collections for collection in self collections result append yield home calendarWithName collection else for collection in yield home calendars if collection name inbox result append collection returnValue result
"l{fixuuidnormalization } will fix the normalization of uuids . if a home is found with the wrong case but no duplicate , it will simply be upper - cased .",inlineCallbacks def test_fixUUIDNormalization_lowerToUpper_notification self t1 self transactionUnderTest yield t1 notificationsWithUID denormalizedUID create True yield self commit yield fixUUIDNormalization self storeUnderTest self assertEqual yield self allHomeUIDs schema NOTIFICATION_HOME normalizedUID
global print log function : param msg : : param type : : return :,def printf msg type INFO if pylogger is None set_default_logger if type INFO pylogger info msg elif type DEBUG pylogger debug msg elif type ERROR pylogger error msg elif type STREAM if pylogger level DEBUG if PY3 if stream_logger is None set_stream_logger stream_logger debug msg decode encoding sys getdefaultencoding else print msg end
list of uuids that represent available services .,property def service_UUIDs self u return self Get constants LE_ADVERTISEMENT_IFACE u ServiceUUIDs
translate all user and channel ids in an event to human - readable names,def _translate_event self event if user in event event event event user self _lookup_user event event user if channel in event event chan event event channel if isinstance chan dict event event channel chan name else c self _lookup_channel_by_id chan event event channel c channel_name event mentions self _lookup_user u for u in event mentions return event
"decrypt a message , validating its sequence number is as we expect .",def decrypt self ciphertext plaintext self _rx_tinh dec ciphertext if plaintext is None logger error Message decryption failure raise s_exc CryptoErr mesg Message decryption failure seqn next self _rx_sn sn mesg s_msgpack un plaintext if sn seqn logger error Message out of sequence got d expected d sn seqn raise s_exc CryptoErr mesg Message out of sequence expected seqn got sn return mesg
"appends ' _ licensed ' to the end of file name , before extension - test",def generate_new_path file_name split_file_name file_name split new_file_name split_file_name 0 _licensed split_file_name 1 new_path os path join os getcwd new_file_name print new_path return new_path
"returns username for uid , or "" uid "" when not found",def pw_name uid if uid 0 raise ValueError s_uid u uid if s_uid in CACHE_BY_UID return CACHE_BY_UID s_uid try pwd_entry pwd getpwuid uid except KeyError CACHE_BY_UID s_uid s_uid return s_uid CACHE_BY_UID s_uid pwd_entry pw_name return pwd_entry pw_name
stop the file system monitor ( stops the separate thread ),def stop self raise NotImplemented
forcefully kill the process ( needs to be implemented by subclasses ) .,def kill_helper self raise NotImplementedError You need to implement the kill_helper method
"given a url and a key / val pair , remove an item in the query parameters of the url , and return the new url .",def remove_query_param url key scheme netloc path query fragment urlparse urlsplit url query_dict urlparse parse_qs query keep_blank_values True query_dict pop key None query urlparse urlencode sorted list query_dict items doseq True return urlparse urlunsplit scheme netloc path query fragment
turn a django template into something that is understood by xgettext . it does so by translating the django translation tags into standard gettext function invocations .,def templatize src origin None charset u utf 8 u n Turn a Django template into something that is understood by xgettext It n does so by translating the Django translation tags into standard gettext n function invocations n src force_text src charset out StringIO u message_context None intrans False inplural False trimmed False singular plural incomment False comment lineno_comment_map comment_lineno_cache None raw_prefix u u if six PY3 else u def join_tokens tokens trim False message u join tokens if trim message trim_whitespace message return message for t in Lexer src tokenize if incomment if t token_type TOKEN_BLOCK and t contents u endcomment content u join comment translators_comment_start None for lineno line in enumerate content splitlines True if line lstrip startswith TRANSLATOR_COMMENT_MARK translators_comment_start lineno for lineno line in enumerate content splitlines True if translators_comment_start is not None and lineno translators_comment_start out write u s line else out write u n incomment False comment else comment append t contents elif intrans if t token_type TOKEN_BLOCK endbmatch endblock_re match t contents pluralmatch plural_re match t contents if endbmatch if inplural if message_context out write u npgettext p r p r p r count format message_context join_tokens singular trimmed join_tokens plural trimmed p raw_prefix else out write u ngettext p r p r count format join_tokens singular trimmed join_tokens plural trimmed p raw_prefix for part in singular out write blankout part u S for part in plural out write blankout part u P else if message_context out write u pgettext p r p r format message_context join_tokens singular trimmed p raw_prefix else out write u gettext p r format join_tokens singular trimmed p raw_prefix for part in singular out write blankout part u S message_context None intrans False inplural False singular plural elif pluralmatch inplural True else filemsg u if origin filemsg u file s origin raise SyntaxError u Translation blocks must not include other block tags s sline d t contents filemsg t lineno elif t token_type TOKEN_VAR if inplural plural append u s s t contents else singular append u s s t contents elif t token_type TOKEN_TEXT contents t contents replace u u if inplural plural append contents else singular append contents else if comment_lineno_cache is not None cur_lineno t lineno t contents count u n if comment_lineno_cache cur_lineno if t token_type TOKEN_COMMENT for c in lineno_comment_map comment_lineno_cache filemsg u if origin filemsg u file s origin warn_msg u The translator targeted comment s sline d was ignored because it wasn t the last item on the line c filemsg comment_lineno_cache warnings warn warn_msg TranslatorCommentWarning lineno_comment_map comment_lineno_cache else out write u s u join lineno_comment_map comment_lineno_cache comment_lineno_cache None if t token_type TOKEN_BLOCK imatch inline_re match t contents bmatch block_re match t contents cmatches constant_re findall t contents if imatch g imatch group 1 if g 0 u g g strip u elif g 0 u g g strip u g g replace u u if imatch group 2 context_match context_re match imatch group 2 message_context context_match group 1 if message_context 0 u message_context message_context strip u elif message_context 0 u message_context message_context strip u out write u pgettext p r p r format message_context g p raw_prefix message_context None else out write u gettext p r format g p raw_prefix elif bmatch for fmatch in constant_re findall t contents out write u _ s fmatch if bmatch group 1 context_match context_re match bmatch group 1 message_context context_match group 1 if message_context 0 u message_context message_context strip u elif message_context 0 u message_context message_context strip u intrans True inplural False trimmed u trimmed in t split_contents singular plural elif cmatches for cmatch in cmatches out write u _ s cmatch elif t contents u comment incomment True else out write blankout t contents u B elif t token_type TOKEN_VAR parts t contents split u cmatch constant_re match parts 0 if cmatch out write u _ s cmatch group 1 for p in parts 1 if p find u _ 0 out write u s p split u 1 1 else out write blankout p u F elif t token_type TOKEN_COMMENT if t contents lstrip startswith TRANSLATOR_COMMENT_MARK lineno_comment_map setdefault t lineno append t contents comment_lineno_cache t lineno else out write blankout t contents u X return out getvalue
"sets the cache , if needed .",def process_response self request response if not self _should_update_cache request response return response if response streaming or response status_code not in 200 304 return response if not request COOKIES and response cookies and has_vary_header response Cookie return response timeout get_max_age response if timeout is None timeout self cache_timeout elif timeout 0 return response patch_response_headers response timeout if timeout and response status_code 200 cache_key learn_cache_key request response timeout self key_prefix cache self cache if hasattr response render and callable response render response add_post_render_callback lambda r self cache set cache_key r timeout else self cache set cache_key response timeout return response
returns ogr getname and driver for the data source .,def __str__ self return s s self name str self driver
returns the lower - left coordinate .,property def ll self return self min_x self min_y
returns the spatial aggregate sql name .,def spatial_aggregate_name self agg_name agg_name unionagg if agg_name lower union else agg_name lower return getattr self agg_name
return the portion of the file 's mode that can be set by os.chmod ( ) .,def S_IMODE mode return mode 4095
set the index to which the functions relate .,def set_index self index indexinrawtext len self rawtext len self text get index self stopatindex if indexinrawtext 0 raise ValueError Index s precedes the analyzed statement index self indexinrawtext indexinrawtext self indexbracket 0 while self indexbracket len self bracketing 1 and self bracketing self indexbracket 1 0 self indexinrawtext self indexbracket 1 if self indexbracket len self bracketing 1 and self bracketing self indexbracket 1 0 self indexinrawtext and not self isopener self indexbracket 1 self indexbracket 1
return the dict for the current thread . raises keyerror if none defined .,def get_dict self thread current_thread return self dicts id thread 1
formats time to mm : ss : param time_to_format : long to format : return : string of time,staticmethod def __time_format time_to_format m s divmod time_to_format 60 return 02d 02d m s
test that post request with single resource only creates a single resource .,def test_post_single self data name foo random_input 1 2 3 response self client post groups json dumps data content_type application json self assertEqual response status_code status HTTP_201_CREATED self assertEqual 1 Group objects all count
enable serialisation without pk . not needed atm .,def get_by_natural_key self username return self get username username
keyword args : claim_lines : medical claim lines table,def provider_level_counts claim_lines codes claims add_claims_procedure_stems claim_lines codes correlate None alias claims columns claims c servicing_provider_npi claims c procedure_name_stem claims c procedure_code sa sql func count label occurrences groups claims c servicing_provider_npi claims c procedure_name_stem claims c procedure_code return sa select columns group_by groups
main method that adds loopback interface 99 to both the spine switches .,def main loopback_add config System xmlns http cisco com ns yang cisco nx os device intf items lb items LbRtdIf list id lo99 id adminSt up up descr Interface added via NETCONF descr LbRtdIf list lb items intf items System config for device in DEVICES with manager connect host device port PORT username USER password PASS hostkey_verify False device_params name nexus look_for_keys False allow_agent False as m print nNow adding Loopback99 device n format DEVICE_NAMES device device netconf_response m edit_config target running config loopback_add print netconf_response
checks if the a request is targeting an api endpoint .,def is_api_request request if request path startswith api return True elif request path startswith user_api return True elif request path startswith notifier_api return True return False
create replicated folder data item . ' publisher_folder_hostname ' required if ' publisher_folder_path ' is drive letter location . ' returns tuple of data item path and dictionary representing the data item .,def create_replicated_folder_item name publisher_folder_path server_folder_path publisher_folder_hostname None info _infopathkey server_folder_path _conntypekey _conntype_replicated if publisher_folder_hostname info _hostnamekey publisher_folder_hostname item _pathkey _path_folder name _typekey _type_folder _clientpathkey publisher_folder_path _infokey info return item _pathkey _itemkey item
calculates the vertical distances from the samples to the model .,def distance self samples X samples 0 Y samples 1 k self params 0 m self params 1 dists abs k X m Y return dists
generates a one - use only link for resetting password and sends to the user,def save self domain_override None email_template_name registration password_reset_email html use_https False token_generator default_token_generator from_email None request None from django core mail import send_mail for user in self users_cache if not domain_override current_site get_current_site request site_name current_site name domain current_site domain else site_name domain domain_override t loader get_template email_template_name c email user email domain domain site_name site_name uid urlsafe_base64_encode str user id user user token token_generator make_token user protocol use_https and https or http send_mail _ Password reset on s site_name t render Context c from_email user email
"calculate the n - th discrete difference along given axis . the first difference is given by `` out[n ] = a[n+1 ] - a[n ] `` along the given axis , higher differences are calculated by using ` diff ` recursively .",def diff a n 1 if n 0 return a if n 0 raise ValueError order must be non negative but got repr n b map lambda x x 1 x 0 zip a 1 a 1 if n 1 return diff b n 1 return b
extract the first signal for each time frame,def get_init_signals self init_signals for tf in self _time_frames s self signals self signals 3 tf 0 init_signals tf fin s 0 cur s 1 nxt s 2 return init_signals
"setup the items and pattern based on the parameters for this specific action , then let the base class complete the validation .",def validate self params self job device actions boot methods self method_name parameters if item_markup not in params or item_class not in params or separator not in params self errors Missing device parameters for UEFI menu operations return if commands not in self parameters and not self commands self errors Missing commands in action parameters return if not self commands and isinstance self parameters commands str if self parameters commands not in self job device actions boot methods self method_name self errors Missing commands for s self parameters commands return self commands self parameters commands if not self commands return self selector item_markup params item_markup self selector item_class params item_class self selector separator params separator if label_class in params self selector label_class params label_class else self selector label_class DEFAULT_UEFI_LABEL_CLASS self selector prompt params bootloader_prompt if boot_message in params and not self boot_message self boot_message params boot_message if not self items if self commands not in self job device actions boot methods self method_name self errors No boot configuration called s for boot method s self commands self method_name return self items self job device actions boot methods self method_name self commands if line_separator in self parameters uefi_type self parameters line_separator else uefi_type self job device actions boot methods self method_name get line_separator dos if uefi_type dos self line_sep UEFI_LINE_SEPARATOR elif uefi_type unix self line_sep LINE_SEPARATOR else self errors Unrecognised line separator configuration super UefiMenuSelector self validate
construct input for cifar evaluation using the reader ops .,def inputs eval_data data_dir batch_size if not eval_data filenames os path join data_dir data_batch_ d bin i for i in xrange 1 6 num_examples_per_epoch NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN else filenames os path join data_dir test_batch bin num_examples_per_epoch NUM_EXAMPLES_PER_EPOCH_FOR_EVAL for f in filenames if not tf gfile Exists f raise ValueError Failed to find file f filename_queue tf train string_input_producer filenames read_input read_cifar10 filename_queue reshaped_image tf cast read_input uint8image tf float32 height IMAGE_SIZE width IMAGE_SIZE resized_image tf image resize_image_with_crop_or_pad reshaped_image width height float_image tf image per_image_standardization resized_image min_fraction_of_examples_in_queue 0 4 min_queue_examples int num_examples_per_epoch min_fraction_of_examples_in_queue if eval_data read_input label set_shape 1 return _generate_image_and_label_batch float_image read_input label min_queue_examples batch_size shuffle False
determine if this device has ever been paired with a web backend,def has_been_paired id IdentityManager load return id uuid is not None and id uuid
initiate connection the database . if connection credentials are not available or connection fails throw exception .,def __init__ self try self db MySQLdb connect host os environ MYSQL_HOST user os environ MYSQL_USER passwd os environ MYSQL_PASSWD db os environ MYSQL_DB charset utf8 self cursor self db cursor except KeyError sys exit Please make sure all required environment variables are set MYSQL_HOST MYSQL_DB MYSQL_USER MYSQL_PASSWD except MySQLdb Error as e sys exit ERROR 0 IN CONNECTION 1 format e args 0 e args 1
processes the image of the roulette wheel into a number of slice objects .,def process self blurred cv2 GaussianBlur self image 5 5 0 hsv_im cv2 cvtColor blurred cv2 COLOR_BGR2HSV lower_red np array 0 100 100 upper_red np array 10 255 255 red_low_hues cv2 inRange hsv_im lower_red upper_red lower_red np array 160 100 100 upper_red np array 179 255 255 red_high_hues cv2 inRange hsv_im lower_red upper_red red_filtered cv2 addWeighted red_high_hues 1 0 red_low_hues 1 0 0 red_closed cv2 morphologyEx red_filtered cv2 MORPH_CLOSE 9 9 red_mask cv2 dilate red_closed 13 13 iterations 6 x y radius self get_circle red_mask 1 center_mask np zeros shape red_mask shape dtype np uint8 cv2 circle center_mask int x int y int radius 0 3 255 1 mask_inv cv2 bitwise_not center_mask red_mask cv2 bitwise_and red_mask mask_inv red_slices self get_slice_moments red_mask Color RED if len red_slices 2 return self origin int x int y self radius int radius 0 85 binary_wheel np zeros shape red_mask shape dtype np uint8 cv2 circle binary_wheel int x int y int radius 255 1 lower_green np array 40 100 100 upper_green np array 75 255 255 green_hues cv2 inRange hsv_im lower_green upper_green green_hues cv2 bitwise_and mask_inv green_hues green_mask cv2 morphologyEx green_hues cv2 MORPH_CLOSE 9 9 green_slices self get_slice_moments green_mask Color GREEN if len green_slices 2 return binary_wheel cv2 bitwise_and binary_wheel cv2 bitwise_not red_mask binary_wheel cv2 bitwise_and binary_wheel cv2 bitwise_not green_mask low_black np array 0 0 0 high_black np array 180 255 30 black_values cv2 inRange hsv_im low_black high_black binary_wheel cv2 bitwise_and binary_wheel mask_inv black_mask_closed cv2 morphologyEx binary_wheel cv2 MORPH_CLOSE 9 9 black_mask cv2 bitwise_and black_mask_closed black_values black_slices self get_slice_moments black_mask Color BLACK if len black_slices 2 return cv2 circle self image self origin self radius 255 255 0 2 for red in red_slices cv2 circle self image red origin 4 255 0 0 2 for green in green_slices cv2 circle self image green origin 4 0 0 255 2 for black in black_slices cv2 circle self image black origin 4 0 155 0 2 wheel np zeros shape red_mask shape 0 red_mask shape 1 3 dtype np uint8 cv2 circle wheel self origin self radius 255 255 255 1 wheel cv2 bitwise_not wheel green_mask_color cv2 cvtColor green_mask cv2 COLOR_GRAY2BGR green_mask_color green_mask 0 0 255 0 red_mask_color cv2 cvtColor red_mask cv2 COLOR_GRAY2BGR red_mask_color red_mask 0 0 0 255 black_mask_color cv2 cvtColor black_mask cv2 COLOR_GRAY2BGR black_mask_color black_mask 0 255 0 0 wheel cv2 bitwise_or wheel green_mask_color wheel cv2 bitwise_or wheel red_mask_color wheel cv2 bitwise_or wheel black_mask_color self visual_slices cv2 resize wheel 0 0 fx 0 5 fy 0 5 return red_slices green_slices black_slices
uses remove_ingredient ( ) method of coredata,def delete_ingredient self i recipes_affected self remove_ingredient i self json_write_ingredients self order ingredients remove i self json_write_order del self restr_dict ingredient_ i self json_write_restrictions for j in recipes_affected self recipe_dict j remove_ingredient self i self json_write_recipes
return x as a binary type .,def Binary x if PY2 return bytearray x else return bytes x
"given a player 's payoff matrix ` payoff_matrix ` , an array ` own_supp ` of this player 's actions , and an array ` opp_supp ` of the opponent 's actions , each of length k , compute the opponent 's mixed action whose support equals ` opp_supp ` and for which the player is indifferent among the actions in ` own_supp ` , if any such exists . return ` true ` if such a mixed action exists and actions in ` own_supp ` are indeed best responses to it , in which case the outcome is stored in ` out ` ; ` false ` otherwise . array ` a ` is used in intermediate steps .",jit nopython True cache True def _indiff_mixed_action payoff_matrix own_supp opp_supp A out m payoff_matrix shape 0 k len own_supp for i in range k for j in range k A j i payoff_matrix own_supp i opp_supp j A 1 1 1 A 1 1 1 A 1 1 0 out 1 0 out 1 1 r _numba_linalg_solve A out if r 0 return False for i in range k if out i 0 return False val out 1 if k m return True own_supp_flags np zeros m np bool_ own_supp_flags own_supp True for i in range m if not own_supp_flags i payoff 0 for j in range k payoff payoff_matrix i opp_supp j out j if payoff val return False return True
special version to deal with the code in the first 8 bytes of a user comment . first 8 bytes gives coding system e.g. ascii vs. jis vs unicode .,def make_string_uc seq seq seq 8 return make_string make_string seq
provide the ability for a widget to serialize itself,def serialize self xml Xml xml create_doc config element xml create_element element xml set_attribute element name self name display xml create_element display xml set_attribute display class Common get_full_class_name self element appendChild display for name value in self kwargs items if value option xml create_text_element name value else option xml create_element name display appendChild option return xml to_string element
"determine the package name currently being edited , or none .",def _guess_package_name self path None path path or self _guess_folder name os path basename path return name if name User else None
experimental function to convert python functions directly to porcupine 's json format ( by converting it ) first to a nipype node .,def pyfunc2json pass
decorator function to register a function as a plugin:// url endpoint,def register self mode args None kwargs None if args is None args if kwargs is None kwargs def decorator f if mode in self func_registry message Error s already registered as s str f mode logger log message log_utils LOGERROR raise Exception message self func_registry mode strip f self args_registry mode args self kwargs_registry mode kwargs return f return decorator
"create(heading [ , message])--create and show a background progress dialog.n",def create self heading message pass
"determines the cdn folder , e.g. : net.rieter.xot.channel.be.canvas",def _GetCdnSubFolder self channel if channel path in self __cdnPaths return self __cdnPaths channel path parts channel path rsplit os sep 2 2 cdn join parts self __cdnPaths channel path cdn return cdn
enable or disable applications over usb .,config command click pass_context click_force_option click option e enable multiple True type UpperCaseChoice APPLICATION __members__ keys help Enable applications click option d disable multiple True type UpperCaseChoice APPLICATION __members__ keys help Disable applications click option l list is_flag True help List enabled applications click option a enable all is_flag True help Enable all applications click option L lock code help A 16 byte lock code used to protect the application configuration click option touch eject is_flag True help When set the button toggles the state of the smartcard between ejected and inserted CCID only click option no touch eject is_flag True help Disable touch eject CCID only click option autoeject timeout required False type int default 0 metavar SECONDS help When set the smartcard will automatically eject after the given time Implies touch eject click option chalresp timeout required False type int default 0 metavar SECONDS help Sets the timeout when waiting for touch for challenge response in the OTP application def usb ctx enable disable list enable_all touch_eject no_touch_eject autoeject_timeout chalresp_timeout lock_code force def ensure_not_all_disabled ctx usb_enabled for app in APPLICATION if app usb_enabled return ctx fail Can not disable all applications over USB if not list or enable_all or enable or disable or touch_eject or no_touch_eject or autoeject_timeout or chalresp_timeout ctx fail No configuration options chosen enable APPLICATION __members__ keys if enable_all else enable _ensure_not_invalid_options ctx enable disable if touch_eject and no_touch_eject ctx fail Invalid options dev ctx obj dev usb_supported dev config usb_supported usb_enabled dev config usb_enabled flags dev config device_flags if not usb_supported ctx fail USB interface not supported if list _list_apps ctx usb_enabled if touch_eject flags FLAGS MODE_FLAG_EJECT if no_touch_eject flags FLAGS MODE_FLAG_EJECT if lock_code lock_code _parse_lock_code ctx lock_code for app in enable if APPLICATION app usb_supported usb_enabled APPLICATION app else ctx fail not supported over USB format app for app in disable if APPLICATION app usb_supported usb_enabled APPLICATION app else ctx fail not supported over USB format app ensure_not_all_disabled ctx usb_enabled f_confirm Configure USB interface format Enable n format join str APPLICATION app for app in enable if enable else Disable n format join str APPLICATION app for app in disable if disable else Set touch eject if touch_eject else Disable touch eject n if no_touch_eject else Set autoeject timeout to format autoeject_timeout if autoeject_timeout else Set challenge response timeout to format chalresp_timeout if chalresp_timeout else force or click confirm f_confirm abort True try dev write_config device_config usb_enabled usb_enabled flags flags auto_eject_timeout autoeject_timeout chalresp_timeout chalresp_timeout reboot True lock_key lock_code except Exception as e logger error Failed to write config exc_info e ctx fail Failed to configure USB applications
initialize a reciever with a function that will handle incoming data and a socket address : param forwards : a function that the reciever will forward its data too .,def __init__ self socketInfo engine super __init__ address type socketInfo self RECOVERY_TIMEOUT 500 self stopped False self outlet CanOutlet engine message_type type self canSocket CanSocket address self daemonThread threading Thread target self recieve_and_forward self daemonThread setDaemon True self _stop threading Event self time_buffer array array B 0 8 self _inRecovery False self canSocket socket setsockopt socket SOL_SOCKET SO_TIMESTAMPNS 1
default constructor of the class .,def __init__ self integer bitfield self __convert_to_binary integer self __size len bitfield 4 self __bits bitfield
install a course with no content using a fixture .,def setUp self is_staff True super TextbooksTest self setUp is_staff self textbook_page TextbooksPage self browser self course_info org self course_info number self course_info run self textbook_page visit disable_animations self
determines whether the given request is an asset request,def is_asset_request self request return request path startswith XASSET_LOCATION_TAG or request path startswith AssetLocator CANONICAL_NAMESPACE
add directories to relevant paths for comprehensive theming .,def enable_comprehensive_theme theme_dir changes comprehensive_theme_changes theme_dir for name value in changes settings iteritems setattr settings name value for template_dir in changes template_paths settings DEFAULT_TEMPLATE_ENGINE DIRS insert 0 template_dir settings MAKO_TEMPLATES main insert 0 template_dir
"returns the xblock that is the parent of the specified xblock , or none if it has no parent .",def get_parent_xblock xblock locator xblock location parent_location modulestore get_parent_location locator if parent_location is None return None return modulestore get_item parent_location
tests that adding to creator group fails if user is not active,def test_add_user_not_active self with mock patch dict django conf settings FEATURES DISABLE_COURSE_CREATION False ENABLE_CREATOR_GROUP True self user is_active False add_users self admin CourseCreatorRole self user self assertFalse user_has_role self user CourseCreatorRole
"verifies that going to the courseware with an unanswered survey , redirects to the survey",def test_visiting_course_with_survey_redirects self self _assert_survey_redirect self course
create a runtime that actually does html rendering,def new_module_runtime self runtime super XModuleRenderingTestBase self new_module_runtime runtime render_template render_to_string return runtime
return the course tree breadcrumb shown above the sequential bar,property def breadcrumb self return part strip for part in self q css path text 0 split
checks if the utc timestamp of the last successful import is visible,def is_timestamp_visible self return self q css item progresspoint success date visible
"compare this package 's version with a package name and version . returns an int with the standard _ _ cmp _ _ semantics : -1 iff a < b , 0 iff a = b , 1 iff a > b",def compare_package_versions distro_flavor pkg_a ver_a pkg_b ver_b fulla join str pkg_a str ver_a fullb join str pkg_b str ver_b if fulla fullb return 0 if distro_flavor RHEL fixfile pkg_b ver_b arch rpm imagefile pkg_a ver_a arch rpm n1 v1 r1 e1 a1 split_rpm_filename imagefile n2 v2 r2 e2 a2 split_rpm_filename fixfile if compare_labels 1 v1 r1 1 v2 r2 0 return 1 else return 1 elif distro_flavor DEB if deb_compare_versions ver_a lt ver_b return 1 else return 1 elif distro_flavor ALPINE if apk_compare_versions ver_a lt ver_b return 1 else return 1 else raise ValueError unsupported distro cannot compare package versions
"use descriptive strings from first ( header ) row of csv to generate column identifiers for database . tries to use the first word of each description to generate a human - friendly column name , but falls back to simpler ' col'n if that fails . will fail in an unlikely edge case .",def genColumnIds colHeaders colNames colNameMap for i cdesc in enumerate colHeaders words re findall w cdesc if len words 0 or words 0 in colNameMap cid col str i else cid words 0 colNames append cid cdesc colNameMap cid True return colNames
retrieve a list of gdb . value objects of type tcb that are the tasks that are currently waiting to receive data on this queue object .,def GetTasksWaitingToReceive self rxList ListInspector self _queue xTasksWaitingToReceive return rxList GetElements TaskInspector TCBType
test basic usage of the csv2dicts function .,def test_csv2dicts self offers seasonal_jobbing csv2dicts self offers_csv offers_proto dict mongo collection_to_proto_mapping offers seasonal_jobbing_pb2 MonthlySeasonalJobbingStats self assertEqual 3 list offers_proto keys march_proto offers_proto 3 self assertEqual 06 d departement_id for d in march_proto departement_stats first_departement_proto march_proto departement_stats 0 self assertEqual 06 first_departement_proto departement_id self assertEqual 793 first_departement_proto departement_seasonal_offers self assertEqual 11 len first_departement_proto job_groups self assertEqual Personnel de cuisine first_departement_proto job_groups 0 name strip self assertEqual 166 first_departement_proto job_groups 0 offers self assertEqual G1602 first_departement_proto job_groups 0 rome_id
compute the employment type of the job offer .,def _employment_type job_offer if job_offer contract_type_code CDI return job_pb2 CDI if job_offer contract_type_code MIS return job_pb2 INTERIM duration int job_offer contract_duration if job_offer contract_dur_unit_code MO duration 30 if duration 30 3 return job_pb2 CDD_OVER_3_MONTHS return job_pb2 CDD_LESS_EQUAL_3_MONTHS
get_bytes(n : int ) : string return n bytes of random data .,def get_bytes self N s i pool self _getPos self _randpool h self _hash dsize self _hash digest_size num N while num 0 h update self _randpool i i dsize s s h digest num num dsize i i dsize self bytes if i dsize self stir i self _getPos self _getPos i self _updateEntropyEstimate 8 N return s N
post - request hook . by default it takes care of throw_on_error and returns response content .,def finalize self name result args kwargs if self throw_on_error and result status_code 400 error_msg Error when invoking with parameters raise APIError error_msg format name args kwargs result __dict__ response result if self load_json content result content if isinstance result content str else result content decode utf 8 return json loads content return result content
"using a date indexed contracts series and a dictionary of contracts , creates a continuous time series .",def stitch_contracts cts_assigned ctd price_col rolls rolldates cts_assigned rolldates2 for rolldate from_con to_con in rolls if str from_con in ctd keys and str to_con in ctd keys rolldates2 append rolldate from_con to_con rolldates3 for i rolldate from_con to_con in enumerate rolldates2 for j in range 300 rolldate np power 1 j datetime timedelta days j if rolldate in ctd str from_con index and rolldate in ctd str to_con index break assert j 299 rolldates3 append rolldate from_con to_con rolldates4 contract_ids for d f t in rolldates3 contract_ids append f contract_ids append t rolldates4 append d contracts ctd x copy for x in list np unique contract_ids df_stitched futures stitch_prices contracts s rolldates4 ctd return df_stitched
depends on begin and end only . : return : hash : rtype : number,def __hash__ self return hash self begin self end
create prepped reference directory for pisces .,def _prep_genome out_dir data genome_name utils splitext_plus os path basename dd get_ref_file data 0 out_dir utils safe_makedir os path join out_dir genome_name ref_file dd get_ref_file data utils symlink_plus ref_file os path join out_dir os path basename ref_file with open os path join out_dir GenomeSize xml w as out_handle out_handle write sequenceSizes genomeName s genome_name for c in pysam AlignmentFile s dict utils splitext_plus ref_file 0 header SQ cur_ploidy ploidy get_ploidy data region c SN out_handle write chromosome fileName s contigName s totalBases s knownBases s isCircular false ploidy s md5 s os path basename ref_file c SN c LN c LN cur_ploidy c M5 out_handle write sequenceSizes return out_dir
retrieve version of a single commandline program .,def _get_cl_version p config if not p get has_cl_version True return try prog config_utils get_program p cmd config except config_utils CmdNotFound localpy_cmd os path join os path dirname sys executable p cmd if os path exists localpy_cmd prog localpy_cmd else return args p get args cmd prog args subp subprocess Popen cmd format locals stdout subprocess PIPE stderr subprocess STDOUT shell True with contextlib closing subp stdout as stdout if p get stdout_flag v _parse_from_stdoutflag stdout p stdout_flag elif p get paren_flag v _parse_from_parenflag stdout p paren_flag else lines l strip for l in stdout read split n if l strip v lines 1 if v endswith v v 1 return v
convert cwl input into dictionary required for a cwl2wdl input object .,def _input_to_dict i records remapped None if not remapped remapped var_type records _to_variable_type i type records if var_type startswith Array and inputBinding in i get type ib i type inputBinding elif inputBinding in i ib i inputBinding else ib prefix None itemSeparator position None name _id_to_localname i id if id in i else i name return name remapped get name or name variable_type var_type prefix ib prefix separator ib itemSeparator position ib position is_required True default i get default None separate ib get separate True records
"get the ( image_name , args ) of the subprocess to spawn .",def get_server_process_details self u raise NotImplementedError
test that multiple sessions on the same socket connection are allowed,pytest mark execute_serially def test_multiple_sessions self num_sessions self impalad_test_service get_metric_value impala server num open hiveserver2 sessions session_ids for _ in xrange 5 open_session_req TCLIService TOpenSessionReq resp self hs2_client OpenSession open_session_req TestHS2 check_response resp assert resp sessionHandle not in session_ids session_ids append resp sessionHandle self impalad_test_service wait_for_metric_value impala server num open hiveserver2 sessions num_sessions 5 self socket close self socket None self impalad_test_service wait_for_metric_value impala server num open hiveserver2 sessions num_sessions
simple api to get the id of an url,def get_id self url u return self get_ids url 0
return full path to the user - specific cache dir for this application .,def user_cache_dir appname appauthor None version None opinion True Return full path to the user specific cache dir for this application appname is the name of application appauthor only required and used on Windows is the name of the appauthor or distributing body for this application Typically it is the owning company name version is an optional version path element to append to the path You might want to use this if you want multiple versions of your app to be able to run independently If used this would typically be major minor opinion boolean can be False to disable the appending of Cache to the base app data dir for Windows See discussion below Typical user cache directories are Mac OS X Library Caches AppName Unix cache appname XDG default Win XP C Documents and Settings username Local Settings Application Data AppAuthor AppName Cache Vista C Users username AppData Local AppAuthor AppName Cache On Windows the only suggestion in the MSDN docs is that local settings go in the CSIDL_LOCAL_APPDATA directory This is identical to the non roaming app data dir the default returned by user_data_dir above Apps typically put cache data somewhere under the given dir here Some examples Mozilla Firefox Profiles ProfileName Cache Acme SuperApp Cache 1 0 OPINION This function appends Cache to the CSIDL_LOCAL_APPDATA value This can be disabled with the opinion False option if sys platform startswith win if appauthor is None raise AppDirsError must specify appauthor on Windows path os path join _get_win_folder CSIDL_LOCAL_APPDATA appauthor appname if opinion path os path join path Cache elif sys platform darwin path os path join os path expanduser Library Caches appname else path os path join os getenv XDG_CACHE_HOME os path expanduser cache appname lower if version path os path join path version return path
gets the server list from dynamodb table . only the servers that are alive will be selected . the servers that have been there too much time without sending keepalives will be deleted .,def get_servers print Create list of active servers timestamp int time time dbclient boto3 resource dynamodb table dbclient Table DYNAMO_NAME response table scan items response Items results for item in items if item ip PUBLIC_IP continue if item time timestamp SERVERS_TIMEOUT print Add s item ip results append item ip if item time timestamp DELETE_TIMEOUT print Delete s item ip table delete_item Key ip item ip print Found d NATS servers len results return results
verify that add_connection ( ) gives us a valid twisted connector .,patch twisted internet reactor connectTCP def test_add_connection self mock_connectTCP self obj_ut add_connection self assertTrue self obj_ut connector is not None self assertTrue mock_connectTCP called
parse tasks from db and prepare them to be shown in the output table . @params rows : data from db @return : task list,def parse_tasks rows tasks if rows for row in rows task id row id target row target category row category status row status added_on row added_on processed False if os path exists os path join CUCKOO_ROOT storage analyses str task id reports report html task processed True if row category file sample db view_sample row sample_id task md5 sample md5 tasks append task return tasks
bulk - creates `` subjectpermissiongroup``s for the all the `` subject``s under this `` node `` .,def _bulk_create_subject_permission_groups self permission_group subject_queryset subject_permission_group_list for subject in subject_queryset subject_permission_group_list append account_models SubjectPermissionGroup subject subject permissiongroup permission_group account_models SubjectPermissionGroup objects bulk_create subject_permission_group_list
converts the points in `` old_feedbackset `` to current grading configuration in `` self.assignment `` . decimals will be rounded up to give favor for the student .,def convert_points self old_feedbackset old_grading_points old_feedbackset grading_points old_passing_grade_min_points old_feedbackset group parentnode passing_grade_min_points old_max_points old_feedbackset group parentnode max_points new_passing_grade_min_points self assignment passing_grade_min_points new_max_points self assignment max_points if old_max_points old_grading_points return new_max_points old_range old_max_points old_passing_grade_min_points new_range new_max_points new_passing_grade_min_points new_grading_points old_grading_points old_passing_grade_min_points new_range new_grading_points new_grading_points float old_range if old_range 0 else 0 new_grading_points math ceil new_grading_points new_passing_grade_min_points return new_grading_points if new_grading_points new_max_points else new_max_points
enumerate a set of anchors for each aspect ratio wrt an anchor .,def _ratio_enum anchor ratios w h x_ctr y_ctr _whctrs anchor size w h size_ratios size ratios ws np round np sqrt size_ratios hs np round ws ratios anchors _mkanchors ws hs x_ctr y_ctr return anchors
"returns list of numtilings tiles corresponding to variables ( floats and ints ) , hashed down to mem , using ctable to check for collisions - wrap version",def loadtileswrap tiles startelement numtilings memctable floats wrapwidths ints global _widthxnumtilings if isinstance memctable CollisionTable hashfun hash else hashfun hashUNH numfloats len floats numcoord 1 numfloats len ints _coordinates 0 numcoord startTiles _coordinates numtilings floats ints _widthxnumtilings wrapwidths i numtilings for i in xrange numfloats for j in xrange numtilings fixcoordwrap _coordinates numtilings numfloats j wrapwidths hnum hashfun _coordinates numcoord memctable tiles startelement j hnum
"converts a list of ' creators ' ( authors , contributors , creators ) into a string for ezid",def make_creator_list self creator_list if isinstance creator_list list self creator join creator_list elif isinstance creator_list str self creator creator_list else self creator None
saves a data in the appropriate path + file,def save_serialized_json self key act_dir dict_obj if json not in key file_name key json else file_name key dir_file self set_check_directory act_dir file_name print save to path dir_file json_output json dumps dict_obj indent 4 ensure_ascii False file codecs open dir_file w utf 8 file write json_output file close
makes metadata for an ark i d,def make_doi_metadata_by_uuid self uuid oc_item None metadata None if oc_item is None oc_item OCitem exists oc_item check_exists uuid if oc_item exists oc_item generate_json_ld meta_doi metaDOI if dc terms title in oc_item json_ld meta_doi title oc_item json_ld dc terms title if dc terms issued in oc_item json_ld meta_doi publicationyear oc_item json_ld dc terms issued elif dc terms modified in oc_item json_ld meta_doi publicationyear oc_item json_ld dc terms modified else meta_doi publicationyear str datetime datetime now year creator_list if dc terms contributor in oc_item json_ld for dc_item in oc_item json_ld dc terms contributor creator_list append str dc_item label if dc terms creator in oc_item json_ld and len creator_list 1 for dc_item in oc_item json_ld dc terms creator creator_list append str dc_item label meta_doi make_creator_list creator_list metadata meta_doi make_metadata_dict metadata _target oc_item json_ld id return metadata
str : the current url .,property def current_url self raise NotImplementedError
remove build / dist artifacts generated by deploy task,task def clean local rm rf build dist
creates lmdbs for generic inference returns the filename for a test image,def create_lmdbs folder image_width None image_height None image_count None if image_width is None image_width IMAGE_SIZE if image_height is None image_height IMAGE_SIZE if image_count is None train_image_count TRAIN_IMAGE_COUNT else train_image_count image_count val_image_count VAL_IMAGE_COUNT yy xx np mgrid image_height image_width astype float for phase image_count in train train_image_count val val_image_count image_db lmdb open os path join folder s_images phase map_async True max_dbs 0 label_db lmdb open os path join folder s_labels phase map_async True max_dbs 0 image_sum np zeros image_height image_width float64 for i in xrange image_count xslope yslope np random random_sample 2 0 5 a xslope 255 image_width b yslope 255 image_height image a xx image_width 2 b yy image_height 2 127 5 image_sum image image image astype uint8 pil_img PIL Image fromarray image image_datum caffe_pb2 Datum image_datum height image shape 0 image_datum width image shape 1 image_datum channels 1 s StringIO pil_img save s format PNG image_datum data s getvalue image_datum encoded True _write_to_lmdb image_db str i image_datum SerializeToString label_datum caffe_pb2 Datum label_datum channels label_datum height label_datum width 1 1 2 label_datum float_data extend np array xslope yslope flat _write_to_lmdb label_db str i label_datum SerializeToString image_db close label_db close mean_image image_sum image_count astype uint8 _save_mean mean_image os path join folder s_mean png phase _save_mean mean_image os path join folder s_mean binaryproto phase xslope yslope 0 5 0 5 a xslope 255 image_width b yslope 255 image_height test_image a xx image_width 2 b yy image_height 2 127 5 test_image test_image astype uint8 pil_img PIL Image fromarray test_image test_image_filename os path join folder test png pil_img save test_image_filename return test_image_filename
creates a detector parsing given data file,def __init__ self case_sensitive True unknown_value u andy self case_sensitive case_sensitive self unknown_value unknown_value self _parse os path join os path dirname __file__ data nam_dict txt
computes mc / dc tables out of counterexamples .,def compute_mcdc_tables context inst_a inst_b decision2traces trace2condition decisions decision2table decision2independencepairs seen for decision traces in decision2traces iteritems inst_a_conds_dec inst_a nets cond for cond in decisions decision inst_a nets decision inst_a_testnets inst_a inputs values inst_a_conds_dec inst_b_conds_dec inst_b nets cond for cond in decisions decision inst_b nets decision inst_b_testnets inst_b inputs values inst_b_conds_dec header cond for cond in decisions decision header append decision header_nets_a set inst_a_conds_dec header_nets_b set inst_b_conds_dec decision2table decision header decision2independencepairs decision test_number 0 for trace in traces test_a_number None test_b_number None simulator context mk_simulator for net in inst_a_testnets simulator add_watch net for net in inst_b_testnets simulator add_watch net simulator simulate trace trace get_max_depth full_test_a trace get_as_net_dictionary full_test_b trace get_as_net_dictionary test_a_candidate v 0 for k v in full_test_a iteritems if k in inst_a_testnets and k in header_nets_a test_b_candidate v 0 for k v in full_test_b iteritems if k in inst_b_testnets and k in header_nets_b test_a_hash compute_hash test_a_candidate test_b_hash compute_hash test_b_candidate if test_a_hash in seen _ test_a_number seen test_a_hash else seen test_a_hash test_a_candidate test_number decision2table decision append test_a_candidate test_a_number test_number test_number 1 if test_b_hash in seen _ test_b_number seen test_b_hash else seen test_b_hash test_b_candidate test_number decision2table decision append test_b_candidate test_b_number test_number test_number 1 condition trace2condition trace condition decisions decision condition decision2independencepairs decision condition test_a_number test_b_number return decision2table decision2independencepairs
returns state with a given index,def index2state Is n Juv Jdv None Nu Juv shape 0 if Jdv is None Ius np mod Is Nu states_up de2bi Juv Ius n return states_up else Ius np mod Is Nu Ids np floor Is Nu astype int states_up de2bi Juv Ius n states_down de2bi Jdv Ids n return states_up states_down
function returning the predictions of a model_binomial_icar model .,def predict self new_data None if new_data is None new_x build_design_matrices self _x_design_info self data else new_x build_design_matrices self _x_design_info new_data X new_x 1 cell new_x 1 astype np int if len self rho shape 1 rho self rho cell else rho np mean self rho axis 0 cell return invlogit np dot X self betas rho
add a new site to the current list of basis sites,def append_to_basis self new_site self _basis append new_site self _initialize
"makes a blob containing "" name "" , "" timestamp "" and "" value "" attributes .",def make_fancy_blob self name timestamp_seconds value assert isinstance name types StringTypes assert isinstance timestamp_seconds float return id name timestamp utilities seconds_to_timestamp timestamp_seconds value value
context manager : signs in a google apps user .,def DomainLogin uid domain return LoginContext uid domain uid domain
put your custom aggregation logic here .,def aggregate node datapoints values value for timestamp value in datapoints if value is not None metadata node readMetadata method metadata get aggregationMethod avg if method average return float sum values len values elif method sum return sum values elif method min return min values elif method max return max values elif method median values sort return values len values 2
create list of `` crophint `` objects from a protobuf response .,def _make_crop_hints_from_pb crop_hints return CropHint from_pb hint for hint in crop_hints crop_hints
returns a sublime text range representing the vim line range that the ex command should operate on .,def resolve self view start self resolve_line_reference view self start or TokenDot if not self separator if start 1 return R 1 1 if len self start 1 and isinstance self start 0 TokenPercent return R 0 view size return view full_line view text_point start 0 new_start start if self separator else 0 end self resolve_line_reference view self end or TokenDot current new_start return view full_line R view text_point start 0 view text_point end 0
generate xml from the current settings .,def to_xml self opts defaultdict lambda None if not self launch_url or not self secure_launch_url raise InvalidLTIConfigError Invalid LTI configuration root etree Element cartridge_basiclti_link attrib s s NSMAP xsi schemaLocation http www imsglobal org xsd imslticc_v1p0 http www imsglobal org xsd lti ltiv1p0 imslticc_v1p0 xsd http www imsglobal org xsd imsbasiclti_v1p0 http www imsglobal org xsd lti ltiv1p0 imsbasiclti_v1p0p1 xsd http www imsglobal org xsd imslticm_v1p0 http www imsglobal org xsd lti ltiv1p0 imslticm_v1p0 xsd http www imsglobal org xsd imslticp_v1p0 http www imsglobal org xsd lti ltiv1p0 imslticp_v1p0 xsd xmlns http www imsglobal org xsd imslticc_v1p0 nsmap NSMAP for key in title description launch_url secure_launch_url option etree SubElement root s s NSMAP blti key option text getattr self key vendor_keys name code description url if any vendor_ key for key in vendor_keys or self vendor_contact_email vendor_node etree SubElement root s s NSMAP blti vendor for key in vendor_keys if getattr self vendor_ key None v_node etree SubElement vendor_node s s NSMAP lticp key v_node text getattr self vendor_ key if getattr self vendor_contact_email v_node etree SubElement vendor_node s s NSMAP lticp contact c_name etree SubElement v_node s s NSMAP lticp name c_name text self vendor_contact_name c_email etree SubElement v_node s s NSMAP lticp email c_email text self vendor_contact_email if len self custom_params 0 custom_node etree SubElement root s s NSMAP blti custom for key val in sorted self custom_params items c_node etree SubElement custom_node s s NSMAP lticm property c_node set name key c_node text val if len self extensions 0 for key params in sorted self extensions items extension_node etree SubElement root s s NSMAP blti extensions platform key self recursive_options extension_node params if getattr self cartridge_bundle identifierref etree SubElement root cartridge_bundle identifierref self cartridge_bundle if getattr self cartridge_icon identifierref etree SubElement root cartridge_icon identifierref self cartridge_icon return xml version 1 0 encoding UTF 8 etree tostring root
calculate and return the metaparameter settings to be validated ( = jobs ) .,def _calculateJobs self ndim len self _min_params linspaces for i in range ndim linspaces append self _permuteSequence list linspace self _min_params i self _max_params i self _n_steps i nr_c len linspaces 0 nr_g len linspaces 1 i 0 j 0 jobs while i nr_c or j nr_g if i float nr_c j float nr_g line for k in range 0 j line append linspaces 0 i linspaces 1 k i 1 jobs append line else line for k in range 0 i line append linspaces 0 k linspaces 1 j j 1 jobs append line return jobs
ensures a minimum size of the sheet .,def resizeToAtLeast self rows None cols None if rows is None and cols is None return feed self _getFeed f_cols f_rows int feed find _ns_sheet colCount text int feed find _ns_sheet rowCount text if rows is None or rows f_rows rows None if cols is None or cols f_cols cols None self _resize feed rows cols
"get full class name under path search_dir , if class_name is ' mytest ' , and there exists a class ' hello . mytest ' , this method will return ' hello . mytest '",def get_full_class_name class_name search_dir abspath os path abspath search_dir all_files listfiles search_dir all_classes f len abspath 1 len f 6 replace for f in all_files for c in all_classes if c class_name return c for c in all_classes if c lower endswith class_name lower return c return class_name
test if the java executable is installed and in path . @fn test_java_exists @param self @return,def test_java_exists self status _ self target run which java self assertEqual status 0 msg java binary not in PATH or on target
called from dealer when notification received from roundmanager,def receive_notification self message msg_type message message_type if msg_type game_start_message info self __parse_game_start_message message self receive_game_start_message info elif msg_type round_start_message round_count hole seats self __parse_round_start_message message self receive_round_start_message round_count hole seats elif msg_type street_start_message street state self __parse_street_start_message message self receive_street_start_message street state elif msg_type game_update_message new_action round_state self __parse_game_update_message message self receive_game_update_message new_action round_state elif msg_type round_result_message winners hand_info state self __parse_round_result_message message self receive_round_result_message winners hand_info state
return whether or not this account should be considered a funding source for budgets .,hybrid_property def is_budget_source self if self acct_type AcctType Bank or self acct_type AcctType Cash return True return False
"delete a file , if possible .",def remove self path return SFTP_OP_UNSUPPORTED
returns the number of reproduction events since the beginning of the simulation .,def get_num_reproduction_events self return self __simulator get_num_reproduction_events
create astng for a living data descriptor object,def object_build_datadescriptor node member name u return _base_class_object_build node member name
returns true if arg is a none node,def isNone arg u n Returns True if arg is a None node n return arg type token NAME and arg value u None
"takes a list of strings which are interpreted to be latex tabular lines ( ending with \ ) and transposes the tabular , meaning that the rows become the columns and vice versa",staticmethod def transpose_table lines Takes a list of strings which are interpreted to be latex tabular lines ending with and transposes the tabular meaning that the rows become the columns and vice versa entries for i in range len lines if lines i strip entries append lines i strip split transposed for line_idx in range len entries 0 cols for col_idx in range len entries cols append entries col_idx line_idx strip transposed append join cols return transposed
return the type signature of x. used to prevent comparison across types .,def get_type x if isinstance x float return N elif isinstance x Date return D elif isinstance x basestring if not x startswith fb raise ValueError NameValue does not start with fb format x tokens x split if len tokens 2 raise ValueError is not an entity format x return tokens 0 else raise ValueError Unknown type for format type x
: type path : str : rtype : str,classmethod def fromPath cls path kwargs styleSheet cls data styleSheet read path data StyleSheet format data kwargs styleSheet setData data return styleSheet
returns true if weight ( ) is a value greater than qfont::normal,def bold self return self font 0 bold
get and set path to radiance libraries .,property def radlib_path self return config radlib_path
folder to write analemma files .,property def analemma_folder self return os path join self light_source_folder analemma
send a packet to a radius server .,def SendPacket self pkt if isinstance pkt packet AuthPacket return self _SendPacket pkt self authport else return self _SendPacket pkt self acctport
create a many2many through model with two foreign key fields and a compositefieldid depending on the two foreign keys .,def Many2ManyThroughModel field from stdnet odm import ModelType StdModel ForeignKey CompositeIdField name_model field model _meta name name_relmodel field relmodel _meta name if name_model name_relmodel name_relmodel 2 through field through if through is None name 0 _ 1 format name_model name_relmodel class Meta app_label field model _meta app_label through ModelType name StdModel Meta Meta field through through field1 ForeignKey field model related_name field name related_manager_class makeMany2ManyRelatedManager field relmodel name_model name_relmodel field1 register_with_model name_model through field2 ForeignKey field relmodel related_name field related_name related_manager_class makeMany2ManyRelatedManager field model name_relmodel name_model field2 register_with_model name_relmodel through pk CompositeIdField name_model name_relmodel pk register_with_model id through
test ` backward ` function with ` channels_first ` data format .,def test_backward_grads_and_vars_channels_first self if not tf test is_gpu_available self skipTest GPU not available with tf device gpu 0 input_shape 32 224 224 data_shape 16 input_shape x tf random_normal shape data_shape y tf random_normal shape data_shape dy tf random_normal shape data_shape block blocks RevBlock n_res 3 filters 32 strides 1 1 input_shape input_shape dy grads vars_ block backward_grads_and_vars x y dy self assertEqual dy shape x shape self assertTrue isinstance grads list self assertTrue isinstance vars_ list y tf random_normal shape 16 32 112 112 dy tf random_normal shape 16 32 112 112 block blocks RevBlock n_res 3 filters 32 strides 2 2 input_shape input_shape dy grads vars_ block backward_grads_and_vars x y dy self assertEqual dy shape x shape self assertTrue isinstance grads list self assertTrue isinstance vars_ list
test : txt help arg generate,def test_txt_help_arg_generate self assert txt HLP_ARG_GENERATE is not None
lazy testing of the main function . checks the exitcode if everythings runs as planed .,def test_main_success self command usr bin env python3 cheat cheat py git dev null status os system command self assertEqual status self exit_0
determines if word is a valid word .,def isWord wordList word word word lower word word strip _ return word in wordList
convert a size value to a number with a magnitude appended .,def cvtToMag rh size rh printSysLog Enter generalUtils cvtToMag mSize size size 1024 1024 if size 1024 5 size size 1024 mSize 1fG size else mSize 1fM size rh printSysLog Exit generalUtils cvtToMag magSize mSize return mSize
the data is originally two empty array . the first array will be two dimensional input array called x that is m x n. the second array called y is the output array that is m x 1 . the number of stocks is denoted by m and the number of dates used for learning is denoted by n. all notation is to be consistent with the coursera machine learning course as much as possible .,def __init__ self self X self y self m 0 self n 0
the inventory can take asset data as well,with_setup clean def test_save_asset_data inventory_ copy deepcopy self _inventory asset inventory_ assets 0 asset update key value inventory save name self _project name config self _config inventory inventory_ asset io find_one type asset name asset name print asset assert_equals asset data key value
test nd_dist function on 2d data with ' euclidean ' metric .,def test_euclidean_dist2D self assert_allclose np asarray nd_dist self coords2d result_2D atol 0 1
od.__repr _ _ ( ) < = = > repr(od ),def __repr__ self _repr_running call_key id self _get_ident if call_key in _repr_running return _repr_running call_key 1 try if not self return s self __class__ __name__ return s r self __class__ __name__ self items finally del _repr_running call_key
common parsing logic for both use_macro and macro_block,def parse_macro_params token try bits token split_contents tag_name macro_name values bits 0 bits 1 bits 2 except IndexError raise template TemplateSyntaxError 0 tag requires at least one argument macro name format token contents split 0 args kwargs kwarg_regex A Za z_ w_ 0 0 A Za z_ w_ format arg_regex A Za z_ w_ 0 0 d format for value in values kwarg_match regex_match kwarg_regex value if kwarg_match kwargs kwarg_match groups 0 template Variable kwarg_match groups 1 else arg_match regex_match arg_regex value if arg_match args append template Variable arg_match groups 0 else raise template TemplateSyntaxError Malformed arguments to the 0 tag format tag_name return tag_name macro_name args kwargs
return whether this nonce is valid .,def useNonce self server_url timestamp salt if abs timestamp time time nonce SKEW return False if server_url proto rest server_url split 1 else proto rest domain _filenameEscape rest split 1 0 url_hash _safe64 server_url salt_hash _safe64 salt filename 08x s s s s timestamp proto domain url_hash salt_hash filename os path join self nonce_dir filename try fd os open filename os O_CREAT os O_EXCL os O_WRONLY 128 except OSError as why if why errno EEXIST return False else raise else os close fd return True
"generate a trie that is used for a special case where only one letter is given to the autocomplete function . since it 's very expensive to go over all combinations each time , this function does it once and stores the result . : return : a one - letter trie , which also gets stored on the drive",def one_letter try grams pd read_pickle resources words pkl except IOError grams load_words short_grams grams copy short_grams indices short_grams index res short_grams groupby first apply lambda group group nlargest 50 columns freq indices res indices values grams grams iloc indices grams freq grams freq apply lambda x x freqs grams freq values phrases grams first grams second fmt i phrases list map lambda x np unicode x phrases triee marisa RecordTrie fmt zip phrases freqs with open resources short_trie pkl wb as output pickle dump triee output pickle HIGHEST_PROTOCOL return triee
returns the data sent from the given path in pd .,def get self path host LOCALHOST port IN id s s s path host port if not id in self _callback self _callback id PDCallback path host port return self _callback id data
returns a good default set of parameters to use in the l4 region .,def getL2Params return inputWidth 256 16 cellCount 4096 sdrSize 40 synPermProximalInc 0 5 synPermProximalDec 0 0 initialProximalPermanence 0 6 minThresholdProximal 9 sampleSizeProximal 10 connectedPermanenceProximal 0 5 synPermDistalInc 0 1 synPermDistalDec 0 001 initialDistalPermanence 0 41 activationThresholdDistal 13 sampleSizeDistal 30 connectedPermanenceDistal 0 5 learningMode True
recover permamnece for a single column : param columnindex : index of the column of interest : return : perminfo ( dict ) with the following traces over time avgpermconnectedsyn : mean permanence for connected synapses avgpermnonconnectedsyn : mean permanence for non - connected synapses numconnectedsyn : number of connected synapses numnonconnectedsyn : number of non - connected synapses,def recoverPermanence self columnIndex verbose 0 getPermTrace 0 activeColumns self mmGetTraceActiveColumns activeInputs self mmGetTraceActiveInputs learnTrace self mmGetTraceLearn initialPermanence self mmGetDataInitialPermanence columnNumber inputSize initialPermanence shape potential numpy zeros inputSize dtype uintType self getPotential columnIndex potential maskPotential numpy where potential 0 0 permChanges numpy zeros inputSize dtype realDType perm numpy copy initialPermanence columnIndex numStep len activeColumns data numConnectedSyn avgPermConnected avgPermNonConnected activeSteps permTrace for i in range numStep if learnTrace data i is False continue if columnIndex in activeColumns data i 0 activeSteps append i if verbose print Column active at step format columnIndex i print active inputs format activeInputs data i permChanges fill 1 self _synPermInactiveDec permChanges activeInputs data i self _synPermActiveInc perm maskPotential permChanges maskPotential perm perm self _synPermTrimThreshold 0 numpy clip perm self _synPermMin self _synPermMax out perm if getPermTrace permTrace i perm numConnectedSyn append numpy sum perm self _synPermConnected permMask perm maskPotential avgPermConnected append numpy mean permMask permMask self _synPermConnected avgPermNonConnected append numpy mean permMask permMask self _synPermConnected truePermanence numpy zeros inputSize dtype realDType self getPermanence columnIndex truePermanence if numpy max numpy abs perm truePermanence 1e 10 raise RuntimeError Permamnence reconstruction failed The reconstructedpermamnence does not match the real permamnence numNonConnectedSyn len maskPotential numpy array numConnectedSyn permInfo avgPermConnectedSyn numpy array avgPermConnected avgPermNonConnectedSyn numpy array avgPermNonConnected numConnectedSyn numpy array numConnectedSyn numNonConnectedSyn numpy array numNonConnectedSyn permTrace permTrace activeSteps activeSteps return permInfo
byte - compile one python source file to python bytecode .,def compile file cfile None dfile None doraise False try _py_compile compile file cfile dfile except Exception as err py_exc PyCompileError err __class__ err args dfile or file if doraise raise py_exc else sys stderr write py_exc msg n return
returns whether the remote host runs systemd. otherwise it 's sysv init .,def isSystemD self if self m_is_systemd None return self m_is_systemd try self runRemote pgrep systemd silent True self m_is_systemd True except SshFailed self m_is_systemd False return self m_is_systemd
power on the specified machine .,staticmethod def poweron machine_id user pass
callback function to be passed to greenthread.link ( ) when we spawn ( ) .,def _on_thread_done _greenthread group thread group thread_done thread
"od.popitem ( ) - > ( k , v ) , return and remove a ( key , value ) pair . pairs are returned in lifo order if last is true or fifo order if false .",def popitem self last True if not self raise KeyError dictionary is empty root self __root if last link root 0 link_prev link 0 link_prev 1 root root 0 link_prev else link root 1 link_next link 1 root 1 link_next link_next 0 root key link 2 del self __map key value dict pop self key return key value
any instances which are not in the main queryset should be removed if the `` remove `` kwarg is `` true `` .,def test_remove self all_pks self video0 pk self video1 pk self video2 pk self video3 pk self video4 pk haystack_update apply args Video _meta app_label Video _meta module_name all_pks self video1 status Video REJECTED self video1 save update_index False expected set all_pks 1 results set int r pk for r in SearchQuerySet self assertEqual results expected haystack_update apply args Video _meta app_label Video _meta module_name all_pks kwargs remove True expected set all_pks 2 results set int r pk for r in SearchQuerySet self assertEqual results expected self video2 status Video REJECTED self video2 save update_index False expected set all_pks 2 results set int r pk for r in SearchQuerySet self assertEqual results expected haystack_update apply args Video _meta app_label Video _meta module_name all_pks kwargs remove False expected set all_pks 2 results set int r pk for r in SearchQuerySet self assertEqual results expected
test image closeness on opaque alpha for random 3 class dataset,def test_alpha self visualizer ParallelCoordinates alpha 1 0 visualizer fit_transform self dataset X self dataset y visualizer poof self assert_images_similar visualizer tol 0 25
non - numeric values for ' sample ' argument should raise .,def test_sample_invalid_type self with self assertRaises YellowbrickTypeError ParallelCoordinates sample foo
list of isomorphically equivalent field pairs for which value is not equal,property def field_with_different_value self return self _fields_with_different_value
"pil_usm.gblur(im , [ radius ] )",def gaussian_blur im radius None if radius is None radius 5 0 im load return im im gaussian_blur radius
a and b are vectors n is number of points of a to cut off anew and bnew will be the same length .,def shift a b n anew a list range 0 n len a if len anew len b anew anew list range 0 len b bnew b else bnew b list range 0 len anew return anew bnew
numerically upper bound the error in the ground state energy for the second order trotter - suzuki expansion .,def error_bound terms tight False zero QubitOperator error 0 0 if tight error sum abs coefficient for coefficient in error_operator terms terms values elif not tight for alpha in range len terms term_a terms alpha coefficient_a term_a terms values if coefficient_a error_a 0 0 for beta in range alpha 1 len terms term_b terms beta coefficient_b term_b terms values if not trivially_commutes term_a term_b or commutator term_a term_b zero error_a abs coefficient_b error 4 0 abs coefficient_a error_a 2 return error
should correctly interpret an ns query to elastic.co,def test_NS self self render_config_template dns_ports 53 self run_packetbeat pcap dns_ns pcap objs self read_output assert len objs 1 o objs 0 assert o type dns assert o transport udp assert o method QUERY assert o query class IN type NS elastic co assert o dns question type NS assert o status OK
"returns the value of the "" cc "" field .",def get_cc self return self cc
returns paginated queryset of pagerevision instances for specified page instance .,def get_revisions page page_num 1 revisions page revisions order_by created_at current page get_latest_revision if current revisions exclude id current id paginator Paginator revisions 5 try revisions paginator page page_num except PageNotAnInteger revisions paginator page 1 except EmptyPage revisions paginator page paginator num_pages return revisions
construct the tensor product operator basis of ` n ` pauli_basis 's .,def n_qubit_pauli_basis n if n 1 return PAULI_BASIS n else raise ValueError n should be at least 1 format n
odometry thread code - collects and sends out odometry esimate .,def run self while self is_looping timestamp rospy Time now try memData self memProxy getListData self dataNamesList odomData self motionProxy getPosition Torso motion SPACE_WORLD True positionData self motionProxy getAngles Body self useJointSensors if self useJointSensors referenceData self motionProxy getAngles Body False else referenceData positionData stiffnessData self motionProxy getStiffnesses Body except RuntimeError as e print Error accessing ALMemory exiting n print e rospy signal_shutdown No NaoQI available anymore self torsoOdom header stamp timestamp if len odomData 2 odomData odomData 1 elif len odomData 6 print Error getting odom data continue self torsoOdom pose pose position x odomData 0 self torsoOdom pose pose position y odomData 1 self torsoOdom pose pose position z odomData 2 q transformations quaternion_from_euler odomData 3 odomData 4 odomData 5 self torsoOdom pose pose orientation x q 0 self torsoOdom pose pose orientation y q 1 self torsoOdom pose pose orientation z q 2 self torsoOdom pose pose orientation w q 3 if self useOdometry t self torsoOdom pose pose position q self torsoOdom pose pose orientation self tf_br sendTransform t x t y t z q x q y q z q w timestamp self base_frameID self torsoOdom header frame_id self torsoOdomPub publish self torsoOdom for i m in enumerate memData if m is None memData i 0 if len memData len self dataNamesList print memData length does not match expected length print memData continue self torsoIMU header stamp timestamp q transformations quaternion_from_euler memData 1 memData 2 memData 3 self torsoIMU orientation x q 0 self torsoIMU orientation y q 1 self torsoIMU orientation z q 2 self torsoIMU orientation w q 3 self torsoIMU angular_velocity x memData 4 self torsoIMU angular_velocity y memData 5 self torsoIMU angular_velocity z memData 6 self torsoIMU linear_acceleration x memData 7 self torsoIMU linear_acceleration y memData 8 self torsoIMU linear_acceleration z memData 9 self torsoIMU orientation_covariance 0 1 self torsoIMU angular_velocity_covariance 0 1 self torsoIMU linear_acceleration_covariance 0 1 self torsoIMUPub publish self torsoIMU self jointState header stamp timestamp self jointState header frame_id self base_frameID self jointState position positionData self jointState effort map lambda x y x y positionData referenceData if len self jointState position 22 self jointState position insert 6 0 0 self jointState position insert 7 0 0 self jointState position append 0 0 self jointState position append 0 0 self jointStatePub publish self jointState self jointStiffness header stamp timestamp self jointStiffness header frame_id self base_frameID self jointStiffness effort stiffnessData self jointStiffnessPub publish self jointStiffness self sensorRate sleep
raise the patch part of the version,def bump_patch version verinfo parse version return format_version verinfo major verinfo minor verinfo patch 1
return the root doc element ( if there is one ),property def doc self guess self while guess is not None and guess tag Doc guess guess parent return guess
"takes no args . maybe we could specify colors , lidar params , etc .",def __init__ self tk Frame __init__ self borderwidth 4 relief sunken self master geometry str DISPLAY_CANVAS_SIZE_PIXELS x str DISPLAY_CANVAS_SIZE_PIXELS self master title Hokuyo URG04LX ESC to quit self grid self master rowconfigure 0 weight 1 self master columnconfigure 0 weight 1 self grid sticky tk W tk E tk N tk S self background DISPLAY_CANVAS_COLOR self canvas tk Canvas self width DISPLAY_CANVAS_SIZE_PIXELS height DISPLAY_CANVAS_SIZE_PIXELS background DISPLAY_CANVAS_COLOR self canvas grid row 0 column 0 rowspan 1 columnspan 1 sticky tk W tk E tk N tk S self bind Key self _key self focus_set self lines self lidar URG04LX URG_DEVICE self scandata scan_angle_rad radians URG_DETECTION_DEG 2 float k URG_SCAN_SIZE URG_DETECTION_DEG for k in range URG_SCAN_SIZE self half_canvas_pix DISPLAY_CANVAS_SIZE_PIXELS 2 scale self half_canvas_pix float URG_MAX_SCAN_DIST_MM self cos cos angle scale for angle in scan_angle_rad self sin sin angle scale for angle in scan_angle_rad self lines self canvas create_line self half_canvas_pix self half_canvas_pix self half_canvas_pix self sin k URG_MAX_SCAN_DIST_MM self half_canvas_pix self cos k URG_MAX_SCAN_DIST_MM for k in range URG_SCAN_SIZE self canvas itemconfig line fill DISPLAY_SCAN_LINE_COLOR for line in self lines thread start_new_thread grab_scan self self running True
sets a value in the container,def set_value self labels value if labels self _label_names_correct labels with mutex self values labels value
parse unregister request from sparcs sso server : param data_dict : a data dictionary that the server sent : returns : the user 's service i d : raises runtimeerror : raise iff the request is invalid,def parse_unregister_request self data_dict client_id data_dict get client_id sid data_dict get sid timestamp data_dict get timestamp sign data_dict get sign if client_id self client_id raise RuntimeError INVALID_REQUEST elif not self _validate_sign sid timestamp sign raise RuntimeError INVALID_REQUEST return sid
: param inpaths : list of input file paths : param itype : input type or none : param fmsg : message if it can not detect otype by ` inpath ` : return : output type : : str,def _output_type_by_input_path inpaths itype fmsg msg Specify inpath and or outpath type s with I itype or O otype option explicitly if itype is None try otype API find_loader inpaths 0 type except API UnknownFileTypeError _exit_with_output fmsg inpaths 0 msg 1 except ValueError IndexError _exit_with_output msg 1 else otype itype return otype
each row that contains an email address should get added to the list,def test_add_contact_info_emails self row self empty_row row Department A row Agency B contact_dict layer add_contact_info contact_dict row self assertEqual contact_dict A B emails row Email Address a b com layer add_contact_info contact_dict row self assertEqual contact_dict A B emails a b com row Email Address c d gov layer add_contact_info contact_dict row self assertEqual contact_dict A B emails a b com c d gov row Email Address c d gov layer add_contact_info contact_dict row self assertEqual contact_dict A B emails a b com c d gov
old fileio provided for backwards compatibility,def _legacy_fileio self filename IO data None if IO save and data None return self save_json filename data elif IO load and data None return self load_json filename elif IO check and data None return self is_valid_json filename else raise InvalidFileIO FileIO was called with invalid parameters
create an http server for tensorboard .,def make_simple_server tb_app host port 0 path_prefix try if host server serving make_server host port tb_app threaded True if in host and not host startswith final_host format host else final_host host else try server serving make_server host port tb_app threaded True except socket error server serving make_server port tb_app threaded True final_host socket gethostname server daemon_threads True except socket error if port 0 msg TensorBoard unable to find any open port else msg TensorBoard attempted to bind to port d but it was already in use port logger error msg print msg raise server handle_error _handle_error final_port server socket getsockname 1 tensorboard_url http s d s final_host final_port path_prefix return server tensorboard_url
create a real time graph of the free memory in the system .,def graph_memory_usage u x np linspace 0 50 1000 y np linspace 0 1 1000 scale int generate_memory_stats next if scale 1600000 scale 1600000 y 0 scale plt ion fig plt figure ax fig add_subplot 111 line1 ax plot x y u r xmin xmax 0 50 ymin ymax 0 scale 1 1 plt axis xmin xmax ymin ymax try for record in generate_memory_stats y np append y 1 record line1 set_ydata y fig canvas draw except KeyboardInterrupt print u Memory graph exited
filters and removes possible nones in texts and tails ref : http://stackoverflow.com/questions/4624062/get-all-text-inside-a-tag-in-lxml,def stringify_affiliation node parts node text list chain c text if c tag label and c tag sup else c tail for c in node getchildren node tail return join filter None parts
"creates a extrusion from a face , along the vector vector . with a distance legnth . note that the normal vector does not necessary be normalized . by default , the extrusion is along the z axis .",def make_extrusion face length vector gp_Vec 0 0 0 0 1 0 vector Normalize vector Scale length return BRepPrimAPI_MakePrism face vector Shape
there should be a blank line before epytext markups .,def d self a return a
"run provided component . this function takes care of running setup , performing the component . it takes of ignoring the error , if the component is non - critical . : param component_obj : component object to be run . : param component_times : dictionary in which each components times should be recorded . : return : true if component ran fine else false .",def __run_component component_obj component_times setup_msg component_obj setup if setup_msg is None log_success Setup for component component_obj get_name complete st_time time time ret_val component_obj perform total_time time time st_time component_times component_obj get_name total_time if ret_val log_success Component component_obj get_name ran successfully return True else log_warning Component component_obj get_name failed if not component_obj is_critical return True else log_error Setup failed for component component_obj get_name with Error setup_msg return False
returns dictionary with data corresponding to the app_name given .,def get_app_dict_from_plist self plist_path app_name try app_dicts self get_plist_app_dicts plist_path for app_dict in app_dicts if app_dict get name app_name return app_dict except Exception as e logger error Failed getting info from plist for app_name logger exception e return
dummy to retain interface - compatibility with other operating systems .,def expandvars path return path
set : set an object 's data . required argument : the object for the command keyword argument to : the new value . keyword argument _ attributes : appleevent attribute dictionary,def _set self _object _attributes _arguments _code core _subcode setd keysubst _arguments self _argmap_set _arguments _object _reply _arguments _attributes self send _code _subcode _arguments _attributes if _arguments get errn 0 raise Error decodeerror _arguments if in _arguments return _arguments
"the external energy of the point , a combination of line and edge",def _externalEnergy image smooth_image point pixel 255 image point 1 point 0 smooth_pixel 255 smooth_image point 1 point 0 external_energy _W_LINE pixel _W_EDGE smooth_pixel 2 return external_energy
create a message from a simple pydict template,test_1 def test_blank_template self msg Message Message BLANK print msg msg dump
test getting an element for a plain error .,def test_getElementPlain self e error BaseError feature not implemented element e getElement self assertIdentical element uri None self assertEqual len element children 1
"constructor . called in the urlconf ; can contain helpful extra keyword arguments , and other things .",def __init__ self kwargs u n Constructor Called in the URLconf can contain helpful extra n keyword arguments and other things n for key value in six iteritems kwargs setattr self key value
"set up a l{team } with inspectable , synchronous workers that can be single - stepped .",def setUp self coordinator self coordinateOnce createMemoryWorker self coordinator ContextualWorker coordinator worker coordinator self workerPerformers self allWorkersEver self allUnquitWorkers self activePerformers self noMoreWorkers lambda False def createWorker if self noMoreWorkers return None worker performer createMemoryWorker self workerPerformers append performer self activePerformers append performer cw ContextualWorker worker worker len self workerPerformers self allWorkersEver append cw self allUnquitWorkers append cw realQuit cw quit def quitAndRemove realQuit self allUnquitWorkers remove cw self activePerformers remove performer cw quit quitAndRemove return cw self failures def logException self failures append Failure self team Team coordinator createWorker logException
"when l{finger . finger } receives a blank line , it responds with a message rejecting the request for all online users .",def test_list self self protocol dataReceived r n self assertEqual self transport value Finger online list denied n
generates a javascript array of glatlng objects for the given coordinates .,def latlng_from_coords self coords u return u s u join u new GLatLng s s y x for x y in coords
l{crammd5credentials } implements the l{iusernamehashedpassword } interface .,def test_interface self self assertTrue IUsernameHashedPassword implementedBy CramMD5Credentials
"retrieves a list of stored messages . returns a tuple of the messages and a flag indicating whether or not all the messages originally intended to be stored in this storage were , in fact , stored and retrieved ; e.g. , `` ( messages , all_retrieved ) `` .",def _get self args kwargs u n Retrieves a list of stored messages Returns a tuple of the messages n and a flag indicating whether or not all the messages originally n intended to be stored in this storage were in fact stored and n retrieved e g messages all_retrieved n n This method must be implemented by a subclass n n If it is possible to tell if the backend was not used as opposed to n just containing no messages then None should be returned in n place of messages n raise NotImplementedError u subclasses of BaseStorage must provide a _get method
parses a duration string and returns a datetime.timedelta .,def parse_duration value match standard_duration_re match value if not match match iso8601_duration_re match value if match kw match groupdict if kw get microseconds kw microseconds kw microseconds ljust 6 0 kw k float v for k v in six iteritems kw if v is not None return datetime timedelta kw
l{cdata.__repr _ _ } returns a value which makes it easy to see what 's in the comment .,def test_cdataReprPy2 self self assertEqual repr CDATA u test data CDATA u test data
cleans any instances of invalid sphinx wording .,def _clean_changelog_message msg u Cleans any instances of invalid sphinx wording n n This escapes removes any instances of invalid characters n that can be interpreted by sphinx as a warning or error n when translating the Changelog into an HTML file for n documentation building within projects n n Escapes _ which is interpreted as a link n Escapes which is interpreted as a new line n Escapes which is interpreted as a literal n msg msg replace u u msg msg replace u _ u _ msg msg replace u u return msg
returns the default time zone as a tzinfo instance .,lru_cache lru_cache def get_default_timezone if isinstance settings TIME_ZONE six string_types and pytz is not None return pytz timezone settings TIME_ZONE else return LocalTimezone
"handles merging together conflicted migrations interactively , if it 's safe ; otherwise , advises on how to fix it .",def handle_merge self loader conflicts if self interactive questioner InteractiveMigrationQuestioner else questioner MigrationQuestioner defaults ask_merge True for app_label migration_names in conflicts items merge_migrations for migration_name in migration_names migration loader get_migration app_label migration_name migration ancestry mig for mig in loader graph forwards_plan app_label migration_name if mig 0 migration app_label merge_migrations append migration all_items_equal lambda seq all item seq 0 for item in seq 1 merge_migrations_generations zip m ancestry for m in merge_migrations common_ancestor_count sum 1 for common_ancestor_generation in takewhile all_items_equal merge_migrations_generations if not common_ancestor_count raise ValueError Could not find common ancestor of s migration_names for migration in merge_migrations migration branch migration ancestry common_ancestor_count migrations_ops loader get_migration node_app node_name operations for node_app node_name in migration branch migration merged_operations sum migrations_ops if self verbosity 0 self stdout write self style MIGRATE_HEADING Merging s app_label for migration in merge_migrations self stdout write self style MIGRATE_LABEL Branch s migration name for operation in migration merged_operations self stdout write s n operation describe if questioner ask_merge app_label numbers MigrationAutodetector parse_number migration name for migration in merge_migrations try biggest_number max x for x in numbers if x is not None except ValueError biggest_number 1 subclass type Migration Migration dependencies app_label migration name for migration in merge_migrations new_migration subclass 04i_merge biggest_number 1 app_label writer MigrationWriter new_migration if not self dry_run with open writer path wb as fh fh write writer as_string if self verbosity 0 self stdout write nCreated new merge migration s writer path elif self verbosity 3 self stdout write self style MIGRATE_HEADING Full merge migrations file s writer filename n self stdout write s n writer as_string
hook overloading the one used in plain telnet,def _write self data data data replace n r n replace r r n r n super TelnetProtocol self _write mccp_compress self data
set the lut from an external source,def set_lut self lut self lut lut
add all the key / value pairs in l{dict } to this dirdbm . any conflicting keys will be overwritten with the values from l{dict}.,def update self dict for key val in dict items self key val
render as html a listing of all known users with links to their personal resources .,def render_GET self request domImpl getDOMImplementation newDoc domImpl createDocument None ul None listing newDoc documentElement for link text in self _users linkElement newDoc createElement a linkElement setAttribute href link textNode newDoc createTextNode text linkElement appendChild textNode item newDoc createElement li item appendChild linkElement listing appendChild item htmlDoc self template users listing toxml return htmlDoc encode utf 8
generates the download url for each photo size .,def url_maker self sizes flickr_api photos_getSizes photo_id self flickr_spec get id out_dict for size_element in sizes find sizes findall size label size_element attrib label url size_element attrib source out_dict label url return out_dict
obtain the first account name from public key,def getAccountFromPublicKey self pub names self rpc get_key_references pub 0 if not names return None else return names 0
returns checkpoint filename given directory or specific filepattern .,def _get_checkpoint_filename filepattern if gfile IsDirectory filepattern return saver latest_checkpoint filepattern return filepattern
a wrapper around commandhandlerregistry.register_command_handler ( ) .,def register_command_handler self prefix handler help_info prefix_aliases None self _command_handler_registry register_command_handler prefix handler help_info prefix_aliases prefix_aliases self _tab_completion_registry extend_comp_items prefix if prefix_aliases self _tab_completion_registry extend_comp_items prefix_aliases
annotate a python source file with a list of ops created at each line .,def annotate_source dump source_file_path do_dumped_tensors False file_stack_top False min_line None max_line None py_graph dump python_graph if not py_graph raise ValueError Cannot perform source annotation due to a lack of set Python graph in the dump object source_file_path _norm_abs_path source_file_path line_to_op_names for op in py_graph get_operations for file_path line_number _ _ in reversed dump node_traceback op name if min_line is not None and line_number min_line or max_line is not None and line_number max_line continue if _norm_abs_path file_path source_file_path continue if do_dumped_tensors watch_keys dump debug_watch_keys op name items_to_append list set map _convert_watch_key_to_tensor_name watch_keys else items_to_append op name if line_number in line_to_op_names line_to_op_names line_number extend items_to_append else line_to_op_names line_number items_to_append if file_stack_top break return line_to_op_names
computes the global norm of multiple tensors .,def global_norm t_list name None if not isinstance t_list collections Sequence or isinstance t_list six string_types raise TypeError t_list should be a sequence t_list list t_list with ops name_scope name global_norm t_list as name values ops convert_to_tensor t values if isinstance t ops IndexedSlices else t name t_ d i if t is not None else t for i t in enumerate t_list half_squared_norms for v in values if v is not None with ops colocate_with v half_squared_norms append gen_nn_ops l2_loss v half_squared_norm math_ops reduce_sum array_ops stack half_squared_norms norm math_ops sqrt half_squared_norm constant_op constant 2 0 dtype half_squared_norm dtype name global_norm return norm
return 2**n for integer n such that 2**n > = value .,def _enclosing_power_of_two value value_static tensor_util constant_value value if value_static is not None return constant_op constant int 2 np ceil np log value_static np log 2 0 value dtype return math_ops cast math_ops pow 2 0 math_ops ceil math_ops log math_ops to_float value math_ops log 2 0 value dtype
compute set union of elements in last dimension of ` a ` and ` b ` .,def set_union a b validate_indices True a b _ _convert_to_tensors_or_sparse_tensors a b return _set_operation a b union validate_indices
def : function to get the user choice from the versions list view . notice that we might allow the user to selected another movie in the lower levels of the call stack . input : list of subversion . list of submovies . optional - logmsg ( will call writelog ) . return : the selected subversion / submovie,def getVersionChoice self subVersions subMovies logMsg None raise NotImplementedError IInteractor getVersionChoice
unquote unicode or str using query string rules .,def _qs_decode_py2 s if isinstance s unicode s s encode utf 8 return urllib unquote_plus s decode utf 8
: type device : str : type partitions : list[diskpartition ] : type size : int : type type : enumdiskinfotype : rtype : diskinfo,staticmethod def create device partitions size type return DiskInfo device device partitions partitions size size type type
write the macros section of a cdt settings export file .,def WriteMacros out eclipse_langs defines out write section name org eclipse cdt internal ui wizards settingswizards Macros n out write language name holder for library settings language n for lang in eclipse_langs out write language name s n lang for key in sorted defines iterkeys out write macro name s name value s value macro n escape key escape defines key out write language n out write section n
set the display mode to normal .,def set_normal_mode self self mmio write iop_const MAILBOX_OFFSET iop_const MAILBOX_PY2IOP_CMD_OFFSET 3 while self mmio read iop_const MAILBOX_OFFSET iop_const MAILBOX_PY2IOP_CMD_OFFSET 3 pass
recodes variables from the respondent frame .,def CleanFemResp df pass
used to play a sound matching a category : param subdir : which subdir to pull the file out of . base dir is audio : return : a full path to the sound file chosen .,def get_random_wav_file subdir return get_full_path subdir random choice list_all_sound_files subdir
test pattern match using regular expression faillure,def test_patternmatch_with_regex_not_found match_scorer PatternMatch flag assert match_scorer This is a flag 1 assert match_scorer Incorrect 1
parse all data necessary for loading a case into scout,def parse_case_data config None ped None owner None vcf_snv None vcf_sv None vcf_cancer None peddy_ped None peddy_sex None peddy_check None delivery_report None config_data copy deepcopy config or if analysis_date not in config_data config_data analysis_date datetime datetime now if ped family_id samples parse_ped ped config_data family family_id config_data samples samples if owner not in config_data if not owner raise SyntaxError Case has no owner else config_data owner owner if gene_panels in config_data config_data gene_panels panel strip for panel in config_data gene_panels config_data default_gene_panels panel strip for panel in config_data default_gene_panels config_data peddy_ped peddy_ped or config_data get peddy_ped config_data peddy_sex_check peddy_sex or config_data get peddy_sex config_data peddy_ped_check peddy_check or config_data get peddy_check add_peddy_information config_data config_data vcf_snv vcf_snv if vcf_snv else config_data get vcf_snv config_data vcf_sv vcf_sv if vcf_sv else config_data get vcf_sv config_data vcf_cancer vcf_cancer if vcf_cancer else config_data get vcf_cancer config_data delivery_report delivery_report if delivery_report else config_data get delivery_report config_data rank_model_version config_data get rank_model_version config_data rank_score_threshold config_data get rank_score_threshold 0 return config_data
"returns the path of this ` uncdirectory ` with the authorization string prepended . if this ` uncdirectory ` has no associated credentials , the returned path will be the ` uncdirectory ` 's path unmodified . otherwise , the returned path will resemble the http basic authentication scheme in its format .",def get_auth_path self creds self get_auth_string return creds at path format creds creds at if creds else path self _path
record fatal ` message ` .,def fatal self system message print_traceback False if self stream sys stderr self log F system message stream sys stderr self log F system message if print_traceback traceback print_exc file self stream if self exit_on_fatal sys exit 1 else raise WeaverError system message
adds the urls of all views provided by `` publishablemixin `` models .,def scan_views self args kwargs views super PublishableEntityOptions self scan_views args kwargs publishable_views url api P lang w name s P pk d P slug _ w pdf format name self modelname self document_public_view as_view model self model name s_printable self modelname url api P lang w name s P pk d P slug _ w html format name self modelname self markup_public_view as_view model self model return publishable_views views
setup test_occupancy class by establishing parameters,def setUp self bed_list ChunkList read example example bed self chunk bed_list 0 self vmat V VMat open example example VMat self vmat V VMat open example example VMat self mat FragmentMat2D self chunk chrom self chunk start self vmat w self chunk end self vmat w self vmat lower self vmat upper self mat makeFragmentMat example example bam self signal Nuc SignalTrack self chunk chrom self chunk start self chunk end self signal calculateSignal self mat self vmat
the url to redirect to when a token has expired .,def get_auth_expired_url self u raise NotImplemented u 0 must implement the get_auth_expired_url method format self __class__
: type root : treenode : rtype : int,def findSecondMinimumValue self root res float inf def traverse node if not node return if root val node val res 0 res 0 node val traverse node left traverse node right traverse root return 1 if res 0 float inf else res 0
read csv delimited input from slurm .,def _read_output self command cmd cmd extend self _prefix cmd extend self _path iP cmd extend command command cmd logger debug Cmd s command null open dev null w process subprocess Popen command stdout subprocess PIPE stderr null null close results reader csv reader _input_csv process stdout delimiter str try headers next reader logger debug headers s headers except StopIteration logger debug Cmd s headers not found command headers for row in reader _output_csv row logger debug row s row this_row i 0 for i in range 0 len headers key headers i value row i this_row key value results append this_row process stdout close retcode process wait if retcode 0 logger error Cmd s returned d error command retcode raise subprocess CalledProcessError retcode command if len headers 0 logger error Cmd s didn t return any headers command raise RuntimeError Cmd s didn t return any headers command logger debug Returned d good retcode return results
called when a local reader is added or removed . create remote pyro reader objects for added readers . delete remote pyro reader objects for removed readers .,def update self observable actions addedreaders removedreaders actions for reader in addedreaders remotereader RemoteReader reader self remotereaders reader name remotereader name join reader name split name pyscard smartcard readers join name split uri self daemon connect remotereader name for reader in removedreaders remotereader self remotereaders reader name self daemon disconnect remotereader del self remotereaders reader name self pn listall
switch the units of the entered number,def switchUnits self if self data units INCHES self data units MM self unitsBtn text MM else self data units INCHES self unitsBtn text INCHES
utility function : prints using shell colors .,def _do_print_color vargs kwargs colorcode kwargs pop colorcode destination kwargs pop file sys stderr colors_on _COLORS COLORS_OFF colors_forced _COLORS COLORS_FORCED if colors_on and destination isatty or colors_forced vargs list vargs for index varg in enumerate vargs varg_lines for line in str varg split n varg_lines append x1b 00 im s x1b 00m colorcode line vargs index n join varg_lines print file destination vargs kwargs if n in kwargs get end n destination flush
recursively finds all db references to be dereferenced,def _find_references self items depth 0 reference_map if not items or depth self max_depth return reference_map if isinstance items dict iterator items values else iterator items depth 1 for item in iterator if isinstance item Document EmbeddedDocument for field_name field in item _fields iteritems v item _data get field_name None if isinstance v LazyReference continue elif isinstance v DBRef reference_map setdefault field document_type set add v id elif isinstance v dict SON and _ref in v reference_map setdefault get_document v _cls set add v _ref id elif isinstance v dict list tuple and depth self max_depth field_cls getattr getattr field field None document_type None references self _find_references v depth for key refs in references iteritems if isinstance field_cls Document TopLevelDocumentMetaclass key field_cls reference_map setdefault key set update refs elif isinstance item LazyReference continue elif isinstance item DBRef reference_map setdefault item collection set add item id elif isinstance item dict SON and _ref in item reference_map setdefault get_document item _cls set add item _ref id elif isinstance item dict list tuple and depth 1 self max_depth references self _find_references item depth 1 for key refs in references iteritems reference_map setdefault key set update refs return reference_map
list of tensors that were provided as initialization inputs .,property def inputs self return self _chol
wrapper view function for the following pages : /features,def features_page request context RequestContext request if GET request method return render request features index html context else raise MethodNotAllowed request
alert when a cert 's expiration is within 60 days,def check_future_expiration self cert_item expiration cert_item config get NotAfter None if expiration expiration parser parse expiration now expiration now tzutc time_to_expiration expiration now days if 0 time_to_expiration 60 notes Expires on 0 format str expiration self add_issue 5 Cert will expire soon cert_item notes notes
returns summation of all values in a list .,staticmethod def sum lst return sum lst
"makes a plot representing how the scores vary over the parameter grid automatically decides whether to use a simple line plot ( varying over one parameter ) or a heatmap ( varying over two parameters ) : param scores : a list of scores , estimated using scoremodels : param paramgrid : the parameter grid specified when fitting the models using fitmodels : param scorelabel : the specified label ( dependent on scoring metric used ) , e.g. ' auc ' : param vrange : the visible range over which to display the scores : return :",def plotScores scores paramGrid scoreLabel None vrange None keys sorted list paramGrid 0 keys uniqParams dict order dict for k in keys order k np unique params k if params k is not None else None for params in list paramGrid return_index True 1 uniqParams k params k for params in np asarray list paramGrid sorted order k keysToPlot list for k in keys if len uniqParams k 1 keysToPlot append k for k in keys if k not in keysToPlot uniqParams pop k None numDim len keysToPlot if numDim 3 print Too many dimensions to plot elif numDim 3 plot3DGrid scores uniqParams keysToPlot scoreLabel vrange elif numDim 2 plot2DGrid scores uniqParams keysToPlot scoreLabel vrange elif numDim 1 plot1DGrid scores uniqParams scoreLabel vrange else print No parameters that vary in the grid
construct a tcpserver from a factory defined in pericote,def makeService self options factory application MambaApplicationFactory settings httpserver internet TCPServer int options port factory httpserver setName Application format settings name httpserver setServiceParent application return httpserver
create an aggregation request . this request may then be passed to ` client.aggregate ( ) ` .,def __init__ self query self _query query self _groups self _projections self _loadfields self _limit Limit self _sortby self _max 0 self _with_schema False self _verbatim False self _cursor
take screenshots until one of the ' done ' subimages is found . image is saved when subimage found or at timeout .,def screenshot_until_match save_to timeout subimg_candidates expected_count gen from PIL import ImageGrab assert save_to endswith png stop_after time time timeout while True with ImageGrab grab next gen as rgba with rgba convert mode RGB as screenshot count_found try_candidates screenshot subimg_candidates expected_count if count_found expected_count or time time stop_after screenshot save save_to assert count_found expected_count return time sleep 0 5
"the stix v1.1.1 schemas enforces id uniqueness , so this overrides the default `` _ get_duplicates ( ) `` .",def _get_duplicates self root pass
: param table_filename : name of the dummy table file : param table_filedir : directory for the table file,def __init__ self table_filename table_filedir table_name None self table None self _table_filename table_filename self _table_filedir table_filedir self _full_path os path join table_filedir s s self _table_filename settings SCISHEETS_EXT self _table_name table_name if self _table_name is None self _table_name table_filename
calibration routine . measures the color of the ball and stores it in the class . : param img_hsv : hsv - image to use for calculation . the ball has to be positioned in the center : return : none,def calibrate self img_hsv x_center int round img_hsv shape 1 2 y_center int round img_hsv shape 0 2 color img_hsv y_center x_center lower_border_arr color 20 20 20 upper_border_arr color 20 20 20 lower_border tuple lower_border_arr tolist upper_border tuple upper_border_arr tolist mask cv2 inRange img_hsv lower_border upper_border colors img_hsv mask 255 h_mean int round np mean colors 0 s_mean int round np mean colors 1 v_mean int round np mean colors 2 av h_mean s_mean v_mean self ball_color tuple av
list all the recipes in a default space .,def list_recipes self return self public_recipe self private_recipe
get the env with all variables parsed using python string formatting,def get_env env env update api env for setting overrides in ENV_OVERRIDES iteritems for k v in overrides iteritems if env setting k env update v passes ENV_PARSE_PASSES found 1 while passes and found found 0 for k v in env items if isinstance v basestring and in v env k v env found 1 passes 1 api env update env return api env
create and initialize a logger object .,def __init__ self name cfg_path None default_level logging INFO default_conf None extra None env_key CONF_PATH self name name self cfg_path cfg_path self default_level default_level self default_conf default_conf self env_key env_key self extra extra self logger self setup_logging
parse a boolean ' or ' expression .,def _parse_exp_or self ret False while True ret self _parse_exp_and or ret tok self lex peek if tok self lex tok_par_close return ret elif tok self lex tok_or self lex advance else return ret return False
how to load the data from the layer / provider . implementation is completely up to the developer . may choose to have a copy of the data in the class or just the info needed to query the provider,abc abstractmethod def load self timeLayer args kwargs pass
updates goals as follows on enrollment changes : 1 ) set the course goal to ' certify ' when the user enrolls as a verified user . 2 ) remove the course goal when the user 's enrollment is no longer active .,receiver models signals post_save sender CourseEnrollment dispatch_uid update_course_goal_on_enroll_change def update_course_goal_on_enroll_change sender instance kwargs course_id str instance course_id decode utf8 ignore if not instance is_active remove_course_goal instance user course_id elif instance mode CourseMode VERIFIED add_course_goal instance user course_id GOAL_KEY_CHOICES certify
returns boolean indicating if credentials should be issued .,property def is_learner_issuance_enabled self return self enabled and self enable_learner_issuance
selects images type filter checkbox which filters the results . returns false if no filter .,wait_for_js def select_type_filter self filter_number self wait_for_ajax if self is_filter_element_on_page self q css self TYPE_FILTER_ELEMENT form check form check input nth filter_number click self wait_for_ajax return True return False
safely and consistently format numeric values,def safe_string value if isinstance value NUMERIC_TYPES if isnan value value else value 16g value elif value is None value none elif not isinstance value basestring value str value return value
"return the low - level touch frame consisting into a touch int and a list of filtered values for each touch key in calibrated mode : return : ( touch_int , touch_key_booleans ]",def get_touch_frame self return self _touch_int self _touch_keys_booleans
patching but still using the original function,def test_method_uses_original self k testmod Original self assertEqual k get_strings testmod STR_ORI self assertEqual k get_strings test testmod STR_ORI test with patchy testmod Original testmod SuperPatchyThings as p p add get_strings self assertEqual k get_strings testmod STR_ADD testmod STR_ORI self assertEqual k get_strings test testmod STR_ADD testmod STR_ORI test
same as : py : meth:`ratio ` .,def quick_ratio self return self ratio
"separate url keyword arguments into their functional category . incoming kwargs are separated into one of 4 categories , depending on how the argument controls the pipeline :",def get_cleaned_options self kwargs options dotdict for kwarg_category in control_kwargs es_kwargs esqb_kwargs transform_kwargs options setdefault kwarg_category dotdict for option settings in getattr self kwarg_category items if option in kwargs or settings get default None is not None options get kwarg_category setdefault option kwargs get option settings default if options esqb_kwargs userquery for k in kwargs keys if re match self web_settings USERQUERY_KWARG_REGEX k options esqb_kwargs setdefault userquery_kwargs dotdict options esqb_kwargs userquery_kwargs self web_settings USERQUERY_KWARG_TRANSFORM k kwargs get k return options
acquire singleton pluginasset instance from a graph .,def get_plugin_asset plugin_asset_cls graph None if graph is None graph ops get_default_graph if not plugin_asset_cls plugin_name raise ValueError Class s has no plugin_name plugin_asset_cls __name__ name _PLUGIN_ASSET_PREFIX plugin_asset_cls plugin_name container graph get_collection name if container if len container is not 1 raise ValueError Collection for s had d items expected 1 name len container instance container 0 if not isinstance instance plugin_asset_cls raise ValueError Plugin name collision between classes s and s plugin_asset_cls __name__ instance __class__ __name__ else instance plugin_asset_cls graph add_to_collection name instance graph add_to_collection _PLUGIN_ASSET_PREFIX plugin_asset_cls plugin_name return instance
get fixed / sorted order of goog.provide statements .,def GetFixedProvideString self token return self _GetFixedRequireOrProvideString self _GetRequireOrProvideTokens token goog provide
return temperature in celsius degrees .,def parse_temperature text match re search u s s s text return float match group 1 if match else None
this function writes the log .,def write_log text write_file read_file log_file log n text
return a random periodic element symbol .,def symbol self return choice self _elements values
allow initialization from args from both this class and its superclass . default ctypes implementation seems to assume that this class is only initialized with its own _ fields _ ( for non - keyword - args ) .,def __init__ self args kwargs super_self super DYNAMIC_TIME_ZONE_INFORMATION self super_fields super_self _fields_ super_args args len super_fields self_args args len super_fields for field arg in zip super_fields super_args field_name spec field kwargs field_name arg super DYNAMIC_TIME_ZONE_INFORMATION self __init__ self_args kwargs
cookies is a list of scopecookie . filters is a list of filterspec .,def __init__ self cookies filters object_callback None finished_callback None close_callback None self _closed False self _close_callback stack_context wrap close_callback self _cookies get_cookie_map cookies self _filters filters self _connections dict h _DiamondConnection h self close for h in self _cookies self _blast _DiamondBlastSet self _connections values object_callback finished_callback
"requests the last known production mix ( in mw ) of a given zone arguments : zone_key ( optional ) -- used in case a parser is able to fetch multiple zones session ( optional ) -- request session passed in order to re - use an existing session return : a list of dictionaries in the form : { ' zonekey ' : ' fr ' , ' datetime ' : ' 2017 - 01 - 01t00:00:00z ' , ' production ' : { ' biomass ' : 0.0 , ' coal ' : 0.0 , ' gas ' : 0.0 , ' hydro ' : 0.0 , ' nuclear ' : null , ' oil ' : 0.0 , ' solar ' : 0.0 , ' wind ' : 0.0 , ' geothermal ' : 0.0 , ' unknown ' : 0.0 } , ' storage ' : { ' hydro ' : -10.0 , } , ' source ' : ' mysource.com ' }",def fetch_production zone_key US IPC session None target_datetime None logger getLogger __name__ if target_datetime is not None raise NotImplementedError This parser is not yet able to parse past dates raw_data get_data session session processed_data data_processer raw_data logger production_data for item in processed_data datapoint zoneKey zone_key datetime item 0 production item 1 storage source idahopower com production_data append datapoint return production_data
function to delete models from the appcache and remove them from the models module in which they 're defined .,def _cleanup models from django db models loading import cache deleted imp acquire_lock try for app_label model_dict in cache app_models items for django_name klass in model_dict items name format klass __module__ klass __name__ if name in models module sys modules klass __module__ delattr module klass __name__ del model_dict django_name deleted append name if sorted deleted sorted models expected join models expected expected if expected else none actual join deleted actual actual if actual else none raise AssertionError Expected to delete actually deleted format expected actual cache loaded False cache _get_models_cache cache handled cache postponed cache nesting_level 0 cache _populate finally imp release_lock
"` tokens ` = a pos - tagged sentence [ ( w1 , t1 ) , ... ] ` index ` = the index of the token we want to extract features for ` history ` = the previous predicted iob tags",def features tokens index history stemmer SnowballStemmer english tokens __START2__ __START2__ __START1__ __START1__ list tokens __END1__ __END1__ __END2__ __END2__ history __START2__ __START1__ list history index 2 word pos tokens index prevword prevpos tokens index 1 prevprevword prevprevpos tokens index 2 nextword nextpos tokens index 1 nextnextword nextnextpos tokens index 2 return word word lemma stemmer stem word pos pos next word nextword next pos nextpos next next word nextnextword nextnextpos nextnextpos prev word prevword prev pos prevpos prev prev word prevprevword prev prev pos prevprevpos
"generate detections results using rpn . : param predictor : predictor : param test_data : data iterator , must be non - shuffled : param imdb : image database : param vis : controls visualization : param thresh : thresh for valid detections : return : list of detected boxes",def generate_proposals predictor test_data imdb vis False thresh 0 0 assert vis or not test_data shuffle data_names k 0 for k in test_data provide_data i 0 t time time imdb_boxes list original_boxes list for im_info data_batch in test_data t1 time time t t time time scale im_info 0 2 scores boxes data_dict im_proposal predictor data_batch data_names scale t2 time time t t time time dets np hstack boxes scores original_boxes append dets keep np where dets 4 thresh 0 dets dets keep imdb_boxes append dets if vis vis_all_detection data_dict data asnumpy dets obj scale logger info generating d d i 1 imdb num_images proposal d dets shape 0 data 4fs net 4fs t1 t2 i 1 assert len imdb_boxes imdb num_images calculations not complete rpn_folder os path join imdb root_path rpn_data if not os path exists rpn_folder os mkdir rpn_folder rpn_file os path join rpn_folder imdb name _rpn pkl with open rpn_file wb as f cPickle dump imdb_boxes f cPickle HIGHEST_PROTOCOL if thresh 0 full_rpn_file os path join rpn_folder imdb name _full_rpn pkl with open full_rpn_file wb as f cPickle dump original_boxes f cPickle HIGHEST_PROTOCOL logger info wrote rpn proposals to s rpn_file return imdb_boxes
return the routing key for an object given `` kwargs `` .,def get_key_from_kwargs self kwargs return sum int kwargs f for f in self key
adds ops for loss to the computational graph .,def add_loss_op self pred raise NotImplementedError Each Model must re implement this method
terminate an elastic mapreduce job flow,def terminate_jobflows self jobflow_ids params self build_list_params params jobflow_ids JobFlowIds member return self get_status TerminateJobFlows params verb POST
"creates an ordered , minimal perfect hash function for the given sequence of words .",def make_hash words args kwargs return CzechHashBuilder words args kwargs hash_function
"joins one or more path components to the base path component intelligently . returns a normalized , absolute version of the final path .",def safe_join base paths base force_unicode base paths force_unicode p for p in paths final_path normcase abspathu join base paths base_path normcase abspathu base base_path_len len base_path if not final_path startswith base_path or final_path base_path_len base_path_len 1 not in sep raise ValueError the joined path is located outside of the base path component return final_path
converts objects to table - style list of rows with heading :,def object_list_to_table headings dict_list return headings tuple getattr_by_path row heading None for heading in headings for row in dict_list
"returns the value of the field , instead of an instance of the field object . may take a string of the field name or a field object as parameters .",def get self field field_name getattr field name field return self field_name value
"puts the transaction manager into a manual state : managed transactions have to be committed explicitly by the user . if you switch off transaction management and there is a pending commit / rollback , the data will be commited .",def managed flag True using None if using is None using DEFAULT_DB_ALIAS connection connections using thread_ident thread get_ident top state get thread_ident get using None if top top 1 flag if not flag and is_dirty using using connection _commit set_clean using using else raise TransactionManagementError This code isn t under transaction management
apply any necessary pre - save moderation steps to new comments .,def pre_save_moderation self sender comment request kwargs model comment content_type model_class if model not in self _registry return content_object comment content_object moderation_class self _registry model if not moderation_class allow comment content_object request return False if moderation_class moderate comment content_object request comment is_public False
set a nicer error message than the orm .,def clean_email self email self cleaned_data email try get_user_model _default_manager get email email except get_user_model DoesNotExist return email raise forms ValidationError self error_messages duplicate_email
"this function will connect to the specified vcenter server . if it fails , it will retry",def connect_vcenter logger logging getLogger __name__ ssl_context ssl SSLContext ssl PROTOCOL_TLSv1 ssl_context verify_mode ssl CERT_NONE server_instance None try logger debug Connecting to VCENTER_SERVER server_instance SmartConnect host VCENTER_SERVER user VCENTER_USERNAME pwd VCENTER_PASSWORD sslContext ssl_context server_instance _stub connectionPoolTimeout 1 except Exception as error logger error Error connecting to VCENTER_SERVER str error return server_instance
energy of li atom ( dft ) close to -7.3321 ?,def runTest self E main self assertInside E energy 0 0001
get power state from a list of vm isntance statuses,def get_power_state self statuses for status in statuses if status code startswith Power return status code 11
reads an internal partner object parameter .,def get_param self number logger debug retreiving param number s number type_ snap7 snap7types param_types number value type_ code self library Par_GetParam self pointer ctypes c_int number ctypes byref value check_error code return value value
"returns true if the line contains data , false otherwise",def _is_data self line return len line 0
creates and subsequently auto - imports a python module .,IPython core magic register_line_cell_magic def pymodule line cell None u Creates and subsequently auto imports a python module n parser _commands CommandParser create u pymodule parser add_argument u n u name help u the name of the python module to create and import parser set_defaults func _pymodule_cell return _utils handle_magic_line line cell parser
check if an http server runs on a given port .,def is_http_running_on port u Check if an http server runs on a given port n n Args n The port to check n Returns n True if it is used by an http server False otherwise n try conn httplib HTTPConnection u 127 0 0 1 str port conn connect conn close return True except Exception return False
construct a c{carbon - relay } service .,def makeService self options from carbon import service return service createRelayService options
"this is called to set a coil 's v or t or tr or i attribute to the state argument . it simply looks up the instance in the coils vector and applies the coil 's method with the state given as argument . note that the attribute is converted to an index to be passed to the coil 's setfuncs vector to find the correct method to call . once the user representation is updated , the bitmgr is called with the same arguments to update the next bit vectors . usage : > > > a.set('m',state.vol,state.l0 )",def set self name att state pass
test that extract_dot_git ( ) correctly extracts repository information from a .git folder 's config file .,mock patch gslab_scons _release_tools open def test_extract_dot_git self mock_open mock_open side_effect fx dot_git_open_side_effect repo_info tools extract_dot_git git self assertEqual repo_info 0 repo self assertEqual repo_info 1 org self assertEqual repo_info 2 branch with self assertRaises ReleaseError repo_info tools extract_dot_git not git mock_open side_effect fx dot_git_open_side_effect url False with self assertRaises ReleaseError repo_info tools extract_dot_git git
a simple wrapper around `` cocreateinstance < https://msdn.microsoft.com/en-us/library/windows/desktop/ms686615(v=vs.85).aspx > ``,def create_instance clsiid targetinterface custom_iid None context CLSCTX_INPROC_SERVER CLSCTX_LOCAL_SERVER if custom_iid is None custom_iid targetinterface IID return winproxy CoCreateInstance byref clsiid None context byref custom_iid byref targetinterface
parses highlighted results returned from elasticsearch query on the text,def _parse_es_search_results results entity_value_list variant_value_list variant_dictionary if results and results hits total 0 for hit in results hits hits if highlight not in hit continue count_of_variants len hit highlight variants count 0 while count count_of_variants entity_value_list append hit _source value variant_value_list append hit highlight variants count count 1 count 0 while count len variant_value_list variant_value_list count re sub s variant_value_list count strip if variant_value_list count count em len variant_value_list count split variant variant_value_list count replace em variant variant replace em if variant strip in variant_dictionary existing_value variant_dictionary variant strip if len existing_value split len entity_value_list count split variant_dictionary variant strip entity_value_list count else variant_dictionary variant strip entity_value_list count count 1 return variant_dictionary
generate all possible combinations ( cartesian product ) of the hyperparameter values returns : a new dictionary with a grid of all the possible hyperparameter combinations,def grid_params dict keys dict keys val_arr for key in keys val_arr append dict key permutations list itertools product val_arr args_dict slice_index 0 for key in keys args_arr for val in list zip permutations slice_index args_arr append val slice_index 1 args_dict key args_arr return args_dict
gets the available versions of the game .,def GetKSPVersions pattern None global cached_versions if not cached_versions LOGGER debug Requesting versions to cache response _CallAPI _MakeAPIUrl API_GET_VERSIONS None None cached_versions map lambda x name x friendly_version id x id response 0 if pattern regex re compile pattern return filter lambda x regex match x name cached_versions return cached_versions
userfactory can be saved with invalid data if build is used,def test_build_save self user UserFactory build username bad user result user save self assertIsNone result self assertEqual self user_model objects count 1 self assertEqual self user_model objects get username bad user user
this essentially replicates what 's done when awslimitchecker is called from the command line with `` -u `` . this replicates some of the internal logic of : py : class:`~awslimitchecker.runner . runner ` .,pytest mark integration skip_if_pr def test_verify_usage self checker_args creds_type service_name expect_usage allow_endpoint_error boto3 DEFAULT_SESSION None if creds_type normal creds self normal_creds elif creds_type sts creds self sts_creds elif creds_type sts_mfa creds self sts_mfa_creds checker_args mfa_serial_number creds 2 else raise RuntimeError unknown creds type s creds_type os environ AWS_ACCESS_KEY_ID creds 0 os environ AWS_SECRET_ACCESS_KEY creds 1 if mfa_token in checker_args checker_args mfa_token self totp_code creds 3 with LogCapture as l checker AwsLimitChecker checker_args checker find_usage service service_name limits checker get_limits service service_name logs LogRecordHelper l have_usage False data for svc in sorted limits keys for lim in sorted limits svc keys limit limits svc lim data s l format s svc l lim v format v limit get_current_usage_str for usage in limit get_current_usage if usage get_value 0 have_usage True logs verify_region checker_args get region REGION print dict2cols data if expect_usage assert have_usage is True records logs unexpected_logs allow_endpoint_error allow_endpoint_error assert len records 0 awslimitchecker emitted unexpected log messages at WARN or higher s n join records
states[0 ] is the initial state .,def __init__ self states self states states self state states 0 self entryHooks self exitHooks
function that traverses all qap output directory tree and locates scan - specific target pdf files to be processed,def find_pdf_files qap_output_directory scan_dirname Returns a list of matched files found_files target_file_types fd pdf mosaic pdf for root1 dirs1 files1 in os walk qap_output_directory if scan_dirname in dirs1 for root2 dirs2 files2 in os walk os path join root1 scan_dirname for filename in files2 if filename in target_file_types found_files append os path join root2 filename return found_files
receives a c_ast . decl note and returns its explanation in english .,def _explain_decl_node decl_node storage join decl_node storage if decl_node storage else return decl_node name is a storage _explain_type decl_node type
this function computes mcfs score and ranking features according to feature weights matrix w,def feature_ranking W mcfs_score W max 1 idx np argsort mcfs_score 0 idx idx 1 return idx
read linker information into object from the library,def read_linker self linker_index library hd_lib self index linker_index self name library linker_names linker_index 1 self atom_names library atom_names linker_index 1 self atom_coors library atom_coors linker_index 1 self num_of_atoms library number_of_atoms linker_index 1 self connectivity library connectivity linker_index 1
: param value : : return : ascii url,def value2url_param value if value None Log error Can not encode None into a URL if isinstance value Mapping value_ wrap value output join value2url_param k value2url_param v if isinstance v basestring else value2url_param value2json v for k v in value_ leaves elif isinstance value unicode output join _map2url c for c in value encode utf8 elif isinstance value str output join _map2url c for c in value elif hasattr value __iter__ output join value2url_param v for v in value else output str value return output
determine if it is necessary to download a page,def needs_update self fname timestamp if not os path exists fname return True local datetime datetime utcfromtimestamp os path getmtime fname if local timestamp or local self epoch return True return False
"perform multi - stage preprocessing on the input image args : blur_kn_size ( [ int ] ) : kernel size for median blurring . low_int_threshold ( [ int ] ) : cutoff used in artifacts suppression . high_int_threshold ( [ int ] ) : cutoff used in pectoral muscle removal . returns : a tuple of ( processed_image , color_image_with_boundary ) . if pectoral removal was not called , the color image is none .",def process self img median_filtering True blur_kn_size 3 artif_suppression True low_int_threshold 0 05 kernel_size 15 pect_removal False high_int_threshold 0 8 pect_kwargs img_proc img copy if median_filtering img_proc cv2 medianBlur img_proc blur_kn_size if artif_suppression img_proc mask_ self suppress_artifacts img_proc global_threshold low_int_threshold kernel_size kernel_size else _ mask_ self suppress_artifacts img_proc if pect_removal img_proc img_col self remove_pectoral img_proc mask_ high_int_threshold high_int_threshold pect_kwargs else img_col None return img_proc img_col
return the lib dir under the ' home ' installation scheme,def home_lib home if hasattr sys pypy_version_info lib site packages else lib os path join lib python return os path join home lib
returns the number of items in the dictionary,def __len__ self return len self __dict
get all revisions of an article after revision_id,def get_forward_revisions title revision_id time_delta start _ get_revisions title rvstartid revision_id count 1 start_time wikipedia_api iso_to_datetime start 0 timestamp end_time start_time time_delta results cont None while True revisions query_cont get_revisions title rvstartid revision_id count BATCH_SIZE rvend wikipedia_api datetime_to_iso end_time rvcontinue cont if not revisions or not len revisions break cont query_cont results revisions if not cont break return results
returns the derivative of the logistic ( sigmoid ) function at y ( output ),def bprop self y return self bprop_func y
configure the raspberry gpios : rtype : none,staticmethod def setup GPIO setmode GPIO BCM GPIO setup BOARD LED GPIO OUT GPIO output BOARD LED 0 GPIO setup BOARD SWITCH GPIO IN pull_up_down GPIO PUD_DOWN for gpio_pin in BOARD DIO0 BOARD DIO1 BOARD DIO2 BOARD DIO3 GPIO setup gpio_pin GPIO IN pull_up_down GPIO PUD_DOWN BOARD blink 0 1 2
return the next quote date 's data event from all subscribed symbol,def stream_next self try data_event next self data_stream except StopIteration self continue_backtest False return self current_date data_event date self update_data data_event quotes self queue put data_event
"decorator that passes a praw object to any number of functions that persist the object to a new data store . the decorated function must return a praw object ( e.g. : praw.models.reddit.submission.submission , praw.models.reddit.comment.comment )",def reddit_object_persist persistence_funcs def api_indexing_listener_inner func wraps func def wrapped_api_func args kwargs reddit_obj func args kwargs try for persistence_func in persistence_funcs persistence_func reddit_obj except Exception log exception Error occurred while trying to serialize and index PRAW object return reddit_obj return wrapped_api_func return api_indexing_listener_inner
takes a tuple of pokertools . card objects and returns a sorted list of counts of the card ranks .,memoize def sorted_count_of_values cards list_of_ranks card numerical_rank for card in cards return sorted Counter list_of_ranks values reverse True
get a single line of input as a string from a textfield,def line_input args kwargs line_input wtforms TextField args kwargs line_input input_type line return line_input
"wrap a view function , verifying that the user hsa all of the specified permissions .",staticmethod def require permissions assert permissions Must specify at least one permission for perm in permissions if not perm exists raise RuntimeError Cannot require undocumented permission s perm wrapt decorator def req wrapped instance args kwargs if not can permissions if util is_browser and current_user is_anonymous return current_app login_manager unauthorized else abort 403 return wrapped args kwargs return req
plot a 2d trace of time - series data .,msme_colors def plot_trace2d data obs 0 1 ts 1 0 cbar True ax None xlabel None ylabel None labelsize 14 cbar_kwargs None scatter_kwargs None plot_kwargs None if ax is None ax pp gca if scatter_kwargs is None scatter_kwargs if plot_kwargs is None plot_kwargs if not isinstance obs tuple raise ValueError obs must be a tuple if isinstance data list for item in data prune item obs ax plot prune 0 prune 1 plot_kwargs else prune data obs c ax scatter prune 0 prune 1 c np linspace 0 data shape 0 ts data shape 0 scatter_kwargs if cbar if cbar_kwargs is None cbar_kwargs pp colorbar c cbar_kwargs if xlabel ax set_xlabel xlabel size labelsize if ylabel ax set_ylabel ylabel size labelsize return ax
restore a snapshot for all shapes of a specific ctrls .,def fetch_ctrl_shapes source target pymel delete filter lambda x isinstance x pymel nodetypes CurveShape target getShapes for source_shape in source getShapes shape_snapshot _duplicate_shape source_shape tmp_transform shape_snapshot getParent shape_snapshot setParent target r True s True shape_snapshot rename target name Shape pymel delete tmp_transform
handle a bit which is the next breakpoint by checking the current breakpoint scope is finished or can be finished and then shift to the next scope .,def handle_next_breakpoint self bit self check_required self options shift_breakpoint self arguments self options get_arguments if self arguments self current_argument self arguments pop 0 else self current_argument None
list messages from the journal .,def list_messages ns reverse False tail False inst ns LMI_JournalMessageLog first_instance if not inst raise LmiFailed Cannot initialize Journald provider hint check if it s installed if reverse or tail r inst PositionToLastRecord else r inst PositionToFirstRecord if not IterationIdentifier in r rparams raise LmiFailed Cannot initialize Journald iteration hint check SELinux AVCs iter_id r rparams IterationIdentifier if tail r inst PositionAtRecord IterationIdentifier iter_id MoveAbsolute False RecordNumber NUM_TAIL iter_id r rparams IterationIdentifier try while True r inst GetRecord IterationIdentifier iter_id PositionToNext not reverse if r rval 0 break iter_id r rparams IterationIdentifier if reverse x inst PositionAtRecord IterationIdentifier iter_id MoveAbsolute False RecordNumber 1 iter_id x rparams IterationIdentifier print join map chr r rparams RecordData except KeyboardInterrupt pass inst CancelIteration IterationIdentifier iter_id return 0
check asserttrue / false(a in / not in b ) with collection contents .,skip_ignored_lines def assert_true_or_false_with_in logical_line filename res re_assert_true_false_with_in_or_not_in search logical_line or re_assert_true_false_with_in_or_not_in_spaces search logical_line if res yield 0 N323 assertTrue assertFalse A in not in B sentences not allowed you should use assertIn A B or assertNotIn A B instead
"normalize path : return canonical path , normalizing case on windows .",def normalize_path path if path startswith ASSET_SCHEME return path return os path normcase os path realpath path
a specialization of ` inf_nan_callback ` that checks for ` inf`s only .,def inf_callback op_type op_name attrs inputs outputs action _DEFAULT_CALLBACK_ACTION inf_nan_callback op_type op_name attrs inputs outputs check_inf True check_nan False action action
takes a list of lists object with each csv row as a list,def write_csv dest df df to_csv dest
name of the file with params,def text_model_filename textset_id model_type params folder get_data_folder texts s textset_id if not os path exists folder os makedirs folder params_name join key _ str params key for key in params keys for c in params_name params_name replace c return folder s model_type params_name replace _
send the list of pixel colors to the opc server on the given channel .,def put_pixels self pixels channel 0 self _debug put_pixels connecting is_connected self _ensure_connected if not is_connected self _debug put_pixels not connected ignoring these pixels return False len_hi_byte int len pixels 3 256 len_lo_byte len pixels 3 256 command 0 header struct pack BBBB channel command len_hi_byte len_lo_byte pieces struct pack BBB min 255 max 0 int r min 255 max 0 int g min 255 max 0 int b for r g b in pixels if sys version_info 0 3 message header join pieces else message header join pieces self _debug put_pixels sending pixels to server try self _socket send message except socket error self _debug put_pixels connection lost could not send pixels self _socket None return False if not self _long_connection self _debug put_pixels disconnecting self disconnect return True
initialization function which could take an existing curve as an option . if you build your own sea - level curve you need to define this parameter as none .,def __init__ self curve None self df None self time None self func None if curve None self build False self df pd read_csv curve1 sep s header None names h t else self build True self func None self time None return
create a list with tree nodes for which the < filter > function returned true in a post order foashion,def test_known_values_post_order_list self L child_2_1 child_3_1 child_2_2 child_1_1 child_2_3 child_1_2 root l n id for n in post_order_list self o self assertEqual l L l
resets this preprocessor to some initial state . this method is called whenever an episode ends . this could be useful if the preprocessor stores certain episode - sequence information to do the processing and this information has to be reset after the episode terminates .,def tf_reset self pass
return whether the action should render .,def should_render self context u Return whether the action should render n n Args n context dict n The current render context n n Returns n bool n Whether the action should render n review_request context u review_request user context u request user return review_request status ReviewRequest PENDING_REVIEW and not is_site_read_only_for user and context u request user pk review_request submitter_id or context u perms u reviews u can_change_status and review_request public
"fetches the previous page , returning the page data .",def next self u Fetches the previous page returning the page data n n Subclasses must override this to provide the logic for n fetching pages n n If there isn t a next page available this must raise n InvalidPageError n raise NotImplementedError
check the validity of a repository hosted on assembla .,def check_repository self path username password scmtool_class local_site_name assembla_project_id None args kwargs u Check the validity of a repository hosted on Assembla n n Perforce repositories are handled specially The Assembla project ID n will be used as the Perforce host which is needed to tell Assembla n which repository on the server to use n n Args n path unicode n The repository path n n username unicode n The username used for authenticating n n password unicode n The password used for authenticating n n scmtool_class type n The SCMTool for the repository n n local_site_name unicode n The name of the Local Site if any n n assembla_project_id unicode n The project ID for the Assembla team n n args tuple n Additional arguments to pass to the superclass n n kwargs dict n Additional keyword arguments to pass to the superclass n username self account username password self get_password if scmtool_class name u Perforce scmtool_class check_repository path path username username password password local_site_name local_site_name p4_host assembla_project_id p4_client self make_p4_client_name assembla_project_id else super Assembla self check_repository path path username username password password local_site_name local_site_name scmtool_class scmtool_class kwargs
adds query parameters onto the given url .,def _add_query_params self url new_query_params u scheme netloc path query_string fragment urlsplit url query_params parse_qs query_string query_params update new_query_params new_query_string urlencode key value for key value in sorted six iteritems query_params key lambda i i 0 doseq True return urlunsplit scheme netloc path new_query_string fragment
a function returning a decorator to skip some test on a given distribution - version combination,def skip_on skip_on_distros skip_on_version skip_on_arch reason if isinstance skip_on_distros str skip_on_distros skip_on_distros distro version get_version arch os uname 1 def decorator func if distro in skip_on_distros and not skip_on_version or skip_on_version version and not skip_on_arch or skip_on_arch arch msg not supported on this distribution in this version and arch s reason if reason else return unittest skip msg func else return func return decorator
return the default settings for generating latex circuits .,def get_default_settings settings dict settings gate_shadow True settings lines style very thin double_classical True init_quantum True double_lines_sep 0 04 settings gates HGate width 0 5 offset 0 3 pre_offset 0 1 XGate width 0 35 height 0 35 offset 0 1 SwapGate width 0 35 height 0 35 offset 0 1 Rx width 1 0 height 0 8 pre_offset 0 2 offset 0 3 Ry width 1 0 height 0 8 pre_offset 0 2 offset 0 3 Rz width 1 0 height 0 8 pre_offset 0 2 offset 0 3 EntangleGate width 1 8 offset 0 2 pre_offset 0 2 DeallocateQubitGate height 0 15 offset 0 2 width 0 2 pre_offset 0 1 AllocateQubitGate height 0 15 width 0 2 offset 0 1 pre_offset 0 1 draw_id False MeasureGate width 0 75 offset 0 2 height 0 5 pre_offset 0 2 settings control size 0 1 shadow False return settings
read sstable files directly from disk,def _get_sstable_files self node ks table ret for data_dir in node data_directories keyspace_dir os path join data_dir ks for ext in db txt adler32 crc32 ret extend glob glob os path join keyspace_dir table ext return sorted ret
import : : = filler import_name store_fast import : : = filler import_name store_name,def p_import15 self args
set of all fields marked as not nullable in db model that are currently not defined,property def null_required_fields self self _null_required_fields key for key in self required_keys if self get key is None return self _null_required_fields
query ( list ) volumes . : param offset : pagination offset . : param limit : pagination limit . : param api : api instance . : return : collection object .,classmethod def query cls offset None limit None api None api api or cls _API return super Volume cls _query url cls _URL query offset offset limit limit fields _all api api
return a sequence of notes that match the given query .,def search self query return self search_function self query
"receive a feature report . blocks , unless you configured provided file ( descriptor ) to be non - blocking .",def getFeatureReport self report_num 0 length 63 length 1 buf ctypes create_string_buffer length buf 0 chr report_num self _ioctl _HIDIOCGFEATURE length buf True return buf value
handles retrying failed requests and error handling .,def _request self method endpoint id None kwargs request getattr requests method None if not callable request raise RequestError Invalid method s method data kwargs get data if data files for name value in list data items if hasattr value read or isinstance value tuple files name data pop name if files kwargs setdefault files update files path api self version endpoint if id path append str id path join path if not path endswith path while in path path path replace url self url path kwargs setdefault headers setdefault User Agent HTTP_USER_AGENT trys retrys 0 3 while True if trys retrys raise RequestError Could not complete request after s trys trys trys 1 try return self _do_request request url kwargs except ResponseError as e if self throttle_wait and e status_code 503 m THROTTLE_PATTERN match e response headers get x throttle if m time sleep float m group 1 continue raise
read parameters from a lan file header .,def read_erdas_lan_header fileName byte_order 0 u Read parameters from a lan file header n n Arguments n n fileName str n n File to open n n byte_order int default 0 n n Specifies whether to read as little 0 or big 1 endian n from array import array import sys import spectral from spectral utilities python23 import IS_PYTHON3 typecode from spyfile import InvalidFileError if IS_PYTHON3 import builtins else import __builtin__ as builtins f builtins open fileName u rb h h u format u lan h u fileName fileName h u sizeOfHeader 128 h u type f read 6 if h u type not in HEAD74 HEADER raise InvalidFileError u Does not look like an ERDAS Lan header word array typecode u h dword array typecode u i float array typecode u f word fromfile f 2 f seek 16 if h u type HEAD74 dword fromfile f 4 else float fromfile f 4 f seek 88 word fromfile f 2 f seek 106 word fromfile f 1 float fromfile f 5 if byte_order spectral byte_order word byteswap dword byteswap float byteswap h u packing word pop 0 h u nbands word pop 0 if h u type HEAD74 h u ncols dword pop 0 h u nrows dword pop 0 h u pixel_xcoord dword pop 0 h u pixel_ycoord dword pop 0 else h u ncols int float pop 0 h u nrows int float pop 0 h u pixel_xcoord float pop 0 h u pixel_ycoord float pop 0 h u map_type word pop 0 h u nclasses word pop 0 h u area_unit word pop 0 h u ypixel_size float pop h u xpixel_size float pop h u map_ycoord float pop h u map_xcoord float pop h u narea_units float pop f close return h
rule : id ' : ' ' ; ',def p_rule_empty p p 0 p 1
return absolute path from where this file is located,def absPath path return os path join os path dirname os path abspath __file__ path
tests that the caseclass class can not be instantiated directly .,def test_no_direct self self assertRaises exceptions NotInstantiableClassException case_class CaseClass
this method called when plugin was stopped,def stop self pass
ensure that the build directory is present .,def check_build if not os path isdir build_dir try os makedirs build_dir except OSError as exc if exc errno errno EEXIST pass else raise
"computes ( vec1 , vec2 ) < - ( alpha*vec1+beta*vec2 , -beta*vec1+alpha*vec2 )",def plane_rotation vec1 vec2 alpha beta if isinstance vec1 Node vec1 vec1 result if isinstance vec2 Node vec2 vec2 result if isinstance alpha Node alpha alpha result if isinstance beta Node beta beta result if isinstance vec1 Vector x vec1 vcl_leaf if isinstance vec2 Vector if vec1 dtype vec2 dtype raise TypeError Vector dtypes must be the same y vec2 vcl_leaf else y vec2 else x vec1 if isinstance vec2 Vector y vec2 vcl_leaf else y vec2 if isinstance alpha ScalarBase if isinstance vec1 Vector if alpha dtype vec1 dtype raise TypeError Vector and scalar dtypes must be the same a alpha value else a alpha if isinstance beta ScalarBase if isinstance vec1 Vector if beta dtype vec1 dtype raise TypeError Vector and scalar dtypes must be the same b beta value else b beta return _v plane_rotation x y a b
update push token that is already in use by another device .,def testDuplicateToken self self _tester UpdateDevice self _cookie self _mobile_device device_id _DEVICE_DICT user device_id self _tester RegisterGoogleUser name Andy email kimball andy emailscrubbed com verified_email True cookie self _GetSecureUserCookie user device_id self _tester UpdateDevice cookie device_id push_token _DEVICE_DICT push_token
"creates a performance counter which tracks the accumulation of a value since the previous sample of the counter , thus providing a delta of the underlying value of the counter . the performance counter can be incremented using one of several increment methods :",def define_delta name description manager counters counter _DeltaCounter name description manager register counter return counter
test forced expiration of a shorturl .,def testExpire self self _RunAsync self _short_url Expire self _client response self _RunAsync self http_client fetch self _url method GET self assertEqual response code 403
verify that a contact without any identities succeeds .,def testUploadContactWithNoIdentities self contacts identities contact_source Contact IPHONE name Mike Purtell given_name Mike family_name Purtell upload_result self _tester UploadContacts self _cookie contacts self assertEqual len upload_result contact_ids 1 contact_id upload_result contact_ids 0 result self _tester QueryContacts self _cookie self assertEqual len result contacts 1 self assertEqual len result contacts 0 identities 0 self _tester RemoveContacts self _cookie contact_id result self _tester QueryContacts self _cookie self assertEqual len result contacts 1 self assertIn removed result contacts 0 labels
get zookeeper server stats as a map,def get_stats self data self _send_cmd mntr if data return self _parse data else data self _send_cmd stat return self _parse_stat data
this class is important because it leaves the bullet ready to trigger .,def __init__ self text to_lang from_lang None content_type text plain category None self text text self to to_lang self from_lang from_lang self contentType content_type self category category
ensure we can not access a resource that requirest authentication without an appropriate authentication header,def test_request_without_authentication self response self test_client get url_for api messagelistresource _external True headers self get_accept_content_type_headers self assertTrue response status_code status HTTP_401_UNAUTHORIZED
simple method for generating a unique identifier .,def generate_uuid args t long time time 1000 r long random random 1000000000000000L a random random 1000000000000000L data s s s s str t str r str a str args return hashlib md5 data hexdigest
generate a random sample of rois comprising foreground and background examples .,def _sample_rois all_rois gt_boxes fg_rois_per_image rois_per_image num_classes overlaps bbox_overlaps np ascontiguousarray all_rois 1 5 dtype np float np ascontiguousarray gt_boxes 4 dtype np float gt_assignment overlaps argmax axis 1 max_overlaps overlaps max axis 1 labels gt_boxes gt_assignment 4 fg_inds np where max_overlaps cfg TRAIN FG_THRESH 0 fg_rois_per_this_image min fg_rois_per_image fg_inds size if fg_inds size 0 fg_inds npr choice fg_inds size fg_rois_per_this_image replace False bg_inds np where max_overlaps cfg TRAIN BG_THRESH_HI max_overlaps cfg TRAIN BG_THRESH_LO 0 bg_rois_per_this_image rois_per_image fg_rois_per_this_image bg_rois_per_this_image min bg_rois_per_this_image bg_inds size if bg_inds size 0 bg_inds npr choice bg_inds size bg_rois_per_this_image replace False keep_inds np append fg_inds bg_inds labels labels keep_inds labels fg_rois_per_this_image 0 rois all_rois keep_inds bbox_target_data _compute_targets rois 1 5 gt_boxes gt_assignment keep_inds 4 labels bbox_targets bbox_inside_weights _get_bbox_regression_labels bbox_target_data num_classes return labels rois bbox_targets bbox_inside_weights
compute pairwise iou similarity between the two boxlists .,def _compare self boxlist1 boxlist2 return box_list_ops iou boxlist1 boxlist2
get grouped files based on the dirname,staticmethod def _get_dir_grouped_files files files_grouped for file in files rel_path os path relpath file os getcwd dir_path os path dirname rel_path if dir_path dir_path Source_Files if not dir_path in files_grouped keys files_grouped dir_path files_grouped dir_path append file return files_grouped
lists all aggregate_cls events defined within the application . note : only events with a defined ` mutate_event ` flow and are not marked as abstract will be returned .,def list_aggregate_events aggregate_cls events _list_internal_classes aggregate_cls DomainEvent return event_cls for event_cls in events if is_event_mutating event_cls and not is_abstract event_cls
returns the `` json `` representation of the instance .,def to_json self return json dumps self to_dict
returns help message with description and usage,def help_msg self mod importlib import_module s self name return getattr mod parser format_help
stops monitoring power utilization and returns collects stats,def StopMonitoringPowerAsync self raise NotImplementedError
prepare the results for this page .,def Stop self page tab assert self _histogram_start Must call Start first for h in _HISTOGRAMS if h name not in self _histogram_start continue histogram_data histogram_util GetHistogram h type h name tab self _histogram_delta h name histogram_util SubtractHistogram histogram_data self _histogram_start h name
encrypt the passed - in bytes .,def encrypt self bytes paddedBytes self _addPKCS1Padding bytes 2 m bytesToNumber paddedBytes if m self n raise ValueError c self _rawPublicKeyOp m encBytes numberToBytes c return encBytes
generate the structures required by a property such as object classes and enums .,def _GenerateTypes self types is_toplevel False generate_typedefs False c Code for type_ in types c Cblock self _GenerateType type_ is_toplevel is_toplevel generate_typedefs generate_typedefs return c
: param bundle : : param prov_type : valid prov type like prov : entry as string : param prov_id : valid i d as string like < namespace>:<name > : param properties : dict{attr_name : attr_value } dict with all properties ( prov and additional ) : param type_map : dict{attr_name : type_str } contains the type information for each property ( only if type is necessary ) : return : provrecord,def create_prov_record bundle prov_type prov_id properties type_map if isinstance properties dict properties_list properties items elif isinstance properties list properties_list properties else raise SerializerException Please provide properties as list key value or dict your provided format properties __class__ __name__ attributes dict other_attributes membership_extra_members None for attr_name values in properties_list attr PROV_ATTRIBUTES_ID_MAP attr_name if attr_name in PROV_ATTRIBUTES_ID_MAP else bundle valid_qualified_name attr_name if attr in PROV_ATTRIBUTES if isinstance values list if len values 1 if prov_type PROV_MEMBERSHIP and attr PROV_ATTR_ENTITY membership_extra_members values 1 value values 0 else error_msg The prov package does not support PROV attributes having multiple values logger error error_msg raise SerializerException error_msg else value values 0 else value values if attr in PROV_ATTRIBUTE_QNAMES value bundle valid_qualified_name value elif isinstance value datetime value value else parse_xsd_datetime value attributes attr value else value_type None if type_map value_type type_map get attr_name if isinstance values list other_attributes extend attr decode_json_representation value value_type bundle for value in values else other_attributes append attr decode_json_representation values value_type bundle record bundle new_record prov_type prov_id attributes other_attributes if membership_extra_members collection attributes PROV_ATTR_COLLECTION for member in membership_extra_members bundle membership collection bundle valid_qualified_name member return record
handle entries that want to set the position / size of other entries,def GetEntryPositions self for entry in self _entries values pos_dict entry GetPositions for name info in pos_dict iteritems self _SetEntryPosSize name info
constructor inputs : url - admin url securityhandler - handler that handles site security username - admin username password - admin password,def __init__ self url securityHandler proxy_url None proxy_port None initialize False self _proxy_port proxy_port self _proxy_url proxy_url self _url url self _securityHandler securityHandler if initialize self __init
configure and start logging based on user preferences,def start self console logfile debug global predicate level LogLevel debug if debug else LogLevel info predicate LogLevelFilterPredicate defaultLogLevel level if console f sys stdout else if os path exists logfile and not os path isfile logfile print Logfile s is not a valid file Exiting logfile return False try f open logfile a except IOError print Can t open logfile s Exiting logfile return False observer textFileLogObserver f observers FilteringLogObserver observer observer predicates predicate globalLogBeginner beginLoggingTo observers return True
convert the angular velocities from earth frame to body frame . thanks to james goppert for the formula,def EarthRatesToBodyRates dcm earth_rates from math import sin cos phi theta psi dcm to_euler phiDot earth_rates x thetaDot earth_rates y psiDot earth_rates z p phiDot psiDot sin theta q cos phi thetaDot sin phi psiDot cos theta r cos phi psiDot cos theta sin phi thetaDot return Vector3 p q r
search for obligation type by name,def search isamAppliance name ret_obj get_all isamAppliance return_obj isamAppliance create_return_object for obj in ret_obj data if obj name name logger info Found 0 1 with id 2 format artifact_type name obj id return_obj data obj id return_obj rc 0 return return_obj
download one snapshot file to a zip file . todo : can handle multiple i d 's - but rest of logic deals with just one for now,def download isdsAppliance filename id check_mode False force False if force is True or _check isdsAppliance id id is True and os path exists filename is False if check_mode is False uri snapshots download record_ids 0 format id return isdsAppliance invoke_get_file Downloading snapshots uri filename return isdsAppliance create_return_object
"parameters ---------- values : [ term , ... ]",staticmethod def build values idxstore IndexStore idxstore _i2val list values idxstore _val2i term i for i term in enumerate values idxstore _next_i len values return idxstore
backwardcompatibility ( ) - > bool,def BackwardCompatibility self if not _FResult__messages in self __dict__ keys self __messages for output in self __outputs self __messages append return True return False
"get the frequency of ` word ` , in the language with code ` lang ` , on the zipf scale .",def zipf_frequency word lang wordlist best minimum 0 0 freq_min zipf_to_freq minimum freq word_frequency word lang wordlist freq_min return round freq_to_zipf freq 2
"take each line2d in the axes , ax , and convert the line style to be suitable for black and white viewing .",def setAxLinesBW ax MARKERSIZE 3 COLORMAP r marker None dash None None g marker None dash 5 2 m marker None dash 11 3 b marker None dash 6 3 2 3 c marker None dash 1 3 y marker None dash 5 3 1 2 1 10 k marker o dash None None for line in ax get_lines origColor line get_color line set_dashes COLORMAP origColor dash line set_marker COLORMAP origColor marker line set_markersize MARKERSIZE
load logging config json file from treadmill_xx / logging / xxx.json,def _load_logging_file plugin_name name u Load logging config json file from treadmill_xx logging xxx json n utf8_reader codecs getreader u utf8 log_conf_file utf8_reader pkg_resources resource_stream plugin_name name return json load log_conf_file
validates getting a test tar file with an invalid sha256 hash_code .,def test_get_tar__invalid_sha256 self u Validates getting a test tar file with an invalid sha256 hash_code n repo tar TarImageRepository self tm_env with self assertRaises Exception repo get u file 0 sleep tar sha256 1 format os path abspath os path dirname __file__ u asdfadsfasdfasdf
"kills app , endpoints , and server node .",def kill_node zkclient node u _LOGGER info u killing node s node try zkutils get zkclient z path server node except kazoo client NoNodeError _LOGGER info u node does not exist return apps zkclient get_children z path placement node for app in apps _LOGGER info u removing app presence s app try manifest zkutils get zkclient z path scheduled app app_presence EndpointPresence zkclient manifest hostname node appname app app_presence unregister_running app_presence unregister_endpoints except kazoo client NoNodeError _LOGGER info u app s no longer scheduled app _LOGGER info u removing server presence s node unregister_server zkclient node
"insert item to data structure while inserting , add a edge from parent to child in self.graph : param item : item to be added",def insert self item pass
l{fddetector._getimplementation } returns the first method from its c{_implementations } list which returns results which reflect a newly opened file descriptor .,def test_selectFirstWorking self def failWithException raise ValueError This does not work def failWithWrongResults return 0 1 2 def correct return self _files self detector _implementations failWithException failWithWrongResults correct self assertIs correct self detector _getImplementation
"adds the given folder to the python path . supports namespaced packages . by default , packages in the given folder take precedence over site - packages and any previous path manipulations . args : folder : path to the folder containing packages , relative to `` os.getcwd ( ) `` position : where in `` sys.path `` to insert the vendor packages . by default this is set to 1 . it is inadvisable to set it to 0 as it will override any modules in the current working directory .",def add folder index 1 site_dir os path join folder lib python sys version 3 site packages if os path exists site_dir folder site_dir else folder os path join os path dirname __file__ folder sys path remainder sys path 1 sys path 1 site addsitedir folder sys path extend remainder
add a callback when you get new data,run_in_broker def addCallback self fn async True if not async fn run_in_thread fn self _deferred addCallback fn
call the distance matrix api . see distance_points,def __call__ self origin destinations return self distance_points origin destinations
get name of this shader file with full modules path .,staticmethod def get_name return __name__
adds new face to piece .,def add_face self material vert_indicies vert_normals vert_uvs uvs_names uvs_aliases vert_rgbas rgbas_names if len vert_indicies 3 return False for vertex in vert_indicies if vertex 0 or vertex self __vertex_count return False if not len vert_indicies len vert_normals len vert_uvs len vert_rgbas return False face Face len self __faces material vert_indicies for i in range 0 len vert_indicies face add_normal vert_normals i face add_uvs vert_uvs i uvs_names uvs_aliases face add_rgbas vert_rgbas i rgbas_names self __faces append face Piece __global_face_count 1 return True
the test user has logged in .,def post self self write status okay email test_creator fixtures com
"returns all extracted attributs for a url : param urls : list of urls to extract entities from type = none for all types , specify a type for that type only . : return : { attrtype : [ value1,value2 , .. ] , ... }",def get_extracted_domain_entities_from_urls self domain urls type None self _check_conn urls_in join s for i in range len urls params domain params extend urls if type is None sql select url entity_type entity_value from domain_extractor_web_index where domain s and url in urls_in else sql select url entity_type entity_value from domain_extractor_web_index where domain s and url in urls_in and entity_type s params append type self _check_conn try cursor self cnx cursor cursor execute sql params results for row in cursor fetchall url row 0 attr row 1 value row 2 if url not in results results url if attr not in results url results url attr value else results url attr append value return results except self close raise
create tables for keeping track of the separate counts,def __init__ self p coloring table_hints td execdata_file None super ColorCount self __init__ p coloring table_hints td self totals Counter self raw_count Counter self tree_depth self min_p self n_colors None from lib pattern_counting dp import ColorDPTable self table_type ColorDPTable
pirqcon query with context role exact match,def test_020_role_exact self q PirqconQuery self p role role20_r role_regex False irq sorted p irq for p in q results self assertListEqual 20 irq
mls rule query with object class regex match .,def test_022_class_regex self q MLSRuleQuery self p tclass infoflow 5 6 tclass_regex True r sorted q results self assertEqual len r 2 self validate_rule r 0 RT range_transition test22 test22 infoflow5 s1 self validate_rule r 1 RT range_transition test22 test22 infoflow6 s2
respond to incoming calls with a simple text message .,app route methods GET POST def hello_monkey resp MessagingResponse resp message Hello Mobile Monkey return str resp
"run the simple example code in a python subprocess and then compare its stderr to what we expect to see from it . we run it in a subprocess to best capture its stderr . we expect to see match_lines in order in the output . this test is just a sanity check to ensure that the progress bar progresses from 1 to 10 , it does not make sure that the",def test_list_example testdir v testdir makepyfile import time import freezegun import progressbar with freezegun freeze_time as fake_time bar progressbar ProgressBar term_width 65 bar _MINIMUM_UPDATE_INTERVAL 1e 9 for i in bar list range 9 fake_time tick 1 result testdir runpython v result stderr lines l rstrip for l in result stderr lines if l strip pprint pprint result stderr lines width 70 result stderr fnmatch_lines N A 0 of 9 Elapsed Time 00 00 ETA 11 1 of 9 Elapsed Time 00 01 ETA 00 08 22 2 of 9 Elapsed Time 00 02 ETA 00 07 33 3 of 9 Elapsed Time 00 03 ETA 00 06 44 4 of 9 Elapsed Time 00 04 ETA 00 05 55 5 of 9 Elapsed Time 00 05 ETA 00 04 66 6 of 9 Elapsed Time 00 06 ETA 00 03 77 7 of 9 Elapsed Time 00 07 ETA 00 02 88 8 of 9 Elapsed Time 00 08 ETA 00 01 100 9 of 9 Elapsed Time 00 09 Time 00 09
just quote out stuff before sending it out,def write self data args parse_qs self handler environ get QUERY_STRING if i in args i args i else i 0 super JSONPolling self write io j s s i data
retrieve dnashape feature values for the hits .,def get_shapes hits bed_file first_shape second_shape extension 0 scaled False bigwigs first_shape second_shape import subprocess import os peaks_pos get_positions_from_bed bed_file with open os devnull w as devnull tmp_file print_extended_hits hits peaks_pos extension shapes HelT ProT MGW Roll HelT2 ProT2 MGW2 Roll2 hits_shapes for indx bigwig in enumerate bigwigs if bigwig out_file 0 1 format tmp_file shapes indx subprocess call BWTOOL ex bed tmp_file bigwig out_file stdout devnull if indx 4 hits_shapes append get_scores out_file shapes indx scaled else hits_shapes append get_scores out_file shapes indx subprocess call rm f 0 HelT format tmp_file 0 MGW format tmp_file 0 ProT format tmp_file 0 Roll format tmp_file 0 HelT2 format tmp_file 0 MGW2 format tmp_file 0 ProT2 format tmp_file 0 Roll2 format tmp_file tmp_file return hits_shapes
"if the header looks like : { "" alg "" : "" rs256 "" , "" kid "" : "" ac2b63faefcf8362f4c528e7c78433879387016b "" }",def header_kid_invalid jwt_string header payload signature decode_jwt jwt_string header kid invalid yield encode_jwt header payload signature
"generate the list of examples , as well as the contents of examples .",def generate_example_rst app root_dir os path join app builder srcdir auto_examples example_dir os path abspath app builder srcdir example_dir os path join example_dir examples try plot_gallery eval app builder config plot_gallery except TypeError plot_gallery bool app builder config plot_gallery if not os path exists example_dir os makedirs example_dir if not os path exists root_dir os makedirs root_dir fhindex file os path join root_dir index rst w fhindex write raw html style type text css div sidebarbutton display none figure float left margin 10px width auto height 200px width 180px figure img display inline figure caption width 170px text align center important style Code examples _examples index generate_dir_rst fhindex example_dir root_dir plot_gallery fhindex flush
streams the list of keys for the table through an iterator .,def ts_stream_keys self table timeout None raise NotImplementedError
initialize client with an api key .,def __init__ self api_key self api_key api_key self _start_date None self _end_date None
"this is some fancy magic that comes from batagelj and mrvar 's paper . it treats each link between v , u , w as a bit in the binary representation of an integer . this number then is mapped to one of the 16 triad types .",def _tricode G v u w combos v u 1 u v 2 v w 4 w v 8 u w 16 w u 32 return sum x for u v x in combos if v in G u
return slug suitable for accessing this view in a urlconf .,classmethod def slug cls slug cls __name__ lower if slug endswith view slug slug 4 return slug
establish a socket connection and set nodelay settings on it .,def _new_conn self extra_kw if self source_address extra_kw source_address self source_address if self socket_options extra_kw socket_options self socket_options try conn connection create_connection self host self port self timeout extra_kw except SocketTimeout as e raise ConnectTimeoutError self Connection to s timed out connect timeout s self host self timeout except SocketError as e raise NewConnectionError self Failed to establish a new connection s e return conn
"gets rid of < and > and & and , for good measure , :",def xssescape text return escape text quote True replace 58
linked list initialized with head .,def __init__ self data None self _length 0 self head None try for val in data self push val except TypeError if data self push data
performs the conversion of the python parameter value to its couchdb equivalent .,def _py_to_couch_translate key val try if key in keys endkey_docid startkey_docid stale update return key val elif val is None return key None arg_converter TYPE_CONVERTERS get type val return key arg_converter val except Exception as ex raise CloudantArgumentError 136 key ex
create a new hashing object and return it .,def new key msg None digestmod None return HMAC key msg digestmod
connects to host with netmiko and gather monitor data,def connect args device device_type args platform ip args c username args u password args p secret args e verbose args verbose print INFO Connecting to device SSHClass netmiko ssh_dispatcher device_type device device_type conn SSHClass device platform Platform args platform command platform get_command args i while True result conn send_command command parsed_result platform parse result csv_row datetime datetime now args i csv_row extend parsed_result values with open args o ab as f csv_file csv writer f delimiter t csv_file writerow csv_row if not args no table print table args o print s Added row to CSV datetime datetime now time sleep int args interval
show details of the subscriptions belonging to this user .,def get self subscription_id None stream None historics_id None page None per_page None order_by None order_dir None include_finished None params if subscription_id params id subscription_id if stream params hash stream if historics_id params historics_id historics_id if page params page page if per_page params per_page per_page if order_by params order_by order_by if order_dir params order_dir order_dir if include_finished params include_finished 1 if include_finished else 0 return self request get get params params
query whether an option exists .,def assert_new_option self key try _ self options key return True except BlobException return False
"return user details , browserid only provides email .",def get_user_details self response email response email return username email split 1 0 email email fullname first_name last_name
utility function for accepting single tag input in a flexible manner .,def get_tag tag from tagging models import Tag if isinstance tag Tag return tag try if isinstance tag six string_types return Tag objects get name tag elif isinstance tag six integer_types return Tag objects get id tag except Tag DoesNotExist pass return None
"given the hostname and an untrusted url to redirect to , this method tests it to make sure it is n't garbage / harmful and returns it , else returns none , similar as how 's it done on django.contrib.auth.views .",def sanitize_redirect host redirect_to if not redirect_to or not isinstance redirect_to six string_types return None netloc urlparse redirect_to 1 if netloc and netloc host return None return redirect_to
"retrieves information about a user , the result is only limited to what the callee has access to view . : param user_id : : param kwargs : : return :",def get_user_info self user_id kwargs return GetUserInfo settings self settings kwargs call user_id user_id kwargs
test the functionality of clusters_from_uc_file ( ) method,def test_clusters_from_uc_file self with open self usearch_file U as usearch_f clusters unassigned_seqs clusters_from_uc_file uc_lines usearch_f otu_id_field 9 expected_clusters 299228 s1_32798 size 150 4364652 s1_67100 size 201 s1_83977 size 1 s1_83957 size 1 4348382 s1_3756 size 153 4383559 s1_95719 size 151 4372973 s1_47350 size 219 s1_47396 size 1 s1_47400 size 1 s1_47605 size 1 s1_47427 size 1 4404830 s1_33608 size 157 expected_failures s1_104394 size 135 s1_104394 size 135 s1_102755 size 129 self assertEqual len expected_clusters len clusters for key in clusters self assertTrue key in expected_clusters clusters key sort expected_clusters key sort self assertEqual clusters key expected_clusters key expected_failures sort unassigned_seqs sort self assertEqual expected_failures unassigned_seqs
update the modification time for a dependency,def _touch self filename offset time timezone now timedelta hours 1 DBEntry objects filter label_id str filename update modified time
hook for subtypes to add relaxed constraints for retry logic,staticmethod def relaxed_constraints return
"pass in array of json objects , a dictionary with key / value pairs to match against , and another dictionary with expected key / value pairs .",def check_array_result object_array to_match expected num_matched 0 for item in object_array all_match True for key value in to_match items if item key value all_match False if not all_match continue for key value in expected items if item key value raise AssertionError s expected s s str item str key str value num_matched num_matched 1 if num_matched 0 raise AssertionError No objects matched s str to_match
: type s : str : rtype : int,def numDecodings self s length len s if length 0 return 0 dp 0 for __ in range length 1 dp length 1 dp length 1 1 if s length 1 0 else 0 for i in range length 2 1 1 if s i 0 dp i dp i 1 dp i 2 if int s i i 2 26 else dp i 1 return dp 0
sign the parameters with md5 hash,def _sign self params pairs join s s k v for k v in sortedItems params return md5 self secret pairs encode utf 8 hexdigest
resets the chromium repo and runs the testcase .,def reset_and_run_testcase testcase_id category release delete_if_exists CHROMIUM_OUT delete_if_exists CLUSTERFUZZ_CACHE_DIR clean version prepare_binary_and_get_version release for opts in TEST_OPTIONS update_auth_header return_code run_testcase testcase_id opts opts logs read_logs stackdriver_logging send_run testcase_id category version release return_code logs opts sleep return_code
like os.listdir but returns full paths .,def ListdirFullpath directory return os path join directory filename for filename in os listdir directory
@return a string representation in typical python format of the currently active / raised exception .,def exception_traceback limit 50 type value tb sys exc_info lines traceback format_tb tb limit lines extend traceback format_exception_only type value str Traceback innermost last n str str 20s s string join lines 1 lines 1 return str
collect the species to which the material might decompose to .,def get_competing_phases u n Collect the species to which the material might decompose to n n Returns n A list of phases as tuples formatted as n formula_1 Materials_Project_ID_1 n formula_2 Materials_Project_ID_2 n composition Structure from_file u POSCAR composition try energy Vasprun u vasprun xml final_energy except energy 100 entries MPR get_entries_in_chemsys elt symbol for elt in composition my_entry ComputedEntry composition energy entries append my_entry pda PhaseDiagram entries decomp pda get_decomp_and_e_above_hull my_entry allow_negative True competing_phases entry composition reduced_formula entry entry_id for entry in decomp 0 return competing_phases
"read log files , combine and format .",def GetDeviceLogs log_filenames logger device_logs for device device_files in log_filenames iteritems logger debug s s device str device_files device_file_lines for cur_file in device_files with open cur_file as f device_file_lines cur_file f read splitlines combined_lines CombineLogFiles device_file_lines logger device_logs n device 5 join combined_lines return device_logs
stores downloaded .torrent file contents in a temporary file within a filesystem . returns a filepath to that file .,def store_tmp_torrent self file_contents fd fpath tempfile mkstemp f os fdopen fd w f write file_contents f close return fpath
list all actions have been registered in mistral .,def do_action_list args actions actions_cli get_all_registered fileds name description input_str utils print_list actions fileds sortby_index 0
console entry point - instantiate a : py : class:`~.runner ` and call its : py : meth:`~.runner.console_entry_point ` method .,def console_entry_point r Runner try r console_entry_point except KeyboardInterrupt logger warning Exiting on keyboard interrupt raise SystemExit 0
check that filter_denovogear_sites ( ) works correctly,def test_filter_denovogear_sites self initial True True status filter_denovogear_sites self variants initial self assertTrue all status Series True True
"return a tuple ( start , end ) that says where to find s within m.",def _search self m s lo 0 hi None def advance i c while i lenm and m i c i 1 return i if not s return lo lo lenm len m if not hi hi lenm while lo hi mid lo hi 2 start mid while start 0 and m start 1 n start 1 end advance start x00 if m start end s lo advance end 40 n 1 else hi start end advance lo x00 found m lo end if cmp s found 0 end advance end 40 n return lo end 1 else return lo lo
rescale the values in a list between the values in newrange ( a tuple with the new minimum and maximum ),def rescale inlist newrange 0 1 OldMax max inlist OldMin min inlist if OldMin OldMax raise RuntimeError list contains of only one unique value OldRange OldMax OldMin NewRange newrange 1 newrange 0 result float x OldMin NewRange OldRange newrange 0 for x in inlist return result
test that consonants are correctly identified,def test_is_consonant self for i in self consonants self consonants upper self assertTrue validate is_consonant i for i in self vowels self numbers self assertFalse validate is_consonant i
adds a percentage sign ( ' % ' ) infront of each character,def tamper payload kwargs if payload retVal i 0 while i len payload if payload i and i len payload 2 and payload i 1 i 2 in string hexdigits and payload i 2 i 3 in string hexdigits retVal payload i i 3 i 3 elif payload i retVal s payload i i 1 else retVal payload i i 1 return retVal
use google email or i d as unique i d,def get_user_id self details response user_id super GoogleOAuth2Backend self get_user_id details response if setting GOOGLE_OAUTH2_USE_UNIQUE_USER_ID False return response id return user_id
method that sends a get request for url : param url : str containing webpage url : returns : str containing request response,def get self url self request requests get url return self request text
check attach interface result via simple interface number comparison,def check_attach_interface num1 num2 if num2 num1 return True else return False
adadelta . based on : http://www.matthewzeiler.com/pubs/googletr2012/googletr2012.pdf,def adadelta self cost params rho 0 95 epsilon 1e 06 consider_constant None rho theano shared np float32 rho astype floatX epsilon theano shared np float32 epsilon astype floatX gradients self get_gradients cost params consider_constant accu_gradients theano shared np zeros_like param get_value borrow True astype floatX for param in params accu_deltas theano shared np zeros_like param get_value borrow True astype floatX for param in params updates for param gradient accu_gradient accu_delta in zip params gradients accu_gradients accu_deltas new_accu_gradient rho accu_gradient 1 0 rho gradient 2 0 delta_x T sqrt accu_delta epsilon new_accu_gradient epsilon gradient new_accu_delta rho accu_delta 1 0 rho delta_x 2 0 updates append accu_gradient new_accu_gradient updates append accu_delta new_accu_delta updates append param param delta_x return updates
"may be overridden , for example : :",def __init__ self request args kwargs pass
returns a list of field names from an admin fieldsets structure .,def get_inline_views_from_fieldsets fieldsets inline_views for _ opts in fieldsets or if fieldsets in opts inline_views get_inline_views_from_fieldsets opts get fieldsets elif inline_view in opts inline_views append opts get inline_view return inline_views
"sets the state of vjoy button to on or off . setbtn(state , rid , buttonid )",def SetBtn state rID buttonID result _vj SetBtn state rID buttonID if result 0 raise vJoyButtonError else return True
sends a text email to a list of recipients ( one email per recipient ) via batch .,classmethod def send_batch cls subject body recipients sender_address None sender_name None chunk_size settings MAILGUN_BATCH_CHUNK_SIZE raise_for_status True recipients email context or for email context in recipients if settings MAILGUN_RECIPIENT_OVERRIDE is not None body body n n overridden recipient n recipient_data format body body recipient_data n join format recipient json dumps context for recipient context in recipients recipients settings MAILGUN_RECIPIENT_OVERRIDE responses exception_pairs for chunk in chunks recipients chunk_size chunk_size chunk_dict email context for email context in chunk emails list chunk_dict keys params to emails subject subject text body recipient variables json dumps chunk_dict if sender_address params from sender_address try response cls _mailgun_request requests post messages params sender_name sender_name raise_for_status raise_for_status responses append response except ImproperlyConfigured raise except Exception as exception exception_pairs append emails exception if exception_pairs raise SendBatchException exception_pairs return responses
get frame number of last depth frame : return : frame number,def getLastDepthNum self return dsc getLastDepthNum
pushes a message on the registered api keys . takes 5 arguments : - ( req ) application : application name [ 256 ] - ( req ) event : event name [ 1000 ] - ( req ) description : description [ 10000 ] - ( opt ) url : url [ 512 ] - ( opt ) priority : from -2 ( lowest ) to 2 ( highest ) ( def:0 ) - ( opt ) batch_mode : call api 5 by 5 ( def : false ),def push self application event description url priority 0 batch_mode False datas application application 256 encode utf8 event event 1024 encode utf8 description description 10000 encode utf8 priority priority if url datas url url 512 if self _developerkey datas developerkey self _developerkey results if not batch_mode for key in self _apikey datas apikey key res self callapi POST ADD_PATH datas results key res else for i in range 0 len self _apikey 5 datas apikey join self _apikey i i 5 res self callapi POST ADD_PATH datas results datas apikey res return results
formats a timestamp in the format used by http .,def format_timestamp ts if isinstance ts tuple time struct_time pass elif isinstance ts datetime datetime ts ts utctimetuple elif isinstance ts numbers Real ts time gmtime ts else raise TypeError unknown timestamp type r ts return time strftime a d b Y H M S GMT ts
check if bag is valid : param obj bag : bag : return none :,def validate_md5 bag logger_bagit info validate_md5 if bag is_valid print Valid md5 else print Invalid md5 logger_bagit debug invalid bag return
"computes the state of ` layer ' , given the state of its incoming neighbours .",def ComputeUp self layer train False step 0 maxsteps 0 layer dirty False perf None if layer is_input or layer is_initialized layer GetData else for i edge in enumerate layer incoming_edge if edge in layer outgoing_edge continue inputs layer incoming_neighbour i state if edge conv or edge local if i 0 ConvolveUp inputs edge layer state else AddConvoleUp inputs edge layer state else w edge params weight factor edge proto up_factor if i 0 cm dot w T inputs target layer state if factor 1 layer state mult factor else layer state add_dot w T inputs mult factor b layer params bias if layer replicated_neighbour is None layer state add_col_vec b else layer state add_dot b layer replicated_neighbour NN layer ApplyActivation if layer hyperparams sparsity layer state sum axis 1 target layer dimsize perf deepnet_pb2 Metrics perf MergeFrom layer proto performance_stats perf count layer batchsize layer dimsize sum axis 0 target layer unitcell perf sparsity layer unitcell euclid_norm layer dimsize shape 0 layer unitcell greater_than 0 if layer unitcell euclid_norm 0 perf sparsity 1 if layer hyperparams fast_dropout layer data assign layer state if layer hyperparams dropout if train and maxsteps step layer hyperparams stop_dropout_for_last if layer hyperparams mult_dropout layer mask fill_with_randn layer mask add 1 layer state mult layer mask else layer mask fill_with_rand layer mask greater_than layer hyperparams dropout_prob if layer hyperparams blocksize 1 layer mask blockify layer hyperparams blocksize layer state mult layer mask elif layer hyperparams mult_dropout pass else layer state mult 1 0 layer hyperparams dropout_prob return perf
get the split line before a bracket or semicolon .,def getSplitLineBeforeBracketSemicolon line bracketSemicolonIndex min line find line find if bracketSemicolonIndex 0 return line split return line bracketSemicolonIndex split
get the functions with the search string in the files .,def getFunctionsWithStringByFileNames fileNames searchString functions for fileName in fileNames functions getFunctionsWithStringByFileName fileName searchString functions sort return functions
read in the sampling table section . it contains a table length ( byte ) and the table entries .,def readTableEntry self file tableEntrySize ord file read 1 if tableEntrySize 0 print Sampling table size is zero exit for index in xrange tableEntrySize sampleTableEntry SampleTableEntry file self layerHeight sampleTableEntry layerHeight
used to suport list values in html forms . supports lists of primitives and/or dictionaries .,def parse_html_list dictionary prefix ret regex re compile s 0 9 re escape prefix for field value in dictionary items match regex match field if not match continue index key match groups index int index if not key ret index value elif isinstance ret get index dict ret index key value else ret index MultiValueDict key value return ret item for item in sorted ret keys
utility function that take a request and returns an instance of ` oauth2_provider.backends . oauthlibcore `,def get_oauthlib_core u n Utility function that take a request and returns an instance of n oauth2_provider backends OAuthLibCore n from oauthlib oauth2 import Server server Server oauth2_settings OAUTH2_VALIDATOR_CLASS return OAuthLibCore server
return the name of the state .,property def name self return self _stateName
: param address_families : the set of addressfamily to use,def set_defaults self defaults defaults address_families super BGP self set_defaults defaults
ensures that we can tell an object that some other object is managing its memory .,def test_markAdopted1 self a osim Model assert a this assert a thisown a _markAdopted assert a this assert not a thisown
process the given data received from the cloud - config userdata .,def process self data if not isinstance data list dict raise exception CloudbaseInitException Can t process the type of data r type data if isinstance data dict data data for item in data self _process_item item
special migration for the blueprint to support keystone v3 . we drop all tenant_id columns and create project_id columns instead .,def contract_creation_exceptions return sa Column join table project_id for table in get_tables sa Index get_tables
delete table safely . no errors @param tablename : name of table @type tablename : string,def dropTable self tableName cursor self connection cursor try cursor execute DROP TABLE IF EXISTS s tableName self connection commit finally cursor close
helper function for determining how many pixels are masked .,def get_mask_percent mask cond mask 0 num_masked np extract cond mask size mask_percent float 100 num_masked mask size return mask_percent
"get all packages , which provide one package .",def providers args package arch None must_exist True indexes None if not indexes arch arch or args arch_native indexes pmb helpers repo apkindex_files args arch ret collections OrderedDict for path in indexes index_packages parse args path if package not in index_packages continue for provider_pkgname provider in index_packages package items version provider version if provider_pkgname in ret version_last ret provider_pkgname version if pmb parse version compare version version_last 1 logging verbose package provided by provider_pkgname version in path but version_last is higher continue logging verbose package provided by provider_pkgname version in path ret provider_pkgname provider if ret and must_exist logging debug Searched in APKINDEX files join indexes raise RuntimeError Could not find package package return ret
"iterate through the urls and add them to the database to be crawled , testing if they exists if required .",def run self valid_urls invalid_urls self log info SyncDB run Syncing to database from s started self file_path try file_buffer open self file_path except IOError self log error SyncDB run Sync file path not set or can t be found if not invalid_urls url_list file_buffer readlines else url_list invalid_urls invalid_urls for url in url_list url url strip valid True if self test_exists valid self exists url if not valid invalid_urls append url if valid valid_urls append url self save url self log info SyncDB run Saved s url if invalid_urls and self retry_failed while i self retry_failed self retry_failed 1 self run valid_urls invalid_urls else self log info SyncDB run Completed s urls added len valid_urls
test the unicode function returns the url,def test_unicode self self assertEqual unicode self whitelisted_rss_url self whitelisted_rss_url url
standard entry point for processing requests in django,def process_request self request if not hasattr request user or not request user is_authenticated return timeout_in_seconds getattr settings SESSION_INACTIVITY_TIMEOUT_IN_SECONDS None if timeout_in_seconds utc_now datetime utcnow last_touch request session get LAST_TOUCH_KEYNAME if last_touch time_since_last_activity utc_now last_touch if time_since_last_activity timedelta seconds timeout_in_seconds del request session LAST_TOUCH_KEYNAME auth logout request return request session LAST_TOUCH_KEYNAME utc_now
recursively strips ' filename ' from all children 's definitions .,def strip_filenames descriptor print strip filename from desc format desc descriptor location to_deprecated_string if descriptor _field_data has descriptor filename descriptor _field_data delete descriptor filename if hasattr descriptor xml_attributes if filename in descriptor xml_attributes del descriptor xml_attributes filename for child in descriptor get_children strip_filenames child descriptor save
arguments : course : this can be either a course overview object or a course descriptor .,def get_link_for_about_page course is_social_sharing_enabled getattr settings SOCIAL_SHARING_SETTINGS get CUSTOM_COURSE_URLS if is_social_sharing_enabled and course social_sharing_url course_about_url course social_sharing_url elif settings FEATURES get ENABLE_MKTG_SITE and getattr course marketing_url None course_about_url course marketing_url else course_about_url u about_base_url courses course_key about format about_base_url settings LMS_ROOT_URL course_key unicode course id return course_about_url
convert a list of dictionaries to be compatible with create_csv_response,def format_dictlist dictlist features def dict_to_entry dct Convert dictionary to a list for a csv row relevant_items k v for k v in dct items if k in features ordered sorted relevant_items key lambda k v header index k vals v for _ v in ordered return vals header features datarows map dict_to_entry dictlist return header datarows
gets the course summary data from the course blocks api and returns a list of data objects summarizing each courses xblock usage,def _get_course_data_summary auth_token months_restriction xblock_type_set api_root course_count None response requests get api_root api courses v1 courses json_result response json num_courses 0 num_pages 1 if PAGINATION_KEY in json_result and NUM_PAGES_KEY in json_result PAGINATION_KEY num_pages json_result PAGINATION_KEY NUM_PAGES_KEY num_courses json_result PAGINATION_KEY count course_summary_data block_type_url _get_block_count_url_string xblock_type_set if course_count is None course_count num_courses course_count_limit False total_courses 0 while num_pages 0 and not course_count_limit if RESULTS_KEY in json_result results_list json_result RESULTS_KEY for course in results_list course_data _get_course_data auth_token course block_type_url months_restriction months_restriction if course_data is not None course_summary_data append course_data if total_courses course_count course_count_limit True break total_courses 1 num_pages 1 page_data json_result get PAGINATION_KEY None if page_data is not None next_page page_data get next if not next_page break json_result requests get next_page json sys stdout write sys stdout flush print Processed d courses total_courses return course_summary_data
create a fake certificate for a user .,def handle self args options if len args 2 raise CommandError self USAGE user User objects get username args 0 course_key CourseKey from_string args 1 cert_mode options get cert_mode honor status options get status CertificateStatuses downloadable grade options get grade cert created GeneratedCertificate eligible_certificates get_or_create user user course_id course_key cert mode cert_mode cert status status cert grade grade if status CertificateStatuses downloadable cert download_uuid test cert verify_uuid test cert download_url http www example com cert save if created LOGGER info u Created certificate for user s in course s with mode s status s and grade s user id unicode course_key cert_mode status grade else LOGGER info u Updated certificate for user s in course s with mode s status s and grade s user id unicode course_key cert_mode status grade
un - monkey - patch an attribute,def unpatch module attribute_name was_patched False attribute getattr module attribute_name if hasattr attribute __BACKUP_ATTRIBUTE_NAME attribute_old getattr attribute __BACKUP_ATTRIBUTE_NAME setattr module attribute_name attribute_old was_patched True return was_patched
generate the text field used for general search .,def content_text self with translation override en return u name n description n country n language format name self course_team name description self course_team description country self course_team country name format language self _language_name
send an event object to all the initialized backends .,dog_stats_api timed track send def send event dog_stats_api increment track send count for name backend in backends iteritems with dog_stats_api timer track send backend 0 format name backend send event
"ensures that the user is authenticated ( e.g. not an anonymoususer ) , unless debug mode is enabled .",def perform_authentication self request super CourseViewMixin self perform_authentication request if request user is_anonymous and not settings DEBUG raise AuthenticationFailed
checks that the right compentents are rendered for user with `` user_tag ``,def _check_split_test self user_tag UserCourseTagFactory user self student course_id self course id key xblock partition_service partition_ 0 format self partition id value str user_tag resp self client get reverse courseware_section kwargs course_id self course id to_deprecated_string chapter self chapter url_name section self sequential url_name content resp content self assertIn button class inactive nav item tab format self ICON_CLASSES user_tag content for tooltip in self TOOLTIPS user_tag self assertIn tooltip content unicode_content content decode utf 8 for key in self included_usage_keys user_tag self assertIn unicode key unicode_content for key in self excluded_usage_keys user_tag self assertNotIn unicode key unicode_content for visible in self VISIBLE_CONTENT user_tag self assertIn visible content
returns an iterator over all of the blocks in a course .,def iter_blocks course def visit block get child blocks yield block for child in block get_children for descendant in visit child yield descendant return visit course
"make a get request to the specified url with an oauth2 bearer token . if no token is provided , a valid token will be used . query parameters can also be passed in if desired .",def get_with_bearer_token self target_url params None token None u n Make a GET request to the specified URL with an OAuth2 bearer token If n no token is provided a valid token will be used Query parameters can n also be passed in if desired n auth self _create_authorization_header token return self csrf_client get target_url params HTTP_AUTHORIZATION auth
"returns the score values from the courseware student module , via scoresclient , if found .",def _get_score_from_csm csm_scores block weight score csm_scores get block location has_valid_score score and score total is not None if has_valid_score if score correct is not None first_attempted score created raw_earned score correct else first_attempted None raw_earned 0 0 raw_possible score total return raw_earned raw_possible weighted_score raw_earned raw_possible weight first_attempted
"handle ajax call from "" show notes "" checkbox .",login_required def edxnotes_visibility request course_id course_key CourseKey from_string course_id course get_course_with_access request user load course_key field_data_cache FieldDataCache course course_key request user course_module get_module_for_descriptor request user request course field_data_cache course_key course course if not is_feature_enabled course raise Http404 try visibility json loads request body visibility course_module edxnotes_visibility visibility course_module save return JsonResponse status 200 except ValueError KeyError log warning Could not decode request body as JSON and find a boolean visibility field s request body return JsonResponseBadRequest
install a course with no content using a fixture .,def setUp self super CoursePagesTest self setUp self pages clz self browser self course_info org self course_info number self course_info run for clz in AssetIndexPage CourseUpdatesPage PagesPage ExportCoursePage ImportCoursePage CourseTeamPage CourseOutlinePage SettingsPage AdvancedSettingsPage GradingPage TextbookUploadPage
return the port that the service is listening on .,property def port self _ port self server_address return port
render static resource using provided context .,def render_resource self path context return render_resource path context
run a class specific model on any dataset .,def runEnsemble inputTest models dataFolder classDataFolders questionTypeArray data it loadDataset dataFolder classAnsIdict for df in classDataFolders data_c it loadDataset df classAnsIdict append data_c ansIdict ensembleOutputTest __runEnsemble inputTest models data ansDict classAnsIdict questionTypeArray return ensembleOutputTest
calculates the final power rankings based on input metrics,def calc_power teams week w_dom 0 18 w_lsq 0 18 w_col 0 18 w_awp 0 18 w_sos 0 06 w_luck 0 06 w_cons 0 1 w_strk 0 06 for t in teams dom float t rank dom lsq float t rank lsq col float t rank col awp float t stats awp sos float t rank sos luck float t rank luck cons float t rank cons strk float t stats streak int t stats streak_sgn strk 0 25 strk if strk 1 0 else 0 0 power dom w_dom lsq w_lsq col w_col awp w_awp sos w_sos luck w_luck cons w_cons strk w_strk t rank power 100 np tanh power 0 5
should fail if the data is invalid and no header was provided .,def test_invalid_data_without_specifiying_a_header self csv_data iPhone 5c blue Smartphones USD 699 http apple com iphone http apple com iphone jpg reader smartcsv reader StringIO csv_data columns COLUMNS_1 header_included False try next reader except InvalidCSVException as e self assertTrue e errors is not None self assertTrue row_length in e errors else assert False Shouldn t pass Exception expected
preprocess parameters that will be used to search for resources in the cloud .,def preprocess_meta meta proc_meta for key value in meta iteritems key key lower if key in SEARCH_PROPERTIES key convert SEARCH_PROPERTIES key try value convert value except ValueError as error raise _errors MachineError error proc_meta key value return proc_meta
factory for utils.analyze_xml stub functions .,def make_stub_analyze_xml type sample_xml article foo article sample_meta if type valid result annotations sample_xml validation_errors None meta sample_meta err None elif type invalid result annotations sample_xml validation_errors meta sample_meta err None elif type throw_io_error result None err IOError u Error reading file foo xml elif type syntax_error result None err Exception u Premature end of data in tag unclosed_tag line 5 line 5 column 17 else raise ValueError Unknown type value def stub__analyze_xml f extra_schematron None return result err return stub__analyze_xml
a list of recipients who will receive copies of this email .,property def ccs self return self _ccs
"retrieves a dictionary containing the image and the associated container , if active , as values .",gen coroutine authenticated def items self items_response kwargs accs self application db get_accounting_for_user self current_user account result for entry in accs resource self resource_class identifier entry id try yield self retrieve resource except NotFound continue result append resource items_response set result
create additional optimizer state such as momentum .,def create_state self index weight if self momentum 0 0 return None else return zeros weight shape weight context dtype weight dtype
dispatch the given command & args .,def run self argv command argv 0 handlers clean self clean create self create disable self disable enable self enable list self list update self update handler handlers get command None if handler is None error Unrecognized command s command 2 handler argv 1
stop the stratisd simulator and daemon .,def tearDown self self _service tearDown
asserts that the specified lines has an error .,def assertError self lines expected_line_number self had_error False def error_for_test line_number category confidence message Checks if the expected error occurs self assertEqual expected_line_number line_number self assertEqual whitespace tab category self had_error True self process_file_data lines error_for_test self assertTrue self had_error s should have an error whitespace tab lines
locate the configuration file and return its configuration .,def get_config filename find_config_file if filename is None return Configuration ignore list message_template None return load_config_file filename
"beatable , but not so stupid it seems mindless .",def drunk_play w i grid return min successors grid key drunk_value
check whether the launch paramters set the role .,def has_role self role return self roles and any re search role our_role re I for our_role in self roles
compute the image for the cropped map when map_image is cropped by bounds and had origin before .,def computed_cropped_origin map_image bounds resolution origin ox origin 0 oy origin 1 oth origin 2 dx bounds 0 resolution dy map_image size 1 bounds 3 resolution new_ox ox dx math cos oth dy math sin oth new_oy oy dx math sin oth dy math cos oth return new_ox new_oy oth
"from a gt_types_decoded single value in ( 0 , 1 , 2 , 3 ) from gemini , build the mask aggregating the various genotype_bit _ * ( powers of 2 ) .",def variant_build_gt_type_bit gt return gt_to_bit get gt GENOTYPE_BIT_UNKNOWN
returns the list containting the single variable used in this unary operation,def getUseList self return self source
test one table is returned for indexing .,def test_one_table self job base_job Job os path join os getcwd my_sql_one json job connect_to_database self assertEqual states mysql_worker get_tables job
return lambda for reading pretrained initial model,def _get_init_pretrained if not FLAGS tune_from return None saver_reader tf train Saver tf get_collection tf GraphKeys GLOBAL_VARIABLES ckpt_path FLAGS tune_from init_fn lambda sess saver_reader restore sess ckpt_path return init_fn
"returns ( height , x , y , width_x , width_y ) the gaussian parameters of a 2d distribution by calculating its moments",def moments data normalize_height False total data sum X Y np indices data shape x X data sum total y Y data sum total col data int y width_x np sqrt abs np arange col size y 2 col sum col sum row data int x width_y np sqrt abs np arange row size x 2 row sum row sum height data max if not normalize_height else 1 return height x y width_x width_y 0 0
: return : the given file(s ) as a list of alignedsent objects . : rtype : list(alignedsent ),def aligned_sents self fileids None return concat AlignedSentCorpusView fileid enc True True self _word_tokenizer self _sent_tokenizer self _alignedsent_block_reader for fileid enc in self abspaths fileids True
create min . peak hold curve,def create_peak_hold_min_curve self self curve_peak_hold_min self plot plot pen self peak_hold_min_color self curve_peak_hold_min setZValue 800
this will fail if the formula needs arguments to construct the design .,def _get_matrix self if not hasattr self _matrix self compute_matrix return self _matrix
find the offset of the given value in the bowcaster overflowbuffer string .,def find_offset self value return self header find_offset value
build a motors list given a frame type,def build_motors frame frame frame lower if frame in quad x motors Motor 90 False 1 Motor 270 False 2 Motor 0 True 3 Motor 180 True 4 if frame in x quadx for i in range 4 motors i angle 45 0 elif frame in y6 motors Motor 60 False 1 Motor 60 True 7 Motor 180 True 4 Motor 180 False 8 Motor 60 True 2 Motor 60 False 3 elif frame in hexa hexa motors Motor 0 True 1 Motor 60 False 4 Motor 120 True 8 Motor 180 False 2 Motor 240 True 3 Motor 300 False 7 elif frame in hexax motors Motor 30 False 7 Motor 90 True 1 Motor 150 False 4 Motor 210 True 8 Motor 270 False 2 Motor 330 True 3 elif frame in octa octa octax motors Motor 0 True 1 Motor 180 True 2 Motor 45 False 3 Motor 135 False 4 Motor 45 False 5 Motor 135 False 6 Motor 270 True 7 Motor 90 True 8 if frame octax for i in range 8 motors i angle 22 5 elif frame in octa quad motors Motor 45 False 1 Motor 45 True 2 Motor 135 False 3 Motor 135 True 4 Motor 45 False 5 Motor 45 True 6 Motor 135 False 7 Motor 135 True 8 else raise RuntimeError Unknown multicopter frame type s frame return motors
extract the metrics in report file from an epoch to a numpy array,def getMetricsFromReportsInEpoch reportName outputFolder nTrajs u n Extract the metrics in report file from an epoch to a numpy array n metrics for i in range 1 nTrajs report np loadtxt os path join outputFolder reportName i if len report shape 2 metrics append report tolist i 0 else traj_line np array i report shape 0 snapshot_line np array range report shape 0 metrics extend np hstack report traj_line np newaxis snapshot_line np newaxis return np array metrics
"the dualshock4 has an led bar on the front of the controller . this function allows you to set the value of this bar . note that the controller must be connected for this to work , if it 's not the call will just be ignored .",def set_leds self hue 0 0 saturation 1 0 value 1 0 r g b hsv_to_rgb hue saturation value write_led_value self device_unique_name red r 255 0 write_led_value self device_unique_name green g 255 0 write_led_value self device_unique_name blue b 255 0
this api download yang schema from device and bundle it,def download_schema request req logger debug Download Schemas modules download_yang request req session_dir ServerSettings schema_path request session session_key http_host request META HTTP_HOST current str datetime now current current replace current current current rindex zfname schema current zip zfile session_dir zfname homedir os getcwd os chdir session_dir with ZipFile zfile w as lz for f in glob glob yang lz write f os remove f if not lz namelist os remove zfile os chdir homedir url nhttp http_host download session url request session session_key zfname return HttpResponse Response success download msg url
returns an array of the values along the supplied dimension .,classmethod def values cls holocube dim expanded True flat True dim holocube get_dimension dim if dim in holocube vdims data holocube data copy data coord_names c name for c in holocube data dim_coords if c name in holocube kdims dim_inds coord_names index d name for d in holocube kdims data data transpose dim_inds elif expanded idx holocube get_dimension_index dim data util cartesian_product holocube data coords d name 0 points for d in holocube kdims idx else data holocube data coords dim name 0 points return data flatten if flat else data
handle argument parsing and dispatch to appropriate functions,def main parser argparse ArgumentParser description Create a condor submit file for processing job log data parser add_argument location dest location default None help Location of directory to place submit files parser add_argument startdate dest start_date default None help Date to start processing logs parser add_argument enddate dest end_date default None help Date to stop processing logs parser add_argument force dest force default False action store_true help Force overwrite of directory in location arg args parser parse_args sys argv 1 if args location is None args location tempfile mkdtemp elif not os path exists args location os mkdir args location 448 elif os path exists args location if not args force overwrite raw_input 0 exists overwrite format args location if overwrite lower strip y sys stderr write Exiting sys exit 0 shutil rmtree args location os mkdir args location start_date validate_date args start_date if start_date is None sys stderr write startdate must be in YYYYMMDD format got 0 n format args start_date sys exit 1 end_date validate_date args end_date if end_date is None sys stderr write enddate must be in YYYYMMDD format got 0 n format args end_date sys exit 1 create_weekly_submission start_date end_date args location sys stdout write Submission set up at 0 n format args location sys exit 0
"when handling non english versions , the counters do n't work quite as documented . this is because strings like "" bytes sent / sec "" might appear multiple times in the english master , and might not have mappings for each index .",def _make_counter_path self machine_name counter_name instance_name counters path if WinPDHCounter _use_en_counter_names In this case we don t have any translations Just attempt to make the counter path try path win32pdh MakeCounterPath machine_name self _class_name instance_name None 0 counter_name self logger debug Successfully created English only path except Exception as e self logger warning Unable to create English only path s str e raise return path counter_name_index_list WinPDHCounter pdh_counter_dict counter_name for index in counter_name_index_list c win32pdh LookupPerfNameByIndex None int index if c is None or len c 0 self logger debug Index s not found skipping index continue if c not in counters try self logger debug Index s counter s not in counter list index unicode c except self logger debug Index s not in counter list index pass continue try path win32pdh MakeCounterPath machine_name self _class_name instance_name None 0 c self logger debug Successfully created path s index break except try self logger info Unable to make path with counter s trying next available unicode c except self logger info Unable to make path with counter index s trying next available index pass return path
enables use of meta classes across python versions . taken from jinja2/_compat.py .,def with_metaclass meta bases class metaclass meta __call__ type __call__ __init__ type __init__ def __new__ cls name this_bases d if this_bases is None return type __new__ cls name d return meta name bases d return metaclass temporary_class None
gets the annotation with the given id,def byID self key return self _annots key
query for a set of stored activities .,def get_activities self keys user None start None end None filters None limit None offset None order None if end and end start raise ValueError End time must be greater than start time format end start now datetime datetime now if not start start now datetime timedelta hours 1 if not end end now titan_files files OrderedFiles for key in keys filters filters or filters files FileProperty activity_keys key files FileProperty created start files FileProperty created end if user filters append files FileProperty user user email new_titan_files files OrderedFiles list BASE_DIR recursive True filters filters order order limit limit offset offset _internal True titan_files update new_titan_files final_results for titan_file in titan_files itervalues final_results append self _loads_activity titan_file content return final_results
check the hash invariant for equal objects .,def check self x y self assertTrue cmp x y 0 self assertTrue hash x hash y
save the corpus to a text file in the original format .,def to_file self path mode w with open path mode mode as f for tree in self for label line in tree to_labeled_lines f write line n
pops oldest email from the queue .,def pop self k self _pop_key msg get_json_msg k return Message k msg
"adds a new synonym to this replacer @param name : synonym name @param simplesearch : search text for sysnonym , if you supply this , then the synonym will automatically generate a matching regex pattern that 'll be used to search for this string , if you want to specificy the regex explicitly then use regexfind instead . @param regexfind : provide this regex only if you did n't provide simplesearch , it represents the regex that 'll be used in search for this synonym . it overrides the default synonym search pattern @param regexfindforreplace : the subset within regexfind that 'll be replaced for this synonym",def synonymAdd self name simpleSearch regexFind regexFindForReplace replaceWith replaceExclude addConfluenceLinkTags False synonym Synonym name replaceWith simpleSearch addConfluenceLinkTags replaceExclude if regexFind synonym setRegexSearch regexFind regexFindForReplace self synonyms append synonym
return cuisine object connected to this instance of the machine .,property def cuisine self return self executor cuisine
"internal function , not intended for external calling",def _set_watch self self key self event_type self path if self session watches add self key self try self _watch_key except zookeeper ConnectionLossException watches set self session watches pop self key for w in watches w _deleted if self session in watches watches remove self session if watches zc zk logger critical lost watches s watches raise pass else self _notify self session exists self path
creates a submission set from any submissions matching the given tag that are not part of an existing set .,def _create_submission_set request submission_set_tag exists True bump 1 sub_slug submission_set_tag 1 while exists sub_slug s s submission_set_tag bump bump bump 1 exists SubmissionSet objects filter user request user slug sub_slug set_questions Question objects filter tags__name submission_set_tag values_list slug flat True submissions Submission objects filter submission_set None question__in set_questions user request user if submissions submission_set SubmissionSet objects create slug sub_slug tag submission_set_tag user request user submissions update submission_set submission_set
assumes level is out of 100,def brightness level 100 group 0 if level not in range 0 101 raise Exception Brightness must be value between 0 and 100 b int floor level 10 0 commands list darkest group for i in range 0 b commands append COMMANDS BRIGHTER return tuple commands
"processes votes , then resets . override !",def process self do_print True target self result self reset pass
attaches an option to the command . all positional arguments are passed as parameter declarations to : class:`argument ` ; all keyword arguments are forwarded unchanged . this is equivalent to creating an : class:`option ` instance manually and attaching it to the : attr:`command.params ` list .,def argument param_decls attrs def decorator f _param_memo f Argument param_decls attrs return f return decorator
build a list of participant protobuf from a json entry .,def _get_participants_per_team_ids self json_entry identities for identity in json_entry participantIdentities summoner constants_pb2 Summoner id identity player summonerId name identity player summonerName region constants_pb2 Region Value json_entry region identities identity participantId summoner teams for participant_json in json_entry participants stats self convert_player_statistics participant_json stats summoner identities participant_json participantId summoner league constants_pb2 League Value participant_json highestAchievedSeasonTier if participant_json timeline lane BOTTOM if participant_json timeline role DUO_CARRY role constants_pb2 ADCARRY else role constants_pb2 SUPPORT else role constants_pb2 Role Value participant_json timeline lane participant match_pb2 Participant id participant_json participantId summoner summoner summoner_spell_1 self game_constant get_summoner_spell_by_id participant_json spell1Id summoner_spell_2 self game_constant get_summoner_spell_by_id participant_json spell2Id statistics stats champion self game_constant get_champion_by_id participant_json championId role role teams setdefault participant_json teamId append participant return teams
"allow packagers to change the user - agent to whatever they like by placing a file called ` user - agent ` into the ` tools ` directory . if no file is found , we go with a sensible default + the version .",staticmethod def _get_user_agent try custom os path join os path dirname __file__ user agent with open custom as f return f readline strip 128 except IOError pass return RIPE Atlas Tools Magellan format __version__
updates user information in the json . this is a seperate method in order to account for password and i d manipulation ( otherwise ` save_user ( ) ` alone works fine ) .,def update_user_credentials self filename accounts json self delete_user filename self save_user filename
adjusts formula to a given step width c by dividing all interval bounds by c.,def adjust self c return RELEASE self operand1 adjust c self operand2 adjust c self lower_bound float c self upper_bound float c
"simulate photon arrival times , with use_spline option enabled .",def test_simulate_times_with_spline self lc Lightcurve self time self counts_flat gti self gti ev EventList ev simulate_times lc use_spline True lc_sim ev to_lc dt lc dt tstart lc tstart tseg lc tseg assert np all lc lc_sim counts 3 np sqrt lc counts
convert a set of keywords into a connection strings .,def make_dsn dsn None kwargs if dsn is None and not kwargs return if not kwargs parse_dsn dsn return dsn if database in kwargs if dbname in kwargs raise TypeError you can t specify both database and dbname arguments kwargs dbname kwargs pop database kwargs dict k v for k v in kwargs iteritems if v is not None if dsn is not None tmp parse_dsn dsn tmp update kwargs kwargs tmp dsn join s s k _param_escape str v for k v in kwargs iteritems parse_dsn dsn return dsn
total energy generated by inverter in kwh,property def e_total self return self __get_long 71
read a 8-bit value from the provided memory address .,def readmem8 self address return self _readmem address mdb
stream code into the bot .,def extend self code self rs stream code self rs sort_replies
give the message to each of the messengers .,def send message for messenger in MESSENGERS_LIST messenger _indent message
| soft bit lut generator for constellation : | | 0000 0100 | 1100 1000 | | 0001 0101 | 1101 1001 | ----------------------- | 0011 0111 | 1111 1011 | | 0010 0110 | 1110 1010,def sd_qam_16_0x2_0_1_2_3 x Es 1 x_re 3 x real x_im 3 x imag if x_re 2 b3 2 x_re 1 elif x_re 2 b3 x_re else b3 2 x_re 1 if x_im 2 b1 2 x_im 1 elif x_im 2 b1 x_im else b1 2 x_im 1 b2 abs x_re 2 b0 abs x_im 2 return b3 b2 b1 b0
creates a copy of this instance .,since 1 4 0 def copy self extra None if extra is None extra dict that Params copy self extra stages stage copy extra for stage in that getStages return that setStages stages
use gflex module to compute flexure from surface load .,def _compute_flexure self if self Te1 is None self flex Te self Te else coeff self Te1 numpy sqrt self dtime self flex Te coeff numpy ones self ny self nx self Te self flex initialize self flex run self flex finalize return
initialize a variances data structure .,contract def init_variances window_sizes number_of_states variances for i in range number_of_states variances append for j in range number_of_states variances i append dict zip window_sizes len window_sizes 1 0 return variances
split format specifiers between numeric ( qt ) and others ( strprintf ),def split_format_specifiers specifiers numeric other for s in specifiers if s in 1 2 3 4 5 6 7 8 9 numeric append s else other append s return set numeric other
returns the right follow / unfollow url,def follow_url user obj return toggle_link obj
"network objects are opaque . for unit tests , some operations are supported .",def test_create_network driver network assert len network addresses 254 for addr in network addresses assert addr in network
renders the ui for listing alerts .,def get self self RenderStaticHtml alerts html
parses an individual process string returned by _ getprocessesasstrings ( ) .,def _ParseProcessString self proc_string raise NotImplementedError
starts agent tracing for tracing controller,def StartAgentTracing self config timeout 10 return self _tracing_controller_backend StartAgentTracing config timeout
verify that misaligned bytesfield data raises an error .,def testBytesMisalignedEncoding self for encoded in garbagebb a a abcde self assertRaises messages DecodeError self __protojson decode_field MyMessage var_bytes encoded
gets all of the email addresses to send mail to for a sheriff .,def GetSheriffEmails sheriff receivers sheriff email if sheriff email else sheriff_on_duty _GetSheriffOnDutyEmail sheriff if sheriff_on_duty receivers append sheriff_on_duty return join receivers
pre - serializes a value to a dict for output as json .,def AsDict self return self _AsDictImpl
function to be used as setuptools script entry point .,def run_main new_name flags _GetMainModule sys modules new_name sys modules __main__ for flag in FLAGS FlagsByModuleDict get __name__ FLAGS _RegisterFlagByModule new_name flag for key_flag in FLAGS KeyFlagsByModuleDict get __name__ FLAGS _RegisterKeyFlagForModule new_name key_flag sys modules __main__ sys modules __name__ appcommands Run sys modules __main__ sys modules pop new_name
instantiate an anonymous file - based bucket around a single key .,def __init__ self name contained_key self name name self contained_key contained_key
parse a doxygen source file and return a dictionary of all the values . values will be strings and lists of strings .,def DoxyfileParse file_contents file_dir env data import shlex lex shlex shlex instream file_contents posix True lex wordchars lex whitespace lex whitespace replace n lex escape lineno lex lineno token lex get_token key token last_token key_token True new_data True def append_data data key new_data token if token 2 try token env token 2 1 except KeyError print ERROR Variable s used in Doxygen file is not in environment token token token token split if len token append_data data key new_data token 0 for i in token 1 append_data data key True i return if new_data or len data key 0 data key append token else data key 1 token while token if token in n if last_token not in key_token True elif token in pass elif key_token key token key_token False elif token if not data has_key key data key list elif token data key list elif key INCLUDE filename token if not os path isabs filename filename os path join file_dir filename lex push_source open filename filename else append_data data key new_data token new_data True last_token token token lex get_token if last_token and token n new_data False append_data data key new_data for k v in data items if len v 0 data pop k if k in INPUT FILE_PATTERNS EXCLUDE_PATTERNS continue if len v 1 data k v 0 return data
remove keys that are n't serialized .,def format_event event to_delete id created_at updated_at deleted_at deleted action_id for key in to_delete if key in event del event key if start_time in event event start_time str event start_time replace tzinfo None if finish_time in event event finish_time str event finish_time replace tzinfo None return event
called when a security group gains a new or loses a member .,def trigger_members_refresh self context group_ids pass
retrieves a list of years and months in which articles have been posted .,def get_article_archives parser token args token split_contents argc len args try assert argc 3 and args 1 as except AssertionError raise template TemplateSyntaxError get_article_archives syntax get_article_archives as varname return GetArticleArchivesNode args 2
display the list of valid paths under /api/,app route api app route api def api return render_template api html user_links get_user_links
test that attempting to manually update sdk_tools is ignored .,def testManualUpdateIsIgnored self new_revision self current_revision 1 archive self _BuildUpdaterArchive new new_revision self sdk_tools_bundle RemoveAllArchivesForHostOS archive host_os self sdk_tools_bundle AddArchive archive self sdk_tools_bundle revision new_revision self _WriteManifest sdk_tools_update_dir os path join self basedir nacl_sdk sdk_tools_update self assertFalse os path exists sdk_tools_update_dir stdout self _Run update sdk_tools self assertTrue stdout find Ignoring manual update request 1 self assertFalse os path exists sdk_tools_update_dir
convert all iterable pairs of inputs into a list of list,def convert_args_to_list args list_of_pairs if len args 0 return if any isinstance arg list tuple for arg in args if len args 1 and any isinstance arg list tuple for arg in args 0 for item in args 0 list_of_pairs append list item else for item in args list_of_pairs append list item elif len args 2 list_of_pairs append list args else msg The argument type is invalid format args raise TypeError msg return list_of_pairs
returns a np.ndarray of labels and a list of label ids for each row of ' object_ids ' field .,def get_labels self labels self data labels label_ids list range len labels return labels label_ids
convenience for getting an allele pocket aas,def get_allele_pocket_sequences allele alnindex dict a id a for a in drbaln ref alnindex allele return get_pockets_pseudo_sequence ref
"given a file name , read the file , retrieve the dialogs , and then convert the sentences into a single dialog . if max_length is supplied , any stories longer than max_length tokens will be discarded .",def get_dialogs f candid_dic with open f as f return parse_dialogs_per_response f readlines candid_dic
"know something with the given confidence , and return self for chaining .",def know self what confidence if confidence self confidence self best what self confidence confidence return self
updates shebang lines for actual scripts .,def update_script script_filename new_path with open script_filename as f lines list f if not lines return if not lines 0 startswith return args lines 0 2 strip split if not args return if not args 0 endswith bin python or usr bin env python in args 0 return new_bin os path join new_path bin python if new_bin args 0 return args 0 new_bin lines 0 s n join args print S s script_filename with open script_filename w as f f writelines lines
"tor packages are installed via the fpf apt mirror , and signed with the securedrop release signing key . as such , the official tor public key should * not * be present , since we do n't want to install packages from that source .",def test_tor_keyring_absent host package deb torproject org keyring c host run dpkg l format package assert c rc 1 error_text dpkg query no packages found matching format package assert c stderr rstrip error_text
"verifies if the specified action is permitted , and raises an accessdeniedexception if not .",def _check_permission self sender action try if sender kit dbus SystemBus get_object org freedesktop PolicyKit1 org freedesktop PolicyKit1 Authority kit dbus Interface kit org freedesktop PolicyKit1 Authority granted _ details kit CheckAuthorization system bus name name sender action dbus UInt32 1 timeout 600 if not granted raise AccessDeniedException Session not authorized by PolicyKit except AccessDeniedException raise except dbus DBusException as ex raise AccessDeniedException ex message
respond to existing user 's request to change their email .,account route manage change email methods GET POST login_required def change_email_request form ChangeEmailForm if form validate_on_submit if current_user verify_password form password data new_email form email data token current_user generate_email_change_token new_email change_email_link url_for account change_email token token _external True get_queue enqueue send_email recipient new_email subject Confirm Your New Email template account email change_email user current_user _get_current_object change_email_link change_email_link flash A confirmation link has been sent to format new_email warning return redirect url_for main index else flash Invalid email or password form error return render_template account manage html form form
sniff out the character set in use for connection results .,def _detect_charset self connection try cset_name connection connection character_set_name except AttributeError util warn No character_set_name can be detected with this MySQL Python version please upgrade to a recent version of MySQL Python Assuming latin1 return latin1 else return cset_name
the augmented variable ( ) function which automatically applies cuda ( ) when gpu is available .,def Variable tensor args kwargs if use_cuda return torch autograd Variable tensor args kwargs cuda else return torch autograd Variable tensor args kwargs
attempts to match a given header to a field of the imported model .,def _match_header self header fields options for field in fields if header field name or header lower field string lower return field if not in header return traversal subfields fields for section in header split match self _match_header section strip subfields options if not match return field match 0 subfields field fields traversal append field return traversal
adds a `` settingdict `` object for the `` setting `` model to the context as `` settings `` . automatically creates non - existent settings with an empty string as the default value .,def settings request settings Setting objects all as_dict default context SETTINGS settings return context
check that the specified file looks like a pdf,def can_import self file_uris current_doc None if len file_uris 0 return False for uri in file_uris uri self fs safe uri if not self check_file_type uri return False return True
read a list of lines of uncompressed bytes from the file .,def readlines self size 1 if not isinstance size int if not hasattr size __index__ raise TypeError Integer argument expected size size __index__ with self _lock self _check_can_read return self _buffer readlines size
build the the auth url so the user can authorize the app .,def _authorization_code_flow self options scope getattr self scope non expiring client_id self options get client_id response_type code redirect_uri self _redirect_uri url s s connect self scheme self host self _authorize_url s s url urlencode options
function used to apply post method of ' git_init_handler ' . git init is used to initialize a repository .,def post self my_data json loads self request body decode utf 8 current_path my_data current_path my_output self git init current_path self finish my_output
"given a vector of predictions , save results in csv format .",def save_results predictions filename with open filename w as f f write id ACTION n for i pred in enumerate predictions f write d f n i 1 pred
format a value for use in an sql statement .,def quote_value self value type return quote value type string_escaper self escape_string
disconnect whatever our are state is .,def disconnect self if self connector is not None self connector disconnect else self stopConnecting
"leave multicast group , return deferred of success .",def leaveGroup self addr interface return self reactor resolve addr addCallback self _joinAddr1 interface 0
get just one single document from the collection .,def _get_one self doc_id kwargs response hresponse HandlerResponse result None try obj_id bson objectid ObjectId doc_id result utils db find_one2 self collection models ID_KEY obj_id if result result result data result 0 models ID_KEY obj_id response result result else response status_code 404 response reason Resource s not found doc_id except bson errors InvalidId as ex self log exception ex self log error Provided doc ID s is not valid doc_id response status_code 400 response reason Wrong ID value provided return response
closes the cursor . no further operations are allowed once the cursor is closed .,def close self if self _closed raise ProgrammingError the cursor is already closed if self _id is not None self _connection _client close_statement self _connection _id self _id self _id None self _signature None self _column_data_types self _frame None self _pos None self _closed True
get_all_obj_permissions tag should gripe if syntax is bad,raises TemplateSyntaxError def test_bad_format self template join load teamwork_tags get_all_obj_permissions blah blah blah perms join context dict user self user obj self obj result render template context
a metropolis step : return :,def step self n_print verbose self _substeps n_print verbose
get all the header fields and values .,def items self return self _headers
"filters out charcters in any of these unicode catagories [ cc ] other , control ( 65 characters ) , ... [ cf ] other , format ( 151 characters ) [ cn ] other , not assigned ( 0 characters -- none have this property ) [ co ] other , private use ( 6 characters ) [ cs ] other , surrogate ( 6 characters )",def remove_control_characters self s return join ch for ch in s if unicodedata category ch 0 C
gets the settings for the valve,def get_valve_settings valve_name import configparser list config configparser ConfigParser config read settings ini try name config get valve_name name except ValueError name Ventil xyz list append name try description config get valve_name description except ValueError description Beschreibung xyz list append description try status bool config get valve_name isactive except ValueError status False list append status try basictime int config get valve_name basictime except ValueError basictime 1 list append basictime try watergroup int config get valve_name watergroup except ValueError watergroup 1 list append watergroup return list
callback to copy files using ` gfile . copy ` to an export directory .,def gfile_copy_callback files_to_copy export_dir_path logging info Write assest into s using gfile_copy export_dir_path gfile MakeDirs export_dir_path for source_filepath basename in files_to_copy items new_path os path join compat as_bytes export_dir_path compat as_bytes basename logging info Copying asset s to path s source_filepath new_path if gfile Exists new_path logging info Removing file s new_path gfile Remove new_path gfile Copy source_filepath new_path
returns prediction probabilities for given features ( classification ) .,def predict_proba self x None input_fn None batch_size None as_iterable False return super TensorForestEstimator self predict x x input_fn input_fn batch_size batch_size as_iterable as_iterable
exports inference graph into given dir .,def export_estimator estimator export_dir signature_fn None input_fn _default_input_fn default_batch_size 1 exports_to_keep None checkpoint_path tf_saver latest_checkpoint estimator _model_dir with ops Graph as_default as g contrib_variables create_global_step g examples array_ops placeholder dtype dtypes string shape default_batch_size name input_example_tensor features input_fn estimator examples predictions estimator _get_predict_ops features if signature_fn default_signature named_graph_signatures signature_fn examples features predictions else logging warn Change warning signature_fn will be required after 2016 08 01 Using generic signatures for now To maintain this behavior pass signature_fn export generic_signature_fn Also consider passing a regression or classification signature see cl 126430915 for an example default_signature named_graph_signatures generic_signature_fn examples features predictions if exports_to_keep is not None exports_to_keep gc largest_export_versions exports_to_keep _export_graph g _get_saver checkpoint_path export_dir default_graph_signature default_signature named_graph_signatures named_graph_signatures exports_to_keep exports_to_keep
contents may settle during shipping .,def settle self first ucPos self 0 start for i in range 0 len self if self i end l self i start l 1 endL self i start l 1 else endL self i end l if self i start l first l startL 1 startC self i start c first c else startL self i start l first l 1 startC self i start c if endL first l endL 1 endC self i end c first c else endL endL first l 1 endC self i end c self i self i __class__ self i 0 self i 1 ucPos startL startC ucPos endL endC self i 4 if ucParanoid self check return self
"player select only one profile , we disconnect the player 1",def test_client_bin_logout_user self self test_client_bin_sign_in_one_user self test_client_bin_sign_in_second_user self client_bin on_data smpacket SMPacketClientNSCSU player_id 0 nb_players 1 player_name name binary user2 self session query models User filter_by name clientbin user2 first self assertFalse user2 online user1 self session query models User filter_by name clientbin user1 first self assertTrue user1 online
a : a 4d theano tensor,def partial_max a return a max axis 1 2
ansible oc module for image import,def main module AnsibleModule argument_spec dict kubeconfig dict default etc origin master admin kubeconfig type str state dict default present type str choices present list debug dict default False type bool namespace dict default default type str registry_url dict default None type str image_name dict default None required True type str image_tag dict default None type str force dict default False type bool supports_check_mode True rval OCImage run_ansible module params module check_mode if failed in rval module fail_json rval module exit_json rval
return the correct open vswitch version for the current openshift version,def get_required_ovs_version self openshift_version_tuple self get_major_minor_version self get_var openshift_image_tag if openshift_version_tuple 3 5 return self openshift_to_ovs_version 3 4 openshift_version join str x for x in openshift_version_tuple ovs_version self openshift_to_ovs_version get openshift_version if ovs_version return self openshift_to_ovs_version openshift_version msg There is no recommended version of Open vSwitch for the current version of OpenShift raise OpenShiftCheckException msg format openshift_version
filter to all nodes with fluentd label . returns dict(name : node ),staticmethod def filter_fluentd_labeled_nodes nodes_by_name node_selector label value node_selector split 1 fluentd_nodes name node for name node in nodes_by_name items if node metadata labels get label value if not fluentd_nodes raise OpenShiftCheckException NoNodesLabeled There are no nodes with the fluentd label label This means no logs will be aggregated from the nodes format label node_selector return fluentd_nodes
add a key to the running agent .,def add_key self key named_pipe_path os path join self ssh_auth_sock_dir keypipe str random getrandbits 64 try os mkfifo named_pipe_path 384 except OSError as exception print Failed to create FIFO s exception devnull open os devnull w ssh_add subprocess Popen ssh add named_pipe_path stdout devnull stderr devnull fifo open named_pipe_path w print fifo key fifo close start_time datetime datetime now while ssh_add poll is None if datetime datetime now start_time total_seconds 5 try ssh_add kill except OSError pass raise SshAgentException Unable to add ssh key Timed out Does key have a passphrase time sleep 0 1 os remove named_pipe_path
calculates the total amount of downtime divided into periods ( and number of nodes it found ),def _calculate_total_downtime self periods period_func lambda event ZabbixPlot get_period int event clock periods host_func lambda event event hosts 0 name combo_func lambda event event clock event hosts 0 name sorted_events sorted self events key combo_func reverse False downtime for period in periods downtime period 0 down_since for period_id period_events in groupby sorted_events period_func current_period_end ZabbixPlot get_next_period period_id periods for host_id host_events in groupby period_events host_func for event in host_events deltatime self _calculate_event_downtime event value int event clock host_id down_since if deltatime is None self _calculate_anomaly_downtime int event clock periods downtime else downtime period_id deltatime for host in down_since downtime period_id current_period_end down_since host down_since host current_period_end return downtime
does a comparison to evaluate the logging component,def comp self name if name startswith logging curator ops return curator_ops elif name startswith logging kibana ops or name startswith kibana ops return kibana_ops elif name startswith logging es ops or name startswith logging elasticsearch ops return elasticsearch_ops elif name startswith logging curator return curator elif name startswith logging kibana or name startswith kibana return kibana elif name startswith logging es or name startswith logging elasticsearch return elasticsearch elif name startswith logging fluentd or name endswith aggregated logging fluentd return fluentd else return None
"count ( domain , path prefix ) pairs .",def main sc spark docs Document read spark result docs rdd map Document from_rdd map lambda d d url_domain d url_path_prefix 1 reduceByKey add sortBy lambda x x 1 False take 10000 rows k v for k v in result dump_csv rows tmp prefixes csv domain prefix count
this is only used by tree.ladderize ( ) .,def _ladderize self biggerGroupsOnBottom if not self leftChild pass else nLeaves children ch self leftChild while ch nL len n2 for n2 in ch iterLeaves nLeaves append nL ch nLeaves nL children append ch ch ch sibling allOnes True for ch in children if ch nLeaves 1 allOnes False break if not allOnes children p4 func sortListOfObjectsOnAttribute children nLeaves if not biggerGroupsOnBottom children reverse self leftChild children 0 theLeftChild self leftChild theLeftChild sibling None for ch in children 1 theLeftChild sibling ch theLeftChild ch theLeftChild sibling None for ch in children del ch nLeaves for ch in self iterChildren ch _ladderize biggerGroupsOnBottom
return list of available filters .,def available_filters return _avail_filters keys
test notifycallback with a bad model dict .,def test_bad_model self del self body model address self callback self body self message self assertIsNone self event self assertIsNone self model
populates the response `` service_data `` property with an instance of : class:`controldtcsetting . responsedata < udsoncan.services . controldtcsetting . responsedata > `,classmethod def interpret_response cls response if len response data 1 raise InvalidResponseException response Response data must be at least 1 byte response service_data cls ResponseData response service_data setting_type_echo response data 0
verifies the string value can be resolved to the list .,pytest mark parametrize test_value expected item1 item2 item1 item2 item1 item1 item1 item2 item3 item1 item2 item3 def test_list_value_resolve list_value_type test_value expected assert expected list_value_type resolve test_value
return the node that contains the assignment 's value .,staticmethod abc abstractmethod def _extract_value node raise NotImplementedError
funciones : function id lparen argv rparen lblock bloque_sin_tipo rblock,def p_funcion_sin_tipo p p 0 AST FuncionNType AST TokenNode p 2 p 4 p 7 tabla_sim declarar_funcion p 2 void str p 4 split n 1 tabla_sim ambito_actual main parse write 8
"parse wikipedia database dump , return n - gram and link statistics .",def parse_dump dump db N 7 sentence_splitter None tokenizer None f _open dump redirects c db cursor c execute insert into parameters values version __version__ c execute insert into parameters values dump basename dump c execute insert into parameters values N str N c execute create unique index target_anchor on linkstats ngram_id target _logger info Processing articles for i page in enumerate extract_pages f 1 if i 10000 0 _logger info d articles done i if page redirect is not None redirects page title page redirect continue link ngram page_statistics page content N N tokenizer tokenizer sentence_splitter sentence_splitter tokens chain six iteritems ngram or anchor 0 for _ anchor in six iterkeys link tokens list tokens c executemany insert or ignore into ngrams ngram values g for g _ in tokens c executemany update ngrams set tf tf df df 1 where ngram count token for token count in tokens c executemany insert or ignore into linkstats values select id from ngrams where ngram 0 anchor target for target anchor in six iterkeys link c executemany update linkstats set count count where ngram_id select rowid from ngrams where ngram count anchor for _ anchor count in six iteritems link db commit _logger info Processing d redirects len redirects for redir target in redirects items for anchor count in c execute select ngram_id count from linkstats where target redir c execute insert or ignore into linkstats values 0 anchor target c execute update linkstats set count count where target and ngram_id count target anchor c executemany delete from linkstats where target redir for redir in redirects _logger info Finalizing database c executescript drop index target_anchor vacuum _logger info Dump parsing done processed d articles i db commit
returns a lookup value prepared to be used in queryset filtering .,def prepare_lookup_value key value if key endswith __in value value split if key endswith __isnull and type value str if value lower in false value False else value True return value
returns a new copy of the object .,def clone self return deepcopy self
connect : connect to the default device . connect /dev / device : connect to selected device .,def do_connect self dev if self port None self port Serial c get speed self prompt serial elif self port s isOpen print Already connected
"validates that a handle is ` none ` , or a file - like object .",staticmethod def valid_filehandle handle if handle is None or isinstance handle io IOBase return True readable hasattr handle read and callable handle read writable hasattr handle write and callable handle write if readable and writable return True return handle in FileHandles PIPE FileHandles DEVNULL FileHandles STDOUT
"returns a datastore key object , prefixed with the namespace .",def _key key if not isinstance key datastore Key safe_key key replace key datastore Key os path join NAMESPACE safe_key return key
compulsary function to pass for the feture retriever . compute average of features .,def compute self pointfeats point_pos descriptors self _core_characterizer pointfeats point_pos return descriptors
get a ciphercontext that can be used for decryption .,abc abstractmethod def create_symmetric_decryption_ctx self cipher mode
return true if the relation tags represent a major route relation .,def mz_is_path_major_route_relation tags return tags get type route and tags get route in hiking foot bicycle and tags get network in iwn nwn rwn lwn icn ncn rcn lcn
get search tabs from the server .,staticmethod def GetSearchTabs source search_tabs url s search_json source fp urllib urlopen url if fp getcode 200 search_tabs fp read fp close return search_tabs
submits the query to the database and returns tuples . args : query sql select statement . db the database being queried . returns : results as list of lists ( rows of fields ) .,def Query self query command psql c s P format unaligned P tuples_only P fieldsep s s query self separator_ self database_ out os popen command results for line in out readlines row line strip split self separator_ if len row 1 results append row 0 else results append row out close return results
add randomly distributed gaussian noise with random standard deviation ( between min_sigma and max_sigma ) to an image .,def tf_add_random_sigma_gaussian_noise image shape min_sigma max_sigma sigma_noise tf random_uniform 1 minval min_sigma maxval max_sigma return tf_add_gaussian_noise datum shape sigma_noise
convert a given ratio to a decibel value for power quantities .,def ratio_to_db_power ratio return 10 _safe_log10 ratio
test that has_geocode returns true .,pytest mark django_db def test_has_geocode self lat lng 33 210241 97 148857 name Name objects create name Test Name name_type Name PERSONAL Location objects create belong_to_name name longitude lng latitude lat assert name has_geocode
tests whether the translate decorator appropriately calls translate when validate = false,def test_translate_failure self u n Tests whether the translate decorator appropriately n calls translate when validate False n class TranslateClass ResourceBase apimethod methods u GET translate fields IntegerField u id required True validate False def hey cls req return req RequestContainer body_args dict id u notvalid self assertRaises TranslationException TranslateClass hey req
"generate a full fetchable url from the passed filename , which is relative to the self.location",def _make_full_url self filename ret self _srcdir or self location if not filename return ret if not ret endswith ret return ret filename
create lmdb dataset for crnn training .,def createDataset outputPath configFile imgDir env lmdb open outputPath map_size 1099511627776 cache cnt 1 with open configFile r as f for line in f image_path line strip split 0 img os path join imgDir image_path if checkImageIsValid img key 08d cnt cache key image_path if cnt 10000 0 and cnt 0 writeCache env cache cache print Written d images cnt cnt 1 nSamples cnt 1 cache num samples str nSamples writeCache env cache print Created dataset with d samples nSamples
try to get the architecture for the current platform,def get_current_arch if sys platform startswith win machine platform machine if machine AMD64 return get_arch x86_64 wincc elif sys platform linux if platform architecture 0 64bit return get_arch x86_64
generator that yields all nodes in bottom up way,def bottom_up self tree for t in bottom_up tree yield t node
extract_xml_compressed read xml from compressed file,def extract_xml_compressed tarball tar tarfile open tarball r gz for tar_info in tar if os path splitext tar_info name 1 nxml print Extracting text from s tar_info name file_object tar extractfile tar_info return file_object read replace n
: type s : str : type t : str : rtype : bool,def isOneEditDistance self s t if abs len s len t 1 return False if len s len t count 0 for i in range len s if s i t i continue else count 1 if count 1 return False return False if count 0 else True if len s len t s t t s if not s return True for i in range len s if s i t i return s i t i 1 return True
verifies xml output for a google test binary without actual tests .,def testEmptyXmlOutput self self _TestXmlOutput gtest_no_test_unittest EXPECTED_EMPTY_XML 0
create a new module ( app version ) .,def bound_wifi_stats self kwargs kwargs tenant_id self tenant tenant_id return wifi_stats kwargs
convert a lock identifier into an actual lock instance . @param lockid : a locks . masterlock or locks . workerlock instance @return : a locks . realmasterlock or locks . realworkerlock instance,def getLockByID self lockid assert isinstance lockid locks MasterLock locks WorkerLock if lockid not in self locks self locks lockid lockid lockClass lockid return self locks lockid
given that i have a message pump for a channel when i can not read the message received from that channel then i should acknowledge the message to dicard it,def test_the_pump_should_acknowledge_and_discard_an_unacceptable_message self handler MyCommandHandler request MyCommand channel Mock spec Channel command_processor Mock spec CommandProcessor message_pump MessagePump command_processor channel map_my_command_to_request header BrightsideMessageHeader uuid4 request __class__ __name__ BrightsideMessageType MT_UNACCEPTABLE body BrightsideMessageBody JsonRequestSerializer request request serialize_to_json BrightsideMessageBodyType application_json message BrightsideMessage header body quit_message create_quit_message response_queue message quit_message channel_spec receive side_effect response_queue channel configure_mock channel_spec message_pump run channel receive assert_called_with 0 5 self assertEqual channel receive call_count 2 self assertEqual channel acknowledge call_count 1 self assertEqual command_processor send call_count 0
replace pattern with replacement in a file .,def sed filename pattern replacement import re with open filename r as sources lines sources readlines with open filename w as sources for line in lines sources write re sub pattern replacement line
write the ncml table to a csv file,def writeToFile self with open self ncml_csv_file_path w as csv_file csv_file write codecs BOM_UTF8 ncml_writer UnicodeWriter csv_file for row in self rows print row ncml_writer writerow row csv_file close
this function returns the estimated number of data packets that have been received and are able to be retrieved from the receive fifo .,def getqueuesize self return self fifo qsize
reset the count to zero .,def reset self text self count 0 self oldval 0 self oldtime 0 self text text
create a new paper style .,def __init__ self size orientation lmargin 2 54 rmargin 2 54 tmargin 2 54 bmargin 2 54 self __orientation orientation if orientation PAPER_PORTRAIT self __size PaperSize size get_name size get_height size get_width else self __size PaperSize size get_name size get_width size get_height self __lmargin lmargin self __rmargin rmargin self __tmargin tmargin self __bmargin bmargin
remove all references in this object to object handles in the list .,def remove_handle_references self classname handle_list if classname Citation self remove_citation_references handle_list elif classname Source self remove_source_references handle_list elif classname Media self remove_media_references handle_list elif classname Note self remove_note_references handle_list
returns the interferogram which has the master and slave dates given in ' date_pair ' .,def ifg_date_lookup ifgs date_pair if len date_pair 2 msg Need datetime date datetime date master slave pair raise IfgException msg try if date_pair 0 date_pair 1 date_pair date_pair 1 date_pair 0 except raise ValueError Bad date_pair arg to ifg_date_lookup for i in ifgs if date_pair i master i slave return i raise ValueError Cannot find Ifg with master slave of s str date_pair
checking the structure of the makefile 's involved,def check_makefile folder all_fine logging info Checking makefile has_demo False has_start False has_stop False with open os path join folder Makefile as my_file for line in my_file if line startswith demo has_demo True if line startswith start has_start True if line startswith stop has_stop True if not has_demo all_fine warning No demo target if not has_start all_fine warning No start target if not has_stop all_fine warning No stop target
"iterates over the stanzas in this obo file , yielding a ` stanza ` object for each stanza .",def stanzas self stanza None if self _extra_line and self _extra_line 0 stanza Stanza self _extra_line 1 1 for line in self _lines if not line continue if line 0 if stanza yield stanza stanza Stanza line 1 1 continue tag value self _parse_line line try stanza tags tag append value except KeyError stanza tags tag value
create snapshot of events for time charts,task def create_open_events_snapshot logger debug events tasks create_open_events_snapshot worker up for event in Event objects ongoing_only_queryset exclude is_published False try logger debug events tasks create_open_events_snapshot snapshotting event s unicode event pk event snapshots create_snapshot except logger exception Fatal error during create_open_events_snapshot of event d event id logger debug events tasks create_open_events_snapshot finished snapshotting Events
"a simple socket server , for use with : py : func:`my_ip_address `",def ip_echo_socket port 32123 s socket socket socket AF_INET socket SOCK_STREAM s bind port s listen 0 while True conn addr s accept conn sendall addr 0 conn close
wait for the cluster to be refreshed,def wait_for_exists self view navigate_to self parent All def refresh if self provider self provider refresh_provider_relationships view browser selenium refresh view flush_widget_cache wait_for lambda self exists fail_condition False num_sec 1000 fail_func refresh message Wait cluster to appear
converts camera - object to desired projection and representation(dxf - entity type ),def exportCamera ob mx mw common location mathutils Vector ob loc location projected_co location mx location toGlobalOrigin location view_name validDXFr12name CAM_ ob name camera Camera Get ob getData name_only True if camera type persp mode 1 2 4 16 elif camera type ortho mode 0 2 4 16 leftBottom 0 0 0 0 rightTop 1 0 1 0 center 0 0 0 0 direction mathutils Vector 0 0 0 0 1 0 mx to_euler to_matrix direction normalize target mathutils Vector ob loc direction width height camera scale lens camera lens frontClipping camera clipStart 1 0 backClipping camera clipEnd 1 0 entities vport view None None c camera_as_list GUI_A camera_as val if c POINT dxfPOINT DXF Point points location common entities append dxfPOINT elif c VIEW view DXF View name view_name center center width width height height frontClipping frontClipping backClipping backClipping direction direction target target lens lens mode mode elif c VPORT vport DXF VPort name view_name center center ratio 1 0 height height frontClipping frontClipping backClipping backClipping direction direction target target lens lens mode mode return entities vport view
update uv when vertex coordinates are changed,def __update_uv self context props context scene muv_props texlock obj bpy context active_object bm bmesh from_edit_mesh obj data if muv_common check_version 2 73 0 0 bm verts ensure_lookup_table bm edges ensure_lookup_table bm faces ensure_lookup_table if not bm loops layers uv self report WARNING Object must have more than one UV map return CANCELLED uv_layer bm loops layers uv verify verts v index for v in bm verts if v select verts_orig props intr_verts_orig for vidx v_orig in zip verts verts_orig if vidx v_orig vidx self report ERROR Internal Error return CANCELLED v bm verts vidx link_loops get_link_loops v result for ll in link_loops ini_geom get_ini_geom ll uv_layer verts_orig v_orig target_uv get_target_uv ll uv_layer verts_orig v ini_geom result append l ll l uv target_uv ave Vector 0 0 0 0 for r in result ave ave r uv ave ave len result for r in result r l uv_layer uv ave v_orig moved True bmesh update_edit_mesh obj data muv_common redraw_all_areas props intr_verts_orig vidx v index vco v co copy moved False for v in bm verts if v select
"for decorated fn , return function with stirpped decorator",classmethod def strip_wrappers cls fn if not hasattr fn func_closure or not fn func_closure return fn for f in fn func_closure f f cell_contents if hasattr f __call__ return cls strip_wrappers f return fn
check if the thread is still running .,def check_thread self thread i 0 dir 1 before i 8 after 7 before if not after dir 1 if not before dir 1 i dir self view set_status flow_loader FlowType s s before after if thread is_alive return sublime set_timeout lambda self check_thread thread i dir 100 self view erase_status flow_loader self handle_process thread returncode thread stdout thread stderr
"` str ` : the link target ( if resource is a symlink ) , or ` none ` .",property def target self u str the link target if resource is a symlink or None n n Requires the link namespace n n Raises n fs errors MissingInfoNamespace if the link n namespace is not in the Info n n self _require_namespace u link return self get u link u target
loops playback of recorded joint position waypoints until program is exited,def playback self rospy sleep 1 0 rospy loginfo Waypoint Playback Started print Press Ctrl C to stop self _limb set_joint_position_speed self _speed loop 0 while not rospy is_shutdown loop 1 print Waypoint playback loop d loop for waypoint in self _waypoints if rospy is_shutdown break self _limb move_to_joint_positions waypoint timeout 20 0 threshold self _accuracy rospy sleep 3 0 self _limb set_joint_position_speed 0 3
check if obstacle is to the left of rover .,def at_left_obstacle Rover safe_pixs 50 nav_pixs_left len Rover nav_angles_left return nav_pixs_left safe_pixs
go through the list of rules defined in the configuration and shortcircuit them .,def finish_parsing_end self ruleset super ShortCircuit self finish_parsing_end ruleset for config in self shortcircuit try rule_name stype config split None 1 except ValueError self ctxt err Invalid short circuit s config continue try rule ruleset get_rule rule_name except KeyError self ctxt err Unknown rule s rule_name continue if stype off continue if stype not in on ham spam self ctxt err Invalid short circuit type s stype continue self ctxt log debug Short circuiting rule s s rule name stype new_method self get_wrapped_method rule stype rule match new_method
indicate that a formerly enqueued task is complete .,def task_done self nJob self all_tasks_done acquire try unfinished self unfinished_tasks 1 if unfinished 0 if unfinished 0 raise ValueError task_done called too many times self all_tasks_done notify_all self unfinished_tasks unfinished assert nJob in self _ongoing del self _ongoing nJob self not_empty notify finally self all_tasks_done release
function that increments the vialer_middleware_push_notification_failed_total counter .,def increment_vialer_middleware_failed_push_notifications_metric_counter list_length REDIS_CLUSTER_CLIENT client llen VIALER_MIDDLEWARE_PUSH_NOTIFICATION_FAILED_TOTAL_KEY data_list REDIS_CLUSTER_CLIENT client lrange VIALER_MIDDLEWARE_PUSH_NOTIFICATION_FAILED_TOTAL_KEY 0 list_length for value_str in data_list value_dict literal_eval value_str VIALER_MIDDLEWARE_PUSH_NOTIFICATION_FAILED_TOTAL labels os value_dict OS_KEY direction value_dict DIRECTION_KEY failed_reason value_dict FAILED_REASON_KEY inc REDIS_CLUSTER_CLIENT client ltrim VIALER_MIDDLEWARE_PUSH_NOTIFICATION_FAILED_TOTAL_KEY list_length 1
generate an output schema by determining new columns in the csv,def construct_output_params segments_shp black_spots_csv with fiona open segments_shp r as segments with open black_spots_csv rb as spots reader csv DictReader spots out_schema segments schema copy for field in reader fieldnames if field not in out_schema properties out_schema properties field float return out_schema segments crs
coordinates translation and plane rotation .,def getGUICoords self pos i self tilt_angle big_o self node_angle small_o self ecc_angle cos math cos sin math sin m_11 cos big_o cos small_o cos i sin big_o sin small_o m_12 cos i sin small_o cos big_o sin big_o cos small_o m_13 cos big_o sin i m_21 cos i cos small_o sin big_o cos big_o sin small_o m_22 sin big_o cos i sin small_o cos big_o cos small_o m_23 sin big_o sin i m_31 sin i cos small_o m_32 sin i sin small_o m_33 cos i matrix m_11 m_12 m_13 m_21 m_22 m_23 m_31 m_32 m_33 GUI_coords pos append 0 0 for row coord in zip matrix pos GUI_coords append scalarProduct row pos return GUI_coords 0 GUI_coords 2 GUI_coords 1
defines a namedtuple representing a single cluster .,def cluster_named_tuple return namedtuple Cluster label centroid location
set native ( unsorted ) cuda device id,def set_native_id idx import ctypes as ct from util import safe_call as safe_call from library import backend as backend if backend name cuda raise RuntimeError Invalid backend loaded safe_call backend get afcu_set_native_id idx return
check if the number provided is a valid cas rn .,def is_valid number try return bool validate number except ValidationError return False
return a dataset wrapped in a dataflow object .,def get_data train_or_test cifar_classnum batch_size 128 aug False epochs 100 isTrain train_or_test train if cifar_classnum 10 ds dataset Cifar10 train_or_test else ds dataset Cifar100 train_or_test if isTrain ds RepeatedData ds epochs 1 if isTrain and aug augmentors imgaug Flip horiz True imgaug Brightness 63 imgaug Contrast 0 2 1 8 imgaug GaussianDeform 0 2 0 2 0 2 0 8 0 8 0 8 0 8 0 2 32 32 0 2 3 imgaug ImgScale 255 else augmentors imgaug ImgScale ds AugmentImageComponent ds augmentors ds BatchData ds batch_size remainder not isTrain if isTrain ds PrefetchDataZMQ ds 16 return ds
method to executed upon exit from recognizing state . : return :,def on_exit self pass
"reads the next frame from the video . parameters ---------- scale : float , optional the scale value to resize the frame image . returns ---------- image : ndarray(uint8 ) returns an ndarray of the image or none in case of an error .",def next_frame self scale 1 0 if self _video is None or self _video shape 0 self _frame_idx return None frame self _video self _frame_idx self _frame_idx 1 frame tt utils image resize frame scale return frame
concatenate conditioning vector on feature map axis .,def conv_cond_concat x y x_shapes x get_shape y_shapes y get_shape return concat x y tf ones x_shapes 0 x_shapes 1 x_shapes 2 y_shapes 3 3
post - process the results from xv_eval_params .,def summarize_results raw_results results finish_time datetime now isoformat train_wall_time_avg np mean raw_results train_wall_times train_wall_time_std np std raw_results train_wall_times test_wall_time_avg np mean raw_results test_wall_times test_wall_time_std np std raw_results test_wall_times train_rmsle_avg np mean raw_results train_rmsles train_rmsle_std np std raw_results train_rmsles test_rmsle_avg np mean raw_results test_rmsles test_rmsle_std np std raw_results test_rmsles results update raw_results params return results
tells the operadriver to stop and cleans up the process,def stop self if self process is None return self process kill self process wait
"get the next character , throw stopiteration if at end , check for unused content .",def next self if not self ensure_chars if len self accum 0 raise End of stringstream reached without emptying buffer self accum else raise StopIteration result self pos len self current and self current self pos or None self pos 1 return result
returns a sequence of all locales possible . a locale is a string that represents the language of a jurisdiction . note that locales are not the same as jurisdiction codes .,def locales query_string PREFIX cc http creativecommons org ns PREFIX rdf http www w3 org 1999 02 22 rdf syntax ns PREFIX dc http purl org dc elements 1 1 SELECT lang WHERE x cc defaultLanguage lang x rdf type cc Jurisdiction query RDF Query query_string query_language sparql return s lang literal_value string for s in query execute rdf_helper JURI_MODEL
create the hypothetical bounding box used in determining the next crop,def get_random_box_to_determine_crop box_coords x_shift_frac y_shift_frac x_size_change_frac y_size_change_frac get_cropping_params box_for_crop_x_center box_coords x_center x_shift_frac box_coords width box_for_crop_y_center box_coords y_center y_shift_frac box_coords height box_for_crop_width box_coords width x_size_change_frac box_for_crop_height box_coords height y_size_change_frac box_for_crop_x0 box_for_crop_x_center 0 5 box_for_crop_width box_for_crop_y0 box_for_crop_y_center 0 5 box_for_crop_height box_for_crop_x1 box_for_crop_x_center 0 5 box_for_crop_width box_for_crop_y1 box_for_crop_y_center 0 5 box_for_crop_height box_for_crop Coords box_for_crop_x0 box_for_crop_y0 box_for_crop_x1 box_for_crop_y1 return box_for_crop
remove weird character from the input string .,def _sanitize_holiday_name name new_name c for c in name if c isalpha or c isdigit or c new_name join new_name lower replace _ return new_name
"convert wgs84 cooridnates into rijksdriehoekcoordinates . input parameters : phi ( float ) , lambda ( float ) .",def wgs_to_rd phi lam pqr 0 1 190094 945 1 1 11832 228 2 1 114 221 0 3 32 391 1 0 0 705 3 1 2 34 1 3 0 608 0 2 0 008 2 3 0 148 pqs 1 0 309056 544 0 2 3638 893 2 0 73 077 1 2 157 984 3 0 59 788 0 1 0 433 2 2 6 439 1 1 0 032 0 4 0 092 1 4 0 054 dphi 0 36 phi PHI0 dlam 0 36 lam LAM0 X X0 Y Y0 for p q r in pqr X r dphi p dlam q for p q s in pqs Y s dphi p dlam q return X Y
marshals the firefox options to a ` moz : firefoxoptions ` object .,def to_capabilities self opts if self _binary is not None opts binary self _binary _start_cmd if len self _preferences 0 opts prefs self _preferences if self _profile is not None opts profile self _profile encoded if len self _arguments 0 opts args self _arguments opts update self log to_capabilities if len opts 0 return Options KEY opts return
wrapper to set logging parameters for output,def log_wrapper self log logging getLogger client py try debug self params debug log setLevel logging DEBUG except KeyError log setLevel logging INFO stream logging StreamHandler logformat logging Formatter asctime s name s levelname s message s datefmt b d H M S stream setFormatter logformat log addHandler stream return log
tests if bom holds appropriate movie objects,def test_weekend_chart self assert type self test_movie rank str assert type self test_movie title str assert type self test_movie studio str assert type self test_movie gross str assert in self test_movie gross
"test the "" devstack "" task .",ddt data settings aws asset settings test_static_optimized settings devstack_optimized asset settings test_static_optimized fast True optimized True optimized True fast True no contracts True ddt unpack def test_devstack self server_options options server_options copy is_optimized options get optimized False expected_settings devstack_optimized if is_optimized else options get settings Env DEVSTACK_SETTINGS options system lms options expected_messages EXPECTED_INDEX_COURSE_COMMAND format system cms settings expected_settings self verify_server_task devstack options contracts_default True options system cms options expected_messages EXPECTED_INDEX_COURSE_COMMAND format system cms settings expected_settings self verify_server_task devstack options contracts_default True
decorator for raising http404 if function evaluation is falsey ( e.g. empty queryset ) .,def raise_404_if_none func def func_wrapper self queryset func self if queryset return queryset else raise Http404 return func_wrapper
emulate execution of a generic verticacopytask .,def create_task self credentials None source None overwrite False cls CopyToVerticaDummyTable luigi task Register clear_instance_cache task cls credentials sentinel ignored overwrite overwrite if not credentials credentials host db example com port 5433 user exampleuser password example password if not source source self _get_source_string 1 fake_input credentials FakeTarget value textwrap dedent credentials insert_source FakeTarget value textwrap dedent source fake_output MagicMock return_value self mock_vertica_connector self mock_vertica_connector marker_schema name_of_marker_schema self mock_vertica_connector marker_table name_of_marker_table task input MagicMock return_value fake_input task output fake_output return task
assert that a string matches a regular expression ( regex compiled as multiline ) . allows for more flexible matching than the django assertcontains .,def assertPattern self regex text msg_prefix if msg_prefix msg_prefix self assert_ re search re compile regex re DOTALL text msg_prefix Should match s regex
create a random dungeon instance based on a player 's level,def create_random_dungeon self player dungeon_info InstanceInfo erukar server RandomDungeonInstance self properties copy location self location_for player self launch_dungeon_instance dungeon_info self instances append dungeon_info return dungeon_info
return daily returns of the pair,property def spread self return self returns self data beta sum 1
constructor : param db_client : database client,def __init__ self db_clients ExchangeGateway __init__ self ExchGwApiQuoine db_clients
block contructor . add graphics related params to the block .,def __init__ self self get_params append self get_parent get_parent Param block self n odict name GUI Coordinate key _coordinate type raw value 0 0 hide all self get_params append self get_parent get_parent Param block self n odict name GUI Rotation key _rotation type raw value 0 hide all Element __init__ self
get the file path for the flow graph . @return the file path or '',def get_file_path self return self file_path
"get tokenz freuquencies mood : char , 2-gram , word",def get_freq mode char alpha_sorted False fdist for label in text fdist label if mode char tokenz char for char in text label if mode endswith gram n int mode split 0 tokenz text label i i n for i in range len text label else tokenz word_tokenize text label nltk_txt nltk Text tokenz for char in nltk_txt vocab keys fdist label append char nltk_txt vocab char if alpha_sorted fdist label sort return fdist
"url : websocket url . header : custom header for websocket handshake . on_open : callable object which is called at opening websocket . this function has one argument . the argument is this class object . on_message : callable object which is called when received data . on_message has 2 arguments . the 1st argument is this class object . the 2nd argument is utf-8 string which we get from the server . on_error : callable object which is called when we get error . on_error has 2 arguments . the 1st argument is this class object . the 2nd argument is exception object . on_close : callable object which is called when closed the connection . this function has one argument . the argument is this class object . on_cont_message : callback object which is called when receive continued frame data . on_cont_message has 3 arguments . the 1st argument is this class object . the 2nd argument is utf-8 string which we get from the server . the 3rd argument is continue flag . if 0 , the data continue to next frame data on_data : callback object which is called when a message received . this is called before on_message or on_cont_message , and then on_message or on_cont_message is called . on_data has 4 argument . the 1st argument is this class object . the 2nd argument is utf-8 string which we get from the server . the 3rd argument is data type . abnf.opcode_text or abnf.opcode_binary will be came . the 4th argument is continue flag . if 0 , the data continue keep_running : this parameter is obosleted and ignored it . get_mask_key : a callable to produce new mask keys , see the websocket.set_mask_key 's docstring for more information subprotocols : array of available sub protocols . default is none .",def __init__ self url header None on_open None on_message None on_error None on_close None on_ping None on_pong None on_cont_message None keep_running True get_mask_key None cookie None subprotocols None on_data None self url url self header header if header is not None else self cookie cookie self on_open on_open self on_message on_message self on_data on_data self on_error on_error self on_close on_close self on_ping on_ping self on_pong on_pong self on_cont_message on_cont_message self keep_running False self get_mask_key get_mask_key self sock None self last_ping_tm 0 self last_pong_tm 0 self subprotocols subprotocols
"adjust current li and add the duplicates : fnref2 , fnref3 , etc .",def add_duplicates self li duplicates u for link in li iter u a if link attrib get u class u u footnote backref ref rest link attrib u href split self footnotes get_separator 1 links for index in range 2 duplicates 1 sib_link copy deepcopy link sib_link attrib u href u s d s s ref index self footnotes get_separator rest links append sib_link self offset 1 el list li 1 for l in links el append l break
"remove all the cluster directories for the labels with jobids using the master , but no job info founs .",def clean_cluster_info master cluster_info for info in cluster_info if info pbsjob is None and info jobid endswith master rm_cluster_localworkdir info label rm_cluster_info info label
fail to get number of switches of multinet topology .,def __init__ self additional_error_info err_code 1 SBEmuError __init__ self Fail to get multinet topology total switch number 0 format additional_error_info err_code
test that the correct javascript files are included .,def test_media_js self self assertTrue set self config js issubset self widget media _js
alternative to django_template_minifier 's minify function,def minify template_source template_source re sub n n template_source template_source re sub n 1 template_source return template_source
get information for a pick event on a pathcollection artist ( usually created with `` scatter `` ) .,def scatter_props event ind event ind 0 try sizes event artist get_sizes except AttributeError sizes None if sizes is None or len sizes 1 s None else s sizes ind try xorig yorig event artist get_offsets T x y xorig ind yorig ind return dict x x y y s s except IndexError return dict s s
test the basic funcionality of player,def test_basics self player mommy make Player self assertIsNotNone player name self assertIsNotNone player email
"formats the value like a ' human - readable ' file size ( i.e. 13 kb , 4.1 mb , 102 bytes , etc ) . based on django.template.defaultfilters.filesizeformat",def filesizeformat bytes decimals 1 u n Formats the value like a human readable file size i e 13 KB 4 1 MB n 102 bytes etc n Based on django template defaultfilters filesizeformat n try bytes float bytes except TypeError ValueError UnicodeDecodeError raise ValueError def filesize_number_format value return formats number_format round value decimals decimals units_list sorted six iteritems FILESIZE_UNITS key operator itemgetter 1 value unit None len_unints_list len units_list for i in xrange 1 len_unints_list if bytes units_list i 1 prev_unit units_list i 1 value filesize_number_format bytes prev_unit 1 unit prev_unit 0 break if value is None value filesize_number_format bytes units_list 1 1 unit units_list 1 0 return SIZEFIELD_FORMAT format value value unit unit
gets the session database object . database object is based from web.py's database handling . this utilizes values found in the config.yaml file .,def sessionDB config Config get database return web database dbn config dbn user config user pw config password db config db host config host
"width in pixels of the original image , accepts int .",property def maxwidth self return self _kml maxWidth
checks if a point is in the simplex using the standard barycentric coordinate system algorithm .,def in_simplex self point tolerance 1e 08 return self bary_coords point tolerance all
"returns a string repr of the arg list of a func call , with any defaults",def make_signature func spec signature func if spec defaults is None n_wo_defaults len spec args defaults n_wo_defaults else n_wo_defaults len spec args len spec defaults defaults n_wo_defaults spec defaults args for i var default in enumerate zip spec args defaults args append var if default else var repr default if spec varargs args append spec varargs if spec keywords args append spec keywords return args spec args
use circleci env vars to determine which tests to run,def pytest_collection_modifyitems session config items circle_node_total circle_node_index read_circleci_env_variables deselected for index item in enumerate list items item_location join map str item location encode item_hash int hashlib sha1 item_location hexdigest 16 if item_hash circle_node_total circle_node_index deselected append item items remove item config hook pytest_deselected items deselected
decode from base58 and return data part .,def base58_check_decode s version addrbyte data chk0 base58_check_decode_parts s if addrbyte version raise VersionByteError incorrect version byte chk1 util dhash addrbyte data 4 if chk0 chk1 raise Base58ChecksumError Checksum mismatch 0x xe2 x89 xa0 0x format util hexlify chk0 util hexlify chk1 return data
"converts tags or full names to full names , case sensitive",def normalizeToName val if val not in tagsAndNameSet raise KeyError is not a tag or name string format val else try return tagToFullDict val except KeyError return val
get the build time for the tests : param python2_build_number : a circle ci build number : param python3_build_number : a circle ci build number : return : a number of milliseconds the build took,def get_current_build_performance python2_build_number python3_build_number builds python2_build_number python3_build_number current_build_performance 0 for build in builds api_url https circleci com api v1 1 project github openfisca openfisca france format build response requests get api_url if response status_code 200 response_python json loads response content decode utf 8 else logging warning Cannot reach build Aborting exit 1 current_build_performance response_python build_time_millis return current_build_performance 2
"generate the "" ospf "" section of the bird daemon configuration .",def _build_ospf_config config interface_map retval protocol ospf texport all trfc1583compat yes tarea d DEFAULT_AREA for net in config networks ifname interface_map get net interface ifname if ifname and net is_internal_network modifier stub yes elif ifname and net is_external_network modifier type broadcast else continue retval extend t tinterface s ifname t t tcost 10 t t t s modifier t t retval extend t return n join retval replace t
create network address in cidr format .,def make_cidr gw mask try int_mask 4294967295 32 int mask 4294967295 gw_addr_int struct unpack L socket inet_aton gw 0 int_mask return socket inet_ntoa struct pack I gw_addr_int str mask except socket error struct error ValueError TypeError return
"send a message , blocking .",def send self message condition threading Condition condition acquire self _queue put message condition condition wait
"complete the quiz submission by marking it as complete and grading it . when the quiz submission has been marked as complete , no further modifications will be allowed .",def complete_quiz_submission_turn_it_in request_ctx course_id quiz_id id attempt validation_token access_code None request_kwargs path v1 courses course_id quizzes quiz_id submissions id complete payload attempt attempt validation_token validation_token access_code access_code url request_ctx base_api_url path format course_id course_id quiz_id quiz_id id id response client post request_ctx url payload payload request_kwargs return response
"insert data t into this bst , modifying it in - place .",def insert self t new TNode t if self root is None self root new else node self root while True if t node data if node left is None node left new new parent node break node node left else if node right is None node right new new parent node break node node right return new
return the cryptoid < keyhash > value corresponding to this key .,def hash self raise NotImplementedError
does nothing . no fitting required .,def fit self X pass
restores vocabulary processor from given file .,classmethod def restore cls filename with gfile Open filename rb as f return pickle loads f read
get basic block end address .,property def end_address self if self _instrs is return None return self _instrs 1 address self _instrs 1 size 1
"@type host : string @param host : hostname or ip address to bind server to @type port : integer @param port : port to bind server to @type vmrun : string @param vmrun : path to vmware vmrun.exe @type vmx : string @param vmx : path to vmx file @type snap_name : string @param snap_name : ( optional , def = none ) snapshot name to revert to on restart @type log_level : integer @param log_level : ( optional , def=1 ) log output level , increase for more verbosity @type interactive : boolean @param interactive : ( option , def = false ) interactive mode , prompts for input values",def __init__ self host port vmrun vmx snap_name None log_level 1 interactive False pedrpc server __init__ self host port self host host self port port self interactive interactive if interactive print Entering interactive mode try while 1 print Please browse to the folder containing vmrun exe pidl disp imglist shell SHBrowseForFolder 0 None Please browse to the folder containing vmrun exe fullpath shell SHGetPathFromIDList pidl file_list os listdir fullpath if vmrun exe not in file_list print vmrun exe not found in selected folder please try again else vmrun fullpath vmrun exe print Using s vmrun break except print Error while trying to find vmrun exe Try again without I sys exit 1 try while 1 print Please browse to the folder containing the vmx file pidl disp imglist shell SHBrowseForFolder 0 None Please browse to the folder containing the vmx file fullpath shell SHGetPathFromIDList pidl file_list os listdir fullpath exists False for file in file_list idx file find vmx if idx len file 4 exists True vmx fullpath file print Using s vmx if exists break else print No vmx file found in the selected folder please try again except raise print Error while trying to find the vmx file Try again without I sys exit 1 if interactive snap_name raw_input Please enter the snapshot name log_level raw_input Please enter the log level default 1 if log_level log_level int log_level else log_level 1 if os name nt self vmrun GetShortPathName s vmrun self vmx GetShortPathName s vmx else self vmrun vmrun self vmx vmx self snap_name snap_name self log_level log_level self interactive interactive self log VMControl PED RPC server initialized self log t vmrun s self vmrun self log t vmx s self vmx self log t snap name s self snap_name self log t log level d self log_level self log Awaiting requests
convert a number into bits ( in a string ) : - size : size in bits of the number - value : positive ( or nul ) number - endian : big_endian ( most important bit first ) or little_endian ( least important bit first ) - classic_mode ( default : false ) : reverse each packet of 8 bits,def long2bin size value endian classic_mode False text assert endian in LITTLE_ENDIAN BIG_ENDIAN assert 0 value for index in xrange size if value 1 1 text 1 else text 0 value 1 if endian is LITTLE_ENDIAN text text 1 result while len text 0 if len result 0 result if classic_mode result text 7 1 else result text 8 text text 8 return result
"get the upstream job name if it exist , none otherwise : return : string or none",def get_upstream_job_name self try return self get_actions causes 0 upstreamProject except KeyError return None
new / current session for context / thread . : retrun sqlalchemy.orm.session.session : persistence operations for orm - mapped objects,def connect u n New current session for context thread n retrun sqlalchemy orm session Session persistence operations for ORM mapped objects n FACTORY logger logging getLogger __name__ logger debug u Return Scoped Session r FACTORY return FACTORY
an example view with twython / oauth hooks / calls to fetch data about the user in question .,def user_timeline request user request user twitterprofile twitter Twython settings TWITTER_KEY settings TWITTER_SECRET user oauth_token user oauth_secret user_tweets twitter get_home_timeline return render_to_response tweets html tweets user_tweets
"check if the block contains the correct macro definition line # name(arg0 , arg1 , ... )",def is_valid self return self _valid
test that the context contains required keys in context,def test_get_context_keys_correct_type self letting LettingFactory request self factory get reverse lettings detail kwargs slug letting slug request user UserFactory response DetailPageView as_view request slug letting slug self assertIsInstance response context_data contact LettingContactForm self assertIsInstance response context_data form SearchForm
parses the command - line .,def parse_cmdline argv parser SortedOptParser usage Usage s f filename u url sys argv 0 description download url file use urllib parser add_option o output dest output metavar str help file name for save parser add_option u url dest url metavar URL help url file for download parser add_option f filelist dest filelist metavar FILE help url file list for batch download parser add_option d dest dest dest metavar str action callback callback expand_tilde default help dest dir for save file parser add_option p progress action store_true default False dest progress help disable progress bar fuction default enable options args parser parse_args args argv 1 if options url is None and options filelist is None parser print_usage error_exit option u or f is must if os path exists options dest if not os path isdir options dest parser print_usage error_exit s is not a dir options dest if not os access options dest os W_OK os X_OK error_exit s is not have a write priority options dest else try os makedirs options dest except os error error_exit mkdir for s catch exception options dest return options args
attach an interface to a security group .,click command click argument securitygroup_id click option network component n help The network component to associate with the security group click option server s help The server ID to associate with the security group click option interface i help The interface of the server to associate public private environment pass_env def add env securitygroup_id network_component server interface _validate_args network_component server interface mgr SoftLayer NetworkManager env client component_id _get_component_id env network_component server interface success mgr attach_securitygroup_component securitygroup_id component_id if not success raise exceptions CLIAbort Could not attach network component
rfc822time : simple call using a valid float argument .,def test_rfc822time_normal_float self test_arg 1138371125 target Fri 27 Jan 2006 14 12 05 GMT result rhnLib rfc822time test_arg self assertEqual result target result target
tests plain english messages translated in the mythical go language,def test_go_1 self lang en s Good day target s self _test lang s target
reverse the dataarray along the given dimension .,def _reverse_dim self arr return self _slice_arr_dim slice 1 None 1 arr
initializes the google zoom object .,def __init__ self num_zoom 19 tilesize 256 self _tilesize tilesize self _nzoom num_zoom self _degpp self _radpp self _npix z tilesize for i in xrange num_zoom self _degpp append z 360 0 self _radpp append z 2 pi self _npix append z 2 z 2
unregister a given serializer . this is not a thread - safe operation .,def unregister_serializer format if not _serializers _load_serializers if format not in _serializers raise SerializerDoesNotExist format del _serializers format
returns an extra keyword arguments dictionary that is used with the ` add_item ` call of the feed generator .,def item_extra_kwargs self item u n Returns an extra keyword arguments dictionary that is used with n the add_item call of the feed generator n return
shortens a string to a repeatable mangled version with the given length .,def truncate_name name length None hash_len 4 u Shortens a string to a repeatable mangled version with the given length n if length is None or len name length return name hsh hashlib sha1 force_bytes name hexdigest hash_len return u s s name length hash_len hsh
post process the given sorteddict of files ( called from collectstatic ) .,def post_process self paths dry_run False options u n Post process the given SortedDict of files called from collectstatic n n Processing is actually two separate operations n n 1 renaming files to include a hash of their content for cache busting n and copying those files to the target storage n 2 adjusting files which contain references to other files so they n refer to the cache busting filenames n n If either of these are performed on a file then that file is considered n post processed n if dry_run return hashed_paths matches lambda path matches_patterns path self _patterns keys adjustable_paths path for path in paths if matches path path_level lambda name len name split os sep for name in sorted paths keys key path_level reverse True storage path paths name with storage open path as original_file hashed_name self hashed_name name original_file if hasattr original_file u seek original_file seek 0 hashed_file_exists self exists hashed_name processed False if name in adjustable_paths content original_file read decode settings FILE_CHARSET for patterns in self _patterns values for pattern template in patterns converter self url_converter name template content pattern sub converter content if hashed_file_exists self delete hashed_name content_file ContentFile force_bytes content saved_name self _save hashed_name content_file hashed_name force_text saved_name replace u u processed True elif not hashed_file_exists processed True saved_name self _save hashed_name original_file hashed_name force_text saved_name replace u u hashed_paths self cache_key name replace u u hashed_name yield name hashed_name processed self cache set_many hashed_paths
create and setup a new tornado server .,def main port shell LOGGER info Server is now at 127 0 0 1 format port LOGGER info Shell 0 format shell application create_app shell ioloop tornado ioloop IOLoop instance application listen port address 127 0 0 1 try try ioloop start except KeyboardInterrupt pass finally LOGGER info Closing server n application term_manager shutdown tornado ioloop IOLoop instance stop
method is provided by sublime text through the super class textcommand .,def run self edit args low args low high args high output args output region sublime Region low high original_str self view substr region self view replace edit region output logger info Replacing original_str with output
"fetch sum score defined by chr , st , end 1)st and end are 0-based , half - open . ( st , end ]",def fetch_sum_scores self chr st end chr chr upper lst float self scores chr i for i in range st end if self num_re match str self scores chr i return sum lst
insert the input series into the input dataframe with the specified column header .,def add_series_to_dataframe dataframe series header dataframe loc header pandas Series series index dataframe index
access procedure data as a fhir bundle of procedures ( in json ),procedure_api route patient int patient_id procedure oauth require_oauth def procedure patient_id patient get_user_or_abort patient_id current_user check_role permission view other_id patient_id return jsonify patient procedure_history requestURL request url
return an iterator over the graph nodes .,def nodes_iter G return G nodes_iter
"when not passed a password , pw_decode is noop on the payload .",def test_aes_deencode_without_password self payload u u66f4 u7a33 u5b9a u7684 u4ea4 u6613 u5e73 u53f0 enc pw_decode payload None self assertEqual payload enc
"return the directories where tensorflow summaries are placed . if the directory does not exist , it is created . if val is false , the second item in the returned list is none . a canonical path is built using the name from an imdb and a network ( if not none ) .",def get_output_tb_dir network_name imdb_name val True outdir os path abspath os path join ROOT_DIR tensorboard network_name imdb_name traindir os path join outdir train if not os path exists outdir os makedirs outdir if not os path exists traindir os makedirs traindir if val valdir os path join outdir val if not os path exists outdir os makedirs valdir else valdir None return traindir valdir
"evaluate the quality of the logits at predicting the label . args : logits : logits tensor , float - [ batch_size , num_classes ] . labels : labels tensor ,",def accuracy logits labels with tf name_scope accuracy as scope correct tf equal tf arg_max logits 1 tf arg_max labels 1 correct tf cast correct tf float32 accuracy tf reduce_mean correct 100 0 tf summary scalar scope accuracy accuracy return accuracy
initialize parameters for payments object .,def __init__ self self payment_id self bill_id self bill_payment_id self payment_mode self description self date self reference_number self exchange_rate 0 0 self amount 0 0 self paid_through_account_id self paid_through_account_name self is_single_bill_payment None self amount_applied 0 0 self vendor_id self vendor_name self paid_through
this method parses the given response and returns matching transactions list .,def get_matching_transaction self resp transaction_list TransactionList for value in resp matching_transactions transaction Transaction transaction set_transaction_id value transaction_id transaction set_date value date transaction set_date_formatted value date_formatted transaction set_transaction_type value transaction_type transaction set_transaction_type_formatted value transaction_type_formatted transaction set_reference_number value reference_number transaction set_amount value amount transaction set_amount_formatted value amount_formatted transaction set_debit_or_credit value debit_or_credit transaction_list set_transactions transaction page_context_obj PageContext page_context resp page_context page_context_obj set_page page_context page page_context_obj set_per_page page_context per_page page_context_obj set_has_more_page page_context has_more_page page_context_obj set_sort_column page_context sort_column page_context_obj set_sort_order page_context sort_order for value in page_context search_criteria criteria SearchCriteria criteria set_column_name value column_name criteria set_search_text value search_text criteria set_comparator value comparator page_context_obj set_search_criteria criteria transaction_list set_page_context page_context_obj instrumentation_obj Instrumentation instrumentation resp instrumentation instrumentation_obj set_query_execution_time instrumentation query_execution_time instrumentation_obj set_request_handling_time instrumentation request_handling_time instrumentation_obj set_response_write_time instrumentation response_write_time instrumentation_obj set_page_context_write_time instrumentation page_context_write_time transaction_list set_instrumentation instrumentation_obj return transaction_list
this method is used to create json object for line items .,def to_json self line_item if self item_id line_item item_id self item_id if self account_id line_item account_id self account_id if self name line_item name self name if self description line_item description self description if self unit line_item unit self unit if self rate None line_item rate self rate if self item_order None line_item item_order self item_order if self quantity None line_item quantity self quantity if self discount is not None line_item discount self discount if self tax_id line_item tax_id self tax_id if self amount 0 line_item amount self amount if self debit_or_credit line_item debit_or_credit self debit_or_credit return line_item
tests that updates on both static and non - static columns work as intended,skipUnless PROTOCOL_VERSION 2 only runs against the cql3 protocol v2 0 def test_mixed_updates self instance TestStaticModel create instance static it s shared instance text some text instance save u TestStaticModel get partition instance partition u static it s still shared u text another text u update actual TestStaticModel get partition u partition assert actual static it s still shared
clean out handlers in the library top level logger,def clear_handlers logger for h in logger handlers logger removeHandler h
helper function to retrieve all osf related models .,def get_osf_models return list itertools chain app get_models for app in apps get_app_configs if app label startswith addons_ or app label startswith osf
reduce list of responsibleparty elements to just contributors,def filter_to_contributors parties u return filter_responsible_parties parties u resourceProvider
creates a folder and returns its id .,def createFolder self url services data v20 0 sobjects Folder format self auth instance_url folder_name self param sending folder_name folder Name folder_name DeveloperName folder_name AccessType Hidden Type Document r requests post url headers Authorization Bearer format self auth access_token Content Type application json json folder return r json id
initializes the state . see elsewhere for details .,def __init__ self length 9 assert length 3 assert is too low format length self length length self num_acts 9 self grid np zeros self length self length dtype str self s_start self s_agent self s_goal self _init_grid
generate .js files defining blockly core and language messages .,def main parser argparse ArgumentParser description Convert JSON files to JS parser add_argument source_lang default en help ISO 639 1 source language code parser add_argument source_lang_file default os path join json en json help Path to json file for source language parser add_argument source_synonym_file default os path join json synonyms json help Path to json file with synonym definitions parser add_argument output_dir default js help relative directory for output files parser add_argument key_file default keys json help relative path to input keys file parser add_argument quiet action store_true default False help do not write anything to standard output parser add_argument files nargs help input files args parser parse_args if not args output_dir endswith os path sep args output_dir os path sep source_defs read_json_file os path join os curdir args source_lang_file for key value in source_defs items if _NEWLINE_PATTERN search value print ERROR definition of 0 in 1 contained a newline character format key args source_lang_file sys exit 1 sorted_keys source_defs keys sorted_keys sort synonym_defs read_json_file os path join os curdir args source_synonym_file synonym_text n join Blockscad Msg 0 Blockscad Msg 1 format key synonym_defs key for key in synonym_defs for arg_file in args files _ filename os path split arg_file target_lang filename filename index if target_lang not in qqq keys synonyms target_defs read_json_file os path join os curdir arg_file bad_keys key for key in target_defs if not string_is_ascii key if bad_keys print u These keys in 0 contain non ascii characters 1 format filename join bad_keys for key value in target_defs items if _NEWLINE_PATTERN search value print u WARNING definition of 0 in 1 contained a newline character format key arg_file target_defs key _NEWLINE_PATTERN sub value outname os path join os curdir args output_dir target_lang js with codecs open outname w utf 8 as outfile outfile write This file was automatically generated Do not modify use strict goog provide Blockscad Msg 0 format target_lang replace for key in sorted_keys if key in target_defs value target_defs key comment del target_defs key else value source_defs key comment untranslated value value replace outfile write u Blockscad Msg 0 1 2 n format key value comment if target_defs extra_keys key for key in target_defs if key not in synonym_defs synonym_keys key for key in target_defs if key in synonym_defs if not args quiet if extra_keys print u These extra keys appeared in 0 1 format filename join extra_keys if synonym_keys print u These synonym keys appeared in 0 1 format filename join synonym_keys outfile write synonym_text if not args quiet print Created 0 format outname
only authenticated users can see this,bottle route def index aaa require fail_redirect login return Welcome a href admin Admin page a a href logout Logout a
retrieves item by the specified key .,def __getitem__ self key return self _values key
raise error if filepath or version have invalid values,def check_assertions self if not os path isabs self filepath raise PathError Input file must be a full path name if self version is not None and self version 3 VERSION 3 raise VersionError Required version is greater than the current version
"determines language of a code block from shebang line and whether said line should be removed or left in place . if the sheband line contains a path ( even a single / ) then it is assumed to be a real shebang line and left alone . however , if no path is given ( e.i . : # ! python or : : : python ) then it is assumed to be a mock shebang for language identifitation of a code fragment and removed from the code block prior to processing for code highlighting . when a mock shebang ( e.i : # ! python ) is found , line numbering is turned on . when colons are found in place of a shebang ( e.i . : : : : python ) , line numbering is left in the current state - off by default .",def _getLang self import re lines self src split n fl lines pop 0 c re compile P shebang Shebang or 2 or more colons P path w Zero or 1 path P lang w The language re VERBOSE m c search fl if m try self lang m group lang lower except IndexError self lang None if m group path lines insert 0 fl if m group shebang self linenos True else lines insert 0 fl self src n join lines strip n
creates the virtual environment and installs pip .,def create_virtualenv self no_site_packages True if not os path isdir self venv print Creating venv end if no_site_packages self run_command virtualenv q no site packages self venv else self run_command virtualenv q self venv print done else print venv already exists pass
return user details from reddit account,def get_user_details self response return username response get name email fullname first_name last_name
tests ( pychemia.code.vasp ) [ poscar ] :,def test_poscar self tmpdir tempfile mkdtemp st pychemia code vasp read_poscar tests data vasp_06 self assertEqual st natom 4 with self assertRaises ValueError as context st pychemia code vasp read_poscar tests data vasp_07 POSCAR st pychemia code vasp read_poscar tests data vasp_08 POSCAR_old self assertEqual st natom 2 st pychemia code vasp read_poscar tests data vasp_08 POSCAR_new self assertEqual st natom 2 with self assertRaises ValueError as context pychemia code vasp write_potcar st filepath tmpdir os sep POTCAR basepsp no existing path with self assertRaises ValueError as context pychemia code vasp write_potcar st filepath tmpdir os sep POTCAR basepsp tests data cwd os getcwd os chdir tests data vasp_07 st pychemia code vasp read_poscar POSCAR_new os chdir cwd self assertEqual st natom 44 st pychemia code vasp read_poscar tests data vasp_07 POSCAR_alt pychemia code vasp write_poscar st tmpdir os sep POSCAR1 pychemia code vasp write_poscar st tmpdir os sep POSCAR2 direct False pychemia code vasp write_poscar st tmpdir os sep POSCAR3 newformat False st pychemia code vasp read_poscar tmpdir os sep POSCAR1 self assertAlmostEqual st volume 584 4716192604391 sym pychemia crystal CrystalSymmetry st self assertEqual sym symbol C2 c st pychemia code vasp read_poscar tmpdir os sep POSCAR2 self assertAlmostEqual st volume 584 4716192604391 sym pychemia crystal CrystalSymmetry st self assertEqual sym symbol C2 c st pychemia code vasp read_poscar tmpdir os sep POSCAR3 self assertAlmostEqual st volume 584 4716192604391 sym pychemia crystal CrystalSymmetry st self assertEqual sym symbol C2 c pychemia code vasp write_potcar st filepath tmpdir os sep POTCAR basepsp tests data pychemia code vasp get_potcar_info tmpdir os sep POTCAR shutil rmtree tmpdir
generate random strings of variable length,def random_gen uuid None size 6 chars string ascii_uppercase string digits random_string join random choice chars for _ in range size if uuid return join uuid random_string return random_string
move the write pointer forward with length,def write_empty self length s x00 length self file_object write s
adds a dependency to a specific answer_id,def add self answer_id dependency self _answer_dependencies answer_id add dependency
instance ( instrument ) : an instrument object ordinal ( int ) : the order in the connection chain,def __init__ self instance ordinal self ordinal ordinal self instance instance
decompose a multi - controlled gate u into a single - controlled u.,def _decompose_CnU cmd eng cmd engine qubits cmd qubits ctrl_qureg cmd control_qubits gate cmd gate n get_control_count cmd ancilla_qureg eng allocate_qureg n 1 with Compute eng Toffoli ctrl_qureg 0 ctrl_qureg 1 ancilla_qureg 0 for ctrl_index in range 2 n Toffoli ctrl_qureg ctrl_index ancilla_qureg ctrl_index 2 ancilla_qureg ctrl_index 1 with Control eng ancilla_qureg 1 gate qubits Uncompute eng
set the xml parser to use internally . this should be an instance of `` lxml.etree.xmlparser `` .,def set_xml_parser parser global _XML_PARSER _XML_PARSER parser
"get a unique filepath name in the testing directory . the file will not be created , that is up to the caller . this file will be deleted when the tests are finished . @param file_name : a partial path ex : ' directory / somefile.txt ' @return the full path to the temporary file .",classmethod def get_temp_filename cls file_name temp_dir Settings temp_dir if not os path exists temp_dir os makedirs temp_dir base_name ext os path splitext file_name path 0 1 2 format temp_dir base_name ext count 0 while os path exists path count 1 path 0 1 2 3 format temp_dir base_name count ext cls files_created append path return path
"registerrequest = { "" version "" : "" u2f_v2 "" , "" challenge "" : string , //b64 encoded challenge "" appid "" : string , //app_id }",def register self facet app_id request if not isinstance request RegisterRequest request RegisterRequest request if request version U2F_V2 raise ValueError Unsupported U2F version s request version client_data ClientData typ Type REGISTER value challenge request challenge origin facet client_data client_data json encode utf 8 client_param sha_256 client_data priv_key ec generate_private_key CURVE default_backend pub_key priv_key public_key public_bytes Encoding DER PublicFormat SubjectPublicKeyInfo pub_key pub_key 65 key_handle os urandom 64 app_param sha_256 app_id encode idna self keys key_handle priv_key app_param cert_priv load_pem_private_key CERT_PRIV password None backend default_backend cert CERT data x00 app_param client_param key_handle pub_key signer cert_priv signer ec ECDSA hashes SHA256 signer update data signature signer finalize raw_response x05 pub_key six int2byte len key_handle key_handle cert signature return RegisterResponse version request version registrationData websafe_encode raw_response clientData websafe_encode client_data
returns the message list for this user . this is a list contacts which at the top has the user that the last conversation was with . this is an imitation of the iphone sms functionality .,login_required def message_list request page 1 paginate_by 50 template_name umessages message_list html extra_context None kwargs queryset MessageContact objects get_contacts_for request user if not extra_context extra_context dict return ProfileListView as_view queryset queryset paginate_by paginate_by page page template_name template_name extra_context extra_context context_object_name message kwargs request
returns the shape of an image file,def shape imfile result run convert imfile format w h info shell True check True stdout PIPE return int x for x in result stdout decode utf 8 split
get all listing for a profile by profile_id and listing_id,def get_all_listings_for_profile_by_id current_request_username profile_id listing_id None if profile_id self profile_instance models Profile objects get user__username current_request_username else profile_instance models Profile objects get id profile_id listings models Listing objects for_user current_request_username filter owners__in profile_instance id filter is_deleted False order_by approval_status if listing_id listings listings get id listing_id else listings listings all return listings
"generate a sequence of tuples representing the span of a month ( month_start , month_end ) where starts are inclusive and ends are exclusive ( the end of one month is the same as the start of the next month ) .",def iter_months start end u n Generate a sequence of tuples representing the span of a month n month_start month_end where starts are inclusive and ends are exclusive n the end of one month is the same as the start of the next month n preferred_dom start day while start end next_start min next_month start preferred_dom end yield start next_start start next_start
"perform a very basic functionality test , without cuda",def test_noCUDA ok _basic_par2d if not ok raise RuntimeError Test failed
writes spectra to data - log .,def data_log self file spectra if self datalogflag with open file a as f f write 0 format spectra self vprint 2 Writing spectra to data log at format file
return a git reference based on a local name and a remote name .,def make_remote ref remote return refs remotes remote ref
calculates the root means squared error between two vectors . : param p : one - dimensional numpy array with the predicted values . : param t : one - dimensional numpy array with the known values . : return : float value between 0 and infinity .,def rmse p t return np sqrt np average np square np subtract p t
"// given separate r , g , b , return a packed 32-bit color . // meh , mostly here for parity w / arduino library .",staticmethod def Color r g b assert type r is int assert type g is int assert type b is int assert 0 r 255 assert 0 g 255 assert 0 b 255 return r 16 g 8 b
skip the method decorated if we are using the ` os_type ` .,def __init__ self target_os_list reason self _target_os_list target_os_list self _reason reason
draws nba court on axis . source : http://savvastjortjoglou.com/nba-shot-sharts.html,def draw_court ax None color black lw 2 outer_lines False if ax is None ax plt gca hoop Circle 0 0 radius 7 5 linewidth lw color color fill False backboard Rectangle 30 7 5 60 1 linewidth lw color color outer_box Rectangle 80 47 5 160 190 linewidth lw color color fill False inner_box Rectangle 60 47 5 120 190 linewidth lw color color fill False top_free_throw Arc 0 142 5 120 120 theta1 0 theta2 180 linewidth lw color color fill False bottom_free_throw Arc 0 142 5 120 120 theta1 180 theta2 0 linewidth lw color color linestyle dashed restricted Arc 0 0 80 80 theta1 0 theta2 180 linewidth lw color color corner_three_a Rectangle 220 47 5 0 140 linewidth lw color color corner_three_b Rectangle 220 47 5 0 140 linewidth lw color color three_arc Arc 0 0 475 475 theta1 22 theta2 158 linewidth lw color color center_outer_arc Arc 0 422 5 120 120 theta1 180 theta2 0 linewidth lw color color center_inner_arc Arc 0 422 5 40 40 theta1 180 theta2 0 linewidth lw color color court_elements hoop backboard outer_box inner_box top_free_throw bottom_free_throw restricted corner_three_a corner_three_b three_arc center_outer_arc center_inner_arc if outer_lines outer_lines Rectangle 250 47 5 500 470 linewidth lw color color fill False court_elements append outer_lines for element in court_elements ax add_patch element return ax
uploads video file to cloud storage .,def UploadToCloudStorage self bucket target_path cloud_storage Insert bucket target_path self _video_file_obj name
tests that wait_for_playing timeouts if video does not play .,decorators Disabled linux def testPlayWaitForPlayTimeout self action play PlayAction selector video_1 playing_event_timeout_in_seconds 5 action WillRunAction self _tab self _tab EvaluateJavaScript document getElementById video_1 src self assertFalse self _tab EvaluateJavaScript VIDEO_1_PLAYING_CHECK self assertRaises py_utils TimeoutException action RunAction self _tab
"check if a node is the "" usb3 branch "" of a plugable 7-port usb-3 hub ( model usb3-hub7bc ) the topology of this device is a 4-port hub , with another 4-port hub connected on port 1 .",def _is_plugable_7port_usb3_part3_hub node if 2109 8110 not in node desc return False if not node HasPort 1 return False return 2109 8110 in node PortToDevice 1 desc
override this to return whether the browser brought up by this state instance is suitable for running the given page .,def CanRunOnBrowser self browser_info page del browser_info page return True
"print output in a simple tuple format , one record per line . this makes it easy to import the data somewhere else .",def print_tuples obs output output append Export of network notary version 2 x Observations from s args dbname output append s n time ctime for service key start end in obs output append s s s s service key start end with open output_file a as f for line in output print line n file f
check that test case has installed 4 fixture objects,def testClassFixtures self self assertEqual Article objects count 4 self assertEquals str Article objects all Article Django conquers world Article Copyright is fine the way it is Article Poker has no place on ESPN Article Python program becomes self aware
adding the same relation twice results in a single relation .,def test_recursive_m2m_add_in_both_directions self u self a idols add self d self d stalkers add self a self assertQuerysetEqual self a idols all u David attrgetter u name ordered False self assertEqual self a idols all count 1
this routine is necessary so that distances and geometries returned from extra selection sql get resolved appropriately into python objects .,def resolve_columns self row fields values aliases self query extra_select keys if self query aggregates aliases extend None for i in xrange len self query aggregates rn_offset 0 if self connection ops oracle if self query high_mark is not None or self query low_mark rn_offset 1 index_start rn_offset len aliases values self query convert_values v self query extra_select_fields get a None self connection for v a in izip row rn_offset index_start aliases if self connection ops oracle or getattr self query geo_values False for value field in map None row index_start fields values append self query convert_values value field self connection else values extend row index_start return tuple values
requests the server to run proxy hack for the given stream : param game_id : : param team_type : : return :,def request_proxy_hack game_id team_type global __client_socket__ __connect_to_server if __client_socket__ is None raise Exception Client socket is not connected command_string FuckNeulionService RunProxyHackCommand game_id team_type to_string __client_socket__ send command_string response_string __client_socket__ recv FuckNeulionService MSG_SIZE response FuckNeulionService Response accept response_string log Proxy hack response str response __close_connection return response success response msg
changes things like ` interfaces : ` to ` packetbeat.interfaces : ` at the top level .,process_lines def migrate_packetbeat line sections interfaces protocols procs runoptions ignore_outgoing for sec in sections if line startswith sec return packetbeat line return line
the login page should redirect users to the oauth2 provider 's login page .,def test_login_redirect self response self client get settings LOGIN_URL path reverse social begin args edx oidc self assertRedirectsNoFollow response path status_code 302
: type root : treenode : rtype : list[int ],def postorderTraversal self root if root is None return if root left is None and root right is None return root val result return self traverse root result
"optimized c{broadcast } implementation . depending on type of the session , will json - encode message once and will call either c{send_message } or c{send_jsonifed}.",def broadcast self clients msg json_msg None count 0 for c in clients sess c session if not sess is_closed if sess send_expects_json if json_msg is None json_msg proto json_encode msg sess send_jsonified json_msg stats False else sess send_message msg stats False count 1 self stats packSent count
returns the key if it thinks it found one ...,def find_key self userdata self log info Trying to find key with r userdata parsed parse_barcode userdata cleaned strip_fingerprint parsed fingerprint downloaded_key None for name address port fpr in self discovered_services if cleaned fpr try downloaded_key download_key_http address port if fingerprint_from_keydata downloaded_key cleaned continue except ConnectionError self log exception Error downloading from r r address port return downloaded_key
"given a type and any value , return a runtime value coerced to match the type .",def coerce_value type value if isinstance type GraphQLNonNull return coerce_value type of_type value if value is None return None if isinstance type GraphQLList item_type type of_type if not isinstance value string_types and isinstance value collections Iterable return coerce_value item_type item for item in value else return coerce_value item_type value if isinstance type GraphQLInputObjectType fields type fields obj for field_name field in fields items if field_name not in value if field default_value is not None field_value field default_value obj field out_name or field_name field_value else field_value coerce_value field type value get field_name obj field out_name or field_name field_value return type create_container obj assert isinstance type GraphQLScalarType GraphQLEnumType Must be input type return type parse_value value
converts a categorical feature into a list of intervals .,def cat2intervals self X index None if self dimensions_ 1 return self _assign_intervals X index elif self dimensions_ 2 and index is None raise ValueError Index of X to be discretized needs to be specified else cp_indices X T index return self _assign_intervals cp_indices index
"use python to download the file , without connection authentication .",def download_file_insecure url target src urlopen url try data src read finally src close with open target wb as dst dst write data
clear the tracklist . triggers the : meth:`mopidy.core . corelistener.tracklist_changed ` event .,def clear self options return self mopidy_request core tracklist clear options
"discovers if a gene can be taken from this category args : category(int ) : the category being checked on amount(int ) : the amount required for a category returns : bool : true if a gene can be taken , false otherwise",def can_move self category amount if self amount_of_genes category amount return True return False
integrate a non - isothermal composite kinetic model .,def ni_integrate func T0 args None dT 1 T1 None verbose False n math ceil len args 2 2 1 r ode func set_integrator zvode method bdf with_jacobian False r set_initial_value np zeros n T0 set_f_params args temps alphas while r successful r integrate r t dT if verbose print r t r y if not T1 if r y n 1 1 temps append r t alphas append r y n 1 else break elif r t T1 temps append r t alphas append r y n 1 else break return temps alphas
returns dictionary of parameter name to gradient numpy array .,def load_gradient_message message compressed False header_size_message message 0 4 header_size struct unpack i header_size_message 0 header_message message 4 4 header_size header cPickle loads header_message if compressed data zlib decompress message 4 header_size else data message 4 header_size idx 0 grads for param in header shapes header param lengths np prod shape barista DTYPE_SIZE for shape in shapes grads param for shape length in zip shapes lengths grads param append np frombuffer data idx idx length dtype barista DTYPE reshape shape idx length return grads
method ` create_player ` will create a player - like object which receives its input over the network .,def create_player self name bout mine_count None height None width None conn address self srvsock accept player PlayerServer conn address name bout mine_count height width return player
deactivate user accounts based on active directory 's useraccountcontrol flags . requires ' useraccountcontrol ' to be included in ldap_sync_user_extra_attributes .,def user_active_directory_deactivate user attributes created updated try user_account_control int attributes userAccountControl 0 if user_account_control 2 user is_active False except KeyError pass
champion < str > champion name enemy < str > champion name return http://api.champion.gg/docs/#api-champion-getchampionspecificmatchup,def get_specific_matchup champion enemy request champion name matchup enemy format name champion enemy enemy return datum role Matchup datum for datum in champyongg requests get request
fail if the two json strings are unequal .,def assertJsonEqual self first second msg None self assertEqual loads first loads second msg msg
returns the directory component of a pathname,def dirname p i p rfind 1 head p i if head and head len head head head rstrip return head
sets whether or not ssl communication is in use .,ssl setter def ssl self value self _use_ssl value
"return whether a key , value pair exists",def key_value_exists self key value return self resource exists_env_value key value
sets up vlan trunk and updates the trunk status .,def _setup_trunk self trunk vlan_id None LOG info Binding trunk port s trunk try self _trunk_rpc update_subport_bindings self _context trunk sub_ports vlan_trunk s segmentation_id for s in trunk sub_ports self _set_port_vlan trunk port_id vlan_id vlan_trunk self _trunk_rpc update_trunk_status self _context trunk id t_const ACTIVE_STATUS except Exception LOG exception Failure setting up subports for s trunk port_id self _trunk_rpc update_trunk_status self _context trunk id t_const DEGRADED_STATUS
handle an error due to a non - success status code or other reason .,def handle_error self failure if hasattr self scanner scan_object filescan if isinstance failure value IOError and failure value errno errno EISDIR logging debug File that is failing 0 format failure value filename return self append_file_request file failure value filename elif isinstance failure value IgnoreRequest return elif hasattr self scanner scan_object webscan if not self scanner scan_object webscan do_link_check or isinstance failure value IgnoreRequest and not isinstance failure value HttpError return if hasattr failure value response response failure value response url response request url status_code response status status_message response_status_message status_code if redirect_urls in response request meta url response request meta redirect_urls 0 referer_header response request headers get referer None else url failure request url status_code 1 status_message s failure value referer_header None logging info Handle Error s s status_message url status_message regex sub status_message status_message capitalize_first status_message broken_url Url url url scan self scanner scan_object status_code status_code status_message status_message broken_url save self broken_url_objects url broken_url if referer_header is not None self associate_url_referrer referer_header broken_url self associate_url_referrers broken_url
an identity function used as a default task to test the timing of .,timer timed def identity args kwargs return args kwargs
return the precalculated depth of a block within the block_structure :,classmethod def get_block_depth cls block_structure block_key return block_structure get_transformer_block_field block_key cls cls BLOCK_DEPTH
assert no events were emitted .,def assert_no_events_were_emitted self mock_tracker self assertFalse mock_tracker called
boolean for if the page has an error or not .,property def has_error self return self q css error present
register a mock response for the third party user information endpoint ; success indicates whether the response status code should be 200 or 400,def _setup_provider_response self success False email if success status 200 response self UID_FIELD self social_uid if email response update email email body json dumps response else status 400 body json dumps self _setup_provider_response_with_body status body
returns true / false whether a microsite has a definition for the specified named value,def has_override_value val_name return BACKEND has_override_value val_name
"test the "" test_js_run "" task .",ddt data port 9999 suite lms suite lms port 9999 ddt unpack def test_test_js_dev self options_string options self parse_options_string options_string self reset_task_messages call_task pavelib js_test test_js_dev options options self verify_messages options options dev_mode True
"transforms the given block_structure for the given usage_info , assuming the block_structure contains cached data from a prior call to the collect method of the latest version of the transformer .",abstractmethod def transform self usage_info block_structure raise NotImplementedError
returns the value associated with the given key in the cache ; returns default if not found .,def get self key default None return self map get key default
generate a dict mapping each response / comment in the thread by its ` i d ` .,def _get_comment_map self def _visit obj res for child in obj get children res append child id child if children in child res _visit child return res return dict _visit self thread
makes the test user staff and logs them in,def _setstaff_login self self user is_staff True self user save self client login username self user username password foo
updates dag collected data for the given block .,def on_dag_found self block_key self num_of_dag_blocks 1 self dag_data_by_block_type block_key category num_of_dag_blocks 1
"returns all answers a user ( or all users , when user = none ) has given to an instance of a surveyform",classmethod def get_answers cls form user None limit_num_users 10000 if user answers SurveyAnswer objects filter form form user user else answers SurveyAnswer objects filter form form results OrderedDict num_users 0 for answer in answers user_id answer user id if user_id not in results and num_users limit_num_users results user_id OrderedDict num_users num_users 1 if user_id in results results user_id answer field_name answer field_value return results
low - level problem type introspection for content libraries filtering by problem type,property def problem_types self try tree etree XML self data except etree XMLSyntaxError log error Error parsing problem types from xml for capa module format self display_name return None registered_tags responsetypes registry registered_tags return node tag for node in tree iter if node tag in registered_tags
ensures that known errors are not logged before a retry .,patch lms djangoapps grades tasks log patch lms djangoapps grades tasks recalculate_subsection_grade_v2 retry patch lms djangoapps grades new subsection_grade SubsectionGradeFactory update def test_no_log_known_error self mock_update mock_retry mock_log self set_up_course mock_update side_effect IntegrityError race condition oh noes self _apply_recalculate_subsection_grade self assertFalse mock_log info called self _assert_retry_called mock_retry
should use the correct view .,def test_reading_year_archive_view self ReadingFactory end_date 2017 02 15 self assertEqual resolve reading 2017 func __name__ views ReadingYearArchiveView __name__
write a row into standard profiler format csv with user values followed by mean times for each profiler tag extracted from profiling_data,def write_csv_row profiling_data duration_s dt_s csv_writer extra_column_values from scipy stats import binned_statistic timestep_bins np arange 0 0 duration_s 1000 0 dt_s 1000 0 mean_times np average binned_statistic t 0 t 1 statistic sum bins timestep_bins 0 for t in itervalues profiling_data csv_writer writerow extra_column_values mean_times
check if the command line options are valid,def check_options options result_flag True if options test_cases_conf is not None result_flag check_file_exists os path abspath os path join os path dirname __file__ conf options test_cases_conf return result_flag
"get the named lock . if the semaphore representing the lock does not exit , create it in a thread safe way . note that this is always a blocking call that will wait until the lock is available .",def get_named_lock self name self _named_locks_lock acquire if not name in self _named_locks self _named_locks name BoundedSemaphore self _named_locks_lock release self log debug Grabbing named lock s name self _named_locks name acquire self log debug Got named lock s name
convert yum logging levels using a lookup table .,def __convertLevel level table try new_level table level except KeyError keys sorted table keys if level keys 0 new_level table keys 0 else new_level table keys 2 return new_level
return a fault object created from a python exception .,def FaultFromException ex inheader tb None actor None tracetext None if tb try lines n join s d s name line func for name line func text in traceback extract_tb tb except pass else tracetext lines exceptionName try exceptionName join ex __module__ ex __class__ __name__ except pass elt ZSIFaultDetail string exceptionName n str ex trace tracetext if inheader detail headerdetail None elt else detail headerdetail elt None return Fault Fault Server Processing Failure actor detail headerdetail
create an in - memory cache for records .,def cache source return Cache source
"initializes the ycmd server as a webtest application that will be shared by all tests using the sharedycmd decorator in this package . additional configuration that is common to these tests , like starting a semantic subserver , should be done here .",def setUpPackage u Initializes the ycmd server as a WebTest application that will be shared n by all tests using the SharedYcmd decorator in this package Additional n configuration that is common to these tests like starting a semantic n subserver should be done here global shared_app shared_app SetUpApp WaitUntilCompleterServerReady shared_app u typescript
adds the modules of the imports,def usages_add_import_modules evaluator definitions new set for d in definitions imp_or_stmt d get_definition if isinstance imp_or_stmt tree Import s imports ImportWrapper evaluator d new set s follow is_goto True return set definitions new
remove all subdirectories in this path .,def rm_subdirs path onerror None names try names os listdir path except os error as err if onerror is not None onerror os listdir path sys exc_info else raise for name in names fullname os path join path name if os path isdir fullname if onerror is not None shutil rmtree fullname False onerror else err_count 0 while True try shutil rmtree fullname False None break except os error as err if err_count 0 raise err_count 1 time sleep RM_SUBDIRS_RETRY_TIME
start the stratisd daemon with the simulator .,def setUp self self _service Service self _service setUp
generate a few samples using the fast method and perform sanity checks on the output .,def testGenerateFast self waveform tf placeholder tf int32 np random seed 0 data np random randint 128 proba self net predict_proba_incremental waveform with self test_session as sess sess run tf global_variables_initializer sess run self net init_ops proba sess run proba feed_dict waveform data self assertAllEqual proba shape 128 self assertTrue np all proba 0 proba 128 1
retrieve a task from the background work queue .,def get_task self task_id request_path api_path tasks task_id format api_path self api_path task_id task_id return self connection get_request request_path
the entry point to wllvm .,def main return wcompile wfortran
serializes a user defined function .,def func_dump func code marshal dumps func __code__ decode raw_unicode_escape defaults func __defaults__ if func __closure__ closure tuple c cell_contents for c in func __closure__ else closure None return code defaults closure
"workaround for gridfs index problem ,",classmethod def purge_index cls resource_name with cls app app_context connection cls app data mongo pymongo resource resource_name cx connection _purge_index cls app config MONGO_DBNAME
@type node : etree . element @type tag : str @type ns : str,def get_child node tag ns http schemas microsoft com win 2004 08 events event return node find s s ns tag
handle the exception raised by given listener . send the traceback to all subscribers of topic self.topicuncaughtexc .,def __call__ self listenerID topicObj tbInfo TracebackInfo self __topicObj publish listenerStr listenerID excTraceback tbInfo
"wrapper to load json data , to be compatible with python3 . returns : json data",def load_data data if type data bytes return json loads data decode utf 8 else return json loads data
generate a date - range between the date of the first and last message and returns those dates for which there is no corresponding message in messages,def _getDaysWithoutMessages self daysWithMsgs self df date drop_duplicates datelist pd Series pd date_range self df iloc 0 date self df iloc 1 date datelist datelist apply lambda x x date strftime Message DATE_FORMAT daysWithoutMsgs np setdiff1d datelist daysWithMsgs return daysWithoutMsgs
"determine the position , in the illumina final report , of each interesting field needed for the creation of the sif file(s ) . field 's name must be in the field_name list",def parse_field infh separator field_name line infh readline fld line strip split separator column_id for fn in field_name try column_id fn fld index fn except column_id fn 1 return column_id
insert mongo indexes if need - be ( i.e. for newly created database ),def init_base_indexes config mongo_db processed_blocks ensure_index block_index unique True config mongo_db mempool ensure_index tx_hash
returns whether the path is a directory or not .,def is_directory dirname try status pywrap_tensorflow TF_NewStatus return pywrap_tensorflow IsDirectory compat as_bytes dirname status finally pywrap_tensorflow TF_DeleteStatus status
"if allow_duplicates is true issues identical to an already tracked issue will be added , default is to discard duplicates .",def __init__ self allow_duplicates False super IssueTracker self __init__ self allow_duplicates allow_duplicates self _issues self _err_count 0 self _warn_count 0 self _default_format type c reason
"sw_bs_time = 45 # [ ms ] time lapse for the spiritual weapon being away sw_bs_time_2 = 60 # a longer interval for the second ( "" failsafe "" ) call sw_bs_time_3 = 250",def Spiritual_Weapon_Begone attachee return
docstring comes after type comment .,def method self lst opt 0 args kwargs pass
return true if path refers to an existing path . returns false for broken symbolic links .,def exists path return False
"print a summary of the stack to stdout , or some place else .",def dump_stack_frames limit None out None out out or sys stdout out write short_stack limit limit out write n
return mime message suitable for a patch . charset will be detected as utf-8 or ( possibly fake ) us - ascii . transfer encodings will be used if necessary .,def mimetextpatch s subtype plain display False cs us ascii if not display try s decode us ascii except UnicodeDecodeError try s decode utf 8 cs utf 8 except UnicodeDecodeError pass return mimetextqp s subtype cs
"returns a sorted list of relatives paths currently watched , for debugging purposes .",def debug self return sorted tuple 0 self prefixlen for tuple in self watcher
find and return a single segment from the request session .,def get_segment_by_id self segment_id u Find and return a single segment from the request session n n param segment_id The primary key of the segment n type segment_id int n returns The matching segment n rtype wagtail_personalisation models Segment or None n n segments self _segments ids segment_id if segments exists return segments get
"reads a snpkernel with two cases if returning kerneldata , just calls snpreader._read_kernel , package , kernel_standardize if returning simple snpkernel that needs no more standardization read the reference and learn both standardization ( but ca n't this cause multiple reads ? ) note that snp_standardizer should be none or the standardizer instead the snpkernel should have the placeholder value standardizer ( )",def _read_with_standardizing self to_kerneldata kernel_standardizer DiagKtoN return_trained False if to_kerneldata val snp_trained self snpreader _read_kernel self standardizer block_size self block_size return_trained True kernel KernelData iid self snpreader iid val val name str self kernel kernel_trained kernel standardize kernel_standardizer return_trained True else snpdata snp_trained self snpreader read standardize self standardizer return_trained True snpdata kernel_trained snpdata standardize kernel_standardizer return_trained True kernel SnpKernel snpdata SS_Identity if return_trained return kernel snp_trained kernel_trained else return kernel
apply operators to states in a quantum expression .,def qapply e options from sympy physics quantum density import Density dagger options get dagger False if e 0 return S Zero e e expand commutator True tensorproduct True if isinstance e KetBase return e elif isinstance e Add result 0 for arg in e args result qapply arg options return result elif isinstance e Density new_args qapply state options prob for state prob in e args return Density new_args elif isinstance e TensorProduct return TensorProduct qapply t options for t in e args elif isinstance e Pow return qapply e base options e exp elif isinstance e Mul result qapply_Mul e options if result e and dagger return Dagger qapply_Mul Dagger e options else return result else return e
turn a rule into a branching rule,def yieldify rl def brl expr yield rl expr return brl
numpy version of tensor product of multiple arguments .,def _numpy_tensor_product product if not np raise ImportError answer product 0 for item in product 1 answer np kron answer item return answer
": return : the text contents of the given fileids , as a single string .",def raw self fileids None if fileids is None fileids self _fileids elif isinstance fileids compat string_types fileids fileids return concat self open f read for f in fileids
return all words and punctuation symbols in the corpus or in the specified files .,def words self fileids None return concat self CorpusView path self _read_word_block encoding enc for path enc fileid in self abspaths fileids True True
create the directories needed for getting the core dumps,pytest fixture def create_coredump_dir scope module if not os path exists coredump_path os makedirs coredump_path yield shutil rmtree coredump_path assert not os path exists coredump_path
directly submit a task to be run on the main gui thread . can be called from any thread ( hence the point ... ),def submit_gui_task self task self _task_manager submit task
get the setting of ' session - timeout ' from the parsed ` elements ` in : attr:`data ` and return .,def parse_dom self key_field self get_elements session timeout field_text key_field 0 text if key_field else None parsed_data if field_text and field_text isdigit parsed_data session timeout int field_text return parsed_data
"ensure that when requirements specify a target position , it is taken into account in assignment",def test_pos_cost self bot1 robocup OurRobot 1 self system_state bot1 set_pos_for_testing robocup Point 1 6 bot2 robocup OurRobot 2 self system_state bot2 set_pos_for_testing robocup Point 2 3 req1 role_assignment RoleRequirements req1 destination_shape robocup Point 1 7 req2 role_assignment RoleRequirements req2 destination_shape robocup Point 3 4 req_tree role1 req1 role2 req2 assignments role_assignment assign_roles bot1 bot2 req_tree self assertEqual len assignments 2 self assertEqual assignments role1 1 bot1 self assertEqual assignments role2 1 bot2
fix np.logaddexp in numpy < 1.4 when x1 = = x2 = = -np.inf .,def _logaddexp x1 x2 out None if out is not None result np logaddexp x1 x2 out out else result np logaddexp x1 x2 result np logical_and x1 np inf x2 np inf np inf return result
"this method will get the packet , takes what does need to be taken and let the remaining go , so it returns two values . first value which belongs to this field and the second is the remaining which does need to be dissected with other "" field classes "" . @param pkt : holds the whole packet @param s : holds only the remaining data which is not dissected yet .",def getfield self pkt s cstream 1 if pkt underlayer name TCP cstream dissector check_stream pkt underlayer underlayer fields src pkt underlayer underlayer fields dst pkt underlayer fields sport pkt underlayer fields dport pkt underlayer fields seq s if not cstream 1 s cstream remain value ls s splitlines length len ls if length 1 value ls 0 arguments first True res value split for arg in res if not first arguments arguments arg first False if in res 0 value res 0 3 self get_code_msg res 0 3 res 0 3 else value res 0 self get_code_msg res 0 return arguments 1 value if length 1 reponses for element in ls element element split arguments first True for arg in element if not first arguments arguments arg first False if in element 0 reponses append element 0 3 self get_code_msg element 0 3 element 0 3 arguments 1 else reponses append element 0 self get_code_msg element 0 1 arguments return reponses return
raise alreadyrunningerror if student response csv is still being generated,transaction non_atomic_requests require_POST ensure_csrf_cookie cache_control no_cache True no_store True must_revalidate True require_level staff def get_student_responses_view request course_id course_key SlashSeparatedCourseKey from_deprecated_string course_id try api request_report request course_key student_responses except AlreadyRunningError status _ A student responses report generation task is already in progress Check the Pending Instructor Tasks table for the status of the task When completed the report will be available for download in the table below else status _ The student responses report is being generated response JsonResponse status status return response
called when the recordframes menu entry is selected,def recordFramesCallback self fileName tkFileDialog asksaveasfilename title Create TM Frame Record File initialdir SCOS ENV s_environment tmFilesDir if fileName and fileName self notifyModelTask RECORDFRAMES fileName
parse xml files to retrieve full publication text : param fpath : path to file : return :,def parseXML fpath papers_with_highlights S2352220815001534 xml parser xml sax make_parser parser setFeature xml sax handler feature_namespaces 0 Handler PubHandler parser setContentHandler Handler parser parse fpath print Title Handler title for h in Handler highlights print Highlight h print Abstract Handler abstract for n t in Handler text items print Text t
"return the invocation i d associated with an event : param event : swf event object : return : the invocation i d , or none if not found",def event_invocation_id self event attributes self root_event_attributes event candidate_keys id activityId timerId workflowId markerName signalName for key in candidate_keys if key in attributes return attributes key return None
"read at most n objects , less if read hits eof if size is negative or omitted read all objects until eof returns none if eof is reached before any objects .",def read self n 1 self _complain_ifclosed self closed if n 0 result while 1 try result append self __read except StopIteration break return result elif n 0 return None else result for i in range 0 n try result append self __read except StopIteration break return result
downloads the update url and returns a json object,def download_releases_info self base_url f self fetch_content base_url None try json_data json loads f except ValueError KeyError TypeError as e self output JSON response was s f raise ProcessorError JSON format error s e return json_data
check if host supports the sniffer .,classmethod def is_supported cls session None if session return cls _is_supported_remote session try utils_path find_command cls command return True except utils_path CmdNotFoundError return False
cost function used by the differential evolution optimizer,def _cost_func x kernel_options tuning_options runner results params minimize snap_to_nearest_config x tuning_options tune_params if tuning_options restrictions legal util check_restrictions tuning_options restrictions params tuning_options tune_params keys tuning_options verbose if not legal return 1e 20 res _ runner run params kernel_options tuning_options if len res 0 results append res 0 return res 0 time return 1e 20
"should return the gradient , support automatic differentiation",def grad self x eps_base np random random 1e 08 grad_eps for i in range len x eps np zeros len x eps i eps_base x1 x 2 eps self refresh_cache x1 dtype loss loss1 self loss x1 x2 x eps self refresh_cache x2 dtype loss loss2 self loss x2 x3 x eps self refresh_cache x3 dtype loss loss3 self loss x3 x4 x 2 eps self refresh_cache x4 dtype loss loss4 self loss x4 grad_eps append 1 12 eps_base loss1 8 loss2 8 loss3 loss4 return np array grad_eps
fetches the specified url and streams it out to the client .,app route p path url def proxy url ip_pat re compile d 1 3 d 1 3 d 1 3 d 1 3 re UNICODE ip_mat ip_pat search url if not ip_mat proxy_ref proxy_ref_info request if proxy_ref redirect_url p s s s proxy_ref 0 url request query_string if request query_string else LOG info Redirecting referred URL to s redirect_url return redirect redirect_url else ip ip_mat group 1 if not ip startswith ALLOWED_IP_PREFIX abort 403 r get_source_rsp url LOG info Got s response from s r status_code url headers dict r headers def generate for chunk in r iter_content CHUNK_SIZE yield chunk return Response generate headers headers
parses strings of strike and dip and returns strike and dip measurements following the right - hand - rule .,def parse_strike_dip strike dip strike parse_azimuth strike dip direction split_trailing_letters dip if direction is not None expected_direc strike 90 if opposite_end expected_direc direction strike 180 if strike 360 strike 360 return strike dip
import all of the detector classes into the local namespace to make it easy to do things like ` import scrubadub.detectors.namedetector ` without having to add each new `` detector `` or `` filth ``,def update_locals locals_instance instance_iterator args kwargs for instance in instance_iterator locals_instance update type instance __name__ instance __class__
load configuration from config file .,def configuration filename config yaml logger logging getLogger __name__ config with open os path abspath os path join os path dirname __file__ filename r as f config yaml load f logger info Loaded raw config 0 format config new_config logger info Inspecting configuration to see if any ParameterStore lookups are required for k v in config items key k if isinstance v str value os path expandvars v if k startswith parameterstore_ key k split parameterstore_ 1 value client get_parameter Name value WithDecryption True Parameter Value else value v new_config key value return new_config
"add aggregations representing the facets selected , including potential filters .",def aggregate self search for f facet in iteritems self facets agg facet get_aggregation agg_filter Q match_all for field filter in iteritems self _filters if f field continue agg_filter filter search aggs bucket _filter_ f filter filter agg_filter bucket f agg
how often does each member vote with their party ?,def party self chamber congress CURRENT_CONGRESS return self by_type chamber party congress
docker - compose logs of a specific container,app route API_V1 logs name container_id defaults limit all methods GET app route API_V1 logs name container_id int limit methods GET def container_logs name container_id limit project get_project_with_name name container get_container_from_id project client container_id lines container logs timestamps True tail limit split n return jsonify logs lines
create latex genealogy tree sandclock report .,def __init__ self database options user Report __init__ self database options user menu options menu get_option_by_name menu get_option_by_name get_value lambda name get_option_by_name name get_value self _db self database self _pid get_value pid self max_up menu get_option_by_name genup get_value self max_down menu get_option_by_name gendown get_value self include_images menu get_option_by_name images get_value
force a connection attempt via http get .,app route devices connect device_id methods GET def device_connect device_id success False if device_id in devices devices device_id connect success True return jsonify success success
"set the mpich_{cc , cxx , f77 , f90 , fc } variables .",def _set_mpi_compiler_variables self self MPI_COMPILER_MPIF77 mpif77 self MPI_COMPILER_MPIF90 mpif90 self MPI_COMPILER_MPIFC mpif90 super Psmpi self _set_mpi_compiler_variables
returns the categories in the correct order,def sorted_categories categories ALL_CATEGORIES values categories sort key lambda c c 0 return categories
waits until `` pattern `` disappears on ` application ` in focus at specified `` timeout `` .,def wait_until_pattern_vanish self pattern timeout self _info Setting wait value to s timeout self set_search_region_to_active_app timeout self _clean_string timeout pattern self _pattern_finder _find_pattern pattern hidden None if timeout FOREVER hidden waitVanish pattern FOREVER else timeout float timeout hidden waitVanish pattern timeout self _debug hidden if not hidden raise AssertionError Element s was still visible in s pattern timeout
generate a set of non - overlapping rects that represents the distribution of the specified gid .,def buildDistributionRects tmxmap layer tileset None real_gid None if isinstance tileset int try tileset tmxmap tilesets tileset except IndexError msg Tileset 0 not found in map 1 raise IndexError msg format tileset tmxmap elif isinstance tileset str try tileset t for t in tmxmap tilesets if t name tileset pop except IndexError msg Tileset 0 not found in map 1 raise ValueError msg format tileset tmxmap elif tileset msg Tileset must be either a int or string got 0 raise ValueError msg format type tileset gid None if real_gid try gid flags tmxmap map_gid real_gid 0 except IndexError msg GID 0 not found raise ValueError msg format real_gid if isinstance layer int layer_data tmxmap getLayerData layer data elif isinstance layer str try layer l for l in tmxmap tilelayers if l name layer pop layer_data layer data except IndexError msg Layer 0 not found in map 1 raise ValueError msg format layer tmxmap p product xrange tmxmap width xrange tmxmap height if gid points x y for x y in p if layer_data y x gid else points x y for x y in p if layer_data y x rects simplify points tmxmap tilewidth tmxmap tileheight return rects
"retrieves an accountlistfeed by retrieving a uri based off the document list feed , including any query parameters . an accountlistfeed object can be used to construct these parameters .",def QueryAccountListFeed self uri return self Get uri converter gdata analytics AccountListFeedFromString
saves recordings in the temporary file named in use_cached_session .,def close_session self if self real_client is not None self _save_recordings self _recordings_cache_name
returns proxy host and port .,def _get_proxy_net_location proxy_settings if in proxy_settings protocol proxy_settings split 0 netloc proxy_settings split 1 return s s protocol netloc else return proxy_settings
"return the line number in the current file . before the first line has been read , returns 0 . after the last line of the last file has been read , returns the line number of that line within the file .",def filelineno if not _state raise RuntimeError no active input return _state filelineno
verifies the presence of all necessary arguments and returns the data dir,def handle_arguments if len sys argv 1 stderr no arguments provided show_help try keys values getopt getopt sys argv 1 hf g except getopt GetoptError stderr invalid arguments provided show_help args for key value in keys if key f args file value if key g args group value if not args has_key file stderr import file argument missing show_help elif not file_exists args get file stderr import file does not exist show_help if not args has_key group stderr group file argument missing show_help elif not file_exists args get group stderr group file does not exist show_help return args
perform real work of ` expand ( ) ` function .,def _expand self name cfg self _d name if cfg collection is None base_coll else base_coll cfg collection self SEP qe self _get_qe name cfg coll db qe collection qe db cur_coll coll name for coll_name in db collection_names if coll_name cur_coll or not coll_name startswith base_coll continue ex_cfg cfg copy ex_cfg collection coll_name group_name name self SEP coll_name len base_coll self add group_name ex_cfg expand False
returns a shape function for ops that constrain the rank of their input .,def unchanged_shape_with_rank rank def _ShapeFunction op return op inputs 0 get_shape with_rank rank return _ShapeFunction
creates a ` failedpreconditionerror ` .,def __init__ self node_def op message super FailedPreconditionError self __init__ node_def op message FAILED_PRECONDITION
"calculate the page rank for each element based on the matrix in input we should validate if the matrix is stochastic if not we use the taxation method to ovoid dead ends ( introducing the random surfers ) v ' = mv + ( 1-b)e / n v : eigenvector the term ( 1-b)e / n is a vector each of whose components has value ( 1-b)/n and represents the introduction , with probability 1 - b , of a new random surfer at a random page . the mathematical formulation for the iteration that yields topic - sensitive pagerank is similar to the equation we used for general pagerank . the only difference is how we add the new surfers . suppose s is a set of integers consisting of the row / column numbers for the pages we have identified as belonging to a certain topic ( called the teleport set ) . let es be a vector that has 1 in the components in s and 0 in other components . then the topic - sensitive page- rank for s is the limit of the iteration v ' = bmv + ( 1 - b)es/|s| here , as usual , m is the transition matrix of the web , and |s| is the size of set s.",def page_rank matrix taxation False b 1 Es S set nbr_iterations 10000000 verbose False elements_length len matrix eigenvectors 1 elements_length mat ones elements_length 1 if S and taxation taxation_v 1 b len S Es else taxation_v 1 b elements_length mat ones elements_length 1 if taxation else mat ones elements_length 1 0 eigenvectors_p mat ones elements_length 1 0 itr 0 while eigenvectors_p eigenvectors any and itr nbr_iterations if eigenvectors_p mat ones elements_length 1 0 any eigenvectors eigenvectors_p eigenvectors_p matrix_vector_multiplication matrix eigenvectors elements_length b taxation_v itr 1 if verbose print eigenvectors return eigenvectors
import csv data as it is faster than xml and because we ca n't use noupdate anymore with csv,def post_init cr registry from openerp tools import convert_file filename data res bank csv convert_file cr l10n_ch_bank filename None mode init noupdate True kind init report None
test collecting object_list when there is offset set,def test_get_object_list_with_offset self resource mongoengine CollectionResource objects_class None max_limit 2 object_list resource get_object_list queryset 1 2 3 4 limit None offset 1 self assertEqual 2 3 object_list
"save song in * n * files , where * n * is number of measures in song .",def bisect test song dest_version 3 folder _ path splitext test try os mkdir path join OUTPUT folder except OSError pass trackMeasures track measures for track in song tracks for number _ in enumerate trackMeasures 0 1 dest_path path join OUTPUT folder test 03d gp d number dest_version for track in song tracks track measures trackMeasures track number 1 number guitarpro write song dest_path
default actnode change handler for client . override or monkey - patch this function to implement actual actnode change handling .,def actnode_changed self newact print Client active node changed
"force the given input to only use ` str ` instead of ` bytes ` or ` unicode ` . this works even if the input is a dict , list ,",staticmethod def _byteify input if isinstance input dict return _Auxiliary _byteify key _Auxiliary _byteify value for key value in input items elif isinstance input list return _Auxiliary _byteify element for element in input elif _Constants _PYTHON_3 and isinstance input str return str input encode ascii replace decode ascii elif not _Constants _PYTHON_3 and isinstance input unicode return str input encode ascii replace decode ascii else return input
puts all the widgets in the correct place : return : none,def _grid_widgets self self _family_dropdown grid row 0 column 0 sticky nswe self _size_dropdown grid row 0 column 1 sticky nswe self _properties_frame grid row 0 column 2 sticky nswe
converts a datetime to the given timezone .,def force_tz obj tz if not isinstance tz tzinfo tz pytz timezone tz if obj tzinfo is None or obj tzinfo utcoffset obj is None return tz localize obj else return obj astimezone tz
rewrite config file with default settings,staticmethod def reset_config from common settings import create_default_config create_default_config
"pure implementation of interpolation search algorithm in python by recursion be careful collection must be sorted , otherwise result will be unpredictable first recursion should be started with left=0 and right=(len(sorted_collection)-1 ) : param sorted_collection : some sorted collection with comparable items : param item : item value to search : return : index of found item or none if item is not found",def interpolation_search_by_recursion sorted_collection item left right point left item sorted_collection left right left sorted_collection right sorted_collection left if point 0 or point len sorted_collection return None if sorted_collection point item return point elif sorted_collection point item return interpolation_search_by_recursion sorted_collection item left point 1 else return interpolation_search_by_recursion sorted_collection item point 1 right
gets the images using salt - cloud .,tornado gen coroutine def get_images self images x properties description for x in self cl images all raise tornado gen Return images
creates institutions and their related places from a pandas . dataframe,def create_institutions df institutions for i row in df iterrows inst None if row Institution Name inst _ Institution objects get_or_create name row Institution Name if inst if row Institution GND inst gnd_id row Institution GND if row located at place _ Place objects get_or_create name row located at place_type city if row part of part_of _ Place objects get_or_create name row part of place_type country place part_of part_of if row location geonames ID try geonames http www geonames org format int row location geonames ID except ValueError geonames None if geonames place geonames_id geonames if row location Lat and row location Lng place lat row location Lat place lng row location Lng place save inst place place if row Institution Lat and row Institution Lng inst lat row Institution Lat inst lng row Institution Lng if row institution website inst website row institution website inst save institutions append inst return institutions
guess value of example e under hypothesis h.,def guess_value e h for d in h if disjunction_value e d return True return False
"return : term:`read alignments ` covering a |genomicsegment| , and a count vector mapping reads to each positions in the |genomicsegment| , following the rule specified by : meth:`~bamgenomearray.set_mapping ` . reads are strand - matched to ` roi ` by default . to obtain unstranded reads , set the value of ` roi.strand ` to ` ' . ' `",def get_reads_and_counts self roi roi_order True reads count_dict self get_reads_and_hashed_counts roi roi_order return reads sum count_dict values numpy zeros len roi
: param root : treenode : return : integer,def maxPathSum self root self get_max_component root return self global_max
algorithm : data structure : queue and hashmap,def set self key value if key in self dic self q remove key self q insert 0 key elif len self q 1 self capacity self q insert 0 key else self dic pop self q pop self q insert 0 key self dic key value
"ips are listed backwards , e.g. ip 1.2.3.4 - > 4.3.2.1.pbl.spamhaus.org",def inverse_addr self if self addr is None return None addr_split self addr split addr_split reverse return join addr_split
inserts a widget into the arches db,def register self source import json details with open source as f details json load f try uuid UUID details widgetid except details widgetid unicode uuid uuid4 print Registering widget with widgetid details widgetid instance models Widget widgetid details widgetid name details name datatype details datatype helptext details helptext defaultconfig details defaultconfig component details component instance save
parse ` self.input ` into a document tree .,def parse self self document document self new_document module_section moduleparser parse_module self input self source source_path module_section walk DocformatVisitor self document visitor DocstringFormattingVisitor document document default_parser self default_parser module_section walk visitor self document append module_section
runs cactus realign using the default parameters and checks that the realigned output cigars align the same subsequences .,def testCPecanRealignRescoreByIdentityAndProb self for seqFile1 seqFile2 in seqFilePairGenerator realignCommandByIdentity lastzCommand getCommands seqFile1 seqFile2 realignArguments rescoreByIdentity realignCommandByPosteriorProb getCommands seqFile1 seqFile2 realignArguments rescoreByPosteriorProb 0 realignCommandByIdentityIgnoringGaps getCommands seqFile1 seqFile2 realignArguments rescoreByIdentityIgnoringGaps 0 for realignLineByIdentity realignLineByPosteriorProb realignLineByIdentityIgnoringGaps lastzLine in zip i for i in popenCatch realignCommandByIdentity split n if i i for i in popenCatch realignCommandByPosteriorProb split n if i i for i in popenCatch realignCommandByIdentityIgnoringGaps split n if i i for i in popenCatch lastzCommand split n if i realignCigarByIdentity cigarReadFromString realignLineByIdentity realignCigarByPosteriorProb cigarReadFromString realignLineByPosteriorProb realignCigarByIdentityIgnoringGaps cigarReadFromString realignLineByIdentityIgnoringGaps lastzCigar cigarReadFromString lastzLine self assertTrue realignCigarByIdentity score 0 self assertTrue realignCigarByIdentity score 100 0 self assertTrue realignCigarByPosteriorProb score 0 self assertTrue realignCigarByPosteriorProb score 100 0 self assertTrue realignCigarByIdentityIgnoringGaps score 0 self assertTrue realignCigarByIdentityIgnoringGaps score 100 0
property that returns the unique i d of the platform .,property def id self return self get_uid
: param ref : can be a full reference or a version ( e.g. ' 2.1 ' ) : return :,def make_resources self ref if ref in TRACI_VERSIONS ver ref ref join self _prefix ver else try ver self _trim_origin ref except ValueError raise KeyError Not a valid ref s ref try info TRACI_VERSIONS ver except KeyError raise KeyError Unknown version s ver yield self _make_resource ref os path join self _root info filename ds_type info ds_type interfaces self _ifaces
"adds the resource to a file whose name is the resource 's semantic reference . if the same datasource is already present in the file , replace it with the current resource . otherwise append . : param path : directory to store the resource file . : return :",def write_to_file self path if not os path isdir path if os path exists path raise ValueError Please provide a directory path os makedirs path filename os path join path self reference if os path exists filename with open filename r as fp j json load fp resources k for k in j self reference if not self matches k resources append self serialize else resources self serialize with open os path join path self reference w as fp json dump self reference resources fp indent 2 self _issaved True
this method checks to make sure the address space is being used with a supported profile .,def is_valid_profile self profile return profile metadata get memory_model 32bit 64bit or profile metadata get os Unknown lower mac
tests setting a slice of coefficients to a single coefficient .,def testSetSliceIndexToSingleCoefficient self self lp obj 1 2 0 5 self assertEqual self lp obj 0 0 0 5 0 0 0 5 0 0
unparse a value to a string using the conversion function for this information element . uses the default string conversion for the ie 's type if not overridden at ie creation time .,def unparse self v u n Unparse a value to a string using the conversion function n for this Information Element Uses the default string conversion n for the IE s type if not overridden at IE creation time n n param v value to unparse using this IEs s string conversion n returns string representation of v n raises ValueError if v is not a valid value for this IE n if self valstr return self valstr v else return self type valstr v
changes the iso 8601 date string to a datetime object .,def dt_from_iso row column iso row column try return datetime strptime iso Y m dT H M S f except ValueError return datetime strptime iso Y m dT H M S except TypeError return NaN
primary key and index error when selecting data,def test_issue_8 self conn self connections 0 c conn cursor c execute CREATE TABLE test station int 10 NOT NULL DEFAULT 0 dh datetime NOT NULL DEFAULT 0000 00 00 00 00 00 echeance int 1 NOT NULL DEFAULT 0 me double DEFAULT NULL mo double DEFAULT NULL PRIMARY KEY station dh echeance ENGINE MyISAM DEFAULT CHARSET latin1 try self assertEqual 0 c execute SELECT FROM test c execute ALTER TABLE test ADD INDEX idx_station station self assertEqual 0 c execute SELECT FROM test finally c execute drop table test
create one shell or copy client .,def _add_client self nodes kwargs autoclose kwargs get autoclose False stderr kwargs get stderr False rank kwargs get rank timeout kwargs get timeout if self command is not None cls self __class__ SHELL_CLASS self _clients append cls nodes self command self stderr timeout autoclose rank elif self source cls self __class__ COPY_CLASS self _clients append cls nodes self source self dest self stderr timeout autoclose kwargs get preserve False kwargs get reverse False rank else raise ValueError missing command or source parameter in worker constructor
compute the matrix of predictions versus labels,def confusionMatrix labels_test labels_predicted if len labels_test len labels_predicted return 0 TP 0 FP 0 TN 0 FN 0 for i in range 0 len labels_test if labels_test i 0 or labels_predicted i 0 return 0 if labels_test i 0 if labels_predicted i 0 TP 1 else FN 1 elif labels_predicted i 0 FP 1 else TN 1 return TP TN FP FN
test a line profile using an ndim=3 image,skipif qt_api is None def test_line_profile_rgb plugin setup_line_profile data chelsea for i in range 6 plugin line_tool _thicken_scan_line line_image scan_data plugin output assert_equal line_image line_image 128 size 755 assert_equal line_image line_image 255 size 151 assert_equal line_image shape 300 451 assert_equal scan_data shape 152 3 assert_allclose scan_data max 0 772 rtol 0 001 assert_allclose scan_data mean 0 4355 rtol 0 001
disconnect callback by its i d ( returned by ` connect_event ` ) .,def disconnect_event self callback_id self canvas mpl_disconnect callback_id
return true if input is acceptable for this edge . input : unitlesson,def select_UnitLesson_filter self edge unit_lesson return unit_lesson is_question
braun - blanquet similarity compute the similarity between the dicts x and y with terms + their counts,def _braun_sim x y u n braun blanquet similarity n compute the similarity between the dicts x and y with terms their counts n return _histint_sim x y max _histint_sim x x _histint_sim y y
"generate oauth request , setups callback url",def oauth_request self token url oauth_verifier None extra_params None params if self redirect_uri params oauth_callback self redirect_uri if extra_params params update extra_params if oauth_verifier params oauth_verifier oauth_verifier request OAuthRequest from_consumer_and_token self consumer token token http_url url parameters params request sign_request SignatureMethod_HMAC_SHA1 self consumer token return request
create a new dvd device .,def __init__ self udi interface super DVDDevice self __init__ udi interface self video False self video_udi self label
args : state ( ataristate ) action ( str ),def _transition_func self state action return self next_state
"initializes sodium , picking the best implementations available for this machine .",def sodium_init if lib sodium_init 0 raise CryptoError Could not initialize sodium
initialize the activation function with the given function name .,def __init__ self name functions tanh Tanh relu ReLu sigmoid Sigmoid hardsigmoid HardSigmoid function functions get name if functions is None print Function s does not exist name else self acfun function
a view that sets a session variable,def set_session_view request request session session_var YES return HttpResponse set_session
createpriordaysmaster should produce the right days for a weekly test - 7 days later,def testWeekly2 self result snapintime createpriordaysmaster 1 21 weekly self assertEqual 1 8 9 10 11 12 13 14 result
save video file with codec mpeg4 .,def save_avi self filename vid_width 800 vid_fps 24 kwargs tempdir tempfile mkdtemp jpgs_tempdir os path join tempdir jpgs os mkdir jpgs_tempdir base_filename os path basename filename prefix ext os path splitext base_filename out_filename os path join os path dirname filename prefix avi pngs_filename os path join tempdir tempani png self save_png pngs_filename pngs_list glob glob tempdir os path sep png pngs_list sort for png_file in pngs_list f_basename os path basename png_file name ext os path splitext f_basename jpg_file os path join jpgs_tempdir name jpg print converting s to s png_file jpg_file call convert resize str vid_width quality 100 background white flatten png_file jpg_file jpgs jpgs_tempdir os path sep tempani 03d jpg call ffmpeg r str vid_fps b 1800 y i jpgs out_filename
a decorator for main functions to add themselves as subcommands .,def subcommand name callback None def decorator fn subparser subparsers add_parser name subparser set_defaults _fn fn _name name _parser subparser if callback callback subparser return fn return decorator
test that we can find the path to the projects angreal directory : return :,def test_get_angreal_task_path self original_dir os getcwd os chdir os path join os path dirname __file__ fake repo path get_angreal_path dir angreal assert os path exists path os chdir original_dir
return hash of git data that can be used to display more information to users .,def gitrepo cwd repo Repository cwd if not repo valid return return head id repo gitlog H author_name repo gitlog aN author_email repo gitlog ae committer_name repo gitlog cN committer_email repo gitlog ce message repo gitlog s branch os environ get TRAVIS_BRANCH os environ get APPVEYOR_REPO_BRANCH repo git rev parse abbrev ref HEAD 1 strip remotes name line split 0 url line split 1 for line in repo git remote v 1 if fetch in line
verify response on list view .,def test_list self response self client get self journal_bundle_url self assertEqual response status_code 200 self assertEqual len response data results 1 self assertTrue journals in response data results 0
"verify that if the serializer fails , error message is logged and update fails",def test_update_with_api_exception self url reverse api v1 person detail kwargs uuid self person uuid data self _update_person_data with mock patch object MarketingSitePeople update_person return_value with mock patch course_discovery apps api v1 views people PersonViewSet perform_update side_effect IntegrityError with LogCapture people_logger name as log_capture response self client patch url self _update_person_data format json self assertEqual response status_code 400 log_capture check people_logger name ERROR An error occurred while updating the person in discovery format data given_name data family_name
assert every component contains only data specified in cachet . component_data,def test_keep_component_fields mocker cachet_client cachet_response mock_get mocker patch cachetclient cachet Components get mock_get return_value cachet_response fetched_components cachet_client components for component in fetched_components assert component keys cachet COMPONENT_DATA
radomize a population memeber args : a member of a pop ( dict of lists ),def randomize mem assert type mem is dict for flag in mem items mem flag if len items 1 i random randrange 0 len items swap items 0 i
"scale the lattice object by the given factor . if factors is a list than it is interpreted as a list of factors , one for each corresponding dimensions . otherwise , it is interpreted as a factor by which all the dimensions should be scaled .",def scale self factors if isinstance factors collections Sequence for i f in enumerate factors mn mx nm self min_max_num_list i self min_max_num_list i mn f mx f nm else n len self min_max_num_list f factors for i in range n mn mx nm self min_max_num_list i self min_max_num_list i mn f mx f nm
"checks if a given tweet is a reply . if tweet is a string , returns true when text starts with ' @ ' . if tweet is a tweepy . status object , returns true when `` in_reply_to_status_id `` or `` in_reply_to_user_id `` is set .",def isreply tweet try return bool tweet in_reply_to_user_id except AttributeError try return bool tweet get in_reply_to_user_id or tweet get in_reply_to_status_id except AttributeError try return tweet 0 except AttributeError pass return False
check that no tags are registered in vanilla foliant .,def test_get_available_tags assert utils get_available_tags set
creates the virtual environment and installs pip only into the virtual environment,def create_virtualenv venv VENV print Creating venv run_command virtualenv q no site packages VENV print done print Installing pip in virtualenv if not run_command WITH_VENV easy_install pip strip die Failed to install pip print done print Installing distribute in virtualenv pip_install distribute 0 6 24 print done
fit a dimensionality reduction model on data .,def fit self data print Embedding print Fitting PCA if self algo pca self proj PCA n_components 2 self proj fit data else raise ValueError Unknown algo format self algo
resolve url of a maven artifact .,def resolve_url url redirects s url find if s 0 return url scheme rest url s url s 1 if scheme in redirects root redirects scheme elif scheme in REPO_ROOTS root REPO_ROOTS scheme else return url root root rstrip rest rest lstrip return join root rest
build the subgraph defined by lambda ` fn ` on ` device ` if it 's not none .,def _on_device fn device if device with ops device device return fn else return fn
transitively generate objects for the ` property ` relationship,def transitive_objects self subject property remember None if remember is None remember if subject in remember return remember subject 1 yield subject for object in self objects subject property for o in self transitive_objects object property remember yield o
returns true if input i d is control piece .,def is_control input model_file None model_proto None name None return _gen_sentencepiece_processor_op sentencepiece_get_piece_type input model_file model_file model_proto model_proto name name piece_type 1
return a cmapdata object for the ' cmapdata ' element .,def _read_tree root meta _read_meta root find meta table _read_table root find table return CmapData meta table
image needs to be rgb image that has been casted to float32,def resize_image_maintain_aspect_ratio image target_height target_width height width _ image shape if height width new_height target_height factor new_height float height new_width int np round width factor else new_width target_width factor new_width float width new_height int np round height factor resized_image imresize image new_height new_width output np zeros target_height target_width 3 dtype np float32 output new_height new_width resized_image return output
"deletes rows , chunking the deletes to avoid long table / row locks .",def handle self args options chunk_size sleep_between super Command self handle args options delete_rows VerificationDeadline objects verify_student_historicalverificationdeadline history_id chunk_size sleep_between
finds and returns the earned subsection grade for user,def get_subsection_grade self user_id course_key_or_id usage_key_or_id course_key _get_key course_key_or_id CourseKey usage_key _get_key usage_key_or_id UsageKey return PersistentSubsectionGrade objects get user_id user_id course_id course_key usage_key usage_key
"this is called by courseware.module_render , to handle an ajax call .",def handle_ajax self dispatch data handlers hint_button self hint_button problem_get self get_problem problem_check self submit_problem problem_reset self reset_problem problem_save self save_problem problem_show self get_answer score_update self update_score input_ajax self handle_input_ajax ungraded_response self handle_ungraded_response _ self runtime service self i18n ugettext generic_error_message _ We re sorry there was an error with processing your request Please try reloading your page and trying again not_found_error_message _ The state of this problem has changed since you loaded this page Please refresh your page if dispatch not in handlers return Error is not a known capa action format dispatch before self get_progress before_attempts self attempts try result handlers dispatch data except NotFoundError log info Unable to find data when dispatching s to s for user s dispatch self scope_ids usage_id self scope_ids user_id _ _ traceback_obj sys exc_info raise ProcessingError not_found_error_message None traceback_obj except Exception log exception Unknown error when dispatching s to s for user s dispatch self scope_ids usage_id self scope_ids user_id _ _ traceback_obj sys exc_info raise ProcessingError generic_error_message None traceback_obj after self get_progress after_attempts self attempts progress_changed after before or after_attempts before_attempts curr_score total_possible self get_display_progress result update progress_changed progress_changed current_score curr_score total_possible total_possible attempts_used after_attempts return json dumps result cls ComplexEncoder
"given a course with no discussion set up , add the discussions and set the cohort config on the course descriptor .",def config_course_cohorts_legacy course cohorted auto_cohort_groups None course discussion_topics config cohorted cohorted if auto_cohort_groups is not None config auto_cohort_groups auto_cohort_groups course cohort_config config try modulestore update_item course ModuleStoreEnum UserID test except NotImplementedError pass
"helper class method to look up a survey form , throw formitemnotfound if it does not exists in the database , unless throw_if_not_found = false then we return none",classmethod def get cls name throw_if_not_found True survey None exists SurveyForm objects filter name name exists if exists survey SurveyForm objects get name name elif throw_if_not_found raise SurveyFormNotFound return survey
create a custom userpartition to support dynamic groups .,classmethod def create_user_partition cls id name description groups None parameters None active True return EnrollmentTrackUserPartition id unicode name unicode description cls parameters active
returns a dictionary product after merging configuration and the default value .,def get_dict name default None default default or if is_site_configuration_enabled return get_configuration_dict name default else return microsite get_dict name default
set some useful content and urls for tests,def setUp self super TextbookDetailTestCase self setUp self textbook1 tab_title Economics id 1 chapters title Chapter 1 url a b c ch1 pdf self url1 self get_details_url 1 self textbook2 tab_title Algebra id 2 chapters title Chapter 11 url a b ch11 pdf self url2 self get_details_url 2 self course pdf_textbooks self textbook1 self textbook2 self save_course self url_nonexist self get_details_url 1 20
navigate to courseware using resume course button in the header .,def resume_course_from_outline self self q css self OUTLINE_RESUME_COURSE_SELECTOR first click courseware_page CoursewarePage self browser self parent_page course_id courseware_page wait_for_page
returns whether or not the flag is enabled .,def is_enabled self return self waffle_namespace is_flag_active self flag_name flag_undefined_default self flag_undefined_default
compute the weighted `` percentile `` of `` array `` with `` sample_weight `` .,def _weighted_percentile array sample_weight percentile 50 sorted_idx np argsort array weight_cdf stable_cumsum sample_weight sorted_idx percentile_idx np searchsorted weight_cdf percentile 100 0 weight_cdf 1 return array sorted_idx percentile_idx
radius at which `` rho_0 `` is defined ( cm ),property def r_0 self return self _r_0
"determines the largest square window size that can be used , based on the specified datatype and amount of currently available system memory .",def determineMaxWindowSize dtype limit None vmem psutil virtual_memory maxSize math floor math sqrt vmem available np dtype dtype itemsize if limit is None or limit maxSize return maxSize else return limit
"example below . you can use these keys : { "" geoplugin_request"":""xxx.xxx.xxx.xxx "" , "" geoplugin_status"":200 , "" geoplugin_city"":""castroville "" , "" geoplugin_region"":""tx "" , "" geoplugin_areacode"":210 , "" geoplugin_dmacode"":641 , "" geoplugin_countrycode"":""us "" , "" geoplugin_countryname"":""united states "" , "" geoplugin_continentcode"":""na "" , "" geoplugin_latitude"":29.360000610352 , "" geoplugin_longitude"":-98.892097473145 , "" geoplugin_regioncode"":""tx "" , "" geoplugin_regionname"":""texas "" , "" geoplugin_currencycode"":""usd "" , "" geoplugin_currencysymbol"":""&#36 ; "" , "" geoplugin_currencyconverter"":1 }",def __getitem__ self k return self d k
gets an ip address from a typical wsgi request object,def from_request self request return self __call__ self _request_to_ip request
"parses host entries of the form "" [ user@]host[:port ] "" .",def parse_host host default_user None default_port None user default_user port default_port if in host user host host split 1 if in host host port host rsplit 1 return host port user
the line widths of the plotted bars .,property def linewidths self return np array p get_linewidth for p in self _patches
": type data : dict[str , any ] : rtype : metadata",staticmethod def from_dict data metadata Metadata metadata changes data changes metadata cloud_config data cloud_config metadata instance_config data instance_config metadata ci_provider data ci_provider metadata change_description ChangeDescription from_dict data change_description return metadata
wait for instance to respond to ssh .,def wait self for dummy in range 1 90 try self ssh id return except SubprocessError time sleep 10 raise ApplicationError Timeout waiting for s s instance s self core_ci platform self core_ci version self core_ci instance_id
run module based on play book,def apply self changed False netapp_utils ems_log_event na_ontap_net_routes self server route_exists False existing_route self does_route_exists if existing_route route_exists True if self state absent changed True elif self state present if self new_destination or self new_gateway or self new_metric changed True elif self state present changed True if changed if self module check_mode pass elif not route_exists if self state present self create_net_route elif self state present self modify_net_route elif self state absent self delete_net_route self module exit_json changed changed
"called when a playbook run fails . it generates an inventory which allows re - running on only the failed hosts . this may duplicate some variable information in group_vars / host_vars but that is ok , and expected .",def _generate_retry_inventory self retry_path replay_hosts try makedirs_safe os path dirname retry_path with open retry_path w as fd for x in replay_hosts fd write s n x except Exception as e display warning Could not create retry file s n t s retry_path to_native e return False return True
performs a list of ` actions ` from ` source ` . this should seldom be called directly - use ` queue_actions ` instead .,def trigger_actions self source actions ret for action in actions if isinstance action EventListener self log Registering event listener r on r action self action once True if source type CardType SPELL listener source controller else listener source listener _events append action else ret append action trigger source return ret
returns available cloudwatch logs streams in `` log_group_name `` .,def get_streams self log_group_name None kwargs logGroupName log_group_name or self log_group_name window_start self start or 0 window_end self end or sys float_info max paginator self client get_paginator describe_log_streams for page in paginator paginate kwargs for stream in page get logStreams if firstEventTimestamp not in stream yield stream logStreamName elif max stream firstEventTimestamp window_start min stream lastEventTimestamp window_end yield stream logStreamName
iterator though resultset ( lazy ),def next self self _position 1 try item self _dataset pop 0 return self wrapper self connection item except IndexError if self _has_more self bulk return self next raise StopIteration
lists all the client nodes registered with nomad .,def get_nodes self return self _get
convert integer from genomic to cds coordinates,pos_factory Genome def g2c self gpos dialect None gpos int gpos fmts CDSPosition fmt_dict def _simple_g2c g return self exon_list index g if gpos in self exons return CDSPosition _simple_g2c gpos if gpos self exons start return CDSPosition fmts post CDS format offset gpos self exons start if gpos self exons end return CDSPosition fmts pre CDS format offset gpos self exons end 1 prev_end self exons parts 0 end for part in self exons parts 1 if gpos part start prev_end part end continue len_intron part start prev_end if gpos prev_end floor len_intron 2 0 anchor _simple_g2c part start offset gpos part start assert offset 0 else anchor _simple_g2c prev_end 1 offset gpos prev_end 1 assert offset 0 assert self check_intron anchor offset return CDSPosition fmts intron format pos anchor offset offset assert False
return a sequence of possible rhs 's that cat can be rewritten as .,def rewrites_for self cat return self rules get cat
"# general settings : param s : tf session : param batch_size : training batch size , default 128 : param height : input image height , default 32 : param width : input image width , default 32 : param channel : input image channel , default 3 ( rgb ) : param n_classes : the number of classes , default 10 - in case of cifar , image size is 32x32x3(hwc ) , classes are 10 .",def __init__ self s batch_size 128 height 32 width 32 channel 3 n_classes 10 sample_num 10 10 sample_size 10 z_dim 128 gf_dim 64 df_dim 64 d_fc_unit 512 g_fc_unit 1024 self s s self batch_size batch_size self height height self width width self channel channel self n_classes n_classes self sample_size sample_size self sample_num sample_num self image_shape self height self width self channel self z_dim z_dim self gf_dim gf_dim self df_dim df_dim self d_fc_unit d_fc_unit self g_fc_unit g_fc_unit self y tf placeholder tf float32 shape None self n_classes name y classes self x1_fine tf placeholder tf float32 shape None self height self width self channel name x images self x1_scaled image_sampling self x1_fine down self x1_coarse image_sampling self x1_scaled up self x1_diff self x1_fine self x1_coarse self x2_fine self x1_scaled self x2_scaled image_sampling self x2_fine down self x2_coarse image_sampling self x2_scaled up self x2_diff self x2_fine self x2_coarse self x3_fine self x2_scaled self z self z_noises 32 32 16 16 self z_dim for i in range 3 self z append tf placeholder tf float32 shape None self z_noises i name z noise_ 0 format i self do_rate tf placeholder tf float32 None name do rate self g self g_loss self d_reals self d_fakes self d_loss self d_op self g_op self beta1 0 5 self beta2 0 9 self lr 0 0008 self saver None self merged None self writer None self bulid_lapgan
sort the given list of items by dependency .,def sort tuples allitems for set_ in sort_as_subsets tuples allitems for s in set_ yield s
encode the supplied data ( byte array ) and write to the media transport file descriptor encapsulated as rtp packets . the encoder will calculate the required number of sbc frames and encapsulate as rtp to fit the mtu size .,def encode self fd mtu data u n Encode the supplied data byte array and write to n the media transport file descriptor encapsulated n as RTP packets The encoder will calculate the n required number of SBC frames and encapsulate as n RTP to fit the MTU size n n param int fd Media transport file descriptor n param int mtu Media transport MTU size as returned n when the media transport was acquired n param array byte data Data to encode and send n over the media transport n return n self codec rtp_sbc_encode_to_fd self config ffi new u char data len data mtu self ts self seq_num fd
what is the status of this : param this_sample_id : : param status : : return :,def parse_status this_sample_id status if status in status attrib and status attrib status live sys stderr write WARNING Status is not live status n format this_sample_id status attrib status if when not in status attrib sys stderr write WARNING No time stampe for status n format this_sample_id return unknown return status attrib when
make a parametric surface as the source . : return : vtkpolydata with normal and scalar data .,def MakeParametricSource fn vtk vtkParametricRandomHills fn AllowRandomGenerationOn fn SetRandomSeed 1 fn SetNumberOfHills 30 source vtk vtkParametricFunctionSource source SetParametricFunction fn source SetUResolution 50 source SetVResolution 50 source SetScalarModeToZ source Update source GetOutput GetPointData GetNormals SetName Normals source GetOutput GetPointData GetScalars SetName Scalars return source GetOutput
returns a list with all the ending url for the other page,def getBuses listaWeb for i in range 5 url http www smttaju com br smtt transporte itinerario e horario dos onibus start s i 24 try content UrlReq urlopen url read soup BS content lxml data str soup data data split div class cat items 1 data data split ul 1 data data split ul 0 for c in range len data 1 try passValue data split a href c passValue passValue split title 0 if type passValue None break listaWeb append passValue except IndexError break except Exception as e return Exception occured n str e listaWeb remove smtt transporte itinerario e horario dos onibus 2570 102 soledade maracaju 2 return listaWeb
returns the redirect url for a resourceurl,register simple_tag takes_context True def resourceurl_link context resourceurl alternate_link u Returns the redirect URL for a ResourceURL n n Renders the resource URL redirect link if the user is authenticated n OR if the setting is turned off n link_link u href url title title class css_class if not conf DOWNLOAD_LOGIN_REQUIRED or context u user is_authenticated url resourceurl get_absolute_url title _ u Go to resourceurl url css_class u active link else url alternate_link title _ u Please login on register to download these files or access these links css_class u disabled link return mark_safe link_link format url url title title css_class css_class
"get the gcode files in the directory the file is in if directory setting is true . otherwise , return the file in a list .",def getFileOrDirectoryTypes fileName fileTypes wasCancelled if isEmptyOrCancelled fileName wasCancelled return if isDirectorySetting return archive getFilesWithFileTypesWithoutWords fileTypes fileName return fileName
"set the default settings , execute title & settings filename .",def __init__ self skeinforge_profile addListsToCraftTypeRepository skeinforge_application skeinforge_plugins craft_plugins lift html self self fileNameInput settings FileNameInput getFromFileName fabmetheus_interpret getGNUTranslatorGcodeFileTypeTuples Open File to be Lifted self self activateLift settings BooleanSetting getFromValue Activate Lift self True self cuttingLiftOverLayerStep settings FloatSpin getFromValue 1 0 Cutting Lift over Layer Step ratio self 1 0 0 5 self clearanceAboveTop settings FloatSpin getFromValue 0 0 Clearance above Top mm self 10 0 5 0 self executeTitle Lift
multiply each component of this vector3 .,def __imul__ self other self x other self y other self z other return self
parse a gcode line and add it to the bevel gcode .,def parseLine self line splitLine gcodec getSplitLineBeforeBracketSemicolon line if len splitLine 1 return firstWord splitLine 0 if firstWord G1 self addHomeTravel splitLine self oldLocation gcodec getLocationFromSplitLine self oldLocation splitLine elif firstWord layer self layerCount printProgressIncrement home if len self homeLines 0 self shouldHome True elif firstWord M101 self extruderActive True elif firstWord M103 self extruderActive False self distanceFeedRate addLine line
parse gcode initialization and store the parameters .,def parseInitialization self splodgeRepository for self lineIndex in xrange len self lines line self lines self lineIndex splitLine gcodec getSplitLineBeforeBracketSemicolon line firstWord gcodec getFirstWord splitLine self distanceFeedRate parseSplitLine firstWord splitLine if firstWord extruderInitialization self addLineUnlessIdenticalReactivate gcodec getTagBracketedProcedure splodge return elif firstWord layerThickness self layerThickness float splitLine 1 elif firstWord operatingFeedRatePerSecond self operatingFeedRatePerSecond float splitLine 1 elif firstWord perimeterWidth self perimeterWidth float splitLine 1 self minimumQuantityLength 0 1 self perimeterWidth self addLineUnlessIdenticalReactivate line
this is the start of any reduction .,def __call__ self states use_optimizations True output_mode OutputMode PublishToADS plot_results False output_graph self validate_inputs states use_optimizations output_mode plot_results output_graph self _execute states use_optimizations output_mode plot_results output_graph
get the default gonimoter set it to something else and make sure it was successfully changed,def test_change_default_goniometer self alg run_algorithm CreateWorkspace DataX 1 2 3 4 5 DataY 1 2 3 4 5 NSpec 1 child True ws alg getProperty OutputWorkspace value run ws run g run getGoniometer r np array 1 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 g setR r self assertTrue g getR r all
test that the instrumentvalidator can be constructed with no args,def test_InstrumentValidator_construction self testhelpers assertRaisesNothing self InstrumentValidator
append a data file in the list of files to be processed . @param datafile : data file to be processed @param workspace : optional workspace name for this data file [ default will be the name of the file ],def AppendDataFile datafile workspace None ReductionSingleton append_data_file datafile workspace
generate a list of masked pixels . @param nx_low : number of pixels to mask on the lower - x side of the detector @param nx_high : number of pixels to mask on the higher - x side of the detector @param ny_low : number of pixels to mask on the lower - y side of the detector @param ny_high : number of pixels to mask on the higher - y side of the detector @param workspace : the pixel number and size info will be taken from the workspace,def get_masked_pixels nx_low nx_high ny_low ny_high workspace component_name None id_list get_masked_ids nx_low nx_high ny_low ny_high workspace component_name nx_pixels int workspace getInstrument getNumberParameter number of x pixels 0 ny_pixels int workspace getInstrument getNumberParameter number of y pixels 0 pixel_list current_det_id 3 for i in range ny_pixels for j in range nx_pixels if current_det_id in id_list pixel_list append i j return pixel_list
"adds an entry with the current date / time to the table . retrieve the index of that entry = the "" revision "" . returns the current revision",def add_revision db SQLgetConnection c db cursor query INSERT INTO Revisions VALUES NULL s str datetime datetime now c execute query db commit return get_latest_revison
get features of a dataset .,datasets command name list features short_help List features in a dataset click argument dataset required True click option reverse r default False help Read features in reverse click option start s default None help Feature id to begin reading from click option limit l default None help Maximum number of features to return click option output o default help Save output to a file click pass_context def list_features ctx dataset reverse start limit output stdout click open_file output w service ctx obj get service res service list_features dataset reverse start limit if res status_code 200 click echo res text file stdout else raise MapboxCLIException res text strip
return the median of a list of values .,def median x m r divmod len x 2 if r return sorted x m return sum sorted x m 1 m 1 2
validates uuid of a specified version ( default version is 4 ) .,def validate_uuid string version 4 try _ uuid UUID string version version except ValueError return False return True
"ensure tor packages are installed . includes a check for the keyring , so that automatic updates can handle rotating the signing key if necessary .",pytest mark parametrize package deb torproject org keyring tor def test_tor_packages Package package assert Package package is_installed
by default this is just a simple urlopen call but this method should be overridden for providers with special url requirements ( like cookies ),def getURL self url post_data None heads None if post_data if heads req urllib2 Request url post_data heads else req urllib2 Request url post_data elif heads req urllib2 Request url headers heads else req urllib2 Request url response helpers getURL req if response is None logger log u Error loading self name URL url logger ERROR return response
uvlib is an object that returns uv - coordinates . msh is a mesh data object . uvl is a uv - layer data object . uvl must have the same length as mesh.faces .,def fill_uv_coords uvlib msh uvl uv_data uvl data uvoff 0 for mshpoly in msh polygons uvcoords uvlib get_uvs mshpoly index mshpoly vertices for uv_rel_idx in range len mshpoly vertices uv_pair uvcoords 2 uv_rel_idx 2 uv_rel_idx 2 uv_abs_idx uvoff uv_rel_idx uv_data uv_abs_idx uv uv_pair uvoff len mshpoly vertices msh update
updates the provided data for the campaign specified by < id>. < i d > is the pardot id of the campaign .,def update self id None kwargs response self _post path do update id id format id id params kwargs return response
returns the alias group for a specified tracker url,def getAliasGroup self url self _update if url in self REVERSE_LOOKUP alias self REVERSE_LOOKUP url return self STORE alias else raise AliasError Unknown tracker URL
execute array of handler initializers .,def build_handler tblname hlist klist for h in hlist if not h continue pos h find if pos 0 if h 1 raise Exception handler fmt error name h pos strip args h pos 1 1 split args a strip for a in args else name h args klass _handler_map name klist append klass args klist append TableHandler p None klist reverse for klass args in klist p klass tblname p args return p
retrieves timestamp and ambient light readings .,def retrieve_ambient_light self self _cursor execute SELECT FROM ambient_light data for row in self _cursor fetchall data append parser parse row 0 row 1 AmbientLightRecord collections namedtuple AmbientLightRecord timestamp ambient_light ambient_light_data map AmbientLightRecord _make data return ambient_light_data
method retrieves a tree node identified by the time_qualifier and the timeperiod,def get_node self process_name timeperiod if process_name not in self process_hierarchy raise ValueError unable to retrieve the node due to unknown process 0 format process_name time_qualifier self process_hierarchy process_name process_entry time_qualifier return self _get_node time_qualifier timeperiod
handle the ` pyeval ` vim function .,rpc_export python_eval sync True def python_eval self expr return eval expr self module __dict__
test if swithes defined for same enduse,def switch_testing fuel_switches service_switches capacity_switches all_switches_incl_sectors enduses_fuel_switch set for model_switch in fuel_switches for switch in model_switch enduses_fuel_switch add switch enduse if switch enduse not in all_switches_incl_sectors all_switches_incl_sectors switch enduse set if switch sector None all_switches_incl_sectors switch enduse None else all_switches_incl_sectors switch enduse add switch sector else all_switches_incl_sectors switch enduse add switch sector enduses_service_switch set for model_switch in service_switches for switch in model_switch enduses_service_switch add switch enduse if switch enduse not in all_switches_incl_sectors all_switches_incl_sectors switch enduse set if switch sector None all_switches_incl_sectors switch enduse None else all_switches_incl_sectors switch enduse add switch sector else all_switches_incl_sectors switch enduse add switch sector enduses_capacity_switch set for model_switch in capacity_switches for switch in model_switch enduses_capacity_switch add switch enduse if switch enduse not in all_switches_incl_sectors all_switches_incl_sectors switch enduse set if switch sector None all_switches_incl_sectors switch enduse None else all_switches_incl_sectors switch enduse add switch sector else all_switches_incl_sectors switch enduse add switch sector enduses_fuel_switch list enduses_fuel_switch enduses_service_switch list enduses_service_switch enduses_capacity_switch list enduses_capacity_switch for enduse in enduses_fuel_switch if enduse in enduses_service_switch or enduse in enduses_capacity_switch raise Exception Error Enduse s is defined in fuel switch and also in either service or capacity enduse for enduse in enduses_service_switch if enduse in enduses_fuel_switch or enduse in enduses_capacity_switch raise Exception Error Enduse s is defined in fuel switch and also in either service or capacity enduse for enduse in enduses_capacity_switch if enduse in enduses_fuel_switch or enduse in enduses_service_switch raise Exception Error Enduse s is defined in fuel switch and also in either service or capacity enduse for enduse in all_switches_incl_sectors if all_switches_incl_sectors enduse None all_switches_incl_sectors enduse list all_switches_incl_sectors enduse return all_switches_incl_sectors
returns a list of all signed in users .,property def signed_in self _signed_ins for user in self all if self all user account _signed_ins append self all user return _signed_ins
seek to the specified position or iteration .,def seek self iteration None position None if iteration is not None self first self position image iteration self numFilteredVersionsPerImage self numImages remainingIterations iteration self numFilteredVersionsPerImage if remainingIterations for i in xrange remainingIterations 1 self next seeking True self next else if position image is not None self position image position image if position filters is not None self position filters position filters
check that the data layout is the same as if a ufunc did the operation .,def test_same_as_ufunc data 1 3 3 1 3 3 3 3 3 3 1 3 3 3 3 1 3 3 1 3 3 1 1 3 3 3 3 1 1 1 3 1 3 1 1 3 1 3 1 1 0 0 0 0 0 0 1 0 0 0 0 1 0 0 1 0 0 1 1 0 0 0 0 1 1 1 0 1 0 1 1 0 1 0 1 3 3 3 3 3 3 3 3 3 1 3 3 1 3 3 3 3 3 3 3 3 1 1 3 1 3 1 3 1 3 1 1 1 3 1 3 1 3 1 3 3 1 3 1 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 1 1 0 1 0 1 0 1 0 1 1 1 0 1 0 1 0 1 0 0 1 0 1 for input_shapes expected_shape in data yield assert_same_as_ufunc input_shapes 0 input_shapes 1 yield assert_same_as_ufunc input_shapes 1 input_shapes 0 yield assert_same_as_ufunc input_shapes 0 input_shapes 1 True if not in input_shapes yield assert_same_as_ufunc input_shapes 0 input_shapes 1 False True yield assert_same_as_ufunc input_shapes 0 input_shapes 1 True True
python implementation of the `` _ ior ( ... ) `` macro from linux .,def IOR request_type request_nr size calc _machine_ioctl_calculator request_type _ioc_request_type request_type size _ioc_type_size size return calc ioc calc _IOC_READ request_type request_nr size
types content into the html component and presses save .,def set_content_and_save self content self set_content content self save
returns the users associated with the cohort .,post_generation def users self create extracted kwargs if extracted self users add extracted
displays the course mode choice page .,method_decorator login_required def get self request course_id error None course_key CourseKey from_string course_id embargo_redirect embargo_api redirect_if_blocked course_key user request user ip_address get_ip request url request path if embargo_redirect return redirect embargo_redirect enrollment_mode is_active CourseEnrollment enrollment_mode_for_user request user course_key modes CourseMode modes_for_course_dict course_key has_enrolled_professional CourseMode is_professional_slug enrollment_mode and is_active if CourseMode has_professional_mode modes and not has_enrolled_professional return redirect reverse verify_student_start_flow kwargs course_id unicode course_key if not CourseMode has_verified_mode modes return redirect reverse dashboard if is_active and enrollment_mode in CourseMode VERIFIED_MODES CourseMode NO_ID_PROFESSIONAL_MODE return redirect reverse dashboard donation_for_course request session get donation_for_course chosen_price donation_for_course get unicode course_key None course modulestore get_course course_key has_credit_upsell any CourseMode is_credit_mode mode for mode in CourseMode modes_for_course course_key only_selectable False context course_modes_choose_url reverse course_modes_choose kwargs course_id course_key to_deprecated_string modes modes has_credit_upsell has_credit_upsell course_name course display_name_with_default course_org course display_org_with_default course_num course display_number_with_default chosen_price chosen_price error error responsive True if verified in modes context suggested_prices decimal Decimal x strip for x in modes verified suggested_prices split if x strip context currency modes verified currency upper context min_price modes verified min_price context verified_name modes verified name context verified_description modes verified description return render_to_response course_modes choose html context
test if settings service returns default if setting not found,override_settings XBLOCK_SETTINGS xblock_setting_key2 b 1 def test_get_returns_none_or_default_if_bucket_not_found self self assertEqual getattr settings XBLOCK_SETTINGS self xblock_setting_key2 b 1 self assertEqual self settings_service get_settings_bucket self xblock_mock self assertEqual self settings_service get_settings_bucket self xblock_mock 123 123
verify that check_nonce fails with a key that is none,def test_null_nonce self nonce None self assertFalse SignatureValidator check_nonce nonce
test that checks the default currency_symbol ( $ ) in the response,override_settings PAID_COURSE_REGISTRATION_CURRENCY PKR Rs def test_override_currency_settings_in_the_html_response self CourseFinanceAdminRole self course id add_users self instructor total_amount PaidCourseRegistration get_total_amount_of_purchased_item self course id response self client get self url self assertIn currency amount format currency Rs amount total_amount response content
"send a response back to the client with the http ` status_code ` ( int ) , the given content serialized as json ( str ) , and the headers set appropriately .",def respond self status_code 200 content None headers Access Control Allow Origin if status_code 400 and content headers Content Type application json content json dumps content else headers Content Type text html self send_response status_code content headers
construct file path to be uploaded from the data upload folder .,staticmethod def file_path filename return os sep join __file__ split os sep 4 data imports filename
wait until video will be in given state .,def wait_for_state self state finished self video wait_for_state state
returns the information about each video upload required for the video list,def _get_index_videos course return list attr video attr for attr in edx_video_id client_video_id created duration status for video in _get_videos course
scenario : i should see the correct text when importing a library . given that i have a library to import to when i visit the import page the correct header should be shown,def test_header self self assertEqual self import_page header_text Library Import
format the return value in list into hex .,def _hex list None list list or if list list reverse return int join list 16 return 0
tries to guess kernel by regexp,def guess_kernel chroot regexp None kernel utils guess_filename path os path join chroot boot regexp regexp or vmlinuz if kernel return kernel raise errors GrubUtilsError Error while trying to find kernel regexp s regexp
execute shell command on hosts over ssh .,def execute_on_hosts hosts commands commands_merged for command in commands commands_merged echo command commands_merged command for host in hosts print Host host print subprocess Popen ssh host commands_merged stdout subprocess PIPE stderr subprocess STDOUT shell True communicate 0
process a deleted neutron port .,def delete_port_mac self context port pass
determine whether a cluster supports the sharedfile disk template .,def has_sharedfile cluster return classify cluster GANETI25
expert : an agent implementing the policy - to - be - imitated,def __init__ self expert kwargs super Imitator self __init__ kwargs self expert expert
x is an n x h x w x 3 set of images,def forward self X thX torch fromNumpyArray X transpose 0 3 1 2 cuthX thX _cuda assert torch typename cuthX in cudnn typemap keys thY self model _forward cuthX Y thY asNumpyArray return Y
adds all the glyphs that can be built to the given font .,def add_decomposable_glyphs_to_font self for char in self decompositions self add_glyph_to_font char
should be called to get iban checksum uses the mod-97 - 10 checksumming protocol ( iso / iec 7064:2003 ),def checksum self return self _iban 2 4
emit an xml document for the given ` input_dict ` ( reverse of ` parse ` ) .,def unparse input_dict output None encoding utf 8 full_document True kwargs key value input_dict items must_return False if output is None output StringIO must_return True content_handler XMLGenerator output encoding if full_document content_handler startDocument _emit key value content_handler kwargs if full_document content_handler endDocument if must_return value output getvalue try value value decode encoding except AttributeError pass return value
"opens the file , creates the pipe .",def initialize self starttime 0 self close if starttime 0 offset min 1 starttime i_arg ss 06f starttime offset i self filename ss 06f offset else i_arg i self filename cmd get_setting FFMPEG_BINARY i_arg loglevel error f image2pipe pix_fmt self pix_fmt vcodec rawvideo popen_params bufsize self bufsize stdout sp PIPE stderr sp PIPE stdin DEVNULL if os name nt popen_params creationflags 134217728 self proc sp Popen cmd popen_params
capturing must leave custom excepthooks alone when disabled .,def test_no_capture_preserves_custom_excepthook testdir testdir makepyfile import pytest import sys from pytestqt qt_compat import qt_api QWidget qt_api QWidget QtCore qt_api QtCore def custom_excepthook args sys __excepthook__ args sys excepthook custom_excepthook pytest mark qt_no_exception_capture def test_no_capture qtbot assert sys excepthook is custom_excepthook def test_capture qtbot assert sys excepthook is not custom_excepthook res testdir runpytest res stdout fnmatch_lines 2 passed
"method responsible for storing results . this method calls : meth:`super ` first , thus utilizing the logging provided there .",def __call__ self experiment outcomes u n Method responsible for storing results This method calls n meth super first thus utilizing the logging provided there n n Parameters n n experiment Experiment instance n outcomes dict n the outcomes dict n n super FileBasedCallback self __call__ experiment outcomes self _store_case experiment self _store_outcomes outcomes
"helper function to write out dry up templating . accepts template name ( string ) , path ( string ) , target directory ( string ) , context ( dictionary ) and delete_template ( boolean ) default behavior is to use the key of the dictionary as the template variable names , replace them with the value in the tempalate and delete the template if delete_template is true",def render_template template_name template_path target context delete_template True overwrite False logging info Writing format target logging debug Template Context format context logging debug Overwrite is format overwrite if os path isfile target and overwrite is not True logging warn Cowardly refusing to overwrite existing file format target return False logging debug Attempting to write from template format target template_path template_name template_path os path normpath template_path template_name os path normpath template_name template_permissions os stat template_path template_name st_mode with open target w as vars_file try template jinja2 Environment loader jinja2 FileSystemLoader template_path get_template template_name vars_file write template render context except Exception as e logging error Error writing format target traceback print_exc e return False os chmod target template_permissions if delete_template logging debug Removing format template_path template_name os remove format template_path template_name
this method calls execute on all the registered addons .,def execute self storage ksdata instClass users payload for v in self __dict__ values if hasattr v execute progress_message N_ Executing s addon v name if v execute __code__ co_argcount 6 v execute storage ksdata instClass users payload else v execute storage ksdata instClass users log warning Addon s is using deprecated method signature v name log warning Use execute storage ksdata instClass users payload instead
check if a given string is an existing timezone .,def is_valid_timezone timezone etc_zones Etc zone for zone in ETC_ZONES return timezone in pytz common_timezones etc_zones
"reads an ascii file if it exists , removes blank lines , whitespace , and comments ( denoted by # ) . it then splits values by whitespace , giving a list of all values in the file .",def readFile some_file if os path isfile some_file f open some_file lines f readlines f close lines l for l in lines if l 0 lines l strip for l in lines if len l strip 0 values join lines values values split return values else raise IOError s does not exist some_file
includes alpha function synapse -- needs to be driven with a piecewise constant presynaptic voltage input ( as a parameter ),def makeHHneuron name par_args ic_args with_IA False gentype vode if gentype in vode euler targetlang python else targetlang C vfn_str Iapp ionic v r gsyn s v Esyn tau_v if with_IA rfn_str 1 29 v 0 79 3 3 pow v 0 38 2 r tau_r else rfn_str 1 35 v 1 03 r tau_r auxfndict ionic vv rr 13 1 37 3 67 vv 2 51 vv vv vv 0 55 26 rr vv 0 92 DSargs args DSargs varspecs v vfn_str r rfn_str a a heav vpre vthresh tau_syn s s a tau_syn vpre_aux vpre DSargs pars par_args DSargs fnspecs auxfndict DSargs auxvars vpre_aux DSargs xdomain v 1 1 r 0 1 DSargs tdomain 0 500 DSargs algparams init_step 0 1 max_pts 100000 if gentype vode DSargs algparams stiff True DSargs checklevel 1 DSargs ics ic_args DSargs name name thresh_ev Events makeZeroCrossEvent v 1 name thresh_ev eventtol 1e 05 precise True term False varnames v targetlang targetlang DSargs events thresh_ev if gentype vode return Generator Vode_ODEsystem DSargs elif gentype euler return Generator Euler_ODEsystem DSargs elif gentype radau return Generator Radau_ODEsystem DSargs elif gentype dopri return Generator Dopri_ODEsystem DSargs else raise NotImplementedError Unknown ODE system type s gentype
pop a request timeout not support in this queue class,def pop self timeout 0 pipe self server pipeline pipe multi pipe zrange self key 0 0 zremrangebyrank self key 0 0 results count pipe execute if results return self _decode_request results 0
return a full path for a given filename .,def get_full_path self filename language None version_slug None if re match https filename return filename return resolve_path project self project language language version_slug version_slug filename filename
"this method returns all the object for the passed action type , otherwise none .",def getAction self action_type action None if self isValid action filter lambda action action tag action_type list self contents getroot 0 return action
"given a line , return a list of filepaths from each ( archive ) link in the line",def extract_labels_filepath line filepaths re_archive re compile s Archive labels re findall s Archive line for label in labels filepaths append label return filepaths
find what commits need to be imported,def find_incoming git_object_store git_map refs done set commit_cache def commitdate sha obj git_object_store sha return obj commit_time obj commit_timezone def get_heads refs todo seenheads set for sha in refs itervalues if sha in git_object_store obj git_object_store sha while isinstance obj Tag obj_type sha obj object obj git_object_store sha if isinstance obj Commit and sha not in seenheads seenheads add sha todo append sha todo sort key commitdate reverse True return todo def get_unseen_commits todo get all unseen commits reachable from todo in topological order unseen means not reachable from the done set and not in the git map Mutates todo and the done set in the process commits while todo sha todo 1 if sha in done or sha in git_map todo pop continue assert isinstance sha str if sha in commit_cache obj commit_cache sha else obj git_object_store sha commit_cache sha obj assert isinstance obj Commit for p in obj parents if p not in done and p not in git_map todo append p break else commits append sha done add sha todo pop return commits todo get_heads refs commits get_unseen_commits todo return GitIncomingResult commits commit_cache
get the number of entries we will cache .,def cache_size self return self _max_cache
returns a dictionary containing all cookie information by domain .,def get_cookies self return self _cj _cookies
return function that computes gradient of arguments .,def grad func argnum None grad_with_loss_func grad_and_loss func argnum functools wraps grad_with_loss_func def wrapped args return grad_with_loss_func args 0 return wrapped
"subclass the save method , to hash ndarray subclass , rather than pickling them . off course , this is a total abuse of the pickler class .",def save self obj if isinstance obj self np ndarray try self _hash update self np getbuffer obj except TypeError self _hash update self np getbuffer obj flatten if self coerce_mmap and isinstance obj self np memmap klass self np ndarray else klass obj __class__ obj klass HASHED obj dtype obj shape obj strides Hasher save self obj
test that we can retrieve datanode sizes up to 1mb with default parameters ( depends on zookeeper server ) .,def test_sync_get_large_datanode self data join A for x in range 1024 1023 self ensureDeleted zk python test large datanode zookeeper create self handle zk python test large datanode data perms 31 scheme world id anyone ret stat zookeeper get self handle zk python test large datanode self assertEqual len ret 1024 1023 Should have got 1Mb returned instead got s len ret ret stat zookeeper get self handle zk python test large datanode None 500 self assertEqual len ret 500 Should have got 500 bytes returned instead got s len ret
guess molecule file format from filename .,def guess_mol_format self filename if filename endswith gz filename os path splitext filename 0 if filename endswith sdf mol_format sdf elif filename endswith smi can ism mol_format smi elif filename endswith pkl mol_format pkl else raise NotImplementedError Unrecognized file format return mol_format
save the extension model . allows more fine grained control over model state saving than pickling would allow . the method should save objects that only ca n't be pickled .,def save self folder pass
attempt an operation as long as it fails up to the given timeout . : param target : the callable : param args : the arguments to pass : param timeout : the timeout : param pause : how long to pause between each failed invocation : return : either the result from successfully invoking the callable raises the exception thrown by the callable on timeout .,def try_with_timeout target args timeout pause end time perf_counter timeout result exception try_invoke target args while exception is not None and time perf_counter end time sleep pause result exception try_invoke target args if exception is not None raise exception return result
get page 0x80 serial number using external command .,def vpd_get_page80_sn blkdev cmdargs scsi_id page 0x80 whitelisted device dev blkdev output subprocess Popen cmdargs stdout subprocess PIPE communicate 0 return output decode utf 8 rstrip split 1
helper that returns `` true `` if the field 's type is given in any arg .,def is_a self args u n Helper that returns True if the field s type is given in any arg n return self field_type in args
return a node this node is derived from .,property def parent_type self if not hasattr self defs return None pnode self derived_from self defs if pnode return NodeType pnode self custom_def
"set rawresults = true if you want the query to return dictionnaries instead of document objects . you can use * * moreargs to pass more arguments supported by the api , such as ttl=60 ( time to live )",def AQLQuery self query batchSize 100 rawResults False bindVars options count False fullCount False json_encoder None moreArgs return AQLQuery self query rawResults rawResults batchSize batchSize bindVars bindVars options options count count fullCount fullCount json_encoder json_encoder moreArgs
use addr2line to look up information for the specified addresses . all of the addresses must belong to the same object file .,def translate_file_addresses filename addresses options if not os path isfile filename return args addr2line if options printFunctions args append f args extend e filename proc subprocess Popen args stdin subprocess PIPE stdout subprocess PIPE for address in addresses assert address objectFile filename proc stdin write address address n if options printFunctions function proc stdout readline function function strip if not function raise Exception unexpected EOF from addr2line address function function file_and_line proc stdout readline file_and_line file_and_line strip if not file_and_line raise Exception unexpected EOF from addr2line idx file_and_line rfind if idx 0 msg expected file and line number from addr2line got r file_and_line msg nfile r address r filename address address raise Exception msg address sourceFile file_and_line idx address sourceLine file_and_line idx 1 remaining_out cmd_err proc communicate retcode proc wait if retcode 0 raise subprocess CalledProcessError retcode args
bins the given values for use in a histogram .,tf_export histogram_fixed_width_bins def histogram_fixed_width_bins values value_range nbins 100 dtype dtypes int32 name None with ops name_scope name histogram_fixed_width_bins values value_range nbins values ops convert_to_tensor values name values shape array_ops shape values values array_ops reshape values 1 value_range ops convert_to_tensor value_range name value_range nbins ops convert_to_tensor nbins dtype dtypes int32 name nbins nbins_float math_ops cast nbins values dtype scaled_values math_ops truediv values value_range 0 value_range 1 value_range 0 name scaled_values indices math_ops floor nbins_float scaled_values name indices indices math_ops cast clip_ops clip_by_value indices 0 nbins_float 1 dtypes int32 return array_ops reshape indices shape
"generates 2-dimensional data centered on ( 2,2 ) , ( -1,-1 ) .",staticmethod def make_data num_vectors vectors classes for _ in xrange num_vectors if np random random 0 5 vectors append np random normal 2 0 0 6 np random normal 2 0 0 9 classes append 0 else vectors append np random normal 1 0 0 4 np random normal 1 0 0 5 classes append 1 return np asarray vectors classes
instantiates the ` absolutevalue ` bijector .,def __init__ self validate_args False name absolute_value self _graph_parents self _name name with self _name_scope init super AbsoluteValue self __init__ forward_min_event_ndims 0 is_constant_jacobian True validate_args validate_args name name
creates a filter that keeps one of every n export versions .,def _one_of_every_n_export_versions n def keep paths A filter function that keeps exactly one out of every n paths keeper_map for p in paths if p export_version is None continue interval math floor p export_version 1 n if p export_version else 0 existing keeper_map get interval None if not existing or existing export_version p export_version keeper_map interval p return sorted keeper_map values return keep
tests that rewriting occurs with default gradient names .,def testRewritingDefaultGradientNames self original_metagraph _ _ _ self _GetMetaGraph rewritten_graph_def tf_optimizer OptimizeGraph rewriter_config_pb2 RewriterConfig disable_model_pruning True constant_folding rewriter_config_pb2 RewriterConfig OFF dependency_optimization rewriter_config_pb2 RewriterConfig OFF layout_optimizer rewriter_config_pb2 RewriterConfig OFF arithmetic_optimization rewriter_config_pb2 RewriterConfig OFF memory_optimization rewriter_config_pb2 RewriterConfig RECOMPUTATION_HEURISTICS original_metagraph self assertGreater len rewritten_graph_def node len original_metagraph graph_def node self assertEqual 0 len node for node in original_metagraph graph_def node if Recomputed in node name self assertEqual 20 len node for node in rewritten_graph_def node if Recomputed in node name
the ` operation ` that produces ` values ` as an output .,property def op self return self values op
overload of if_stmt that executes a python if statement .,def _py_if_stmt cond body orelse return body if cond else orelse
merges list of ` estimatorspec ` for eval .,def _merge_eval self all_estimator_spec predictions metrics losses with ops name_scope merge_eval for head spec in zip self _heads all_estimator_spec losses append spec loss head_name head name loss_name head_lib _summary_key head_name metric_keys MetricKeys LOSS metrics loss_name metrics_lib mean spec loss name loss_name metrics update spec eval_metric_ops or for k v in six iteritems spec predictions predictions head_name k v loss _merge_losses losses self _head_weights return model_fn EstimatorSpec mode model_fn ModeKeys EVAL predictions predictions loss loss eval_metric_ops metrics
gets a list of sensor ids as a dataframe indexed on sensor number . can be limited by a list of numbers .,def get_sensors sensor_id None url http cdec water ca gov misc senslist html df pd read_html url header 0 0 df set_index Sensor No if sensor_id is None return df return df ix sensor_id
test when port is not a valid integral value,def test_invalid self tests 1 2 3 4 1 2 2 3 1e10 for test in tests with pytest raises TypeError Preview port test
"converts an arg to numpy , avoiding dangerous string and unicode dtypes .",staticmethod def _convert value result np asarray value order C if result dtype char in SU and result is not value return np asarray value order C dtype object return result
context to colocate with ` var ` if ` colocate_clip_ops_with_vars ` .,contextlib contextmanager def _maybe_colocate_with self var if self _colocate_clip_ops_with_vars with ops colocate_with var yield else yield
create placeholder name for the graph editor .,def placeholder_name t None scope None if scope is not None scope scope_finalize scope if t is not None if not isinstance t tf_ops Tensor raise TypeError Expected a tf Tenfor got format type t op_dirname scope_dirname t op name op_basename scope_basename t op name if scope is None scope op_dirname if op_basename startswith geph__ ph_name op_basename else ph_name geph__ _ format op_basename t value_index return scope ph_name else if scope is None scope return scope geph
forward parsing calls to dedicated typekind handlder,def parse_cursor_type self _cursor_type return self typekind_handler parse_cursor_type _cursor_type
"start a new server - side span . if the span has already been started by ` start_basic_span ` , this method only adds baggage from the headers .",def start_span self request headers peer_host peer_port parent_context None try if headers and hasattr headers iteritems tracing_headers k len TRACING_KEY_PREFIX v for k v in headers iteritems if k startswith TRACING_KEY_PREFIX parent_context self tracer extract format opentracing Format TEXT_MAP carrier tracing_headers if self span and parent_context for k v in parent_context baggage iteritems self span set_baggage_item k v except log exception Cannot extract tracing span from headers if self span is None self span self tracer start_span operation_name request endpoint child_of parent_context tags tags SPAN_KIND tags SPAN_KIND_RPC_SERVER if cn in request headers self span set_tag tags PEER_SERVICE request headers cn if peer_host self span set_tag tags PEER_HOST_IPV4 peer_host if peer_port self span set_tag tags PEER_PORT peer_port if as in request headers self span set_tag as request headers as return self span
"prints a list of all registered receivers . including signal , plugin name and description .",def list_receivers self print Receiver list print n for key receiver in self app signals receivers items print s s s n s n receiver name receiver signal receiver plugin name receiver description
print the rst table header . the header names are vertical .,def print_table_header outfile num_cols header_names print_table_divider outfile num_cols line for name in header_names line name 0 print_table_row outfile Feature line for i in range 1 10 line for name in header_names line name i print_table_row outfile line print_table_divider outfile num_cols
testing whether downloading a torrent from another peer is successful,deferred timeout 20 skipIf sys platform win32 chmod does not work on Windows def test_torrent_download self session1_port self session config get_dispersy_port def start_download _ candidate Candidate 127 0 0 1 session1_port False self session2 lm rtorrent_handler download_torrent candidate self infohashes 0 self session2 lm rtorrent_handler download_torrent candidate self infohashes 1 user_callback do_check_download def do_check_download _ for i infohash_str in enumerate self infohash_strs self _logger info u Checking s self file_names i for _ in self session2 lm torrent_store iterkeys self assertTrue infohash_str in self session2 lm torrent_store u Failed to download torrent file 1 self _logger info u Torrent files 1 and 2 downloaded successfully self test_deferred callback None self infohash_strs 41aea20908363a80d44234e8fef07fab506cd3b4 45a647b1120ed9fe7f793e17585efb4b0efdf1a5 for i infohash in enumerate self infohash_strs self infohashes i infohash decode hex self file_names i file_name u s torrent infohash with open os path join TESTS_DATA_DIR file_name r as torrent_file self session lm torrent_store put infohash torrent_file read self setup_downloader addCallback start_download return self test_deferred
test that the transfer method of a btc wallet,deferred timeout 10 def test_btc_wallet_transfer_error self def mocked_run_cmdline request if request cmd payto return hex abcd elif request cmd broadcast return False abcd test_deferred Deferred wallet BitcoinWallet self session_base_dir mock_daemon MockObject mock_server MockObject mock_server run_cmdline mocked_run_cmdline mock_daemon get_server lambda _ mock_server wallet get_daemon lambda mock_daemon wallet get_balance lambda succeed available 5 return wallet transfer 3 abacd addErrback lambda _ test_deferred callback None
"testing uknkown source added to boosting source , and try to apply archive on top of that",def test_unknown_source self unknown_key 1234567890 sources len self boosting_manager boosting_sources keys self boosting_manager add_source unknown_key self boosting_manager set_archive unknown_key False self assertEqual sources len self boosting_manager boosting_sources keys unknown source added
"private , do not call directly .",def wrap_WebPEncodeRGB args return _libwebp wrap_WebPEncodeRGB args
perform any necessary operations to ready the package for use .,def finalize self if self finalized return file_names self filelist for name in list file_names if os path isabs name raise ValueError Absolute path in filelist s name name os path dirname name rstrip while name if name in file_names raise ValueError Duplicate path in filelist s name elif name in file_names break else file_names append name self files append name name os path dirname name self files sort self finalized True
"return true if the character is a letter , digit , underscore , dollar sign , or non - ascii character .",def isAlphanum c return c a and c z or c 0 and c 9 or c A and c Z or c _ or c or c or c is not None and ord c 126
inject deep into distutils to customize how the dispatch to gcc / nvcc works .,def customize_compiler_for_nvcc self self src_extensions append cu default_compiler_so self compiler_so super self _compile def _compile obj src ext cc_args extra_postargs pp_opts print extra_postargs if os path splitext src 1 cu self set_executable compiler_so CUDA nvcc postargs extra_postargs nvcc else postargs extra_postargs gcc super obj src ext cc_args postargs pp_opts self compiler_so default_compiler_so self _compile _compile
test creation of a single link,def test_basic t BoostBuild Tester t write jamroot jam import link link directory dir1 link src dir1 include location t write src dir1 include file1 h file1 t run_build_system t expect_addition include file1 h t expect_content include file1 h file1 ignore_config t t expect_nothing_more t cleanup
return the length of the queue,def __len__ self raise NotImplementedError
"ensures that remote object exists for specified ct / id . if not , create it . returns remote object and reference .",def ensure_exist ct id obj ct get_object_for_this_type pk id rem ref find_ref ct obj pk if rem is not None return rem ref rem find_natural ct obj if rem is not None ref Reference objects create content_type ct local_object_id id remote_object_id rem pk return rem ref return perform_add ct id
initialise an instance of a module makefile .,def __init__ self args kw kw opengl 1 if qt not in kw kw qt QtCore QtGui QtOpenGL QtGuiModuleMakefile __init__ self args kw
formats the date value from database to the tableau format,def format_date date_to_format date_to_format str date_to_format return time strptime date_to_format Y m d 3
write smother results to a file .,def write self file_or_path append False timeout 10 if isinstance file_or_path six string_types if self coverage file_or_path get_smother_filename file_or_path self coverage config parallel outfile Lock file_or_path mode a timeout timeout fail_when_locked False else outfile noclose file_or_path with outfile as fh if append fh seek 0 try other Smother load fh except ValueError pass else self other fh seek 0 fh truncate json dump self data fh
sets up an interactive console on a socket with a single connected client .,def __spawn_backdoor_server self eventlet_backdoor initialize_if_enabled self _conf eventlet_backdoor_port
"when the user has created a participant , it 's injected into the request .",patch ws models Participant from_user def test_user_with_participant self from_user self request user self user participant Mock Participant def mock_from_user request_user if request_user id self user id raise ValueError Unexpected user was passed return participant from_user side_effect mock_from_user self pm self request self assertIs self request participant participant
"returns index and handle separately , in a tuple .",def remove_index_from_handle handle_with_index split handle_with_index split if len split 2 split 0 int split 0 return split elif len split 1 return None handle_with_index elif len split 2 raise handleexceptions HandleSyntaxError msg Too many colons handle handle_with_index expected_syntax index prefix suffix
use duck typing to check if val is a named tuple . checks that val is of type tuple and contains the attribute _ fields which is defined for named tuples . : param val : value to check type of : return : true if val is a namedtuple,def is_namedtuple val val_type type val bases val_type __bases__ if len bases 1 or bases 0 tuple return False fields getattr val_type _fields None return all isinstance n str for n in fields
checks to see if the torrent is already in the database,def torrentExists self torrent None url None hashString None return self Database torrentExists torrent torrent url url hashString hashString
threads display stack trace dumps for all threads currently executing within the python interpreter .,def do_threads self line all for threadId stack in sys _current_frames items block block append ThreadID s threadId thr threading _active get threadId if thr block append Name s thr name for filename lineno name line in traceback extract_stack stack block append File s line d in s filename lineno name if line block append s line strip all append n join block print self stdout n n join all
counts the number of parameter servers in cluster_spec .,def _count_ps cluster_spec return len cluster_spec as_dict get ps if cluster_spec else 0
tests that a short guid / secret returns an error ( regression would be to crash impalad ),needs_session def test_malformed_get_operation_status self operation_handle TCLIService TOperationHandle operation_handle operationId TCLIService THandleIdentifier operation_handle operationId guid short operation_handle operationId secret short_secret assert len operation_handle operationId guid 16 assert len operation_handle operationId secret 16 operation_handle operationType TCLIService TOperationType EXECUTE_STATEMENT operation_handle hasResultSet False get_operation_status_req TCLIService TGetOperationStatusReq get_operation_status_req operationHandle operation_handle get_operation_status_resp self hs2_client GetOperationStatus get_operation_status_req TestHS2 check_response get_operation_status_resp TCLIService TStatusCode ERROR_STATUS err_msg guid size d expected 16 secret size d expected 16 len operation_handle operationId guid len operation_handle operationId secret assert err_msg in get_operation_status_resp status errorMessage
"returns rc of process , no output",staticmethod def simple cmd working_dir None print_debug cmd in s cmd if True os sys stdout flush ret os system cmd os sys stdout flush return ret else cmd bin bash cmd output to_exec cmd split print going to execute s to_exec subp subprocess Popen to_exec while subp returncode is None com subp communicate 0 if com print com com subp communicate 1 if com print com time sleep 0 05 subp poll return subp returncode
it return the match_part with the best e - value,def _match_part_selector self features blastdb blastdb os path basename blastdb features self _select_features_by_type features match_part features f for f in features if f qualifiers blastdb blastdb if not features return None scores feat qualifiers score for feat in features return features scores index min scores
"after setting the lda model , test the model",def test_model lda_model models LdaModel load zhihu_dat zhihu_10 lda question_lda lda_model question_corpus for doc in question_lda print doc
invokes the volume visualizer by gael varoquaux,def vol_vis self if not self loaded self load from cviewer visualization volume thread_volslice import ThreadedVolumeSlicer logger debug Invoke Volume Slicer action ThreadedVolumeSlicer fname self obj tmpsrc action start
this test tests if count_by_type ( ) can assemble linkage from water network . : return :,def test_count_by_type_multiple_link self grofile Test gro file 5 1ALA N 1 0 000 0 000 0 000 1ALA H 2 0 100 0 000 0 000 2SOL OW 3 0 300 0 000 0 000 2SOL HW2 4 0 400 0 000 0 000 4ALA O 5 0 600 0 000 0 000 1 0 1 0 1 0 u MDAnalysis Universe StringIO grofile format gro wb WaterBridgeAnalysis u protein and resid 1 protein and resid 4 wb _timeseries True wb timesteps 0 wb _water_network SOL 2 2 0 SOL 2 HW1 ALA 1 O 2 0 179 99998 1 2 ALA 1 H SOL 2 OW 2 0 179 99998 3 4 SOL 2 HW2 ALA 4 O 2 0 179 99998 3 2 ALA 4 H SOL 2 OW 2 0 179 99998 result 0 3 ALA 1 O ALA 4 H 1 0 0 4 ALA 1 O ALA 4 O 1 0 1 3 ALA 1 H ALA 4 H 1 0 1 4 ALA 1 H ALA 4 O 1 0 assert_equal sorted wb count_by_type tolist result
returns monitor .dat file info structured as a python dict,def get_monitor mon_file is_header lambda line line startswith header_lines filter is_header open mon_file readlines file_struct_str for j in range 0 len header_lines Line header_lines j Line Line 2 len Line strip Line Line split Field Line 0 Value Value string join string join Line 1 len Line split file_struct_str file_struct_str Field Value if j len header_lines 1 file_struct_str file_struct_str file_struct_str file_struct_str file_struct eval file_struct_str file_struct data numpy loadtxt mon_file file_struct fullpath mon_file file_struct file os path basename mon_file print Loading mon_file return file_struct
: param salt : salt for crypt ( optional ) : type salt : str,def __init__ self salt None Transformer __init__ self self _salt salt
generate a list of broadcast axes for ngraph++ broadcast .,def get_broadcast_axes output_shape input_shape axis None axes_indexes list range 0 len output_shape if axis is None output_begin len output_shape len input_shape else output_begin axis right_axes_indexes list range output_begin output_begin len input_shape for index in reversed right_axes_indexes del axes_indexes index return AxisSet set axes_indexes
returns the code for the knapsack function,def get_code return inspect getsource knapsack
customized method to delete an user . ensures that a respective user projector element is disabled .,def delete self skip_autoupdate False args kwargs Projector remove_any skip_autoupdate skip_autoupdate name users user id self pk return super delete skip_autoupdate skip_autoupdate args kwargs
"recursively merge or update dict - like objects . > > > update({'k1 ' : 1 } , { ' k1 ' : { ' k2 ' : { ' k3 ' : 3 } } } )",def update_dict base head for key value in head items if key in base if isinstance base collections Mapping if isinstance value collections Mapping base key update_dict base get key value else base key head key else base key head key return base
get information about the operating system .,routes route software methods GET def software_info self request cors config_cors request request setHeader Content Type application json data dict data biosVendor self biosVendor data biosVersion self biosVersion data biosDate self biosDate data kernelVersion self kernelVersion data osVersion self osVersion data pdVersion self pdVersion data uptime self uptime return json dumps data
"set bounds on the parameter . for parameters of ordered kind , ` set_bound((none , 0 ) ) ` means that the lower bound is unchanged while the upper bound is reset to zero . for parameters of unordered kind , ` set_bound ` simply reassigns the list of feasible values .",def set_bound self bound if self is_categorical self bound bound else if self bound is None self bound None None if bound 0 is not None self bound 0 bound 0 if bound 1 is not None self bound 1 bound 1 return
create a filter and assign it some permissions .,tier1 def test_positive_create_with_permission self filter_ entities Filter permission self ct_perms create self assertListEqual perm id for perm in filter_ permission perm id for perm in self ct_perms
attempt to create user group with a name of already existent entity .,tier1 def test_negative_create_with_same_name self user_group entities UserGroup create with self assertRaises HTTPError entities UserGroup name user_group name create
prove that the created event has expected attributes .,mock patch requests post def test_attrs_of_created_lock_event self request_mock self client get self url2 self assertEqual Event objects first lock_id str self lock pk self assertEqual Event objects first action lock self assertEqual Event objects first mtype manual self assertEqual Event objects first status failed self assertEqual Event objects first serial str self lock serial
maps an algorithm over a collection .,def map self algorithm opt_dropNulls None element_type self elementType with_cast lambda e algorithm element_type e return self _cast apifunction ApiFunction call_ Collection map self with_cast opt_dropNulls
check the sms table for outgoing message and compare those to the message vumi sent to the mnos .,def audit_outgoing_sms time_threshold now timedelta hours 24 outgoing SMS objects filter is_audited False direction OUTGOING creation_date__lt time_threshold exclude uuid None exclude carrier__name settings HTTPTESTER_BACKEND discrepancies for outgoing_sms in outgoing trail SMSTrail sms outgoing_sms entries VumiLog objects filter uuid outgoing_sms uuid if entries entries update is_audited True vumi_log entries 0 else vumi_log None trail vumi vumi_log trail save if not trail vumi discrepancies append Discrepancy objects create trail trail outgoing update is_audited True return discrepancies
