idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
20,600 | def create_pool ( batch_service_client , pool_id , resource_files , publisher , offer , sku , task_file , vm_size , node_count ) : _log . info ( 'Creating pool [{}]...' . format ( pool_id ) ) # Create a new pool of Linux compute nodes using an Azure Virtual Machines # Marketplace image. For more information about creating pools of Linux # nodes, see: # https://azure.microsoft.com/documentation/articles/batch-linux-nodes/ # Specify the commands for the pool's start task. The start task is run # on each node as it joins the pool, and when it's rebooted or re-imaged. # We use the start task to prep the node for running our task script. task_commands = [ # Copy the python_tutorial_task.py script to the "shared" directory # that all tasks that run on the node have access to. Note that # we are using the -p flag with cp to preserve the file uid/gid, # otherwise since this start task is run as an admin, it would not # be accessible by tasks run as a non-admin user. 'cp -p {} $AZ_BATCH_NODE_SHARED_DIR' . format ( os . path . basename ( task_file ) ) , # Install pip 'curl -fSsL https://bootstrap.pypa.io/get-pip.py | python' , # Install the azure-storage module so that the task script can access # Azure Blob storage, pre-cryptography version 'pip install azure-storage==0.32.0' , # Install E-Cell 4 'pip install https://1028-6348303-gh.circle-artifacts.com/0/root/circle/wheelhouse/ecell-4.1.2-cp27-cp27mu-manylinux1_x86_64.whl' ] # Get the node agent SKU and image reference for the virtual machine # configuration. # For more information about the virtual machine configuration, see: # https://azure.microsoft.com/documentation/articles/batch-linux-nodes/ sku_to_use , image_ref_to_use = select_latest_verified_vm_image_with_node_agent_sku ( batch_service_client , publisher , offer , sku ) user = batchmodels . AutoUserSpecification ( scope = batchmodels . AutoUserScope . pool , elevation_level = batchmodels . ElevationLevel . admin ) new_pool = batch . models . PoolAddParameter ( id = pool_id , virtual_machine_configuration = batchmodels . VirtualMachineConfiguration ( image_reference = image_ref_to_use , node_agent_sku_id = sku_to_use ) , vm_size = vm_size , target_dedicated_nodes = 0 , target_low_priority_nodes = node_count , start_task = batch . models . StartTask ( command_line = wrap_commands_in_shell ( 'linux' , task_commands ) , user_identity = batchmodels . UserIdentity ( auto_user = user ) , wait_for_success = True , resource_files = resource_files ) , ) try : batch_service_client . pool . add ( new_pool ) except batchmodels . BatchErrorException as err : print_batch_exception ( err ) raise | Creates a pool of compute nodes with the specified OS settings . | 765 | 13 |
20,601 | def create_job ( batch_service_client , job_id , pool_id ) : print ( 'Creating job [{}]...' . format ( job_id ) ) job = batch . models . JobAddParameter ( id = job_id , pool_info = batch . models . PoolInformation ( pool_id = pool_id ) ) try : batch_service_client . job . add ( job ) except batchmodels . batch_error . BatchErrorException as err : print_batch_exception ( err ) raise | Creates a job with the specified ID associated with the specified pool . | 114 | 14 |
20,602 | def add_tasks ( batch_service_client , job_id , loads , output_container_name , output_container_sas_token , task_file , acount_name ) : _log . info ( 'Adding {} tasks to job [{}]...' . format ( len ( loads ) , job_id ) ) # _log.info('Adding {} tasks to job [{}]...'.format(len(input_files), job_id)) tasks = list ( ) for ( input_file , output_file , i , j ) in loads : command = [ 'python $AZ_BATCH_NODE_SHARED_DIR/{} ' '--filepath {} --output {} --storageaccount {} ' '--task_id {} --job_id {} ' '--storagecontainer {} --sastoken "{}"' . format ( os . path . basename ( task_file ) , input_file . file_path , output_file , acount_name , i , j , output_container_name , output_container_sas_token ) ] _log . debug ( 'CMD : "{}"' . format ( command [ 0 ] ) ) tasks . append ( batch . models . TaskAddParameter ( id = 'topNtask{}-{}' . format ( i , j ) , command_line = command , resource_files = [ input_file ] ) ) batch_service_client . task . add_collection ( job_id , tasks ) task_ids = [ task . id for task in tasks ] _log . info ( '{} tasks were added.' . format ( len ( task_ids ) ) ) return task_ids | Adds a task for each input file in the collection to the specified job . | 364 | 15 |
20,603 | def wait_for_tasks_to_complete ( batch_service_client , job_ids , timeout ) : timeout_expiration = datetime . datetime . now ( ) + timeout print ( "Monitoring all tasks for 'Completed' state, timeout in {}..." . format ( timeout ) , end = '' ) while datetime . datetime . now ( ) < timeout_expiration : print ( '.' , end = '' ) sys . stdout . flush ( ) # tasks = batch_service_client.task.list(job_id) # incomplete_tasks = [task for task in tasks if # task.state != batchmodels.TaskState.completed] for ( job_id , _ ) in job_ids : tasks = batch_service_client . task . list ( job_id ) incomplete_tasks = [ task for task in tasks if task . state != batchmodels . TaskState . completed ] if incomplete_tasks : break if not incomplete_tasks : print ( ) return True else : time . sleep ( 1 ) raise RuntimeError ( "ERROR: Tasks did not reach 'Completed' state within " "timeout period of " + str ( timeout ) ) | Returns when all tasks in the specified job reach the Completed state . | 254 | 13 |
20,604 | def download_blobs_from_container ( block_blob_client , container_name , directory_path , prefix = None ) : _log . info ( 'Downloading all files from container [{}]...' . format ( container_name ) ) container_blobs = block_blob_client . list_blobs ( container_name , prefix = None ) _log . info ( '{} blobs are found [{}]' . format ( len ( tuple ( container_blobs ) ) , ', ' . join ( blob . name for blob in container_blobs . items ) ) ) for blob in container_blobs . items : destination_file_path = os . path . join ( directory_path , blob . name ) block_blob_client . get_blob_to_path ( container_name , blob . name , destination_file_path ) _log . info ( ' Downloaded blob [{}] from container [{}] to {}' . format ( blob . name , container_name , destination_file_path ) ) _log . info ( ' Download complete!' ) | Downloads all blobs from the specified Azure Blob storage container . | 241 | 14 |
20,605 | def singlerun ( job , task_id = 0 , job_id = 0 ) : import ecell4_base import ecell4 import ecell4 . util . simulation import ecell4 . util . decorator print ( 'ecell4_base.__version__ = {:s}' . format ( ecell4_base . __version__ ) ) print ( 'ecell4.__version__ = {:s}' . format ( ecell4 . __version__ ) ) print ( 'job={}, task_id={}, job_id={}' . format ( str ( job ) , task_id , job_id ) ) with ecell4 . util . decorator . reaction_rules ( ) : A + B == C | ( 0.01 , 0.3 ) res = ecell4 . util . simulation . run_simulation ( 1.0 , y0 = { 'A' : job [ 0 ] , 'B' : job [ 1 ] , 'C' : job [ 2 ] } , rndseed = job_id , solver = 'gillespie' , return_type = 'array' ) print ( 'A simulation was successfully done.' ) return res | This task is for an example . | 258 | 7 |
20,606 | def plot_number_observer ( * args , * * kwargs ) : interactive = kwargs . pop ( 'interactive' , False ) if interactive : plot_number_observer_with_nya ( * args , * * kwargs ) # elif __on_ipython_notebook(): # kwargs['to_png'] = True # plot_number_observer_with_nya(*args, **kwargs) else : if kwargs . pop ( 'to_png' , None ) is not None : #XXX: Remove an option available only on nyaplot for the consistency import warnings warnings . warn ( "An option 'to_png' is not available with matplotlib. Just ignored." ) plot_number_observer_with_matplotlib ( * args , * * kwargs ) | Generate a plot from NumberObservers and show it . See plot_number_observer_with_matplotlib and _with_nya for details . | 183 | 35 |
20,607 | def plot_world ( * args , * * kwargs ) : interactive = kwargs . pop ( 'interactive' , True ) if interactive : plot_world_with_elegans ( * args , * * kwargs ) else : plot_world_with_matplotlib ( * args , * * kwargs ) | Generate a plot from received instance of World and show it . See also plot_world_with_elegans and plot_world_with_matplotlib . | 73 | 35 |
20,608 | def plot_movie ( * args , * * kwargs ) : interactive = kwargs . pop ( 'interactive' , False ) if interactive : plot_movie_with_elegans ( * args , * * kwargs ) else : plot_movie_with_matplotlib ( * args , * * kwargs ) | Generate a movie from received instances of World and show them . See also plot_movie_with_elegans and plot_movie_with_matplotlib . | 73 | 35 |
20,609 | def plot_trajectory ( * args , * * kwargs ) : interactive = kwargs . pop ( 'interactive' , True ) if interactive : plot_trajectory_with_elegans ( * args , * * kwargs ) else : plot_trajectory_with_matplotlib ( * args , * * kwargs ) | Generate a plot from received instance of TrajectoryObserver and show it See also plot_trajectory_with_elegans and plot_trajectory_with_matplotlib . | 79 | 42 |
20,610 | def plot_movie_with_elegans ( worlds , radius = None , width = 500 , height = 500 , config = None , grid = False , species_list = None ) : config = config or { } from IPython . core . display import display , HTML from jinja2 import Template data = { } sizes = { } for i , world in enumerate ( worlds ) : species = __parse_world ( world , radius , species_list ) for species_info in species : if data . get ( species_info [ 'name' ] ) is None : data [ species_info [ 'name' ] ] = [ ] data [ species_info [ 'name' ] ] . append ( { 'df' : species_info [ 'data' ] , 't' : i } ) sizes [ species_info [ 'name' ] ] = species_info [ 'size' ] options = { 'player' : True , 'autorange' : False , 'space_mode' : 'wireframe' , 'grid' : grid , 'range' : __get_range_of_world ( worlds [ 0 ] ) } model_id = '"movie' + str ( uuid . uuid4 ( ) ) + '"' color_scale = default_color_scale ( config = config ) display ( HTML ( generate_html ( { 'model_id' : model_id , 'names' : json . dumps ( list ( data . keys ( ) ) ) , 'data' : json . dumps ( list ( data . values ( ) ) ) , 'colors' : json . dumps ( [ color_scale . get_color ( name ) for name in data . keys ( ) ] ) , 'sizes' : json . dumps ( [ sizes [ name ] for name in data . keys ( ) ] ) , 'options' : json . dumps ( options ) } , 'templates/movie.tmpl' ) ) ) | Generate a movie from received instances of World and show them on IPython notebook . | 415 | 17 |
20,611 | def plot_world_with_elegans ( world , radius = None , width = 350 , height = 350 , config = None , grid = True , wireframe = False , species_list = None , debug = None , max_count = 1000 , camera_position = ( - 22 , 23 , 32 ) , camera_rotation = ( - 0.6 , 0.5 , 0.6 ) , return_id = False , predicator = None ) : config = config or { } from IPython . core . display import display , HTML from . simulation import load_world if isinstance ( world , str ) : world = load_world ( world ) species = __parse_world ( world , radius , species_list , max_count , predicator ) color_scale = default_color_scale ( config = config ) plots = [ ] for species_info in species : plots . append ( { 'type' : 'Particles' , 'data' : species_info [ 'data' ] , 'options' : { 'name' : species_info [ 'name' ] , 'color' : color_scale . get_color ( species_info [ 'name' ] ) , 'size' : species_info [ 'size' ] } } ) if debug is not None : data = { 'type' : [ ] , 'x' : [ ] , 'y' : [ ] , 'z' : [ ] , 'options' : [ ] } for obj in debug : for k , v in obj . items ( ) : data [ k ] . append ( v ) plots . append ( { 'type' : 'DebugObject' , 'data' : data , 'options' : { } } ) model = { 'plots' : plots , 'options' : { 'world_width' : width , 'world_height' : height , 'range' : __get_range_of_world ( world ) , 'autorange' : False , 'grid' : grid , 'save_image' : True # 'save_image': False } } if wireframe : model [ 'options' ] [ 'space_mode' ] = 'wireframe' model_id = '"viz' + str ( uuid . uuid4 ( ) ) + '"' display ( HTML ( generate_html ( { 'model' : json . dumps ( model ) , 'model_id' : model_id , 'px' : camera_position [ 0 ] , 'py' : camera_position [ 1 ] , 'pz' : camera_position [ 2 ] , 'rx' : camera_rotation [ 0 ] , 'ry' : camera_rotation [ 1 ] , 'rz' : camera_rotation [ 2 ] } , 'templates/particles.tmpl' ) ) ) if return_id : return model_id | Generate a plot from received instance of World and show it on IPython notebook . This method returns the instance of dict that indicates color setting for each speices . You can use the dict as the parameter of plot_world in order to use the same colors in another plot . | 612 | 56 |
20,612 | def generate_html ( keywords , tmpl_path , package_name = 'ecell4.util' ) : from jinja2 import Template import pkgutil template = Template ( pkgutil . get_data ( package_name , tmpl_path ) . decode ( ) ) # path = os.path.abspath(os.path.dirname(__file__)) + tmpl_path # template = Template(open(path).read()) html = template . render ( * * keywords ) return html | Generate static html file from JSON model and its own id . | 115 | 13 |
20,613 | def plot_trajectory2d_with_matplotlib ( obs , plane = 'xy' , max_count = 10 , figsize = 6 , legend = True , wireframe = False , grid = True , noaxis = False , plot_range = None , * * kwargs ) : import matplotlib . pyplot as plt plane = plane . lower ( ) if len ( plane ) != 2 or plane [ 0 ] not in ( 'x' , 'y' , 'z' ) or plane [ 1 ] not in ( 'x' , 'y' , 'z' ) : raise ValueError ( "invalid 'plane' argument [{}] was given." . format ( repr ( plane ) ) ) xidx = 0 if plane [ 0 ] == 'x' else ( 1 if plane [ 0 ] == 'y' else 2 ) yidx = 0 if plane [ 1 ] == 'x' else ( 1 if plane [ 1 ] == 'y' else 2 ) data = obs . data ( ) if max_count is not None and len ( data ) > max_count : data = random . sample ( data , max_count ) wrange = __get_range_of_trajectories ( data , plot_range ) wrange = ( wrange [ 'x' ] , wrange [ 'y' ] , wrange [ 'z' ] ) wrange = { 'x' : wrange [ xidx ] , 'y' : wrange [ yidx ] } fig , ax = __prepare_plot_with_matplotlib ( wrange , figsize , grid , wireframe , noaxis ) ax . set_xlabel ( plane [ 0 ] . upper ( ) ) ax . set_ylabel ( plane [ 1 ] . upper ( ) ) lines = [ ] for i , y in enumerate ( data ) : xarr , yarr , zarr = [ ] , [ ] , [ ] for pos in y : xarr . append ( pos [ xidx ] ) yarr . append ( pos [ yidx ] ) lines . append ( ( xarr , yarr ) ) __plot_trajectory2d_with_matplotlib ( lines , ax , * * kwargs ) # if legend: # ax.legend(loc='best', shadow=True) if legend is not None and legend is not False : legend_opts = { "loc" : "best" , "shadow" : True } if isinstance ( legend , dict ) : legend_opts . update ( legend ) ax . legend ( * * legend_opts ) plt . show ( ) | Make a 2D plot from received instance of TrajectoryObserver and show it on IPython notebook . | 571 | 22 |
20,614 | def plot_world2d_with_matplotlib ( world , plane = 'xy' , marker_size = 3 , figsize = 6 , grid = True , wireframe = False , species_list = None , max_count = 1000 , angle = None , legend = True , noaxis = False , scale = 1.0 , * * kwargs ) : import matplotlib . pyplot as plt plane = plane . lower ( ) if len ( plane ) != 2 or plane [ 0 ] not in ( 'x' , 'y' , 'z' ) or plane [ 1 ] not in ( 'x' , 'y' , 'z' ) : raise ValueError ( "invalid 'plane' argument [{}] was given." . format ( repr ( plane ) ) ) xidx = 0 if plane [ 0 ] == 'x' else ( 1 if plane [ 0 ] == 'y' else 2 ) yidx = 0 if plane [ 1 ] == 'x' else ( 1 if plane [ 1 ] == 'y' else 2 ) if species_list is None : species_list = [ p . species ( ) . serial ( ) for pid , p in world . list_particles ( ) ] species_list = sorted ( set ( species_list ) , key = species_list . index ) # XXX: pick unique ones wrange = __get_range_of_world ( world , scale ) wrange = ( wrange [ 'x' ] , wrange [ 'y' ] , wrange [ 'z' ] ) wrange = { 'x' : wrange [ xidx ] , 'y' : wrange [ yidx ] } fig , ax = __prepare_plot_with_matplotlib ( wrange , figsize , grid , wireframe , noaxis ) scatters , plots = __scatter_world2d_with_matplotlib ( world , ( xidx , yidx ) , ax , species_list , marker_size , max_count , scale , * * kwargs ) ax . set_xlabel ( plane [ 0 ] . upper ( ) ) ax . set_ylabel ( plane [ 1 ] . upper ( ) ) # if legend: # ax.legend(handles=plots, labels=species_list, loc='best', shadow=True) if legend is not None and legend is not False : legend_opts = { 'loc' : 'center left' , 'bbox_to_anchor' : ( 1.0 , 0.5 ) , 'shadow' : False , 'frameon' : False , 'fontsize' : 'x-large' , 'scatterpoints' : 1 } if isinstance ( legend , dict ) : legend_opts . update ( legend ) ax . legend ( * * legend_opts ) # ax.legend(handles=plots, labels=species_list, **legend_opts) plt . show ( ) | Make a 2D plot from received instance of World and show it on IPython notebook . | 646 | 18 |
20,615 | def plot_world_with_plotly ( world , species_list = None , max_count = 1000 ) : if isinstance ( world , str ) : from . simulation import load_world world = load_world ( world ) if species_list is None : species_list = [ sp . serial ( ) for sp in world . list_species ( ) ] species_list . sort ( ) import random from ecell4_base . core import Species positions = { } for serial in species_list : x , y , z = [ ] , [ ] , [ ] particles = world . list_particles_exact ( Species ( serial ) ) if max_count is not None and len ( particles ) > max_count : particles = random . sample ( particles , max_count ) for pid , p in particles : pos = p . position ( ) x . append ( pos [ 0 ] ) y . append ( pos [ 1 ] ) z . append ( pos [ 2 ] ) positions [ serial ] = ( x , y , z ) import plotly import plotly . graph_objs as go plotly . offline . init_notebook_mode ( ) marker = dict ( size = 6 , line = dict ( color = 'rgb(204, 204, 204)' , width = 1 ) , opacity = 0.9 , symbol = 'circle' ) data = [ ] for serial , ( x , y , z ) in positions . items ( ) : trace = go . Scatter3d ( x = x , y = y , z = z , mode = 'markers' , marker = marker , name = serial ) data . append ( trace ) layout = go . Layout ( margin = dict ( l = 0 , r = 0 , b = 0 , t = 0 ) ) fig = go . Figure ( data = data , layout = layout ) plotly . offline . iplot ( fig ) | Plot a World on IPython Notebook | 402 | 8 |
20,616 | def getUnitRegistry ( length = "meter" , time = "second" , substance = "item" , volume = None , other = ( ) ) : ureg = pint . UnitRegistry ( ) ureg . define ( 'item = mole / (avogadro_number * 1 mole)' ) try : pint . molar # except UndefinedUnitError: except AttributeError : # https://github.com/hgrecco/pint/blob/master/pint/default_en.txt#L75-L77 ureg . define ( '[concentration] = [substance] / [volume]' ) ureg . define ( 'molar = mol / (1e-3 * m ** 3) = M' ) base_units = [ unit for unit in ( length , time , substance , volume ) if unit is not None ] base_units . extend ( other ) _ = ureg . System . from_lines ( [ "@system local using international" ] + base_units , ureg . get_base_units ) ureg . default_system = 'local' wrap_quantity ( ureg . Quantity ) pint . set_application_registry ( ureg ) # for pickling return ureg | Return a pint . UnitRegistry made compatible with ecell4 . | 268 | 14 |
20,617 | def interactor ( self , geneList = None , org = None ) : geneList = geneList or [ ] organisms = organisms or [ ] querydata = self . interactions ( geneList , org ) returnData = { } for i in querydata : if not returnData . get ( i [ "symB" ] [ "name" ] ) : returnData [ i [ "symB" ] [ "name" ] ] = { "interactions" : [ ] } returnData [ i [ "symB" ] [ "name" ] ] [ "interactions" ] . append ( i ) return returnData | Supposing geneList returns an unique item . | 130 | 9 |
20,618 | def save_sbml ( filename , model , y0 = None , volume = 1.0 , is_valid = True ) : y0 = y0 or { } import libsbml document = export_sbml ( model , y0 , volume , is_valid ) # with open(filename, 'w') as fout: # fout.write(libsbml.writeSBMLToString(document)) # writer = libsbml.SBMLWriter() # writer.writeSBML(document, filename) libsbml . writeSBML ( document , filename ) | Save a model in the SBML format . | 123 | 9 |
20,619 | def load_sbml ( filename ) : import libsbml document = libsbml . readSBML ( filename ) document . validateSBML ( ) num_errors = ( document . getNumErrors ( libsbml . LIBSBML_SEV_ERROR ) + document . getNumErrors ( libsbml . LIBSBML_SEV_FATAL ) ) if num_errors > 0 : messages = "The generated document is not valid." messages += " {} errors were found:\n" . format ( num_errors ) for i in range ( document . getNumErrors ( libsbml . LIBSBML_SEV_ERROR ) ) : err = document . getErrorWithSeverity ( i , libsbml . LIBSBML_SEV_ERROR ) messages += "{}: {}\n" . format ( err . getSeverityAsString ( ) , err . getShortMessage ( ) ) for i in range ( document . getNumErrors ( libsbml . LIBSBML_SEV_FATAL ) ) : err = document . getErrorWithSeverity ( i , libsbml . LIBSBML_SEV_FATAL ) messages += "{}: {}\n" . format ( err . getSeverityAsString ( ) , err . getShortMessage ( ) ) raise RuntimeError ( messages ) return import_sbml ( document ) | Load a model from a SBML file . | 305 | 9 |
20,620 | def get_model ( is_netfree = False , without_reset = False , seeds = None , effective = False ) : try : if seeds is not None or is_netfree : m = ecell4_base . core . NetfreeModel ( ) else : m = ecell4_base . core . NetworkModel ( ) for sp in SPECIES_ATTRIBUTES : m . add_species_attribute ( sp ) for rr in REACTION_RULES : m . add_reaction_rule ( rr ) if not without_reset : reset_model ( ) if seeds is not None : return m . expand ( seeds ) if isinstance ( m , ecell4_base . core . NetfreeModel ) : m . set_effective ( effective ) except Exception as e : reset_model ( ) raise e return m | Generate a model with parameters in the global scope SPECIES_ATTRIBUTES and REACTIONRULES . | 181 | 25 |
20,621 | def run_serial ( target , jobs , n = 1 , * * kwargs ) : return [ [ target ( copy . copy ( job ) , i + 1 , j + 1 ) for j in range ( n ) ] for i , job in enumerate ( jobs ) ] | Evaluate the given function with each set of arguments and return a list of results . This function does in series . | 59 | 24 |
20,622 | def run_multiprocessing ( target , jobs , n = 1 , nproc = None , * * kwargs ) : def consumer ( f , q_in , q_out ) : while True : val = q_in . get ( ) if val is None : q_in . task_done ( ) break i , x = val res = ( i , f ( * x ) ) q_in . task_done ( ) q_out . put ( res ) def mulpmap ( f , X , nproc ) : nproc = nproc or multiprocessing . cpu_count ( ) q_in = multiprocessing . JoinableQueue ( ) q_out = multiprocessing . Queue ( ) workers = [ multiprocessing . Process ( target = consumer , args = ( f , q_in , q_out ) , daemon = True ) for _ in range ( nproc ) ] sent = [ q_in . put ( ( i , x ) ) for i , x in enumerate ( X ) ] num_tasks = len ( sent ) [ q_in . put ( None ) for _ in range ( nproc ) ] #XXX: poison pill [ w . start ( ) for w in workers ] # [w.join() for w in workers] q_in . join ( ) res = [ q_out . get ( ) for _ in range ( num_tasks ) ] return [ x for ( _ , x ) in sorted ( res ) ] res = mulpmap ( target , ( ( job , i + 1 , j + 1 ) for ( i , job ) , j in itertools . product ( enumerate ( jobs ) , range ( n ) ) ) , nproc ) return [ res [ i : i + n ] for i in range ( 0 , len ( res ) , n ) ] | Evaluate the given function with each set of arguments and return a list of results . This function does in parallel by using multiprocessing . | 399 | 30 |
20,623 | def run_azure ( target , jobs , n = 1 , nproc = None , path = '.' , delete = True , config = None , * * kwargs ) : import ecell4 . extra . azure_batch as azure_batch return azure_batch . run_azure ( target , jobs , n , path , delete , config ) | Evaluate the given function with each set of arguments and return a list of results . This function does in parallel with Microsoft Azure Batch . | 78 | 29 |
20,624 | def getseed ( myseed , i ) : rndseed = int ( myseed [ ( i - 1 ) * 8 : i * 8 ] , 16 ) rndseed = rndseed % ( 2 ** 31 ) #XXX: trancate the first bit return rndseed | Return a single seed from a long seed given by genseeds . | 60 | 14 |
20,625 | def list_species ( model , seeds = None ) : seeds = None or [ ] from ecell4_base . core import Species if not isinstance ( seeds , list ) : seeds = list ( seeds ) expanded = model . expand ( [ Species ( serial ) for serial in seeds ] ) species_list = [ sp . serial ( ) for sp in expanded . list_species ( ) ] species_list = sorted ( set ( seeds + species_list ) ) return species_list | This function is deprecated . | 101 | 5 |
20,626 | def _escapeCharacters ( tag ) : for i , c in enumerate ( tag . contents ) : if type ( c ) != bs4 . element . NavigableString : continue c . replace_with ( _escapeCharSub ( r'\\\1' , c ) ) | non - recursively escape underlines and asterisks in the tag | 60 | 14 |
20,627 | def _breakRemNewlines ( tag ) : for i , c in enumerate ( tag . contents ) : if type ( c ) != bs4 . element . NavigableString : continue c . replace_with ( re . sub ( r' {2,}' , ' ' , c ) . replace ( '\n' , '' ) ) | non - recursively break spaces and remove newlines in the tag | 75 | 14 |
20,628 | def convert ( html ) : bs = BeautifulSoup ( html , 'html.parser' ) _markdownify ( bs ) ret = unicode ( bs ) . replace ( u'\xa0' , ' ' ) ret = re . sub ( r'\n{3,}' , r'\n\n' , ret ) # ! FIXME: hack ret = re . sub ( r'<<<FLOATING LINK: (.+)>>>' , r'<\1>' , ret ) # ! FIXME: hack sp = re . split ( r'(<<<BLOCKQUOTE: .*?>>>)' , ret , flags = re . DOTALL ) for i , e in enumerate ( sp ) : if e [ : len ( '<<<BLOCKQUOTE:' ) ] == '<<<BLOCKQUOTE:' : sp [ i ] = '> ' + e [ len ( '<<<BLOCKQUOTE:' ) : - len ( '>>>' ) ] sp [ i ] = sp [ i ] . replace ( '\n' , '\n> ' ) ret = '' . join ( sp ) return ret . strip ( '\n' ) | converts an html string to markdown while preserving unsupported markup . | 320 | 13 |
20,629 | def create ( cls , type ) : if type == 0 : return FilterDropShadow ( id ) elif type == 1 : return FilterBlur ( id ) elif type == 2 : return FilterGlow ( id ) elif type == 3 : return FilterBevel ( id ) elif type == 4 : return FilterGradientGlow ( id ) elif type == 5 : return FilterConvolution ( id ) elif type == 6 : return FilterColorMatrix ( id ) elif type == 7 : return FilterGradientBevel ( id ) else : raise Exception ( "Unknown filter type: %d" % type ) | Return the specified Filter | 133 | 4 |
20,630 | def export ( self , exporter = None , force_stroke = False ) : exporter = SVGExporter ( ) if exporter is None else exporter if self . _data is None : raise Exception ( "This SWF was not loaded! (no data)" ) if len ( self . tags ) == 0 : raise Exception ( "This SWF doesn't contain any tags!" ) return exporter . export ( self , force_stroke ) | Export this SWF using the specified exporter . When no exporter is passed in the default exporter used is swf . export . SVGExporter . Exporters should extend the swf . export . BaseExporter class . | 93 | 48 |
20,631 | def parse ( self , data ) : self . _data = data = data if isinstance ( data , SWFStream ) else SWFStream ( data ) self . _header = SWFHeader ( self . _data ) if self . _header . compressed : temp = BytesIO ( ) if self . _header . compressed_zlib : import zlib data = data . f . read ( ) zip = zlib . decompressobj ( ) temp . write ( zip . decompress ( data ) ) else : import pylzma data . readUI32 ( ) #consume compressed length data = data . f . read ( ) temp . write ( pylzma . decompress ( data ) ) temp . seek ( 0 ) data = SWFStream ( temp ) self . _header . _frame_size = data . readRECT ( ) self . _header . _frame_rate = data . readFIXED8 ( ) self . _header . _frame_count = data . readUI16 ( ) self . parse_tags ( data ) | Parses the SWF . The | 223 | 8 |
20,632 | def int32 ( x ) : if x > 0xFFFFFFFF : raise OverflowError if x > 0x7FFFFFFF : x = int ( 0x100000000 - x ) if x < 2147483648 : return - x else : return - 2147483648 return x | Return a signed or unsigned int | 63 | 6 |
20,633 | def bin ( self , s ) : return str ( s ) if s <= 1 else bin ( s >> 1 ) + str ( s & 1 ) | Return a value as a binary string | 31 | 7 |
20,634 | def calc_max_bits ( self , signed , values ) : b = 0 vmax = - 10000000 for val in values : if signed : b = b | val if val >= 0 else b | ~ val << 1 vmax = val if vmax < val else vmax else : b |= val bits = 0 if b > 0 : bits = len ( self . bin ( b ) ) - 2 if signed and vmax > 0 and len ( self . bin ( vmax ) ) - 2 >= bits : bits += 1 return bits | Calculates the maximim needed bits to represent a value | 114 | 12 |
20,635 | def readbits ( self , bits ) : if bits == 0 : return 0 # fast byte-aligned path if bits % 8 == 0 and self . _bits_pending == 0 : return self . _read_bytes_aligned ( bits // 8 ) out = 0 masks = self . _masks def transfer_bits ( x , y , n , t ) : """ transfers t bits from the top of y_n to the bottom of x. then returns x and the remaining bits in y """ if n == t : # taking all return ( x << t ) | y , 0 mask = masks [ t ] # (1 << t) - 1 remainmask = masks [ n - t ] # (1 << n - t) - 1 taken = ( ( y >> n - t ) & mask ) return ( x << t ) | taken , y & remainmask while bits > 0 : if self . _bits_pending > 0 : assert self . _partial_byte is not None take = min ( self . _bits_pending , bits ) out , self . _partial_byte = transfer_bits ( out , self . _partial_byte , self . _bits_pending , take ) if take == self . _bits_pending : # we took them all self . _partial_byte = None self . _bits_pending -= take bits -= take continue r = self . f . read ( 1 ) if r == b'' : raise EOFError self . _partial_byte = ord ( r ) self . _bits_pending = 8 return out | Read the specified number of bits from the stream . Returns 0 for bits == 0 . | 332 | 17 |
20,636 | def readSB ( self , bits ) : shift = 32 - bits return int32 ( self . readbits ( bits ) << shift ) >> shift | Read a signed int using the specified number of bits | 30 | 10 |
20,637 | def readEncodedU32 ( self ) : self . reset_bits_pending ( ) result = self . readUI8 ( ) if result & 0x80 != 0 : result = ( result & 0x7f ) | ( self . readUI8 ( ) << 7 ) if result & 0x4000 != 0 : result = ( result & 0x3fff ) | ( self . readUI8 ( ) << 14 ) if result & 0x200000 != 0 : result = ( result & 0x1fffff ) | ( self . readUI8 ( ) << 21 ) if result & 0x10000000 != 0 : result = ( result & 0xfffffff ) | ( self . readUI8 ( ) << 28 ) return result | Read a encoded unsigned int | 157 | 5 |
20,638 | def readFLOAT16 ( self ) : self . reset_bits_pending ( ) word = self . readUI16 ( ) sign = - 1 if ( ( word & 0x8000 ) != 0 ) else 1 exponent = ( word >> 10 ) & 0x1f significand = word & 0x3ff if exponent == 0 : if significand == 0 : return 0.0 else : return sign * math . pow ( 2 , 1 - SWFStream . FLOAT16_EXPONENT_BASE ) * ( significand / 1024.0 ) if exponent == 31 : if significand == 0 : return float ( '-inf' ) if sign < 0 else float ( 'inf' ) else : return float ( 'nan' ) # normal number return sign * math . pow ( 2 , exponent - SWFStream . FLOAT16_EXPONENT_BASE ) * ( 1 + significand / 1024.0 ) | Read a 2 byte float | 201 | 5 |
20,639 | def readSTYLECHANGERECORD ( self , states , fill_bits , line_bits , level = 1 ) : return SWFShapeRecordStyleChange ( self , states , fill_bits , line_bits , level ) | Read a SWFShapeRecordStyleChange | 50 | 8 |
20,640 | def readTEXTRECORD ( self , glyphBits , advanceBits , previousRecord = None , level = 1 ) : if self . readUI8 ( ) == 0 : return None else : self . seek ( self . tell ( ) - 1 ) return SWFTextRecord ( self , glyphBits , advanceBits , previousRecord , level ) | Read a SWFTextRecord | 74 | 6 |
20,641 | def readACTIONRECORD ( self ) : action = None actionCode = self . readUI8 ( ) if actionCode != 0 : actionLength = self . readUI16 ( ) if actionCode >= 0x80 else 0 #print "0x%x"%actionCode, actionLength action = SWFActionFactory . create ( actionCode , actionLength ) action . parse ( self ) return action | Read a SWFActionRecord | 84 | 6 |
20,642 | def readCLIPACTIONRECORD ( self , version ) : pos = self . tell ( ) flags = self . readUI32 ( ) if version >= 6 else self . readUI16 ( ) if flags == 0 : return None else : self . seek ( pos ) return SWFClipActionRecord ( self , version ) | Read a SWFClipActionRecord | 68 | 8 |
20,643 | def readRGB ( self ) : self . reset_bits_pending ( ) r = self . readUI8 ( ) g = self . readUI8 ( ) b = self . readUI8 ( ) return ( 0xff << 24 ) | ( r << 16 ) | ( g << 8 ) | b | Read a RGB color | 65 | 4 |
20,644 | def readRGBA ( self ) : self . reset_bits_pending ( ) r = self . readUI8 ( ) g = self . readUI8 ( ) b = self . readUI8 ( ) a = self . readUI8 ( ) return ( a << 24 ) | ( r << 16 ) | ( g << 8 ) | b | Read a RGBA color | 74 | 5 |
20,645 | def readString ( self ) : s = self . f . read ( 1 ) string = b"" while ord ( s ) > 0 : string += s s = self . f . read ( 1 ) return string . decode ( ) | Read a string | 48 | 3 |
20,646 | def readFILTER ( self ) : filterId = self . readUI8 ( ) filter = SWFFilterFactory . create ( filterId ) filter . parse ( self ) return filter | Read a SWFFilter | 39 | 6 |
20,647 | def readFILTERLIST ( self ) : number = self . readUI8 ( ) return [ self . readFILTER ( ) for _ in range ( number ) ] | Read a length - prefixed list of FILTERs | 35 | 11 |
20,648 | def readBUTTONCONDACTIONSs ( self ) : out = [ ] while 1 : action = self . readBUTTONCONDACTION ( ) if action : out . append ( action ) else : break return out | Read zero or more button - condition actions | 46 | 8 |
20,649 | def readtag_header ( self ) : pos = self . tell ( ) tag_type_and_length = self . readUI16 ( ) tag_length = tag_type_and_length & 0x003f if tag_length == 0x3f : # The SWF10 spec sez that this is a signed int. # Shouldn't it be an unsigned int? tag_length = self . readSI32 ( ) return SWFRecordHeader ( tag_type_and_length >> 6 , tag_length , self . tell ( ) - pos ) | Read a tag header | 121 | 4 |
20,650 | def get_dependencies ( self ) : s = super ( SWFTimelineContainer , self ) . get_dependencies ( ) for dt in self . all_tags_of_type ( DefinitionTag ) : s . update ( dt . get_dependencies ( ) ) return s | Returns the character ids this tag refers to | 62 | 9 |
20,651 | def all_tags_of_type ( self , type_or_types , recurse_into_sprites = True ) : for t in self . tags : if isinstance ( t , type_or_types ) : yield t if recurse_into_sprites : for t in self . tags : # recurse into nested sprites if isinstance ( t , SWFTimelineContainer ) : for containedtag in t . all_tags_of_type ( type_or_types ) : yield containedtag | Generator for all tags of the given type_or_types . | 109 | 14 |
20,652 | def build_dictionary ( self ) : d = { } for t in self . all_tags_of_type ( DefinitionTag , recurse_into_sprites = False ) : if t . characterId in d : #print 'redefinition of characterId %d:' % (t.characterId) #print ' was:', d[t.characterId] #print 'redef:', t raise ValueError ( 'illegal redefinition of character' ) d [ t . characterId ] = t return d | Return a dictionary of characterIds to their defining tags . | 111 | 12 |
20,653 | def collect_sound_streams ( self ) : rc = [ ] current_stream = None # looking in all containers for frames for tag in self . all_tags_of_type ( ( TagSoundStreamHead , TagSoundStreamBlock ) ) : if isinstance ( tag , TagSoundStreamHead ) : # we have a new stream current_stream = [ tag ] rc . append ( current_stream ) if isinstance ( tag , TagSoundStreamBlock ) : # we have a frame for the current stream current_stream . append ( tag ) return rc | Return a list of sound streams in this timeline and its children . The streams are returned in order with respect to the timeline . | 117 | 25 |
20,654 | def collect_video_streams ( self ) : rc = [ ] streams_by_id = { } # scan first for all streams for t in self . all_tags_of_type ( TagDefineVideoStream ) : stream = [ t ] streams_by_id [ t . characterId ] = stream rc . append ( stream ) # then find the frames for t in self . all_tags_of_type ( TagVideoFrame ) : # we have a frame for the /named/ stream assert t . streamId in streams_by_id streams_by_id [ t . streamId ] . append ( t ) return rc | Return a list of video streams in this timeline and its children . The streams are returned in order with respect to the timeline . | 136 | 25 |
20,655 | def export ( self , swf , force_stroke = False ) : self . svg = self . _e . svg ( version = SVG_VERSION ) self . force_stroke = force_stroke self . defs = self . _e . defs ( ) self . root = self . _e . g ( ) self . svg . append ( self . defs ) self . svg . append ( self . root ) self . shape_exporter . defs = self . defs self . _num_filters = 0 self . fonts = dict ( [ ( x . characterId , x ) for x in swf . all_tags_of_type ( TagDefineFont ) ] ) self . fontInfos = dict ( [ ( x . characterId , x ) for x in swf . all_tags_of_type ( TagDefineFontInfo ) ] ) # GO! super ( SVGExporter , self ) . export ( swf , force_stroke ) # Setup svg @width, @height and @viewBox # and add the optional margin self . bounds = SVGBounds ( self . svg ) self . svg . set ( "width" , "%dpx" % round ( self . bounds . width ) ) self . svg . set ( "height" , "%dpx" % round ( self . bounds . height ) ) if self . _margin > 0 : self . bounds . grow ( self . _margin ) vb = [ self . bounds . minx , self . bounds . miny , self . bounds . width , self . bounds . height ] self . svg . set ( "viewBox" , "%s" % " " . join ( map ( str , vb ) ) ) # Return the SVG as StringIO return self . _serialize ( ) | Exports the specified SWF to SVG . | 387 | 9 |
20,656 | def export ( self , swf , shape , * * export_opts ) : # If `shape` is given as int, find corresponding shape tag. if isinstance ( shape , Tag ) : shape_tag = shape else : shapes = [ x for x in swf . all_tags_of_type ( ( TagDefineShape , TagDefineSprite ) ) if x . characterId == shape ] if len ( shapes ) : shape_tag = shapes [ 0 ] else : raise Exception ( "Shape %s not found" % shape ) from swf . movie import SWF # find a typical use of this shape example_place_objects = [ x for x in swf . all_tags_of_type ( TagPlaceObject ) if x . hasCharacter and x . characterId == shape_tag . characterId ] if len ( example_place_objects ) : place_object = example_place_objects [ 0 ] characters = swf . build_dictionary ( ) ids_to_export = place_object . get_dependencies ( ) ids_exported = set ( ) tags_to_export = [ ] # this had better form a dag! while len ( ids_to_export ) : id = ids_to_export . pop ( ) if id in ids_exported or id not in characters : continue tag = characters [ id ] ids_to_export . update ( tag . get_dependencies ( ) ) tags_to_export . append ( tag ) ids_exported . add ( id ) tags_to_export . reverse ( ) tags_to_export . append ( place_object ) else : place_object = TagPlaceObject ( ) place_object . hasCharacter = True place_object . characterId = shape_tag . characterId tags_to_export = [ shape_tag , place_object ] stunt_swf = SWF ( ) stunt_swf . tags = tags_to_export return super ( SingleShapeSVGExporterMixin , self ) . export ( stunt_swf , * * export_opts ) | Exports the specified shape of the SWF to SVG . | 452 | 12 |
20,657 | def export ( self , swf , frame , * * export_opts ) : self . wanted_frame = frame return super ( FrameSVGExporterMixin , self ) . export ( swf , * export_opts ) | Exports a frame of the specified SWF to SVG . | 50 | 12 |
20,658 | def _get_args_and_errors ( self , minuit = None , args = None , errors = None ) : ret_arg = None ret_error = None if minuit is not None : # case 1 ret_arg = minuit . args ret_error = minuit . errors return ret_arg , ret_error # no minuit specified use args and errors if args is not None : if isinstance ( args , dict ) : ret_arg = parse_arg ( self , args ) else : ret_arg = args else : # case 3 ret_arg = self . last_arg if errors is not None : ret_error = errors return ret_arg , ret_error | consistent algorithm to get argument and errors 1 ) get it from minuit if minuit is available 2 ) if not get it from args and errors 2 . 1 ) if args is dict parse it . 3 ) if all else fail get it from self . last_arg | 146 | 55 |
20,659 | def draw_residual ( x , y , yerr , xerr , show_errbars = True , ax = None , zero_line = True , grid = True , * * kwargs ) : from matplotlib import pyplot as plt ax = plt . gca ( ) if ax is None else ax if show_errbars : plotopts = dict ( fmt = 'b.' , capsize = 0 ) plotopts . update ( kwargs ) pp = ax . errorbar ( x , y , yerr , xerr , zorder = 0 , * * plotopts ) else : plotopts = dict ( color = 'k' ) plotopts . update ( kwargs ) pp = ax . bar ( x - xerr , y , width = 2 * xerr , * * plotopts ) if zero_line : ax . plot ( [ x [ 0 ] - xerr [ 0 ] , x [ - 1 ] + xerr [ - 1 ] ] , [ 0 , 0 ] , 'r-' , zorder = 2 ) # Take the `grid` kwarg to mean 'add a grid if True'; if grid is False and # we called ax.grid(False) then any existing grid on ax would be turned off if grid : ax . grid ( grid ) return ax | Draw a residual plot on the axis . | 284 | 8 |
20,660 | def draw_pdf ( f , arg , bound , bins = 100 , scale = 1.0 , density = True , normed_pdf = False , ax = None , * * kwds ) : edges = np . linspace ( bound [ 0 ] , bound [ 1 ] , bins ) return draw_pdf_with_edges ( f , arg , edges , ax = ax , scale = scale , density = density , normed_pdf = normed_pdf , * * kwds ) | draw pdf with given argument and bounds . | 107 | 8 |
20,661 | def get_chunks ( sequence , chunk_size ) : return [ sequence [ idx : idx + chunk_size ] for idx in range ( 0 , len ( sequence ) , chunk_size ) ] | Split sequence into chunks . | 45 | 5 |
20,662 | def get_kwargs ( kwargs ) : return { key : value for key , value in six . iteritems ( kwargs ) if key != 'self' } | Get all keys and values from dictionary where key is not self . | 37 | 13 |
20,663 | def check_status_code ( response , codes = None ) : codes = codes or [ httplib . OK ] checker = ( codes if callable ( codes ) else lambda resp : resp . status_code in codes ) if not checker ( response ) : raise exceptions . ApiError ( response , response . json ( ) ) | Check HTTP status code and raise exception if incorrect . | 71 | 10 |
20,664 | def result_or_error ( response ) : data = response . json ( ) result = data . get ( 'result' ) if result is not None : return result raise exceptions . ApiError ( response , data ) | Get result field from Betfair response or raise exception if not found . | 46 | 14 |
20,665 | def make_payload ( base , method , params ) : payload = { 'jsonrpc' : '2.0' , 'method' : '{base}APING/v1.0/{method}' . format ( * * locals ( ) ) , 'params' : utils . serialize_dict ( params ) , 'id' : 1 , } return payload | Build Betfair JSON - RPC payload . | 82 | 8 |
20,666 | def requires_login ( func , * args , * * kwargs ) : self = args [ 0 ] if self . session_token : return func ( * args , * * kwargs ) raise exceptions . NotLoggedIn ( ) | Decorator to check that the user is logged in . Raises BetfairError if instance variable session_token is absent . | 51 | 26 |
20,667 | def nearest_price ( price , cutoffs = CUTOFFS ) : if price <= MIN_PRICE : return MIN_PRICE if price > MAX_PRICE : return MAX_PRICE price = as_dec ( price ) for cutoff , step in cutoffs : if price < cutoff : break step = as_dec ( step ) return float ( ( price * step ) . quantize ( 2 , ROUND_HALF_UP ) / step ) | Returns the nearest Betfair odds value to price . | 98 | 10 |
20,668 | def login ( self , username , password ) : response = self . session . post ( os . path . join ( self . identity_url , 'certlogin' ) , cert = self . cert_file , data = urllib . urlencode ( { 'username' : username , 'password' : password , } ) , headers = { 'X-Application' : self . app_key , 'Content-Type' : 'application/x-www-form-urlencoded' , } , timeout = self . timeout , ) utils . check_status_code ( response , [ httplib . OK ] ) data = response . json ( ) if data . get ( 'loginStatus' ) != 'SUCCESS' : raise exceptions . LoginError ( response , data ) self . session_token = data [ 'sessionToken' ] | Log in to Betfair . Sets session_token if successful . | 180 | 13 |
20,669 | def list_market_profit_and_loss ( self , market_ids , include_settled_bets = False , include_bsp_bets = None , net_of_commission = None ) : return self . make_api_request ( 'Sports' , 'listMarketProfitAndLoss' , utils . get_kwargs ( locals ( ) ) , model = models . MarketProfitAndLoss , ) | Retrieve profit and loss for a given list of markets . | 94 | 12 |
20,670 | def iter_list_market_book ( self , market_ids , chunk_size , * * kwargs ) : return itertools . chain ( * ( self . list_market_book ( market_chunk , * * kwargs ) for market_chunk in utils . get_chunks ( market_ids , chunk_size ) ) ) | Split call to list_market_book into separate requests . | 78 | 12 |
20,671 | def iter_list_market_profit_and_loss ( self , market_ids , chunk_size , * * kwargs ) : return itertools . chain ( * ( self . list_market_profit_and_loss ( market_chunk , * * kwargs ) for market_chunk in utils . get_chunks ( market_ids , chunk_size ) ) ) | Split call to list_market_profit_and_loss into separate requests . | 86 | 16 |
20,672 | def place_orders ( self , market_id , instructions , customer_ref = None ) : return self . make_api_request ( 'Sports' , 'placeOrders' , utils . get_kwargs ( locals ( ) ) , model = models . PlaceExecutionReport , ) | Place new orders into market . This operation is atomic in that all orders will be placed or none will be placed . | 62 | 23 |
20,673 | def update_orders ( self , market_id , instructions , customer_ref = None ) : return self . make_api_request ( 'Sports' , 'updateOrders' , utils . get_kwargs ( locals ( ) ) , model = models . UpdateExecutionReport , ) | Update non - exposure changing fields . | 62 | 7 |
20,674 | def transfer_funds ( self , from_ , to , amount ) : return self . make_api_request ( 'Account' , 'transferFunds' , utils . get_kwargs ( locals ( ) ) , model = models . TransferResponse , ) | Transfer funds between the UK Exchange and Australian Exchange wallets . | 56 | 11 |
20,675 | def parse ( self , text , html = True ) : self . _urls = [ ] self . _users = [ ] self . _lists = [ ] self . _tags = [ ] reply = REPLY_REGEX . match ( text ) reply = reply . groups ( 0 ) [ 0 ] if reply is not None else None parsed_html = self . _html ( text ) if html else self . _text ( text ) return ParseResult ( self . _urls , self . _users , reply , self . _lists , self . _tags , parsed_html ) | Parse the text and return a ParseResult instance . | 124 | 12 |
20,676 | def _text ( self , text ) : URL_REGEX . sub ( self . _parse_urls , text ) USERNAME_REGEX . sub ( self . _parse_users , text ) LIST_REGEX . sub ( self . _parse_lists , text ) HASHTAG_REGEX . sub ( self . _parse_tags , text ) return None | Parse a Tweet without generating HTML . | 80 | 8 |
20,677 | def _html ( self , text ) : html = URL_REGEX . sub ( self . _parse_urls , text ) html = USERNAME_REGEX . sub ( self . _parse_users , html ) html = LIST_REGEX . sub ( self . _parse_lists , html ) return HASHTAG_REGEX . sub ( self . _parse_tags , html ) | Parse a Tweet and generate HTML . | 85 | 8 |
20,678 | def _parse_urls ( self , match ) : mat = match . group ( 0 ) # Fix a bug in the regex concerning www...com and www.-foo.com domains # TODO fix this in the regex instead of working around it here domain = match . group ( 5 ) if domain [ 0 ] in '.-' : return mat # Only allow IANA one letter domains that are actually registered if len ( domain ) == 5 and domain [ - 4 : ] . lower ( ) in ( '.com' , '.org' , '.net' ) and not domain . lower ( ) in IANA_ONE_LETTER_DOMAINS : return mat # Check for urls without http(s) pos = mat . find ( 'http' ) if pos != - 1 : pre , url = mat [ : pos ] , mat [ pos : ] full_url = url # Find the www and force https:// else : pos = mat . lower ( ) . find ( 'www' ) pre , url = mat [ : pos ] , mat [ pos : ] full_url = 'https://%s' % url if self . _include_spans : span = match . span ( 0 ) # add an offset if pre is e.g. ' ' span = ( span [ 0 ] + len ( pre ) , span [ 1 ] ) self . _urls . append ( ( url , span ) ) else : self . _urls . append ( url ) if self . _html : return '%s%s' % ( pre , self . format_url ( full_url , self . _shorten_url ( escape ( url ) ) ) ) | Parse URLs . | 351 | 4 |
20,679 | def _parse_users ( self , match ) : # Don't parse lists here if match . group ( 2 ) is not None : return match . group ( 0 ) mat = match . group ( 0 ) if self . _include_spans : self . _users . append ( ( mat [ 1 : ] , match . span ( 0 ) ) ) else : self . _users . append ( mat [ 1 : ] ) if self . _html : return self . format_username ( mat [ 0 : 1 ] , mat [ 1 : ] ) | Parse usernames . | 115 | 6 |
20,680 | def _parse_lists ( self , match ) : # Don't parse usernames here if match . group ( 4 ) is None : return match . group ( 0 ) pre , at_char , user , list_name = match . groups ( ) list_name = list_name [ 1 : ] if self . _include_spans : self . _lists . append ( ( user , list_name , match . span ( 0 ) ) ) else : self . _lists . append ( ( user , list_name ) ) if self . _html : return '%s%s' % ( pre , self . format_list ( at_char , user , list_name ) ) | Parse lists . | 146 | 4 |
20,681 | def _parse_tags ( self , match ) : mat = match . group ( 0 ) # Fix problems with the regex capturing stuff infront of the # tag = None for i in '#\uff03' : pos = mat . rfind ( i ) if pos != - 1 : tag = i break pre , text = mat [ : pos ] , mat [ pos + 1 : ] if self . _include_spans : span = match . span ( 0 ) # add an offset if pre is e.g. ' ' span = ( span [ 0 ] + len ( pre ) , span [ 1 ] ) self . _tags . append ( ( text , span ) ) else : self . _tags . append ( text ) if self . _html : return '%s%s' % ( pre , self . format_tag ( tag , text ) ) | Parse hashtags . | 181 | 5 |
20,682 | def _shorten_url ( self , text ) : if len ( text ) > self . _max_url_length and self . _max_url_length != - 1 : text = text [ 0 : self . _max_url_length - 3 ] amp = text . rfind ( '&' ) close = text . rfind ( ';' ) if amp != - 1 and ( close == - 1 or close < amp ) : text = text [ 0 : amp ] return text + '...' else : return text | Shorten a URL and make sure to not cut of html entities . | 113 | 14 |
20,683 | def format_list ( self , at_char , user , list_name ) : return '<a href="https://twitter.com/%s/lists/%s">%s%s/%s</a>' % ( user , list_name , at_char , user , list_name ) | Return formatted HTML for a list . | 67 | 7 |
20,684 | def follow_shortlinks ( shortlinks ) : links_followed = { } for shortlink in shortlinks : url = shortlink request_result = requests . get ( url ) redirect_history = request_result . history # history might look like: # (<Response [301]>, <Response [301]>) # where each response object has a URL all_urls = [ ] for redirect in redirect_history : all_urls . append ( redirect . url ) # append the final URL that we finish with all_urls . append ( request_result . url ) links_followed [ shortlink ] = all_urls return links_followed | Follow redirects in list of shortlinks return dict of resulting URLs | 139 | 13 |
20,685 | def _GetFieldAttributes ( field ) : if not isinstance ( field , messages . Field ) : raise TypeError ( 'Field %r to be copied not a ProtoRPC field.' % ( field , ) ) positional_args = [ ] kwargs = { 'required' : field . required , 'repeated' : field . repeated , 'variant' : field . variant , 'default' : field . _Field__default , # pylint: disable=protected-access } if isinstance ( field , messages . MessageField ) : # Message fields can't have a default kwargs . pop ( 'default' ) if not isinstance ( field , message_types . DateTimeField ) : positional_args . insert ( 0 , field . message_type ) elif isinstance ( field , messages . EnumField ) : positional_args . insert ( 0 , field . type ) return positional_args , kwargs | Decomposes field into the needed arguments to pass to the constructor . | 198 | 14 |
20,686 | def _CompareFields ( field , other_field ) : field_attrs = _GetFieldAttributes ( field ) other_field_attrs = _GetFieldAttributes ( other_field ) if field_attrs != other_field_attrs : return False return field . __class__ == other_field . __class__ | Checks if two ProtoRPC fields are equal . | 70 | 11 |
20,687 | def combined_message_class ( self ) : if self . __combined_message_class is not None : return self . __combined_message_class fields = { } # We don't need to preserve field.number since this combined class is only # used for the protorpc remote.method and is not needed for the API config. # The only place field.number matters is in parameterOrder, but this is set # based on container.parameters_message_class which will use the field # numbers originally passed in. # Counter for fields. field_number = 1 for field in self . body_message_class . all_fields ( ) : fields [ field . name ] = _CopyField ( field , number = field_number ) field_number += 1 for field in self . parameters_message_class . all_fields ( ) : if field . name in fields : if not _CompareFields ( field , fields [ field . name ] ) : raise TypeError ( 'Field %r contained in both parameters and request ' 'body, but the fields differ.' % ( field . name , ) ) else : # Skip a field that's already there. continue fields [ field . name ] = _CopyField ( field , number = field_number ) field_number += 1 self . __combined_message_class = type ( 'CombinedContainer' , ( messages . Message , ) , fields ) return self . __combined_message_class | A ProtoRPC message class with both request and parameters fields . | 308 | 13 |
20,688 | def add_to_cache ( cls , remote_info , container ) : # pylint: disable=g-bad-name if not isinstance ( container , cls ) : raise TypeError ( '%r not an instance of %r, could not be added to cache.' % ( container , cls ) ) if remote_info in cls . __remote_info_cache : raise KeyError ( 'Cache has collision but should not.' ) cls . __remote_info_cache [ remote_info ] = container | Adds a ResourceContainer to a cache tying it to a protorpc method . | 113 | 16 |
20,689 | def get_request_message ( cls , remote_info ) : # pylint: disable=g-bad-name if remote_info in cls . __remote_info_cache : return cls . __remote_info_cache [ remote_info ] else : return remote_info . request_type ( ) | Gets request message or container from remote info . | 69 | 10 |
20,690 | def _is_auth_info_available ( ) : return ( _ENDPOINTS_USER_INFO in os . environ or ( _ENV_AUTH_EMAIL in os . environ and _ENV_AUTH_DOMAIN in os . environ ) or _ENV_USE_OAUTH_SCOPE in os . environ ) | Check if user auth info has been set in environment variables . | 79 | 12 |
20,691 | def _get_token ( request = None , allowed_auth_schemes = ( 'OAuth' , 'Bearer' ) , allowed_query_keys = ( 'bearer_token' , 'access_token' ) ) : allowed_auth_schemes = _listlike_guard ( allowed_auth_schemes , 'allowed_auth_schemes' , iterable_only = True ) # Check if the token is in the Authorization header. auth_header = os . environ . get ( 'HTTP_AUTHORIZATION' ) if auth_header : for auth_scheme in allowed_auth_schemes : if auth_header . startswith ( auth_scheme ) : return auth_header [ len ( auth_scheme ) + 1 : ] # If an auth header was specified, even if it's an invalid one, we won't # look for the token anywhere else. return None # Check if the token is in the query string. if request : allowed_query_keys = _listlike_guard ( allowed_query_keys , 'allowed_query_keys' , iterable_only = True ) for key in allowed_query_keys : token , _ = request . get_unrecognized_field_info ( key ) if token : return token | Get the auth token for this request . | 281 | 8 |
20,692 | def _get_id_token_user ( token , issuers , audiences , allowed_client_ids , time_now , cache ) : # Verify that the token is valid before we try to extract anything from it. # This verifies the signature and some of the basic info in the token. for issuer_key , issuer in issuers . items ( ) : issuer_cert_uri = convert_jwks_uri ( issuer . jwks_uri ) try : parsed_token = _verify_signed_jwt_with_certs ( token , time_now , cache , cert_uri = issuer_cert_uri ) except Exception : # pylint: disable=broad-except _logger . debug ( 'id_token verification failed for issuer %s' , issuer_key , exc_info = True ) continue issuer_values = _listlike_guard ( issuer . issuer , 'issuer' , log_warning = False ) if isinstance ( audiences , _Mapping ) : audiences = audiences [ issuer_key ] if _verify_parsed_token ( parsed_token , issuer_values , audiences , allowed_client_ids , # There's some special handling we do for Google issuers. # ESP doesn't do this, and it's both unnecessary and invalid for other issuers. # So we'll turn it off except in the Google issuer case. is_legacy_google_auth = ( issuer . issuer == _ISSUERS ) ) : email = parsed_token [ 'email' ] # The token might have an id, but it's a Gaia ID that's been # obfuscated with the Focus key, rather than the AppEngine (igoogle) # key. If the developer ever put this email into the user DB # and retrieved the ID from that, it'd be different from the ID we'd # return here, so it's safer to not return the ID. # Instead, we'll only return the email. return users . User ( email ) | Get a User for the given id token if the token is valid . | 422 | 14 |
20,693 | def _process_scopes ( scopes ) : all_scopes = set ( ) sufficient_scopes = set ( ) for scope_set in scopes : scope_set_scopes = frozenset ( scope_set . split ( ) ) all_scopes . update ( scope_set_scopes ) sufficient_scopes . add ( scope_set_scopes ) return all_scopes , sufficient_scopes | Parse a scopes list into a set of all scopes and a set of sufficient scope sets . | 92 | 21 |
20,694 | def _are_scopes_sufficient ( authorized_scopes , sufficient_scopes ) : for sufficient_scope_set in sufficient_scopes : if sufficient_scope_set . issubset ( authorized_scopes ) : return True return False | Check if a list of authorized scopes satisfies any set of sufficient scopes . | 53 | 16 |
20,695 | def _set_bearer_user_vars ( allowed_client_ids , scopes ) : all_scopes , sufficient_scopes = _process_scopes ( scopes ) try : authorized_scopes = oauth . get_authorized_scopes ( sorted ( all_scopes ) ) except oauth . Error : _logger . debug ( 'Unable to get authorized scopes.' , exc_info = True ) return if not _are_scopes_sufficient ( authorized_scopes , sufficient_scopes ) : _logger . warning ( 'Authorized scopes did not satisfy scope requirements.' ) return client_id = oauth . get_client_id ( authorized_scopes ) # The client ID must be in allowed_client_ids. If allowed_client_ids is # empty, don't allow any client ID. If allowed_client_ids is set to # SKIP_CLIENT_ID_CHECK, all client IDs will be allowed. if ( list ( allowed_client_ids ) != SKIP_CLIENT_ID_CHECK and client_id not in allowed_client_ids ) : _logger . warning ( 'Client ID is not allowed: %s' , client_id ) return os . environ [ _ENV_USE_OAUTH_SCOPE ] = ' ' . join ( authorized_scopes ) _logger . debug ( 'get_current_user() will return user from matched oauth_user.' ) | Validate the oauth bearer token and set endpoints auth user variables . | 317 | 15 |
20,696 | def _set_bearer_user_vars_local ( token , allowed_client_ids , scopes ) : # Get token info from the tokeninfo endpoint. result = urlfetch . fetch ( '%s?%s' % ( _TOKENINFO_URL , urllib . urlencode ( { 'access_token' : token } ) ) ) if result . status_code != 200 : try : error_description = json . loads ( result . content ) [ 'error_description' ] except ( ValueError , KeyError ) : error_description = '' _logger . error ( 'Token info endpoint returned status %s: %s' , result . status_code , error_description ) return token_info = json . loads ( result . content ) # Validate email. if 'email' not in token_info : _logger . warning ( 'Oauth token doesn\'t include an email address.' ) return if token_info . get ( 'email_verified' ) != 'true' : _logger . warning ( 'Oauth token email isn\'t verified.' ) return # Validate client ID. client_id = token_info . get ( 'azp' ) if ( list ( allowed_client_ids ) != SKIP_CLIENT_ID_CHECK and client_id not in allowed_client_ids ) : _logger . warning ( 'Client ID is not allowed: %s' , client_id ) return # Verify at least one of the scopes matches. _ , sufficient_scopes = _process_scopes ( scopes ) authorized_scopes = token_info . get ( 'scope' , '' ) . split ( ' ' ) if not _are_scopes_sufficient ( authorized_scopes , sufficient_scopes ) : _logger . warning ( 'Oauth token scopes don\'t match any acceptable scopes.' ) return os . environ [ _ENV_AUTH_EMAIL ] = token_info [ 'email' ] os . environ [ _ENV_AUTH_DOMAIN ] = '' _logger . debug ( 'Local dev returning user from token.' ) | Validate the oauth bearer token on the dev server . | 463 | 12 |
20,697 | def _verify_parsed_token ( parsed_token , issuers , audiences , allowed_client_ids , is_legacy_google_auth = True ) : # Verify the issuer. if parsed_token . get ( 'iss' ) not in issuers : _logger . warning ( 'Issuer was not valid: %s' , parsed_token . get ( 'iss' ) ) return False # Check audiences. aud = parsed_token . get ( 'aud' ) if not aud : _logger . warning ( 'No aud field in token' ) return False # Special legacy handling if aud == cid. This occurs with iOS and browsers. # As long as audience == client_id and cid is allowed, we need to accept # the audience for compatibility. cid = parsed_token . get ( 'azp' ) audience_allowed = ( aud in audiences ) or ( is_legacy_google_auth and aud == cid ) if not audience_allowed : _logger . warning ( 'Audience not allowed: %s' , aud ) return False # Check allowed client IDs, for legacy auth. if is_legacy_google_auth : if list ( allowed_client_ids ) == SKIP_CLIENT_ID_CHECK : _logger . warning ( 'Client ID check can\'t be skipped for ID tokens. ' 'Id_token cannot be verified.' ) return False elif not cid or cid not in allowed_client_ids : _logger . warning ( 'Client ID is not allowed: %s' , cid ) return False if 'email' not in parsed_token : return False return True | Verify a parsed user ID token . | 355 | 8 |
20,698 | def _get_cert_expiration_time ( headers ) : # Check the max age of the cert. cache_control = headers . get ( 'Cache-Control' , '' ) # http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 indicates only # a comma-separated header is valid, so it should be fine to split this on # commas. for entry in cache_control . split ( ',' ) : match = _MAX_AGE_REGEX . match ( entry ) if match : cache_time_seconds = int ( match . group ( 1 ) ) break else : return 0 # Subtract the cert's age. age = headers . get ( 'Age' ) if age is not None : try : age = int ( age ) except ValueError : age = 0 cache_time_seconds -= age return max ( 0 , cache_time_seconds ) | Get the expiration time for a cert given the response headers . | 205 | 12 |
20,699 | def _get_cached_certs ( cert_uri , cache ) : certs = cache . get ( cert_uri , namespace = _CERT_NAMESPACE ) if certs is None : _logger . debug ( 'Cert cache miss for %s' , cert_uri ) try : result = urlfetch . fetch ( cert_uri ) except AssertionError : # This happens in unit tests. Act as if we couldn't get any certs. return None if result . status_code == 200 : certs = json . loads ( result . content ) expiration_time_seconds = _get_cert_expiration_time ( result . headers ) if expiration_time_seconds : cache . set ( cert_uri , certs , time = expiration_time_seconds , namespace = _CERT_NAMESPACE ) else : _logger . error ( 'Certs not available, HTTP request returned %d' , result . status_code ) return certs | Get certs from cache if present ; otherwise gets from URI and caches them . | 205 | 15 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.