idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
246,000
def searchDiagrams ( self , whereClause = None , relatedObjects = None , relatedSchematicObjects = None ) : params = { "f" : "json" } if whereClause : params [ "where" ] = whereClause if relatedObjects : params [ "relatedObjects" ] = relatedObjects if relatedSchematicObjects : params [ "relatedSchematicObjects" ] = rel...
The Schematic Search Diagrams operation is performed on the schematic service resource . The result of this operation is an array of Schematic Diagram Information Object .
246,001
def _validateurl ( self , url ) : parsed = urlparse ( url ) path = parsed . path . strip ( "/" ) if path : parts = path . split ( "/" ) url_types = ( "admin" , "manager" , "rest" ) if any ( i in parts for i in url_types ) : while parts . pop ( ) not in url_types : next elif "services" in parts : while parts . pop ( ) n...
assembles the server url
246,002
def admin ( self ) : if self . _securityHandler is None : raise Exception ( "Cannot connect to adminstrative server without authentication" ) from . . manageags import AGSAdministration return AGSAdministration ( url = self . _adminUrl , securityHandler = self . _securityHandler , proxy_url = self . _proxy_url , proxy_...
points to the adminstrative side of ArcGIS Server
246,003
def addUser ( self , username , password , firstname , lastname , email , role ) : self . _invites . append ( { "username" : username , "password" : password , "firstname" : firstname , "lastname" : lastname , "fullname" : "%s %s" % ( firstname , lastname ) , "email" : email , "role" : role } )
adds a user to the invitation list
246,004
def removeByIndex ( self , index ) : if index < len ( self . _invites ) - 1 and index >= 0 : self . _invites . remove ( index )
removes a user from the invitation list by position
246,005
def fromDictionary ( value ) : if isinstance ( value , dict ) : pp = PortalParameters ( ) for k , v in value . items ( ) : setattr ( pp , "_%s" % k , v ) return pp else : raise AttributeError ( "Invalid input." )
creates the portal properties object from a dictionary
246,006
def value ( self ) : val = { } for k in self . __allowed_keys : value = getattr ( self , "_" + k ) if value is not None : val [ k ] = value return val
returns the values as a dictionary
246,007
def tile_fonts ( self , fontstack , stack_range , out_folder = None ) : url = "{url}/resources/fonts/{fontstack}/{stack_range}.pbf" . format ( url = self . _url , fontstack = fontstack , stack_range = stack_range ) params = { } if out_folder is None : out_folder = tempfile . gettempdir ( ) return self . _get ( url = ur...
This resource returns glyphs in PBF format . The template url for this fonts resource is represented in Vector Tile Style resource .
246,008
def tile_sprite ( self , out_format = "sprite.json" , out_folder = None ) : url = "{url}/resources/sprites/{f}" . format ( url = self . _url , f = out_format ) if out_folder is None : out_folder = tempfile . gettempdir ( ) return self . _get ( url = url , param_dict = { } , out_folder = out_folder , securityHandler = s...
This resource returns sprite image and metadata
246,009
def layers ( self ) : if self . _layers is None : self . __init ( ) self . _getLayers ( ) return self . _layers
gets the layers for the feature service
246,010
def _getLayers ( self ) : params = { "f" : "json" } json_dict = self . _get ( self . _url , params , securityHandler = self . _securityHandler , proxy_url = self . _proxy_url , proxy_port = self . _proxy_port ) self . _layers = [ ] if 'layers' in json_dict : for l in json_dict [ "layers" ] : self . _layers . append ( l...
gets layers for the featuer service
246,011
def query ( self , layerDefsFilter = None , geometryFilter = None , timeFilter = None , returnGeometry = True , returnIdsOnly = False , returnCountOnly = False , returnZ = False , returnM = False , outSR = None ) : qurl = self . _url + "/query" params = { "f" : "json" , "returnGeometry" : returnGeometry , "returnIdsOnl...
The Query operation is performed on a feature service resource
246,012
def create_feature_layer ( ds , sql , name = "layer" ) : if arcpyFound == False : raise Exception ( "ArcPy is required to use this function" ) result = arcpy . MakeFeatureLayer_management ( in_features = ds , out_layer = name , where_clause = sql ) return result [ 0 ]
creates a feature layer object
246,013
def featureclass_to_json ( fc ) : if arcpyFound == False : raise Exception ( "ArcPy is required to use this function" ) desc = arcpy . Describe ( fc ) if desc . dataType == "Table" or desc . dataType == "TableView" : return recordset_to_json ( table = fc ) else : return arcpy . FeatureSet ( fc ) . JSON
converts a feature class to JSON
246,014
def get_attachment_data ( attachmentTable , sql , nameField = "ATT_NAME" , blobField = "DATA" , contentTypeField = "CONTENT_TYPE" , rel_object_field = "REL_OBJECTID" ) : if arcpyFound == False : raise Exception ( "ArcPy is required to use this function" ) ret_rows = [ ] with arcpy . da . SearchCursor ( attachmentTable ...
gets all the data to pass to a feature service
246,015
def get_records_with_attachments ( attachment_table , rel_object_field = "REL_OBJECTID" ) : if arcpyFound == False : raise Exception ( "ArcPy is required to use this function" ) OIDs = [ ] with arcpy . da . SearchCursor ( attachment_table , [ rel_object_field ] ) as rows : for row in rows : if not str ( row [ 0 ] ) in ...
returns a list of ObjectIDs for rows in the attachment table
246,016
def get_OID_field ( fs ) : if arcpyFound == False : raise Exception ( "ArcPy is required to use this function" ) desc = arcpy . Describe ( fs ) if desc . hasOID : return desc . OIDFieldName return None
returns a featureset s object id field
246,017
def merge_feature_class ( merges , out_fc , cleanUp = True ) : if arcpyFound == False : raise Exception ( "ArcPy is required to use this function" ) if cleanUp == False : if len ( merges ) == 0 : return None elif len ( merges ) == 1 : desc = arcpy . Describe ( merges [ 0 ] ) if hasattr ( desc , 'shapeFieldName' ) : ret...
merges featureclass into a single feature class
246,018
def insert_rows ( fc , features , fields , includeOIDField = False , oidField = None ) : if arcpyFound == False : raise Exception ( "ArcPy is required to use this function" ) icur = None if includeOIDField : arcpy . AddField_management ( fc , "FSL_OID" , "LONG" ) fields . append ( "FSL_OID" ) if len ( features ) > 0 : ...
inserts rows based on a list features object
246,019
def create_feature_class ( out_path , out_name , geom_type , wkid , fields , objectIdField ) : if arcpyFound == False : raise Exception ( "ArcPy is required to use this function" ) arcpy . env . overwriteOutput = True field_names = [ ] fc = arcpy . CreateFeatureclass_management ( out_path = out_path , out_name = out_na...
creates a feature class in a given gdb or folder
246,020
def download_arcrest ( ) : arcrest_name = "arcrest.zip" arcresthelper_name = "arcresthelper.zip" url = "https://github.com/Esri/ArcREST/archive/master.zip" file_name = os . path . join ( arcpy . env . scratchFolder , os . path . basename ( url ) ) scratch_folder = os . path . join ( arcpy . env . scratchFolder , "temp3...
downloads arcrest to disk
246,021
def handler ( self ) : if hasNTLM : if self . _handler is None : passman = request . HTTPPasswordMgrWithDefaultRealm ( ) passman . add_password ( None , self . _parsed_org_url , self . _login_username , self . _password ) self . _handler = HTTPNtlmAuthHandler . HTTPNtlmAuthHandler ( passman ) return self . _handler els...
gets the security handler for the class
246,022
def token ( self ) : return self . _portalTokenHandler . servertoken ( serverURL = self . _serverUrl , referer = self . _referer )
gets the AGS server token
246,023
def token ( self ) : if self . _token is None or datetime . datetime . now ( ) >= self . _token_expires_on : self . _generateForOAuthSecurity ( self . _client_id , self . _secret_id , self . _token_url ) return self . _token
obtains a token from the site
246,024
def _generateForOAuthSecurity ( self , client_id , secret_id , token_url = None ) : grant_type = "client_credentials" if token_url is None : token_url = "https://www.arcgis.com/sharing/rest/oauth2/token" params = { "client_id" : client_id , "client_secret" : secret_id , "grant_type" : grant_type , "f" : "json" } token ...
generates a token based on the OAuth security model
246,025
def referer_url ( self , value ) : if self . _referer_url != value : self . _token = None self . _referer_url = value
sets the referer url
246,026
def __getRefererUrl ( self , url = None ) : if url is None : url = "http://www.arcgis.com/sharing/rest/portals/self" params = { "f" : "json" , "token" : self . token } val = self . _get ( url = url , param_dict = params , proxy_url = self . _proxy_url , proxy_port = self . _proxy_port ) self . _referer_url = "arcgis.co...
gets the referer url for the token handler
246,027
def servertoken ( self , serverURL , referer ) : if self . _server_token is None or self . _server_token_expires_on is None or datetime . datetime . now ( ) >= self . _server_token_expires_on or self . _server_url != serverURL : self . _server_url = serverURL result = self . _generateForServerTokenSecurity ( serverURL ...
returns the server token for the server
246,028
def exportCertificate ( self , certificate , folder ) : url = self . _url + "/sslcertificates/%s/export" % certificate params = { "f" : "json" , } return self . _get ( url = url , param_dict = params , out_folder = folder )
gets the SSL Certificates for a given machine
246,029
def currentVersion ( self ) : if self . _currentVersion is None : self . __init ( self . _url ) return self . _currentVersion
returns the current version of the site
246,030
def portals ( self ) : url = "%s/portals" % self . root return _portals . Portals ( url = url , securityHandler = self . _securityHandler , proxy_url = self . _proxy_url , proxy_port = self . _proxy_port )
returns the Portals class that provides administration access into a given organization
246,031
def oauth2 ( self ) : if self . _url . endswith ( "/oauth2" ) : url = self . _url else : url = self . _url + "/oauth2" return _oauth2 . oauth2 ( oauth_url = url , securityHandler = self . _securityHandler , proxy_url = self . _proxy_url , proxy_port = self . _proxy_port )
returns the oauth2 class
246,032
def community ( self ) : return _community . Community ( url = self . _url + "/community" , securityHandler = self . _securityHandler , proxy_url = self . _proxy_url , proxy_port = self . _proxy_port )
The portal community root covers user and group resources and operations .
246,033
def content ( self ) : return _content . Content ( url = self . _url + "/content" , securityHandler = self . _securityHandler , proxy_url = self . _proxy_url , proxy_port = self . _proxy_port )
returns access into the site s content
246,034
def search ( self , q , t = None , focus = None , bbox = None , start = 1 , num = 10 , sortField = None , sortOrder = "asc" , useSecurity = True ) : if self . _url . endswith ( "/rest" ) : url = self . _url + "/search" else : url = self . _url + "/rest/search" params = { "f" : "json" , "q" : q , "sortOrder" : sortOrder...
This operation searches for content items in the portal . The searches are performed against a high performance index that indexes the most popular fields of an item . See the Search reference page for information on the fields and the syntax of the query . The search index is updated whenever users add update or delet...
246,035
def hostingServers ( self ) : portals = self . portals portal = portals . portalSelf urls = portal . urls if 'error' in urls : print ( urls ) return services = [ ] if urls != { } : if 'urls' in urls : if 'features' in urls [ 'urls' ] : if 'https' in urls [ 'urls' ] [ 'features' ] : for https in urls [ 'urls' ] [ 'featu...
Returns the objects to manage site s hosted services . It returns AGSAdministration object if the site is Portal and it returns a hostedservice . Services object if it is AGOL .
246,036
def add_codedValue ( self , name , code ) : if self . _codedValues is None : self . _codedValues = [ ] self . _codedValues . append ( { "name" : name , "code" : code } )
adds a value to the coded value list
246,037
def __init ( self ) : res = self . _get ( url = self . _url , param_dict = { "f" : "json" } , securityHandler = self . _securityHandler , proxy_url = self . _proxy_url , proxy_port = self . _proxy_port ) self . _json_dict = res self . _json_string = json . dumps ( self . _json_dict ) for k , v in self . _json_dict . it...
loads the json values
246,038
def areasAndLengths ( self , polygons , lengthUnit , areaUnit , calculationType , ) : url = self . _url + "/areasAndLengths" params = { "f" : "json" , "lengthUnit" : lengthUnit , "areaUnit" : { "areaUnit" : areaUnit } , "calculationType" : calculationType } if isinstance ( polygons , list ) and len ( polygons ) > 0 : p...
The areasAndLengths operation is performed on a geometry service resource . This operation calculates areas and perimeter lengths for each polygon specified in the input array .
246,039
def __geometryToGeomTemplate ( self , geometry ) : template = { "geometryType" : None , "geometry" : None } if isinstance ( geometry , Polyline ) : template [ 'geometryType' ] = "esriGeometryPolyline" elif isinstance ( geometry , Polygon ) : template [ 'geometryType' ] = "esriGeometryPolygon" elif isinstance ( geometry...
Converts a single geometry object to a geometry service geometry template value .
246,040
def __geomToStringArray ( self , geometries , returnType = "str" ) : listGeoms = [ ] for g in geometries : if isinstance ( g , Point ) : listGeoms . append ( g . asDictionary ) elif isinstance ( g , Polygon ) : listGeoms . append ( g . asDictionary ) elif isinstance ( g , Polyline ) : listGeoms . append ( { 'paths' : g...
function to convert the geomtries to strings
246,041
def autoComplete ( self , polygons = [ ] , polylines = [ ] , sr = None ) : url = self . _url + "/autoComplete" params = { "f" : "json" } if sr is not None : params [ 'sr' ] = sr params [ 'polygons' ] = self . __geomToStringArray ( polygons ) params [ 'polylines' ] = self . __geomToStringArray ( polylines ) return self ...
The autoComplete operation simplifies the process of constructing new polygons that are adjacent to other polygons . It constructs polygons that fill in the gaps between existing polygons and a set of polylines .
246,042
def buffer ( self , geometries , inSR , distances , units , outSR = None , bufferSR = None , unionResults = True , geodesic = True ) : url = self . _url + "/buffer" params = { "f" : "json" , "inSR" : inSR , "geodesic" : geodesic , "unionResults" : unionResults } if isinstance ( geometries , list ) and len ( geometries ...
The buffer operation is performed on a geometry service resource The result of this operation is buffered polygons at the specified distances for the input geometry array . Options are available to union buffers and to use geodesic distance .
246,043
def findTransformation ( self , inSR , outSR , extentOfInterest = None , numOfResults = 1 ) : params = { "f" : "json" , "inSR" : inSR , "outSR" : outSR } url = self . _url + "/findTransformations" if isinstance ( numOfResults , int ) : params [ 'numOfResults' ] = numOfResults if isinstance ( extentOfInterest , Envelope...
The findTransformations operation is performed on a geometry service resource . This operation returns a list of applicable geographic transformations you should use when projecting geometries from the input spatial reference to the output spatial reference . The transformations are in JSON format and are returned in o...
246,044
def fromGeoCoordinateString ( self , sr , strings , conversionType , conversionMode = None ) : url = self . _url + "/fromGeoCoordinateString" params = { "f" : "json" , "sr" : sr , "strings" : strings , "conversionType" : conversionType } if not conversionMode is None : params [ 'conversionMode' ] = conversionMode retur...
The fromGeoCoordinateString operation is performed on a geometry service resource . The operation converts an array of well - known strings into xy - coordinates based on the conversion type and spatial reference supplied by the user . An optional conversion mode parameter is available for some conversion types .
246,045
def toGeoCoordinateString ( self , sr , coordinates , conversionType , conversionMode = "mgrsDefault" , numOfDigits = None , rounding = True , addSpaces = True ) : params = { "f" : "json" , "sr" : sr , "coordinates" : coordinates , "conversionType" : conversionType } url = self . _url + "/toGeoCoordinateString" if not ...
The toGeoCoordinateString operation is performed on a geometry service resource . The operation converts an array of xy - coordinates into well - known strings based on the conversion type and spatial reference supplied by the user . Optional parameters are available for some conversion types . Note that if an optional...
246,046
def __init_url ( self ) : portals_self_url = "{}/portals/self" . format ( self . _url ) params = { "f" : "json" } if not self . _securityHandler is None : params [ 'token' ] = self . _securityHandler . token res = self . _get ( url = portals_self_url , param_dict = params , securityHandler = self . _securityHandler , p...
loads the information into the class
246,047
def get_argument_parser ( name = None , ** kwargs ) : if name is None : name = "default" if len ( kwargs ) > 0 or name not in _parsers : init_argument_parser ( name , ** kwargs ) return _parsers [ name ]
Returns the global ArgumentParser instance with the given name . The 1st time this function is called a new ArgumentParser instance will be created for the given name and any args other than name will be passed on to the ArgumentParser constructor .
246,048
def parse ( self , stream ) : items = OrderedDict ( ) for i , line in enumerate ( stream ) : line = line . strip ( ) if not line or line [ 0 ] in [ "#" , ";" , "[" ] or line . startswith ( "---" ) : continue white_space = "\\s*" key = "(?P<key>[^:=;#\s]+?)" value = white_space + "[:=\s]" + white_space + "(?P<value>.+?)...
Parses the keys + values from a config file .
246,049
def parse ( self , stream ) : yaml = self . _load_yaml ( ) try : parsed_obj = yaml . safe_load ( stream ) except Exception as e : raise ConfigFileParserException ( "Couldn't parse config file: %s" % e ) if not isinstance ( parsed_obj , dict ) : raise ConfigFileParserException ( "The config file doesn't appear to " "con...
Parses the keys and values from a config file .
246,050
def write_config_file ( self , parsed_namespace , output_file_paths , exit_after = False ) : for output_file_path in output_file_paths : try : with open ( output_file_path , "w" ) as output_file : pass except IOError as e : raise ValueError ( "Couldn't open %s for writing: %s" % ( output_file_path , e ) ) if output_fil...
Write the given settings to output files .
246,051
def convert_item_to_command_line_arg ( self , action , key , value ) : args = [ ] if action is None : command_line_key = self . get_command_line_key_for_unknown_config_file_setting ( key ) else : command_line_key = action . option_strings [ - 1 ] if action is not None and isinstance ( action , ACTION_TYPES_THAT_DONT_NE...
Converts a config file or env var key + value to a list of commandline args to append to the commandline .
246,052
def get_possible_config_keys ( self , action ) : keys = [ ] if getattr ( action , 'is_write_out_config_file_arg' , None ) : return keys for arg in action . option_strings : if any ( [ arg . startswith ( 2 * c ) for c in self . prefix_chars ] ) : keys += [ arg [ 2 : ] , arg ] return keys
This method decides which actions can be set in a config file and what their keys will be . It returns a list of 0 or more config keys that can be used to set the given action s value in a config file .
246,053
def eval ( lisp ) : macro_values = [ ] if not isinstance ( lisp , list ) : raise EvalError ( 'eval root element must be a list' ) for item in lisp : if not isinstance ( item , list ) : raise EvalError ( 'must evaluate list of list' ) if not all ( isinstance ( i , str ) for i in item ) : raise EvalError ( 'must evaluate...
plash lisp is one dimensional lisp .
246,054
def plash_map ( * args ) : from subprocess import check_output 'thin wrapper around plash map' out = check_output ( [ 'plash' , 'map' ] + list ( args ) ) if out == '' : return None return out . decode ( ) . strip ( '\n' )
thin wrapper around plash map
246,055
def defpm ( name , * lines ) : 'define a new package manager' @ register_macro ( name , group = 'package managers' ) @ shell_escape_args def package_manager ( * packages ) : if not packages : return sh_packages = ' ' . join ( pkg for pkg in packages ) expanded_lines = [ line . format ( sh_packages ) for line in lines ]...
define a new package manager
246,056
def layer ( command = None , * args ) : 'hints the start of a new layer' if not command : return eval ( [ [ 'hint' , 'layer' ] ] ) else : lst = [ [ 'layer' ] ] for arg in args : lst . append ( [ command , arg ] ) lst . append ( [ 'layer' ] ) return eval ( lst )
hints the start of a new layer
246,057
def import_env ( * envs ) : 'import environment variables from host' for env in envs : parts = env . split ( ':' , 1 ) if len ( parts ) == 1 : export_as = env else : env , export_as = parts env_val = os . environ . get ( env ) if env_val is not None : yield '{}={}' . format ( export_as , shlex . quote ( env_val ) )
import environment variables from host
246,058
def write_file ( fname , * lines ) : 'write lines to a file' yield 'touch {}' . format ( fname ) for line in lines : yield "echo {} >> {}" . format ( line , fname )
write lines to a file
246,059
def eval_file ( file ) : 'evaluate file content as expressions' fname = os . path . realpath ( os . path . expanduser ( file ) ) with open ( fname ) as f : inscript = f . read ( ) sh = run_write_read ( [ 'plash' , 'eval' ] , inscript . encode ( ) ) . decode ( ) if sh . endswith ( '\n' ) : return sh [ : - 1 ] return sh
evaluate file content as expressions
246,060
def eval_string ( stri ) : 'evaluate expressions passed as string' tokens = shlex . split ( stri ) return run_write_read ( [ 'plash' , 'eval' ] , '\n' . join ( tokens ) . encode ( ) ) . decode ( )
evaluate expressions passed as string
246,061
def eval_stdin ( ) : 'evaluate expressions read from stdin' cmd = [ 'plash' , 'eval' ] p = subprocess . Popen ( cmd , stdin = sys . stdin , stdout = sys . stdout ) exit = p . wait ( ) if exit : raise subprocess . CalledProcessError ( exit , cmd )
evaluate expressions read from stdin
246,062
def from_map ( map_key ) : 'use resolved map as image' image_id = subprocess . check_output ( [ 'plash' , 'map' , map_key ] ) . decode ( ) . strip ( '\n' ) if not image_id : raise MapDoesNotExist ( 'map {} not found' . format ( repr ( map_key ) ) ) return hint ( 'image' , image_id )
use resolved map as image
246,063
def fields ( self ) : fields = super ( DynamicFieldsMixin , self ) . fields if not hasattr ( self , '_context' ) : return fields is_root = self . root == self parent_is_list_root = self . parent == self . root and getattr ( self . parent , 'many' , False ) if not ( is_root or parent_is_list_root ) : return fields try :...
Filters the fields according to the fields query parameter .
246,064
def setup_admin_on_rest_handlers ( admin , admin_handler ) : add_route = admin . router . add_route add_static = admin . router . add_static static_folder = str ( PROJ_ROOT / 'static' ) a = admin_handler add_route ( 'GET' , '' , a . index_page , name = 'admin.index' ) add_route ( 'POST' , '/token' , a . token , name = ...
Initialize routes .
246,065
async def index_page ( self , request ) : context = { "initial_state" : self . schema . to_json ( ) } return render_template ( self . template , request , context , app_key = TEMPLATE_APP_KEY , )
Return index page with initial state for admin
246,066
async def logout ( self , request ) : if "Authorization" not in request . headers : msg = "Auth header is not present, can not destroy token" raise JsonValidaitonError ( msg ) response = json_response ( ) await forget ( request , response ) return response
Simple handler for logout
246,067
def validate_query_structure ( query ) : query_dict = dict ( query ) filters = query_dict . pop ( '_filters' , None ) if filters : try : f = json . loads ( filters ) except ValueError : msg = '_filters field can not be serialized' raise JsonValidaitonError ( msg ) else : query_dict [ '_filters' ] = f try : q = ListQuer...
Validate query arguments in list request .
246,068
def to_json ( self ) : endpoints = [ ] for endpoint in self . endpoints : list_fields = endpoint . fields resource_type = endpoint . Meta . resource_type table = endpoint . Meta . table data = endpoint . to_dict ( ) data [ 'fields' ] = resource_type . get_type_of_fields ( list_fields , table , ) endpoints . append ( da...
Prepare data for the initial state of the admin - on - rest
246,069
def resources ( self ) : resources = [ ] for endpoint in self . endpoints : resource_type = endpoint . Meta . resource_type table = endpoint . Meta . table url = endpoint . name resources . append ( ( resource_type , { 'table' : table , 'url' : url } ) ) return resources
Return list of all registered resources .
246,070
def get_type_of_fields ( fields , table ) : if not fields : fields = table . primary_key actual_fields = [ field for field in table . c . items ( ) if field [ 0 ] in fields ] data_type_fields = { name : FIELD_TYPES . get ( type ( field_type . type ) , rc . TEXT_FIELD . value ) for name , field_type in actual_fields } r...
Return data types of fields that are in table . If a given parameter is empty return primary key .
246,071
def get_type_for_inputs ( table ) : return [ dict ( type = INPUT_TYPES . get ( type ( field_type . type ) , rc . TEXT_INPUT . value ) , name = name , isPrimaryKey = ( name in table . primary_key ) , props = None , ) for name , field_type in table . c . items ( ) ]
Return information about table s fields in dictionary type .
246,072
def _setup ( app , * , schema , title = None , app_key = APP_KEY , db = None ) : admin = web . Application ( loop = app . loop ) app [ app_key ] = admin loader = jinja2 . FileSystemLoader ( [ TEMPLATES_ROOT , ] ) aiohttp_jinja2 . setup ( admin , loader = loader , app_key = TEMPLATE_APP_KEY ) if title : schema . title =...
Initialize the admin - on - rest admin
246,073
def to_dict ( self ) : data = { "name" : self . name , "canEdit" : self . can_edit , "canCreate" : self . can_create , "canDelete" : self . can_delete , "perPage" : self . per_page , "showPage" : self . generate_data_for_show_page ( ) , "editPage" : self . generate_data_for_edit_page ( ) , "createPage" : self . generat...
Return dict with the all base information about the instance .
246,074
def generate_data_for_edit_page ( self ) : if not self . can_edit : return { } if self . edit_form : return self . edit_form . to_dict ( ) return self . generate_simple_data_page ( )
Generate a custom representation of table s fields in dictionary type if exist edit form else use default representation .
246,075
def generate_data_for_create_page ( self ) : if not self . can_create : return { } if self . create_form : return self . create_form . to_dict ( ) return self . generate_simple_data_page ( )
Generate a custom representation of table s fields in dictionary type if exist create form else use default representation .
246,076
async def register ( self , request ) : session = await get_session ( request ) user_id = session . get ( 'user_id' ) if user_id : return redirect ( request , 'timeline' ) error = None form = None if request . method == 'POST' : form = await request . post ( ) user_id = await db . get_user_id ( self . mongo . user , fo...
Registers the user .
246,077
async def follow_user ( self , request ) : username = request . match_info [ 'username' ] session = await get_session ( request ) user_id = session . get ( 'user_id' ) if not user_id : raise web . HTTPNotAuthorized ( ) whom_id = await db . get_user_id ( self . mongo . user , username ) if whom_id is None : raise web . ...
Adds the current user as follower of the given user .
246,078
async def add_message ( self , request ) : session = await get_session ( request ) user_id = session . get ( 'user_id' ) if not user_id : raise web . HTTPNotAuthorized ( ) form = await request . post ( ) if form . get ( 'text' ) : user = await self . mongo . user . find_one ( { '_id' : ObjectId ( session [ 'user_id' ] ...
Registers a new message for the user .
246,079
def robo_avatar_url ( user_data , size = 80 ) : hash = md5 ( str ( user_data ) . strip ( ) . lower ( ) . encode ( 'utf-8' ) ) . hexdigest ( ) url = "https://robohash.org/{hash}.png?size={size}x{size}" . format ( hash = hash , size = size ) return url
Return the gravatar image for the given email address .
246,080
def waitgrab ( self , timeout = 60 , autocrop = True , cb_imgcheck = None ) : t = 0 sleep_time = 0.3 repeat_time = 1 while 1 : log . debug ( 'sleeping %s secs' % str ( sleep_time ) ) time . sleep ( sleep_time ) t += sleep_time img = self . grab ( autocrop = autocrop ) if img : if not cb_imgcheck : break if cb_imgcheck ...
start process and create screenshot . Repeat screenshot until it is not empty and cb_imgcheck callback function returns True for current screenshot .
246,081
def _setup_xauth ( self ) : handle , filename = tempfile . mkstemp ( prefix = 'PyVirtualDisplay.' , suffix = '.Xauthority' ) self . _xauth_filename = filename os . close ( handle ) self . _old_xauth = { } self . _old_xauth [ 'AUTHFILE' ] = os . getenv ( 'AUTHFILE' ) self . _old_xauth [ 'XAUTHORITY' ] = os . getenv ( 'X...
Set up the Xauthority file and the XAUTHORITY environment variable .
246,082
def _clear_xauth ( self ) : os . remove ( self . _xauth_filename ) for varname in [ 'AUTHFILE' , 'XAUTHORITY' ] : if self . _old_xauth [ varname ] is None : del os . environ [ varname ] else : os . environ [ varname ] = self . _old_xauth [ varname ] self . _old_xauth = None
Clear the Xauthority file and restore the environment variables .
246,083
def GetCookies ( self ) : sectoken = self . GetSecurityToken ( self . Username , self . Password ) url = self . share_point_site + '/_forms/default.aspx?wa=wsignin1.0' response = requests . post ( url , data = sectoken ) return response . cookies
Grabs the cookies form your Office Sharepoint site and uses it as Authentication for the rest of the calls
246,084
def DeleteList ( self , listName ) : soap_request = soap ( 'DeleteList' ) soap_request . add_parameter ( 'listName' , listName ) self . last_request = str ( soap_request ) response = self . _session . post ( url = self . _url ( 'Lists' ) , headers = self . _headers ( 'DeleteList' ) , data = str ( soap_request ) , verif...
Delete a List with given name
246,085
def GetListCollection ( self ) : soap_request = soap ( 'GetListCollection' ) self . last_request = str ( soap_request ) response = self . _session . post ( url = self . _url ( 'SiteData' ) , headers = self . _headers ( 'GetListCollection' ) , data = str ( soap_request ) , verify = self . _verify_ssl , timeout = self . ...
Returns List information for current Site
246,086
def _convert_to_internal ( self , data ) : for _dict in data : keys = list ( _dict . keys ( ) ) [ : ] for key in keys : if key not in self . _disp_cols : raise Exception ( key + ' not a column in current List.' ) _dict [ self . _disp_cols [ key ] [ 'name' ] ] = self . _sp_type ( key , _dict . pop ( key ) )
From Column Title to Column_x0020_Title
246,087
def _convert_to_display ( self , data ) : for _dict in data : keys = list ( _dict . keys ( ) ) [ : ] for key in keys : if key not in self . _sp_cols : raise Exception ( key + ' not a column in current List.' ) _dict [ self . _sp_cols [ key ] [ 'name' ] ] = self . _python_type ( key , _dict . pop ( key ) )
From Column_x0020_Title to Column Title
246,088
def GetView ( self , viewname ) : soap_request = soap ( 'GetView' ) soap_request . add_parameter ( 'listName' , self . listName ) if viewname == None : views = self . GetViewCollection ( ) for view in views : if 'DefaultView' in view : if views [ view ] [ 'DefaultView' ] == 'TRUE' : viewname = view break if self . list...
Get Info on View Name
246,089
def UpdateListItems ( self , data , kind ) : if type ( data ) != list : raise Exception ( 'data must be a list of dictionaries' ) soap_request = soap ( 'UpdateListItems' ) soap_request . add_parameter ( 'listName' , self . listName ) if kind != 'Delete' : self . _convert_to_internal ( data ) soap_request . add_actions ...
Update List Items kind = New Update or Delete
246,090
def GetAttachmentCollection ( self , _id ) : soap_request = soap ( 'GetAttachmentCollection' ) soap_request . add_parameter ( 'listName' , self . listName ) soap_request . add_parameter ( 'listItemID' , _id ) self . last_request = str ( soap_request ) response = self . _session . post ( url = self . _url ( 'Lists' ) , ...
Get Attachments for given List Item ID
246,091
def changes ( new_cmp_dict , old_cmp_dict , id_column , columns ) : update_ldict = [ ] same_keys = set ( new_cmp_dict ) . intersection ( set ( old_cmp_dict ) ) for same_key in same_keys : old_dict = old_cmp_dict [ same_key ] new_dict = new_cmp_dict [ same_key ] dict_keys = set ( old_dict ) . intersection ( set ( new_di...
Return a list dict of the changes of the rows that exist in both dictionaries User must provide an ID column for old_cmp_dict
246,092
def unique ( new_cmp_dict , old_cmp_dict ) : newkeys = set ( new_cmp_dict ) oldkeys = set ( old_cmp_dict ) unique = newkeys - oldkeys unique_ldict = [ ] for key in unique : unique_ldict . append ( new_cmp_dict [ key ] ) return unique_ldict
Return a list dict of the unique keys in new_cmp_dict
246,093
def traceplot ( trace : sample_types , labels : List [ Union [ str , Tuple [ str , str ] ] ] = None , ax : Any = None , x0 : int = 0 ) -> Any : if labels is None : labels = list ( trace . keys ( ) ) if ax is None : _ , ax = plt . subplots ( len ( labels ) , 1 , squeeze = False ) for index , label in enumerate ( labels ...
Plot samples values .
246,094
def read_file_snippets ( file , snippet_store ) : start_reg = re . compile ( "(.*%%SNIPPET_START%% )([a-zA-Z0-9]+)" ) end_reg = re . compile ( "(.*%%SNIPPET_END%% )([a-zA-Z0-9]+)" ) open_snippets = { } with open ( file , encoding = "utf-8" ) as w : lines = w . readlines ( ) for line in lines : printd ( "Got Line: {}" ....
Parse a file and add all snippets to the snippet_store dictionary
246,095
def strip_block_whitespace ( string_list ) : min_ws = min ( [ ( len ( x ) - len ( x . lstrip ( ) ) ) for x in string_list if x != '\n' ] ) return [ x [ min_ws : ] if x != '\n' else x for x in string_list ]
Treats a list of strings as a code block and strips whitespace so that the min whitespace line sits at char 0 of line .
246,096
async def prepare ( self , request ) : if request . method != 'GET' : raise HTTPMethodNotAllowed ( request . method , [ 'GET' ] ) if not self . prepared : writer = await super ( ) . prepare ( request ) self . _loop = request . app . loop self . _ping_task = self . _loop . create_task ( self . _ping ( ) ) self . enable_...
Prepare for streaming and send HTTP headers .
246,097
async def send ( self , data , id = None , event = None , retry = None ) : buffer = io . StringIO ( ) if id is not None : buffer . write ( self . LINE_SEP_EXPR . sub ( '' , 'id: {}' . format ( id ) ) ) buffer . write ( self . _sep ) if event is not None : buffer . write ( self . LINE_SEP_EXPR . sub ( '' , 'event: {}' ....
Send data using EventSource protocol
246,098
async def wait ( self ) : if self . _ping_task is None : raise RuntimeError ( 'Response is not started' ) with contextlib . suppress ( asyncio . CancelledError ) : await self . _ping_task
EventSourceResponse object is used for streaming data to the client this method returns future so we can wain until connection will be closed or other task explicitly call stop_streaming method .
246,099
def ping_interval ( self , value ) : if not isinstance ( value , int ) : raise TypeError ( "ping interval must be int" ) if value < 0 : raise ValueError ( "ping interval must be greater then 0" ) self . _ping_interval = value
Setter for ping_interval property .