idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
1,500
def _register_template ( cls , template_bytes ) : # This implementation won't work if there are nested templates, but # we can't do that anyways due to PyGObject limitations so it's ok if not hasattr ( cls , 'set_template' ) : raise TypeError ( "Requires PyGObject 3.13.2 or greater" ) cls . set_template ( template_byte...
Registers the template for the widget and hooks init_template
344
12
1,501
def _init_template ( self , cls , base_init_template ) : # TODO: could disallow using a metaclass.. but this is good enough # .. if you disagree, feel free to fix it and issue a PR :) if self . __class__ is not cls : raise TypeError ( "Inheritance from classes with @GtkTemplate decorators " "is not allowed at this time...
This would be better as an override for Gtk . Widget
347
13
1,502
def extract_haml ( fileobj , keywords , comment_tags , options ) : import haml from mako import lexer , parsetree from mako . ext . babelplugin import extract_nodes encoding = options . get ( 'input_encoding' , options . get ( 'encoding' , None ) ) template_node = lexer . Lexer ( haml . preprocessor ( fileobj . read ( ...
babel translation token extract function for haml files
134
10
1,503
def get_single_allele_from_reads ( allele_reads ) : allele_reads = list ( allele_reads ) if len ( allele_reads ) == 0 : raise ValueError ( "Expected non-empty list of AlleleRead objects" ) seq = allele_reads [ 0 ] . allele if any ( read . allele != seq for read in allele_reads ) : raise ValueError ( "Expected all Allel...
Given a sequence of AlleleRead objects which are expected to all have the same allele return that allele .
118
22
1,504
def iter_all_children ( self ) : if self . inline_child : yield self . inline_child for x in self . children : yield x
Return an iterator that yields every node which is a child of this one .
32
15
1,505
def initialize ( self , * * kwargs ) : if not set ( kwargs . keys ( ) ) . issuperset ( self . init_keys ) : raise Exception ( "TransferFn needs to be initialized with %s" % ',' . join ( repr ( el ) for el in self . init_keys ) )
Transfer functions may need additional information before the supplied numpy array can be modified in place . For instance transfer functions may have state which needs to be allocated in memory with a certain size . In other cases the transfer function may need to know about the coordinate system associated with the i...
72
57
1,506
def override_plasticity_state ( self , new_plasticity_state ) : self . _plasticity_setting_stack . append ( self . plastic ) self . plastic = new_plasticity_state
Temporarily disable plasticity of internal state .
48
10
1,507
def register_host ( ) : pyblish . api . register_host ( "hython" ) pyblish . api . register_host ( "hpython" ) pyblish . api . register_host ( "houdini" )
Register supported hosts
53
3
1,508
def maintained_selection ( ) : previous_selection = hou . selectedNodes ( ) try : yield finally : if previous_selection : for node in previous_selection : node . setSelected ( on = True ) else : for node in previous_selection : node . setSelected ( on = False )
Maintain selection during context
65
5
1,509
def execute_transaction ( conn , statements : Iterable ) : with conn : with conn . cursor ( ) as cursor : for statement in statements : cursor . execute ( statement ) conn . commit ( )
Execute several statements in single DB transaction .
42
9
1,510
def execute_transactions ( conn , statements : Iterable ) : with conn . cursor ( ) as cursor : for statement in statements : try : cursor . execute ( statement ) conn . commit ( ) except psycopg2 . ProgrammingError : conn . rollback ( )
Execute several statements each as a single DB transaction .
56
11
1,511
def execute_closing_transaction ( statements : Iterable ) : with closing ( connect ( ) ) as conn : with conn . cursor ( ) as cursor : for statement in statements : cursor . execute ( statement )
Open a connection commit a transaction and close it .
45
10
1,512
def select ( conn , query : str , params = None , name = None , itersize = 5000 ) : with conn . cursor ( name , cursor_factory = NamedTupleCursor ) as cursor : cursor . itersize = itersize cursor . execute ( query , params ) for result in cursor : yield result
Return a select statement s results as a namedtuple .
69
12
1,513
def select_dict ( conn , query : str , params = None , name = None , itersize = 5000 ) : with conn . cursor ( name , cursor_factory = RealDictCursor ) as cursor : cursor . itersize = itersize cursor . execute ( query , params ) for result in cursor : yield result
Return a select statement s results as dictionary .
71
9
1,514
def select_each ( conn , query : str , parameter_groups , name = None ) : with conn : with conn . cursor ( name = name ) as cursor : for parameters in parameter_groups : cursor . execute ( query , parameters ) yield cursor . fetchone ( )
Run select query for each parameter set in single transaction .
57
11
1,515
def query_columns ( conn , query , name = None ) : with conn . cursor ( name ) as cursor : cursor . itersize = 1 cursor . execute ( query ) cursor . fetchmany ( 0 ) column_names = [ column . name for column in cursor . description ] return column_names
Lightweight query to retrieve column list of select query .
64
11
1,516
def from_variant_and_transcript ( cls , variant , transcript , context_size ) : if not transcript . contains_start_codon : logger . info ( "Expected transcript %s for variant %s to have start codon" , transcript . name , variant ) return None if not transcript . contains_stop_codon : logger . info ( "Expected transcrip...
Extracts the reference sequence around a variant locus on a particular transcript and determines the reading frame at the start of that sequence context .
244
28
1,517
def create_readme_with_long_description ( ) : this_dir = os . path . abspath ( os . path . dirname ( __file__ ) ) readme_md = os . path . join ( this_dir , 'README.md' ) readme = os . path . join ( this_dir , 'README' ) if os . path . exists ( readme_md ) : # this is the case when running `python setup.py sdist` if os ...
Try to convert content of README . md into rst format using pypandoc write it into README and return it .
271
27
1,518
def stat ( package , graph ) : client = requests . Session ( ) for name_or_url in package : package = get_package ( name_or_url , client ) if not package : secho ( u'Invalid name or URL: "{name}"' . format ( name = name_or_url ) , fg = 'red' , file = sys . stderr ) continue try : version_downloads = package . version_d...
Print download statistics for a package .
426
7
1,519
def browse ( package , homepage ) : p = Package ( package ) try : if homepage : secho ( u'Opening homepage for "{0}"...' . format ( package ) , bold = True ) url = p . home_page else : secho ( u'Opening PyPI page for "{0}"...' . format ( package ) , bold = True ) url = p . package_url except NotFoundError : abort_not_f...
Browse to a package s PyPI or project homepage .
102
12
1,520
def search ( query , n_results , web ) : if web : secho ( u'Opening search page for "{0}"...' . format ( query ) , bold = True ) url = SEARCH_URL . format ( query = urlquote ( query ) ) click . launch ( url ) else : searcher = Searcher ( ) results = searcher . search ( query , n = n_results ) first_line = style ( u'Sea...
Search for a pypi package .
145
8
1,521
def info ( package , long_description , classifiers , license ) : client = requests . Session ( ) for name_or_url in package : package = get_package ( name_or_url , client ) if not package : secho ( u'Invalid name or URL: "{name}"' . format ( name = name_or_url ) , fg = 'red' , file = sys . stderr ) continue # Name and...
Get info about a package or packages .
671
8
1,522
def bargraph ( data , max_key_width = 30 ) : lines = [ ] max_length = min ( max ( len ( key ) for key in data . keys ( ) ) , max_key_width ) max_val = max ( data . values ( ) ) max_val_length = max ( len ( _style_value ( val ) ) for val in data . values ( ) ) term_width = get_terminal_size ( ) [ 0 ] max_bar_width = ter...
Return a bar graph as a string given a dictionary of data .
264
13
1,523
def max_version ( self ) : data = self . version_downloads if not data : return None , 0 return max ( data . items ( ) , key = lambda item : item [ 1 ] )
Version with the most downloads .
43
6
1,524
def min_version ( self ) : data = self . version_downloads if not data : return ( None , 0 ) return min ( data . items ( ) , key = lambda item : item [ 1 ] )
Version with the fewest downloads .
45
7
1,525
def ripping_of_cds ( ) : # install and configure ripit install_package ( 'ripit' ) install_file_legacy ( path = '~/.ripit/config' , username = env . user ) # install burnit run ( 'mkdir -p ~/bin' ) install_file_legacy ( '~/bin/burnit' ) run ( 'chmod 755 ~/bin/burnit' )
Install the tools ripit and burnit in order to rip and burn audio cds .
94
18
1,526
def i3 ( ) : install_package ( 'i3' ) install_file_legacy ( path = '~/.i3/config' , username = env . user , repos_dir = 'repos' ) # setup: hide the mouse if not in use # in ~/.i3/config: 'exec /home/<USERNAME>/repos/hhpc/hhpc -i 10 &' install_packages ( [ 'make' , 'pkg-config' , 'gcc' , 'libc6-dev' , 'libx11-dev' ] ) c...
Install and customize the tiling window manager i3 .
171
11
1,527
def solarized ( ) : install_packages ( [ 'rxvt-unicode' , 'tmux' , 'vim' ] ) install_file_legacy ( '~/.Xresources' ) if env . host_string == 'localhost' : run ( 'xrdb ~/.Xresources' ) # install and call term_colors run ( 'mkdir -p ~/bin' ) install_file_legacy ( '~/bin/term_colors' ) run ( 'chmod 755 ~/bin/term_colors' ...
Set solarized colors in urxvt tmux and vim .
131
14
1,528
def vim ( ) : install_package ( 'vim' ) print_msg ( '## install ~/.vimrc\n' ) install_file_legacy ( '~/.vimrc' ) print_msg ( '\n## set up pathogen\n' ) run ( 'mkdir -p ~/.vim/autoload ~/.vim/bundle' ) checkup_git_repo_legacy ( url = 'https://github.com/tpope/vim-pathogen.git' ) run ( 'ln -snf ~/repos/vim-pathogen/autol...
Customize vim install package manager pathogen and some vim - packages .
369
14
1,529
def pyenv ( ) : install_packages ( [ 'make' , 'build-essential' , 'libssl-dev' , 'zlib1g-dev' , 'libbz2-dev' , 'libreadline-dev' , 'libsqlite3-dev' , 'wget' , 'curl' , 'llvm' , 'libncurses5-dev' , 'libncursesw5-dev' , ] ) if exists ( '~/.pyenv' ) : run ( 'cd ~/.pyenv && git pull' ) run ( '~/.pyenv/bin/pyenv update' ) e...
Install or update the pyenv python environment .
352
9
1,530
def virtualbox_host ( ) : if query_yes_no ( question = 'Uninstall virtualbox-dkms?' , default = 'yes' ) : run ( 'sudo apt-get remove virtualbox-dkms' ) install_packages ( [ 'virtualbox' , 'virtualbox-qt' , 'virtualbox-dkms' , 'virtualbox-guest-dkms' , 'virtualbox-guest-additions-iso' , ] ) users = [ env . user ] for us...
Install a VirtualBox host system .
129
7
1,531
def pencil2 ( ) : repo_name = 'pencil2' repo_dir = flo ( '~/repos/{repo_name}' ) print_msg ( '## fetch latest pencil\n' ) checkup_git_repo_legacy ( url = 'https://github.com/prikhi/pencil.git' , name = repo_name ) print_msg ( '\n## build properties\n' ) update_or_append_line ( flo ( '{repo_dir}/build/properties.sh' ) ,...
Install or update latest Pencil version 2 a GUI prototyping tool .
256
14
1,532
def pencil3 ( ) : repo_name = 'pencil3' repo_dir = flo ( '~/repos/{repo_name}' ) print_msg ( '## fetch latest pencil\n' ) checkup_git_repo_legacy ( url = 'https://github.com/evolus/pencil.git' , name = repo_name ) run ( flo ( 'cd {repo_dir} && npm install' ) , msg = '\n## install npms\n' ) install_user_command_legacy (...
Install or update latest Pencil version 3 a GUI prototyping tool .
168
14
1,533
def powerline_shell ( ) : assert env . host == 'localhost' , 'This task cannot run on a remote host' # set up fonts for powerline checkup_git_repo_legacy ( 'https://github.com/powerline/fonts.git' , name = 'powerline-fonts' ) run ( 'cd ~/repos/powerline-fonts && ./install.sh' ) # run('fc-cache -vf ~/.local/share/fonts'...
Install and set up powerline - shell prompt .
545
10
1,534
def _init_boto3_clients ( self , profile , region ) : try : session = None if profile and region : session = boto3 . session . Session ( profile_name = profile , region_name = region ) elif profile : session = boto3 . session . Session ( profile_name = profile ) elif region : session = boto3 . session . Session ( regio...
The utililty requires boto3 clients to CloudFormation .
142
13
1,535
def determine_drift ( self ) : try : response = self . _cloud_formation . detect_stack_drift ( StackName = self . _stack_name ) drift_request_id = response . get ( 'StackDriftDetectionId' , None ) if drift_request_id : logging . info ( 'drift_request_id: %s - polling' , drift_request_id ) drift_calc_done = False while ...
Determine the drift of the stack .
335
9
1,536
def _print_drift_report ( self ) : try : response = self . _cloud_formation . describe_stack_resources ( StackName = self . _stack_name ) rows = [ ] for resource in response . get ( 'StackResources' , [ ] ) : row = [ ] row . append ( resource . get ( 'LogicalResourceId' , 'unknown' ) ) row . append ( resource . get ( '...
Report the drift of the stack .
224
7
1,537
def set_data ( self , data ) : if data is None : self . data_size = 0 self . data = None return self . data_size = len ( data ) # create a string buffer so that null bytes aren't interpreted # as the end of the string self . data = ctypes . cast ( ctypes . create_string_buffer ( data ) , ctypes . c_void_p )
Use this method to set the data for this blob
87
10
1,538
def get_data ( self ) : array = ctypes . POINTER ( ctypes . c_char * len ( self ) ) return ctypes . cast ( self . data , array ) . contents . raw
Get the data for this blob
44
6
1,539
def printMetaDataFor ( archive , location ) : desc = archive . getMetadataForLocation ( location ) if desc . isEmpty ( ) : print ( " no metadata for '{0}'" . format ( location ) ) return None print ( " metadata for '{0}':" . format ( location ) ) print ( " Created : {0}" . format ( desc . getCreated ( ) . getDateAsStri...
Prints metadata for given location .
213
7
1,540
def printArchive ( fileName ) : archive = CombineArchive ( ) if archive . initializeFromArchive ( fileName ) is None : print ( "Invalid Combine Archive" ) return None print ( '*' * 80 ) print ( 'Print archive:' , fileName ) print ( '*' * 80 ) printMetaDataFor ( archive , "." ) print ( "Num Entries: {0}" . format ( arch...
Prints content of combine archive
273
6
1,541
def mklink ( ) : from optparse import OptionParser parser = OptionParser ( usage = "usage: %prog [options] link target" ) parser . add_option ( '-d' , '--directory' , help = "Target is a directory (only necessary if not present)" , action = "store_true" ) options , args = parser . parse_args ( ) try : link , target = a...
Like cmd . exe s mklink except it will infer directory status of the target .
151
18
1,542
def is_reparse_point ( path ) : res = api . GetFileAttributes ( path ) return ( res != api . INVALID_FILE_ATTRIBUTES and bool ( res & api . FILE_ATTRIBUTE_REPARSE_POINT ) )
Determine if the given path is a reparse point . Return False if the file does not exist or the file attributes cannot be determined .
60
29
1,543
def is_symlink ( path ) : path = _patch_path ( path ) try : return _is_symlink ( next ( find_files ( path ) ) ) # comment below workaround for PyCQA/pyflakes#376 except WindowsError as orig_error : # noqa: F841 tmpl = "Error accessing {path}: {orig_error.message}" raise builtins . WindowsError ( tmpl . format ( * * loc...
Assuming path is a reparse point determine if it s a symlink .
106
16
1,544
def get_final_path ( path ) : desired_access = api . NULL share_mode = ( api . FILE_SHARE_READ | api . FILE_SHARE_WRITE | api . FILE_SHARE_DELETE ) security_attributes = api . LPSECURITY_ATTRIBUTES ( ) # NULL pointer hFile = api . CreateFile ( path , desired_access , share_mode , security_attributes , api . OPEN_EXISTI...
r For a given path determine the ultimate location of that path . Useful for resolving symlink targets . This functions wraps the GetFinalPathNameByHandle from the Windows SDK .
276
36
1,545
def join ( * paths ) : paths_with_drives = map ( os . path . splitdrive , paths ) drives , paths = zip ( * paths_with_drives ) # the drive we care about is the last one in the list drive = next ( filter ( None , reversed ( drives ) ) , '' ) return os . path . join ( drive , os . path . join ( * paths ) )
r Wrapper around os . path . join that works with Windows drive letters .
87
16
1,546
def resolve_path ( target , start = os . path . curdir ) : return os . path . normpath ( join ( start , target ) )
r Find a path from start to target where target is relative to start .
32
15
1,547
def trace_symlink_target ( link ) : if not is_symlink ( link ) : raise ValueError ( "link must point to a symlink on the system" ) while is_symlink ( link ) : orig = os . path . dirname ( link ) link = readlink ( link ) link = resolve_path ( link , orig ) return link
Given a file that is known to be a symlink trace it to its ultimate target .
81
19
1,548
def patch_os_module ( ) : if not hasattr ( os , 'symlink' ) : os . symlink = symlink os . path . islink = islink if not hasattr ( os , 'readlink' ) : os . readlink = readlink
jaraco . windows provides the os . symlink and os . readlink functions . Monkey - patch the os module to include them if not present .
61
31
1,549
def task ( func , * args , * * kwargs ) : prefix = '\n# ' tail = '\n' return fabric . api . task ( print_full_name ( color = magenta , prefix = prefix , tail = tail ) ( print_doc1 ( func ) ) , * args , * * kwargs )
Composition of decorator functions for inherent self - documentation on task execution .
73
15
1,550
def subtask ( * args , * * kwargs ) : depth = kwargs . get ( 'depth' , 2 ) prefix = kwargs . get ( 'prefix' , '\n' + '#' * depth + ' ' ) tail = kwargs . get ( 'tail' , '\n' ) doc1 = kwargs . get ( 'doc1' , False ) color = kwargs . get ( 'color' , cyan ) def real_decorator ( func ) : if doc1 : return print_full_name ( c...
Decorator which prints out the name of the decorated function on execution .
210
15
1,551
def _is_sudoer ( what_for = '' ) : if env . get ( 'nosudo' , None ) is None : if what_for : print ( yellow ( what_for ) ) with quiet ( ) : # possible outputs: # en: "Sorry, user winhost-tester may not run sudo on <hostname>" # en: "sudo: a password is required" (=> is sudoer) # de: "sudo: Ein Passwort ist notwendig" (=...
Return True if current user is a sudoer else False .
175
12
1,552
def install_packages ( packages , what_for = 'for a complete setup to work properly' ) : res = True non_installed_packages = _non_installed ( packages ) packages_str = ' ' . join ( non_installed_packages ) if non_installed_packages : with quiet ( ) : dpkg = _has_dpkg ( ) hint = ' (You may have to install them manually)...
Try to install . deb packages given by list .
344
10
1,553
def checkup_git_repos_legacy ( repos , base_dir = '~/repos' , verbose = False , prefix = '' , postfix = '' ) : run ( flo ( 'mkdir -p {base_dir}' ) ) for repo in repos : cur_base_dir = repo . get ( 'base_dir' , base_dir ) checkup_git_repo_legacy ( url = repo [ 'url' ] , name = repo . get ( 'name' , None ) , base_dir = c...
Checkout or update git repos .
143
8
1,554
def checkup_git_repo_legacy ( url , name = None , base_dir = '~/repos' , verbose = False , prefix = '' , postfix = '' ) : if not name : match = re . match ( r'.*/(.+)\.git' , url ) assert match , flo ( "Unable to extract repo name from '{url}'" ) name = match . group ( 1 ) assert name is not None , flo ( 'Cannot extrac...
Checkout or update a git repo .
304
8
1,555
def install_file_legacy ( path , sudo = False , from_path = None , * * substitutions ) : # source paths 'from_custom' and 'from_common' from_path = from_path or path # remove beginning '/' (if any), eg '/foo/bar' -> 'foo/bar' from_tail = join ( 'files' , from_path . lstrip ( os . sep ) ) if from_path . startswith ( '~/...
Install file with path on the host target .
467
9
1,556
def install_user_command_legacy ( command , * * substitutions ) : path = flo ( '~/bin/{command}' ) install_file_legacy ( path , * * substitutions ) run ( flo ( 'chmod 755 {path}' ) )
Install command executable file into users bin dir .
61
9
1,557
def _line_2_pair ( line ) : key , val = line . split ( '=' ) return key . lower ( ) , val . strip ( '"' )
Return bash variable declaration as name - value pair .
36
10
1,558
def extract_minors_from_setup_py ( filename_setup_py ) : # eg: minors_str = '2.6\n2.7\n3.3\n3.4\n3.5\n3.6' minors_str = fabric . api . local ( flo ( 'grep --perl-regexp --only-matching ' '"(?<=Programming Language :: Python :: )\\d+\\.\\d+" ' '{filename_setup_py}' ) , capture = True ) # eg: minors = ['2.6', '2.7', '3.3...
Extract supported python minor versions from setup . py and return them as a list of str .
167
19
1,559
def vim_janus ( uninstall = None ) : if uninstall is not None : uninstall_janus ( ) else : if not exists ( '~/.vim/janus' ) : print_msg ( 'not installed => install' ) install_janus ( ) else : print_msg ( 'already installed => update' ) update_janus ( ) customize_janus ( ) show_files_used_by_vim_and_janus ( )
Install or update Janus a distribution of addons and mappings for vim .
98
16
1,560
def scan ( host , port = 80 , url = None , https = False , timeout = 1 , max_size = 65535 ) : starts = OrderedDict ( ) ends = OrderedDict ( ) port = int ( port ) result = dict ( host = host , port = port , state = 'closed' , durations = OrderedDict ( ) ) if url : timeout = 1 result [ 'code' ] = None starts [ 'all' ] = ...
Scan a network port
629
4
1,561
def ping ( host , port = 80 , url = None , https = False , timeout = 1 , max_size = 65535 , sequence = 0 ) : try : result = scan ( host = host , port = port , url = url , https = https , timeout = timeout , max_size = max_size ) except ScanFailed as failure : result = failure . result result [ 'error' ] = True result [...
Ping a host
322
3
1,562
def delete ( stack , region , profile ) : ini_data = { } environment = { } environment [ 'stack_name' ] = stack if region : environment [ 'region' ] = region else : environment [ 'region' ] = find_myself ( ) if profile : environment [ 'profile' ] = profile ini_data [ 'environment' ] = environment if start_smash ( ini_d...
Delete the given CloudFormation stack .
105
8
1,563
def list ( region , profile ) : ini_data = { } environment = { } if region : environment [ 'region' ] = region else : environment [ 'region' ] = find_myself ( ) if profile : environment [ 'profile' ] = profile ini_data [ 'environment' ] = environment if start_list ( ini_data ) : sys . exit ( 0 ) else : sys . exit ( 1 )
List all the CloudFormation stacks in the given region .
92
12
1,564
def drift ( stack , region , profile ) : logging . debug ( 'finding drift - stack: {}' . format ( stack ) ) logging . debug ( 'region: {}' . format ( region ) ) logging . debug ( 'profile: {}' . format ( profile ) ) tool = DriftTool ( Stack = stack , Region = region , Profile = profile , Verbose = True ) if tool . dete...
Produce a CloudFormation drift report for the given stack .
104
13
1,565
def start_upsert ( ini_data ) : stack_driver = CloudStackUtility ( ini_data ) poll_stack = not ini_data . get ( 'no_poll' , False ) if stack_driver . upsert ( ) : logging . info ( 'stack create/update was started successfully.' ) if poll_stack : stack_tool = None try : profile = ini_data . get ( 'environment' , { } ) ....
Helper function to facilitate upsert .
438
7
1,566
def read_config_info ( ini_file ) : try : config = RawConfigParser ( ) config . optionxform = lambda option : option config . read ( ini_file ) the_stuff = { } for section in config . sections ( ) : the_stuff [ section ] = { } for option in config . options ( section ) : the_stuff [ section ] [ option ] = config . get ...
Read the INI file
147
5
1,567
def print_stack_info ( self ) : try : rest_api_id = None deployment_found = False response = self . _cf_client . describe_stack_resources ( StackName = self . _stack_name ) print ( '\nThe following resources were created:' ) rows = [ ] for resource in response [ 'StackResources' ] : if resource [ 'ResourceType' ] == 'A...
List resources from the given stack
357
6
1,568
def print_stack_events ( self ) : first_token = '7be7981bd6287dd8112305e8f3822a6f' keep_going = True next_token = first_token current_request_token = None rows = [ ] try : while keep_going and next_token : if next_token == first_token : response = self . _cf_client . describe_stack_events ( StackName = self . _stack_na...
List events from the given stack
387
6
1,569
def trac ( ) : hostname = re . sub ( r'^[^@]+@' , '' , env . host ) # without username if any sitename = query_input ( question = '\nEnter site-name of Your trac web service' , default = flo ( 'trac.{hostname}' ) ) username = env . user site_dir = flo ( '/home/{username}/sites/{sitename}' ) bin_dir = flo ( '{site_dir}/...
Set up or update a trac project .
326
9
1,570
async def query ( self , path , method = 'get' , * * params ) : if method in ( 'get' , 'post' , 'patch' , 'delete' , 'put' ) : full_path = self . host + path if method == 'get' : resp = await self . aio_sess . get ( full_path , params = params ) elif method == 'post' : resp = await self . aio_sess . post ( full_path , ...
Do a query to the System API
291
7
1,571
def revealjs ( basedir = None , title = None , subtitle = None , description = None , github_user = None , github_repo = None ) : basedir = basedir or query_input ( 'Base dir of the presentation?' , default = '~/repos/my_presi' ) revealjs_repo_name = 'reveal.js' revealjs_dir = flo ( '{basedir}/{revealjs_repo_name}' ) _...
Set up or update a reveals . js presentation with slides written in markdown .
382
16
1,572
def tweak_css ( repo_dir ) : print_msg ( "* don't capitalize titles (no uppercase headings)" ) files = [ 'beige.css' , 'black.css' , 'blood.css' , 'league.css' , 'moon.css' , 'night.css' , 'serif.css' , 'simple.css' , 'sky.css' , 'solarized.css' , 'white.css' , ] line = ' text-transform: uppercase;' for file_ in files ...
Comment out some css settings .
632
7
1,573
def decktape ( ) : run ( 'mkdir -p ~/bin/decktape' ) if not exists ( '~/bin/decktape/decktape-1.0.0' ) : print_msg ( '\n## download decktape 1.0.0\n' ) run ( 'cd ~/bin/decktape && ' 'curl -L https://github.com/astefanutti/decktape/archive/' 'v1.0.0.tar.gz | tar -xz --exclude phantomjs' ) run ( 'cd ~/bin/decktape/deckta...
Install DeckTape .
394
5
1,574
def revealjs_template ( ) : from config import basedir , github_user , github_repo run ( flo ( 'rm -f {basedir}/index.html' ) ) run ( flo ( 'rm -f {basedir}/slides.md' ) ) run ( flo ( 'rm -f {basedir}/README.md' ) ) run ( flo ( 'rm -rf {basedir}/img/' ) ) title = 'reveal.js template' subtitle = '[reveal.js][3] presenta...
Create or update the template presentation demo using task revealjs .
405
12
1,575
def spatialDomainNoGrid ( self ) : self . w = np . zeros ( self . xw . shape ) if self . Debug : print ( "w = " ) print ( self . w . shape ) for i in range ( len ( self . q ) ) : # More efficient if we have created some 0-load points # (e.g., for where we want output) if self . q [ i ] != 0 : dist = np . abs ( self . x...
Superposition of analytical solutions without a gridded domain
161
11
1,576
def build_diagonals ( self ) : ########################################################## # INCORPORATE BOUNDARY CONDITIONS INTO COEFFICIENT ARRAY # ########################################################## # Roll to keep the proper coefficients at the proper places in the # arrays: Python will naturally just do verti...
Builds the diagonals for the coefficient array
371
10
1,577
def createArchiveExample ( fileName ) : print ( '*' * 80 ) print ( 'Create archive' ) print ( '*' * 80 ) archive = CombineArchive ( ) archive . addFile ( fileName , # filename "./models/model.xml" , # target file name KnownFormats . lookupFormat ( "sbml" ) , # look up identifier for SBML models True # mark file as mast...
Creates Combine Archive containing the given file .
325
9
1,578
def calc_deviation ( values , average ) : size = len ( values ) if size < 2 : return 0 calc_sum = 0.0 for number in range ( 0 , size ) : calc_sum += math . sqrt ( ( values [ number ] - average ) ** 2 ) return math . sqrt ( ( 1.0 / ( size - 1 ) ) * ( calc_sum / size ) )
Calculate the standard deviation of a list of values
87
11
1,579
def append ( self , value ) : self . count += 1 if self . count == 1 : self . old_m = self . new_m = value self . old_s = 0 else : self . new_m = self . old_m + ( value - self . old_m ) / self . count self . new_s = self . old_s + ( value - self . old_m ) * ( value - self . new_m ) self . old_m = self . new_m self . ol...
Append a value to the stats list
120
8
1,580
def pipeline ( steps , initial = None ) : def apply ( result , step ) : return step ( result ) return reduce ( apply , steps , initial )
Chain results from a list of functions . Inverted reduce .
32
12
1,581
def add ( class_ , name , value , sep = ';' ) : values = class_ . get_values_list ( name , sep ) if value in values : return new_value = sep . join ( values + [ value ] ) winreg . SetValueEx ( class_ . key , name , 0 , winreg . REG_EXPAND_SZ , new_value ) class_ . notify ( )
Add a value to a delimited variable but only when the value isn t already present .
89
18
1,582
def current ( class_ ) : tzi = class_ ( ) kernel32 = ctypes . windll . kernel32 getter = kernel32 . GetTimeZoneInformation getter = getattr ( kernel32 , 'GetDynamicTimeZoneInformation' , getter ) code = getter ( ctypes . byref ( tzi ) ) return code , tzi
Windows Platform SDK GetTimeZoneInformation
75
7
1,583
def dynamic_info ( self ) : if self . key_name : dyn_key = self . get_key ( ) . subkey ( 'Dynamic DST' ) del dyn_key [ 'FirstEntry' ] del dyn_key [ 'LastEntry' ] years = map ( int , dyn_key . keys ( ) ) values = map ( Info , dyn_key . values ( ) ) # create a range mapping that searches by descending year and matches # ...
Return a map that for a given year will return the correct Info
135
13
1,584
def _locate_day ( year , cutoff ) : # MS stores Sunday as 0, Python datetime stores Monday as zero target_weekday = ( cutoff . day_of_week + 6 ) % 7 # For SYSTEMTIMEs relating to time zone inforamtion, cutoff.day # is the week of the month week_of_month = cutoff . day # so the following is the first day of that week da...
Takes a SYSTEMTIME object such as retrieved from a TIME_ZONE_INFORMATION structure or call to GetTimeZoneInformation and interprets it based on the given year to identify the actual day .
274
41
1,585
def redirect ( pattern , to , permanent = True , locale_prefix = True , anchor = None , name = None , query = None , vary = None , cache_timeout = 12 , decorators = None , re_flags = None , to_args = None , to_kwargs = None , prepend_locale = True , merge_query = False ) : if permanent : redirect_class = HttpResponsePe...
Return a url matcher suited for urlpatterns .
844
11
1,586
def __get_table_size ( self ) : length = ctypes . wintypes . DWORD ( ) res = self . method ( None , length , False ) if res != errors . ERROR_INSUFFICIENT_BUFFER : raise RuntimeError ( "Error getting table length (%d)" % res ) return length . value
Retrieve the size of the buffer needed by calling the method with a null pointer and length of zero . This should trigger an insufficient buffer error and return the size needed for the buffer .
71
37
1,587
def get_table ( self ) : buffer_length = self . __get_table_size ( ) returned_buffer_length = ctypes . wintypes . DWORD ( buffer_length ) buffer = ctypes . create_string_buffer ( buffer_length ) pointer_type = ctypes . POINTER ( self . structure ) table_p = ctypes . cast ( buffer , pointer_type ) res = self . method ( ...
Get the table
133
3
1,588
def entries ( self ) : table = self . get_table ( ) entries_array = self . row_structure * table . num_entries pointer_type = ctypes . POINTER ( entries_array ) return ctypes . cast ( table . entries , pointer_type ) . contents
Using the table structure return the array of entries based on the table size .
62
15
1,589
def owncloud ( ) : hostname = re . sub ( r'^[^@]+@' , '' , env . host ) # without username if any sitename = query_input ( question = '\nEnter site-name of Your Owncloud web service' , default = flo ( 'owncloud.{hostname}' ) , color = cyan ) username = env . user fabfile_data_dir = FABFILE_DATA_DIR print ( magenta ( ' ...
Set up owncloud .
850
5
1,590
def doctree_read_handler ( app , doctree ) : # noinspection PyProtectedMember docname = sys . _getframe ( 2 ) . f_locals [ 'docname' ] if docname . startswith ( '_partial' ) : app . env . metadata [ docname ] [ 'orphan' ] = True
Add orphan to metadata for partials
75
7
1,591
def autodoc_skip_member_handler ( app , what , name , obj , skip , options ) : if 'YAMLTokens' in name : return True return False
Skip un parseable functions .
38
6
1,592
def surfplot ( self , z , titletext ) : if self . latlon : plt . imshow ( z , extent = ( 0 , self . dx * z . shape [ 0 ] , self . dy * z . shape [ 1 ] , 0 ) ) #,interpolation='nearest' plt . xlabel ( 'longitude [deg E]' , fontsize = 12 , fontweight = 'bold' ) plt . ylabel ( 'latitude [deg N]' , fontsize = 12 , fontweig...
Plot if you want to - for troubleshooting - 1 figure
240
12
1,593
def twoSurfplots ( self ) : # Could more elegantly just call surfplot twice # And also could include xyzinterp as an option inside surfplot. # Noted here in case anyone wants to take that on in the future... plt . subplot ( 211 ) plt . title ( 'Load thickness, mantle equivalent [m]' , fontsize = 16 ) if self . latlon :...
Plot multiple subplot figure for 2D array
550
9
1,594
def outputDeflections ( self ) : try : # If wOutFile exists, has already been set by a setter self . wOutFile if self . Verbose : print ( "Output filename provided." ) # Otherwise, it needs to be set by an configuration file except : try : self . wOutFile = self . configGet ( "string" , "output" , "DeflectionOut" , opt...
Outputs a grid of deflections if an output directory is defined in the configuration file If the filename given in the configuration file ends in . npy then a binary numpy grid will be exported . Otherwise an ASCII grid will be exported .
252
48
1,595
def TeArraySizeCheck ( self ) : # Only if they are both defined and are arrays # Both being arrays is a possible bug in this check routine that I have # intentionally introduced if type ( self . Te ) == np . ndarray and type ( self . qs ) == np . ndarray : # Doesn't touch non-arrays or 1D arrays if type ( self . Te ) i...
Checks that Te and q0 array sizes are compatible For finite difference solution .
160
16
1,596
def FD ( self ) : if self . Verbose : print ( "Finite Difference Solution Technique" ) # Used to check for coeff_matrix here, but now doing so in self.bc_check() # called by f1d and f2d at the start # # Define a stress-based qs = q0 # But only if the latter has not already been defined # (e.g., by the getters and sette...
Set - up for the finite difference solution method
866
9
1,597
def SAS ( self ) : if self . x is None : self . x = np . arange ( self . dx / 2. , self . dx * self . qs . shape [ 0 ] , self . dx ) if self . filename : # Define the (scalar) elastic thickness self . Te = self . configGet ( "float" , "input" , "ElasticThickness" ) # Define a stress-based qs = q0 self . qs = self . q0 ...
Set - up for the rectangularly - gridded superposition of analytical solutions method for solving flexure
314
21
1,598
def _c3_mro ( cls , abcs = None ) : for i , base in enumerate ( reversed ( cls . __bases__ ) ) : if hasattr ( base , '__abstractmethods__' ) : boundary = len ( cls . __bases__ ) - i break # Bases up to the last explicit ABC are considered first. else : boundary = 0 abcs = list ( abcs ) if abcs else [ ] explicit_bases =...
Computes the method resolution order using extended C3 linearization .
393
13
1,599
def singledispatch ( function ) : # noqa registry = { } dispatch_cache = WeakKeyDictionary ( ) def ns ( ) : pass ns . cache_token = None # noinspection PyIncorrectDocstring def dispatch ( cls ) : """generic_func.dispatch(cls) -> <function implementation> Runs the dispatch algorithm to return the best available implemen...
Single - dispatch generic function decorator .
400
8