idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
50,500 | def routeDefault ( self , request , year = None ) : eventsView = request . GET . get ( 'view' , self . default_view ) if eventsView in ( "L" , "list" ) : return self . serveUpcoming ( request ) elif eventsView in ( "W" , "weekly" ) : return self . serveWeek ( request , year ) else : return self . serveMonth ( request ,... | Route a request to the default calendar view . |
50,501 | def routeByMonthAbbr ( self , request , year , monthAbbr ) : month = ( DatePictures [ 'Mon' ] . index ( monthAbbr . lower ( ) ) // 4 ) + 1 return self . serveMonth ( request , year , month ) | Route a request with a month abbreviation to the monthly view . |
50,502 | def serveMonth ( self , request , year = None , month = None ) : myurl = self . get_url ( request ) def myUrl ( urlYear , urlMonth ) : if 1900 <= urlYear <= 2099 : return myurl + self . reverse_subpage ( 'serveMonth' , args = [ urlYear , urlMonth ] ) today = timezone . localdate ( ) if year is None : year = today . yea... | Monthly calendar view . |
50,503 | def serveWeek ( self , request , year = None , week = None ) : myurl = self . get_url ( request ) def myUrl ( urlYear , urlWeek ) : if ( urlYear < 1900 or urlYear > 2099 or urlYear == 2099 and urlWeek == 53 ) : return None if urlWeek == 53 and num_weeks_in_year ( urlYear ) == 52 : urlWeek = 52 return myurl + self . rev... | Weekly calendar view . |
50,504 | def serveDay ( self , request , year = None , month = None , dom = None ) : myurl = self . get_url ( request ) today = timezone . localdate ( ) if year is None : year = today . year if month is None : month = today . month if dom is None : dom = today . day year = int ( year ) month = int ( month ) dom = int ( dom ) da... | The events of the day list view . |
50,505 | def serveUpcoming ( self , request ) : myurl = self . get_url ( request ) today = timezone . localdate ( ) monthlyUrl = myurl + self . reverse_subpage ( 'serveMonth' , args = [ today . year , today . month ] ) weekNum = gregorian_to_week_date ( today ) [ 1 ] weeklyUrl = myurl + self . reverse_subpage ( 'serveWeek' , ar... | Upcoming events list view . |
50,506 | def serveMiniMonth ( self , request , year = None , month = None ) : if not request . is_ajax ( ) : raise Http404 ( "/mini/ is for ajax requests only" ) today = timezone . localdate ( ) if year is None : year = today . year if month is None : month = today . month year = int ( year ) month = int ( month ) return render... | Serve data for the MiniMonth template tag . |
50,507 | def _allowAnotherAt ( cls , parent ) : site = parent . get_site ( ) if site is None : return False return not cls . peers ( ) . descendant_of ( site . root_page ) . exists ( ) | You can only create one of these pages per site . |
50,508 | def peers ( cls ) : contentType = ContentType . objects . get_for_model ( cls ) return cls . objects . filter ( content_type = contentType ) | Return others of the same concrete type . |
50,509 | def _getEventsOnDay ( self , request , day ) : home = request . site . root_page return getAllEventsByDay ( request , day , day , home = home ) [ 0 ] | Return all the events in this site for a given day . |
50,510 | def _getEventsByDay ( self , request , firstDay , lastDay ) : home = request . site . root_page return getAllEventsByDay ( request , firstDay , lastDay , home = home ) | Return the events in this site for the dates given grouped by day . |
50,511 | def _getEventsByWeek ( self , request , year , month ) : home = request . site . root_page return getAllEventsByWeek ( request , year , month , home = home ) | Return the events in this site for the given month grouped by week . |
50,512 | def _getUpcomingEvents ( self , request ) : home = request . site . root_page return getAllUpcomingEvents ( request , home = home ) | Return the upcoming events in this site . |
50,513 | def _getPastEvents ( self , request ) : home = request . site . root_page return getAllPastEvents ( request , home = home ) | Return the past events in this site . |
50,514 | def _getEventFromUid ( self , request , uid ) : event = getEventFromUid ( request , uid ) home = request . site . root_page if event . get_ancestors ( ) . filter ( id = home . id ) . exists ( ) : return event | Try and find an event with the given UID in this site . |
50,515 | def _getAllEvents ( self , request ) : home = request . site . root_page return getAllEvents ( request , home = home ) | Return all the events in this site . |
50,516 | def _getEventsOnDay ( self , request , day ) : return getAllEventsByDay ( request , day , day , home = self ) [ 0 ] | Return my child events for a given day . |
50,517 | def _getEventsByDay ( self , request , firstDay , lastDay ) : return getAllEventsByDay ( request , firstDay , lastDay , home = self ) | Return my child events for the dates given grouped by day . |
50,518 | def _getEventsByWeek ( self , request , year , month ) : return getAllEventsByWeek ( request , year , month , home = self ) | Return my child events for the given month grouped by week . |
50,519 | def _getEventFromUid ( self , request , uid ) : event = getEventFromUid ( request , uid ) if event . get_ancestors ( ) . filter ( id = self . id ) . exists ( ) : return event | Try and find a child event with the given UID . |
50,520 | def events_this_week ( context ) : request = context [ 'request' ] home = request . site . root_page cal = CalendarPage . objects . live ( ) . descendant_of ( home ) . first ( ) calUrl = cal . get_url ( request ) if cal else None calName = cal . title if cal else None today = dt . date . today ( ) beginOrd = today . to... | Displays a week s worth of events . Starts week with Monday unless today is Sunday . |
50,521 | def minicalendar ( context ) : today = dt . date . today ( ) request = context [ 'request' ] home = request . site . root_page cal = CalendarPage . objects . live ( ) . descendant_of ( home ) . first ( ) calUrl = cal . get_url ( request ) if cal else None if cal : events = cal . _getEventsByWeek ( request , today . yea... | Displays a little ajax version of the calendar . |
50,522 | def subsite_upcoming_events ( context ) : request = context [ 'request' ] home = request . site . root_page return { 'request' : request , 'events' : getAllUpcomingEvents ( request , home = home ) } | Displays a list of all upcoming events in this site . |
50,523 | def group_upcoming_events ( context , group = None ) : request = context . get ( 'request' ) if group is None : group = context . get ( 'page' ) if group : events = getGroupUpcomingEvents ( request , group ) else : events = [ ] return { 'request' : request , 'events' : events } | Displays a list of all upcoming events that are assigned to a specific group . If the group is not specified it is assumed to be the current page . |
50,524 | def next_on ( context , rrevent = None ) : request = context [ 'request' ] if rrevent is None : rrevent = context . get ( 'page' ) eventNextOn = getattr ( rrevent , '_nextOn' , lambda _ : None ) return eventNextOn ( request ) | Displays when the next occurence of a recurring event will be . If the recurring event is not specified it is assumed to be the current page . |
50,525 | def location_gmap ( context , location ) : gmapq = None if getattr ( MapFieldPanel , "UsingWagtailGMaps" , False ) : gmapq = location return { 'gmapq' : gmapq } | Display a link to Google maps iff we are using WagtailGMaps |
50,526 | def getGroupUpcomingEvents ( request , group ) : rrEvents = RecurringEventPage . events ( request ) . exclude ( group_page = group ) . upcoming ( ) . child_of ( group ) . this ( ) qrys = [ SimpleEventPage . events ( request ) . exclude ( group_page = group ) . upcoming ( ) . child_of ( group ) . this ( ) , MultidayEven... | Return all the upcoming events that are assigned to the specified group . |
50,527 | def group ( self ) : retval = None parent = self . get_parent ( ) Group = get_group_model ( ) if issubclass ( parent . specific_class , Group ) : retval = parent . specific if retval is None : retval = self . group_page return retval | The group this event belongs to . Adding the event as a child of a group automatically assigns the event to that group . |
50,528 | def isAuthorized ( self , request ) : restrictions = self . get_view_restrictions ( ) if restrictions and request is None : return False else : return all ( restriction . accept_request ( request ) for restriction in restrictions ) | Is the user authorized for the requested action with this event? |
50,529 | def _upcoming_datetime_from ( self ) : nextDt = self . __localAfter ( timezone . localtime ( ) , dt . time . max , excludeCancellations = True , excludeExtraInfo = True ) return nextDt | The datetime this event next starts in the local time zone or None if it is finished . |
50,530 | def _past_datetime_from ( self ) : prevDt = self . __localBefore ( timezone . localtime ( ) , dt . time . max , excludeCancellations = True , excludeExtraInfo = True ) return prevDt | The datetime this event previously started in the local time zone or None if it never did . |
50,531 | def _first_datetime_from ( self ) : myFromDt = self . _getMyFirstDatetimeFrom ( ) localTZ = timezone . get_current_timezone ( ) return myFromDt . astimezone ( localTZ ) | The datetime this event first started in the local time zone or None if it never did . |
50,532 | def _getFromTime ( self , atDate = None ) : if atDate is None : atDate = timezone . localdate ( timezone = self . tz ) return getLocalTime ( atDate , self . time_from , self . tz ) | What was the time of this event? Due to time zones that depends what day we are talking about . If no day is given assume today . |
50,533 | def _getFromDt ( self ) : myNow = timezone . localtime ( timezone = self . tz ) return self . __after ( myNow ) or self . __before ( myNow ) | Get the datetime of the next event after or before now . |
50,534 | def _futureExceptions ( self , request ) : retval = [ ] myToday = timezone . localdate ( timezone = self . tz ) for extraInfo in ExtraInfoPage . events ( request ) . child_of ( self ) . filter ( except_date__gte = myToday ) : retval . append ( extraInfo ) for cancellation in CancellationPage . events ( request ) . chil... | Returns all future extra info cancellations and postponements created for this recurring event |
50,535 | def _getMyFirstDatetimeFrom ( self ) : myStartDt = getAwareDatetime ( self . repeat . dtstart , None , self . tz , dt . time . min ) return self . __after ( myStartDt , excludeCancellations = False ) | The datetime this event first started or None if it never did . |
50,536 | def _getMyFirstDatetimeTo ( self ) : myFirstDt = self . _getMyFirstDatetimeFrom ( ) if myFirstDt is not None : daysDelta = dt . timedelta ( days = self . num_days - 1 ) return getAwareDatetime ( myFirstDt . date ( ) + daysDelta , self . time_to , self . tz , dt . time . max ) | The datetime this event first finished or None if it never did . |
50,537 | def local_title ( self ) : name = self . title . partition ( " for " ) [ 0 ] exceptDate = getLocalDate ( self . except_date , self . time_from , self . tz ) title = _ ( "{exception} for {date}" ) . format ( exception = _ ( name ) , date = dateFormat ( exceptDate ) ) return title | Localised version of the human - readable title of the page . |
50,538 | def full_clean ( self , * args , ** kwargs ) : name = getattr ( self , 'name' , self . slugName . title ( ) ) self . title = "{} for {}" . format ( name , dateFormat ( self . except_date ) ) self . slug = "{}-{}" . format ( self . except_date , self . slugName ) super ( ) . full_clean ( * args , ** kwargs ) | Apply fixups that need to happen before per - field validation occurs . Sets the page s title . |
50,539 | def what ( self ) : originalFromDt = dt . datetime . combine ( self . except_date , timeFrom ( self . overrides . time_from ) ) changedFromDt = dt . datetime . combine ( self . date , timeFrom ( self . time_from ) ) originalDaysDelta = dt . timedelta ( days = self . overrides . num_days - 1 ) originalToDt = getAwareDat... | May return a postponed or rescheduled string depending what the start and finish time of the event has been changed to . |
50,540 | def _convertTZ ( self ) : tz = timezone . get_current_timezone ( ) dtstart = self [ 'DTSTART' ] dtend = self [ 'DTEND' ] if dtstart . zone ( ) == "UTC" : dtstart . dt = dtstart . dt . astimezone ( tz ) if dtend . zone ( ) == "UTC" : dtend . dt = dtend . dt . astimezone ( tz ) | Will convert UTC datetimes to the current local timezone |
50,541 | def to_naive_utc ( dtime ) : if not hasattr ( dtime , 'tzinfo' ) or dtime . tzinfo is None : return dtime dtime_utc = dtime . astimezone ( pytz . UTC ) dtime_naive = dtime_utc . replace ( tzinfo = None ) return dtime_naive | convert a datetime object to UTC and than remove the tzinfo if datetime is naive already return it |
50,542 | def create_timezone ( tz , first_date = None , last_date = None ) : if isinstance ( tz , pytz . tzinfo . StaticTzInfo ) : return _create_timezone_static ( tz ) first_date = dt . datetime . today ( ) if not first_date else to_naive_utc ( first_date ) last_date = dt . datetime . today ( ) if not last_date else to_naive_u... | create an icalendar vtimezone from a pytz . tzinfo object |
50,543 | def _create_timezone_static ( tz ) : timezone = icalendar . Timezone ( ) timezone . add ( 'TZID' , tz ) subcomp = icalendar . TimezoneStandard ( ) subcomp . add ( 'TZNAME' , tz ) subcomp . add ( 'DTSTART' , dt . datetime ( 1601 , 1 , 1 ) ) subcomp . add ( 'RDATE' , dt . datetime ( 1601 , 1 , 1 ) ) subcomp . add ( 'TZOF... | create an icalendar vtimezone from a pytz . tzinfo . StaticTzInfo |
50,544 | def bend ( mapping , source , context = None ) : context = { } if context is None else context transport = Transport ( source , context ) return _bend ( mapping , transport ) | The main bending function . |
50,545 | def protect ( self , protect_against = None ) : return ProtectedF ( self . _func , * self . _args , protect_against = protect_against , ** self . _kwargs ) | Return a ProtectedF with the same parameters and with the given protect_against . |
50,546 | def init_logs ( args , tool = "NanoPlot" ) : start_time = dt . fromtimestamp ( time ( ) ) . strftime ( '%Y%m%d_%H%M' ) logname = os . path . join ( args . outdir , args . prefix + tool + "_" + start_time + ".log" ) handlers = [ logging . FileHandler ( logname ) ] if args . verbose : handlers . append ( logging . Stream... | Initiate log file and log arguments . |
50,547 | def flag_length_outliers ( df , columnname ) : return df [ columnname ] > ( np . median ( df [ columnname ] ) + 3 * np . std ( df [ columnname ] ) ) | Return index of records with length - outliers above 3 standard deviations from the median . |
50,548 | def _raise_for_status ( response ) : http_error_msg = "" if 400 <= response . status_code < 500 : http_error_msg = "{0} Client Error: {1}" . format ( response . status_code , response . reason ) elif 500 <= response . status_code < 600 : http_error_msg = "{0} Server Error: {1}" . format ( response . status_code , respo... | Custom raise_for_status with more appropriate error message . |
50,549 | def _clear_empty_values ( args ) : result = { } for param in args : if args [ param ] is not None : result [ param ] = args [ param ] return result | Scrap junk data from a dict . |
50,550 | def authentication_validation ( username , password , access_token ) : if bool ( username ) is not bool ( password ) : raise Exception ( "Basic authentication requires a username AND" " password." ) if ( username and access_token ) or ( password and access_token ) : raise Exception ( "Cannot use both Basic Authenticati... | Only accept one form of authentication . |
50,551 | def _download_file ( url , local_filename ) : response = requests . get ( url , stream = True ) with open ( local_filename , 'wb' ) as outfile : for chunk in response . iter_content ( chunk_size = 1024 ) : if chunk : outfile . write ( chunk ) | Utility function that downloads a chunked response from the specified url to a local path . This method is suitable for larger downloads . |
50,552 | def set_permission ( self , dataset_identifier , permission = "private" , content_type = "json" ) : resource = _format_old_api_request ( dataid = dataset_identifier , content_type = content_type ) params = { "method" : "setPermission" , "value" : "public.read" if permission == "public" else permission } return self . _... | Set a dataset s permissions to private or public Options are private public |
50,553 | def get_metadata ( self , dataset_identifier , content_type = "json" ) : resource = _format_old_api_request ( dataid = dataset_identifier , content_type = content_type ) return self . _perform_request ( "get" , resource ) | Retrieve the metadata for a particular dataset . |
50,554 | def download_attachments ( self , dataset_identifier , content_type = "json" , download_dir = "~/sodapy_downloads" ) : metadata = self . get_metadata ( dataset_identifier , content_type = content_type ) files = [ ] attachments = metadata [ 'metadata' ] . get ( "attachments" ) if not attachments : logging . info ( "No a... | Download all of the attachments associated with a dataset . Return the paths of downloaded files . |
50,555 | def replace_non_data_file ( self , dataset_identifier , params , file_data ) : resource = _format_old_api_request ( dataid = dataset_identifier , content_type = "txt" ) if not params . get ( 'method' , None ) : params [ 'method' ] = 'replaceBlob' params [ 'id' ] = dataset_identifier return self . _perform_request ( "po... | Same as create_non_data_file but replaces a file that already exists in a file - based dataset . |
50,556 | def _perform_update ( self , method , resource , payload ) : try : file_type = file except NameError : file_type = IOBase if isinstance ( payload , ( dict , list ) ) : response = self . _perform_request ( method , resource , data = json . dumps ( payload ) ) elif isinstance ( payload , file_type ) : headers = { "conten... | Execute the update task . |
50,557 | def _perform_request ( self , request_type , resource , ** kwargs ) : request_type_methods = set ( [ "get" , "post" , "put" , "delete" ] ) if request_type not in request_type_methods : raise Exception ( "Unknown request type. Supported request types are" ": {0}" . format ( ", " . join ( request_type_methods ) ) ) uri =... | Utility method that performs all requests . |
50,558 | def exec_request ( self , URL ) : interval = time . time ( ) - self . __ts_last_req if ( interval < self . __min_req_interval ) : time . sleep ( self . __min_req_interval - interval ) headers = { "X-ELS-APIKey" : self . api_key , "User-Agent" : self . __user_agent , "Accept" : 'application/json' } if self . inst_token ... | Sends the actual request ; returns response . |
50,559 | def write ( self ) : if ( self . data ) : dataPath = self . client . local_dir / ( urllib . parse . quote_plus ( self . uri ) + '.json' ) with dataPath . open ( mode = 'w' ) as dump_file : json . dump ( self . data , dump_file ) dump_file . close ( ) logger . info ( 'Wrote ' + self . uri + ' to file' ) return True else... | If data exists for the entity writes it to disk as a . JSON file with the url - encoded URI as the filename and returns True . Else returns False . |
50,560 | def write_docs ( self ) : if self . doc_list : dataPath = self . client . local_dir dump_file = open ( 'data/' + urllib . parse . quote_plus ( self . uri + '?view=documents' ) + '.json' , mode = 'w' ) dump_file . write ( '[' + json . dumps ( self . doc_list [ 0 ] ) ) for i in range ( 1 , len ( self . doc_list ) ) : dum... | If a doclist exists for the entity writes it to disk as a . JSON file with the url - encoded URI as the filename and returns True . Else returns False . |
50,561 | def read ( self , els_client = None ) : if ElsProfile . read ( self , self . __payload_type , els_client ) : return True else : return False | Reads the JSON representation of the author from ELSAPI . Returns True if successful ; else False . |
50,562 | def read ( self , els_client = None ) : if super ( ) . read ( self . __payload_type , els_client ) : return True else : return False | Reads the JSON representation of the document from ELSAPI . Returns True if successful ; else False . |
50,563 | def _extract_obo_synonyms ( rawterm ) : synonyms = set ( ) keys = set ( owl_synonyms ) . intersection ( rawterm . keys ( ) ) for k in keys : for s in rawterm [ k ] : synonyms . add ( Synonym ( s , owl_synonyms [ k ] ) ) return synonyms | Extract the synonyms defined in the rawterm . |
50,564 | def _extract_obo_relation ( cls , rawterm ) : relations = { } if 'subClassOf' in rawterm : relations [ Relationship ( 'is_a' ) ] = l = [ ] l . extend ( map ( cls . _get_id_from_url , rawterm . pop ( 'subClassOf' ) ) ) return relations | Extract the relationships defined in the rawterm . |
50,565 | def _relabel_to_obo ( d ) : return { owl_to_obo . get ( old_k , old_k ) : old_v for old_k , old_v in six . iteritems ( d ) } | Change the keys of d to use Obo labels . |
50,566 | def complement ( self ) : if self . complementary : try : return self . _instances [ self . complementary ] except KeyError : raise ValueError ( '{} has a complementary but it was not defined !' ) else : return None | Return the complementary relationship of self . |
50,567 | def topdown ( cls ) : return tuple ( unique_everseen ( r for r in cls . _instances . values ( ) if r . direction == 'topdown' ) ) | Get all topdown Relationship instances . |
50,568 | def bottomup ( cls ) : return tuple ( unique_everseen ( r for r in cls . _instances . values ( ) if r . direction == 'bottomup' ) ) | Get all bottomup Relationship instances . |
50,569 | def unique_everseen ( iterable ) : seen = set ( ) seen_add = seen . add for element in six . moves . filterfalse ( seen . __contains__ , iterable ) : seen_add ( element ) yield element | List unique elements preserving order . Remember all elements ever seen . |
50,570 | def output_str ( f ) : if six . PY2 : def new_f ( * args , ** kwargs ) : return f ( * args , ** kwargs ) . encode ( "utf-8" ) else : new_f = f return new_f | Create a function that always return instances of str . |
50,571 | def nowarnings ( func ) : @ functools . wraps ( func ) def new_func ( * args , ** kwargs ) : with warnings . catch_warnings ( ) : warnings . simplefilter ( 'ignore' ) return func ( * args , ** kwargs ) return new_func | Create a function wrapped in a context that ignores warnings . |
50,572 | def parse ( self , stream , parser = None ) : force , parsers = self . _get_parsers ( parser ) try : stream . seek ( 0 ) lookup = stream . read ( 1024 ) stream . seek ( 0 ) except ( io . UnsupportedOperation , AttributeError ) : lookup = None for p in parsers : if p . hook ( path = self . path , force = force , lookup ... | Parse the given file using available BaseParser instances . |
50,573 | def _get_parsers ( self , name ) : parserlist = BaseParser . __subclasses__ ( ) forced = name is None if isinstance ( name , ( six . text_type , six . binary_type ) ) : parserlist = [ p for p in parserlist if p . __name__ == name ] if not parserlist : raise ValueError ( "could not find parser: {}" . format ( name ) ) e... | Return the appropriate parser asked by the user . |
50,574 | def adopt ( self ) : valid_relationships = set ( Relationship . _instances . keys ( ) ) relationships = [ ( parent , relation . complement ( ) , term . id ) for term in six . itervalues ( self . terms ) for relation in term . relations for parent in term . relations [ relation ] if relation . complementary and relation... | Make terms aware of their children . |
50,575 | def reference ( self ) : for termkey , termval in six . iteritems ( self . terms ) : termval . relations . update ( ( relkey , TermList ( ( self . terms . get ( x ) or Term ( x , '' , '' ) if not isinstance ( x , Term ) else x ) for x in relval ) ) for relkey , relval in six . iteritems ( termval . relations ) ) | Make relations point to ontology terms instead of term ids . |
50,576 | def resolve_imports ( self , imports , import_depth , parser = None ) : if imports and import_depth : for i in list ( self . imports ) : try : if os . path . exists ( i ) or i . startswith ( ( 'http' , 'ftp' ) ) : self . merge ( Ontology ( i , import_depth = import_depth - 1 , parser = parser ) ) else : self . merge ( ... | Import required ontologies . |
50,577 | def include ( self , * terms ) : ref_needed = False for term in terms : if isinstance ( term , TermList ) : ref_needed = ref_needed or self . _include_term_list ( term ) elif isinstance ( term , Term ) : ref_needed = ref_needed or self . _include_term ( term ) else : raise TypeError ( 'include only accepts <Term> or <T... | Add new terms to the current ontology . |
50,578 | def merge ( self , other ) : if not isinstance ( other , Ontology ) : raise TypeError ( "'merge' requires an Ontology as argument," " not {}" . format ( type ( other ) ) ) self . terms . update ( other . terms ) self . _empty_cache ( ) self . adopt ( ) self . reference ( ) | Merge another ontology into the current one . |
50,579 | def _include_term_list ( self , termlist ) : ref_needed = False for term in termlist : ref_needed = ref_needed or self . _include_term ( term ) return ref_needed | Add terms from a TermList to the ontology . |
50,580 | def _include_term ( self , term ) : ref_needed = False if term . relations : for k , v in six . iteritems ( term . relations ) : for i , t in enumerate ( v ) : try : if t . id not in self : self . _include_term ( t ) v [ i ] = t . id except AttributeError : pass ref_needed = True self . terms [ term . id ] = term retur... | Add a single term to the current ontology . |
50,581 | def _empty_cache ( self , termlist = None ) : if termlist is None : for term in six . itervalues ( self . terms ) : term . _empty_cache ( ) else : for term in termlist : try : self . terms [ term . id ] . _empty_cache ( ) except AttributeError : self . terms [ term ] . _empty_cache ( ) | Empty the cache associated with each Term instance . |
50,582 | def _obo_meta ( self ) : metatags = ( "format-version" , "data-version" , "date" , "saved-by" , "auto-generated-by" , "import" , "subsetdef" , "synonymtypedef" , "default-namespace" , "namespace-id-rule" , "idspace" , "treat-xrefs-as-equivalent" , "treat-xrefs-as-genus-differentia" , "treat-xrefs-as-is_a" , "remark" , ... | Generate the obo metadata header and updates metadata . |
50,583 | def _empty_cache ( self ) : self . _children , self . _parents = None , None self . _rchildren , self . _rparents = { } , { } | Empty the cache of the Term s memoized functions . |
50,584 | def _check_section ( line , section ) : if "[Term]" in line : section = OboSection . term elif "[Typedef]" in line : section = OboSection . typedef return section | Update the section being parsed . |
50,585 | def _parse_metadata ( cls , line , meta , parse_remarks = True ) : key , value = line . split ( ':' , 1 ) key , value = key . strip ( ) , value . strip ( ) if parse_remarks and "remark" in key : if 0 < value . find ( ': ' ) < 20 : try : cls . _parse_metadata ( value , meta , parse_remarks ) except ValueError : pass els... | Parse a metadata line . |
50,586 | def _parse_typedef ( line , _rawtypedef ) : if "[Typedef]" in line : _rawtypedef . append ( collections . defaultdict ( list ) ) else : key , value = line . split ( ':' , 1 ) _rawtypedef [ - 1 ] [ key . strip ( ) ] . append ( value . strip ( ) ) | Parse a typedef line . |
50,587 | def _parse_term ( _rawterms ) : line = yield _rawterms . append ( collections . defaultdict ( list ) ) while True : line = yield if "[Term]" in line : _rawterms . append ( collections . defaultdict ( list ) ) else : key , value = line . split ( ':' , 1 ) _rawterms [ - 1 ] [ key . strip ( ) ] . append ( value . strip ( ... | Parse a term line . |
50,588 | def _classify ( _rawtypedef , _rawterms ) : terms = collections . OrderedDict ( ) _cached_synonyms = { } typedefs = [ Relationship . _from_obo_dict ( { k : v for k , lv in six . iteritems ( _typedef ) for v in lv } ) for _typedef in _rawtypedef ] for _term in _rawterms : synonyms = set ( ) _id = _term [ 'id' ] [ 0 ] _n... | Create proper objects out of extracted dictionnaries . |
50,589 | def calculate_first_digit ( number ) : sum = 0 if len ( number ) == 9 : weights = CPF_WEIGHTS [ 0 ] else : weights = CNPJ_WEIGHTS [ 0 ] for i in range ( len ( number ) ) : sum = sum + int ( number [ i ] ) * weights [ i ] rest_division = sum % DIVISOR if rest_division < 2 : return '0' return str ( 11 - rest_division ) | This function calculates the first check digit of a cpf or cnpj . |
50,590 | def validate ( number ) : clean_number = clear_punctuation ( number ) if len ( clean_number ) == 11 : return cpf . validate ( clean_number ) elif len ( clean_number ) == 14 : return cnpj . validate ( clean_number ) return False | This functions acts like a Facade to the other modules cpf and cnpj and validates either CPF and CNPJ numbers . Feel free to use this or the other modules directly . |
50,591 | def validate ( cpf_number ) : _cpf = compat . clear_punctuation ( cpf_number ) if ( len ( _cpf ) != 11 or len ( set ( _cpf ) ) == 1 ) : return False first_part = _cpf [ : 9 ] second_part = _cpf [ : 10 ] first_digit = _cpf [ 9 ] second_digit = _cpf [ 10 ] if ( first_digit == calc . calculate_first_digit ( first_part ) a... | This function validates a CPF number . |
50,592 | def validate ( cnpj_number ) : _cnpj = compat . clear_punctuation ( cnpj_number ) if ( len ( _cnpj ) != 14 or len ( set ( _cnpj ) ) == 1 ) : return False first_part = _cnpj [ : 12 ] second_part = _cnpj [ : 13 ] first_digit = _cnpj [ 12 ] second_digit = _cnpj [ 13 ] if ( first_digit == calc . calculate_first_digit ( fir... | This function validates a CNPJ number . |
50,593 | def xml_open ( filename , expected_root = None ) : if zipfile . is_zipfile ( filename ) : tree = get_xml_from_archive ( filename ) else : tree = ET . parse ( filename ) tree_root = tree . getroot ( ) file_version = Version ( tree_root . attrib . get ( 'version' , '0.0' ) ) if file_version < MIN_SUPPORTED_VERSION : rais... | Opens the provided filename . Handles detecting if the file is an archive detecting the document version and validating the root tag . |
50,594 | def build_archive_file ( archive_contents , zip_file ) : for root_dir , _ , files in os . walk ( archive_contents ) : relative_dir = os . path . relpath ( root_dir , archive_contents ) for f in files : temp_file_full_path = os . path . join ( archive_contents , relative_dir , f ) zipname = os . path . join ( relative_d... | Build a Tableau - compatible archive file . |
50,595 | def from_attributes ( cls , server , dbname , username , dbclass , port = None , query_band = None , initial_sql = None , authentication = '' ) : root = ET . Element ( 'connection' , authentication = authentication ) xml = cls ( root ) xml . server = server xml . dbname = dbname xml . username = username xml . dbclass ... | Creates a new connection that can be added into a Data Source . defaults to which will be treated as prompt by Tableau . |
50,596 | def dbname ( self , value ) : self . _dbname = value self . _connectionXML . set ( 'dbname' , value ) | Set the connection s database name property . |
50,597 | def server ( self , value ) : self . _server = value self . _connectionXML . set ( 'server' , value ) | Set the connection s server property . |
50,598 | def username ( self , value ) : self . _username = value self . _connectionXML . set ( 'username' , value ) | Set the connection s username property . |
50,599 | def dbclass ( self , value ) : if not is_valid_dbclass ( value ) : raise AttributeError ( "'{}' is not a valid database type" . format ( value ) ) self . _class = value self . _connectionXML . set ( 'class' , value ) | Set the connection s dbclass property . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.