idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
234,100 | def _cached_by_domain ( api_name ) : def wrapped ( func ) : def decorated ( self , domains ) : if not self . _cache : return func ( self , domains ) all_responses = self . _cache . bulk_lookup ( api_name , domains ) domains = list ( set ( domains ) - set ( all_responses ) ) if domains : response = func ( self , domains... | A caching wrapper for functions that take a list of domains as parameters . |
234,101 | def domain_score ( self , domains ) : warn ( 'OpenDNS Domain Scores endpoint is deprecated. Use ' 'InvestigateApi.categorization() instead' , DeprecationWarning , ) url_path = 'domains/score/' return self . _multi_post ( url_path , domains ) | Calls domain scores endpoint . |
234,102 | def _multi_get ( self , cache_api_name , fmt_url_path , url_params , query_params = None ) : all_responses = { } if self . _cache : all_responses = self . _cache . bulk_lookup ( cache_api_name , url_params ) url_params = [ key for key in url_params if key not in all_responses . keys ( ) ] if len ( url_params ) : urls =... | Makes multiple GETs to an OpenDNS endpoint . |
234,103 | def security ( self , domains ) : api_name = 'opendns-security' fmt_url_path = u'security/name/{0}.json' return self . _multi_get ( api_name , fmt_url_path , domains ) | Calls security end point and adds an is_suspicious key to each response . |
234,104 | def whois_emails ( self , emails ) : api_name = 'opendns-whois-emails' fmt_url_path = u'whois/emails/{0}' return self . _multi_get ( api_name , fmt_url_path , emails ) | Calls WHOIS Email end point |
234,105 | def whois_nameservers ( self , nameservers ) : api_name = 'opendns-whois-nameservers' fmt_url_path = u'whois/nameservers/{0}' return self . _multi_get ( api_name , fmt_url_path , nameservers ) | Calls WHOIS Nameserver end point |
234,106 | def whois_domains ( self , domains ) : api_name = 'opendns-whois-domain' fmt_url_path = u'whois/{0}' return self . _multi_get ( api_name , fmt_url_path , domains ) | Calls WHOIS domain end point |
234,107 | def whois_domains_history ( self , domains ) : api_name = 'opendns-whois-domain-history' fmt_url_path = u'whois/{0}/history' return self . _multi_get ( api_name , fmt_url_path , domains ) | Calls WHOIS domain history end point |
234,108 | def domain_tag ( self , domains ) : api_name = 'opendns-domain_tag' fmt_url_path = u'domains/{0}/latest_tags' return self . _multi_get ( api_name , fmt_url_path , domains ) | Get the data range when a domain is part of OpenDNS block list . |
234,109 | def rr_history ( self , ips ) : api_name = 'opendns-rr_history' fmt_url_path = u'dnsdb/ip/a/{0}.json' return self . _multi_get ( api_name , fmt_url_path , ips ) | Get the domains related to input ips . |
234,110 | def sample ( self , hashes ) : api_name = 'opendns-sample' fmt_url_path = u'sample/{0}' return self . _multi_get ( api_name , fmt_url_path , hashes ) | Get the information about a sample based on its hash . |
234,111 | def search ( self , patterns , start = 30 , limit = 1000 , include_category = False ) : api_name = 'opendns-patterns' fmt_url_path = u'search/{0}' start = '-{0}days' . format ( start ) include_category = str ( include_category ) . lower ( ) query_params = { 'start' : start , 'limit' : limit , 'includecategory' : includ... | Performs pattern searches against the Investigate database . |
234,112 | def risk_score ( self , domains ) : api_name = 'opendns-risk_score' fmt_url_path = u'domains/risk-score/{0}' return self . _multi_get ( api_name , fmt_url_path , domains ) | Performs Umbrella risk score analysis on the input domains |
234,113 | def _extract_all_responses ( self , resources , api_endpoint , api_name ) : all_responses , resources = self . _bulk_cache_lookup ( api_name , resources ) resource_chunks = self . _prepare_resource_chunks ( resources ) response_chunks = self . _request_reports ( "resource" , resource_chunks , api_endpoint ) self . _ext... | Aux function to extract all the API endpoint responses . |
234,114 | def get_url_distribution ( self , params = None ) : params = params or { } all_responses = { } api_name = 'virustotal-url-distribution' response_chunks = self . _request_reports ( list ( params . keys ( ) ) , list ( params . values ( ) ) , 'url/distribution' ) self . _extract_response_chunks ( all_responses , response_... | Retrieves a live feed with the latest URLs submitted to VT . |
234,115 | def get_url_reports ( self , resources ) : api_name = 'virustotal-url-reports' ( all_responses , resources ) = self . _bulk_cache_lookup ( api_name , resources ) resource_chunks = self . _prepare_resource_chunks ( resources , '\n' ) response_chunks = self . _request_reports ( "resource" , resource_chunks , 'url/report'... | Retrieves a scan report on a given URL . |
234,116 | def get_ip_reports ( self , ips ) : api_name = 'virustotal-ip-address-reports' ( all_responses , ips ) = self . _bulk_cache_lookup ( api_name , ips ) responses = self . _request_reports ( "ip" , ips , 'ip-address/report' ) for ip , response in zip ( ips , responses ) : if self . _cache : self . _cache . cache_value ( a... | Retrieves the most recent VT info for a set of ips . |
234,117 | def get_file_clusters ( self , date ) : api_name = 'virustotal-file-clusters' ( all_responses , resources ) = self . _bulk_cache_lookup ( api_name , date ) response = self . _request_reports ( "date" , date , 'file/clusters' ) self . _extract_response_chunks ( all_responses , response , api_name ) return all_responses | Retrieves file similarity clusters for a given time frame . |
234,118 | def _prepare_resource_chunks ( self , resources , resource_delim = ',' ) : return [ self . _prepare_resource_chunk ( resources , resource_delim , pos ) for pos in range ( 0 , len ( resources ) , self . _resources_per_req ) ] | As in some VirusTotal API methods the call can be made for multiple resources at once this method prepares a list of concatenated resources according to the maximum number of resources per requests . |
234,119 | def _extract_response_chunks ( self , all_responses , response_chunks , api_name ) : for response_chunk in response_chunks : if not isinstance ( response_chunk , list ) : response_chunk = [ response_chunk ] for response in response_chunk : if not response : continue if self . _cache : self . _cache . cache_value ( api_... | Extracts and caches the responses from the response chunks in case of the responses for the requests containing multiple concatenated resources . Extracted responses are added to the already cached responses passed in the all_responses parameter . |
234,120 | def get_editor_widget ( self , request , plugins , plugin ) : cancel_url_name = self . get_admin_url_name ( 'delete_on_cancel' ) cancel_url = reverse ( 'admin:%s' % cancel_url_name ) render_plugin_url_name = self . get_admin_url_name ( 'render_plugin' ) render_plugin_url = reverse ( 'admin:%s' % render_plugin_url_name ... | Returns the Django form Widget to be used for the text area |
234,121 | def get_form_class ( self , request , plugins , plugin ) : widget = self . get_editor_widget ( request = request , plugins = plugins , plugin = plugin , ) instance = plugin . get_plugin_instance ( ) [ 0 ] if instance : context = RequestContext ( request ) context [ 'request' ] = request rendered_text = plugin_tags_to_a... | Returns a subclass of Form to be used by this plugin |
234,122 | def _plugin_tags_to_html ( text , output_func ) : plugins_by_id = get_plugins_from_text ( text ) def _render_tag ( m ) : try : plugin_id = int ( m . groupdict ( ) [ 'pk' ] ) obj = plugins_by_id [ plugin_id ] except KeyError : return u'' else : obj . _render_meta . text_enabled = True return output_func ( obj , m ) retu... | Convert plugin object tags into the form for public site . |
234,123 | def extract_images ( data , plugin ) : if not settings . TEXT_SAVE_IMAGE_FUNCTION : return data tree_builder = html5lib . treebuilders . getTreeBuilder ( 'dom' ) parser = html5lib . html5parser . HTMLParser ( tree = tree_builder ) dom = parser . parse ( data ) found = False for img in dom . getElementsByTagName ( 'img'... | extracts base64 encoded images from drag and drop actions in browser and saves those images as plugins |
234,124 | def default_config_filename ( root_dir = None ) : root_dir = Path ( root_dir ) if root_dir else Path ( '.' ) . abspath ( ) locale_dir = root_dir / 'locale' if not os . path . exists ( locale_dir ) : locale_dir = root_dir / 'conf' / 'locale' return locale_dir / BASE_CONFIG_FILENAME | Returns the default name of the configuration file . |
234,125 | def rtl_langs ( self ) : def is_rtl ( lang ) : base_rtl = [ 'ar' , 'fa' , 'he' , 'ur' ] return any ( [ lang . startswith ( base_code ) for base_code in base_rtl ] ) return sorted ( set ( [ lang for lang in self . translated_locales if is_rtl ( lang ) ] ) ) | Returns the set of translated RTL language codes present in self . locales . Ignores source locale . |
234,126 | def clean_conf_folder ( self , locale ) : dirname = self . configuration . get_messages_dir ( locale ) dirname . removedirs_p ( ) | Remove the configuration directory for locale |
234,127 | def segment_pofiles ( configuration , locale ) : files_written = set ( ) for filename , segments in configuration . segment . items ( ) : filename = configuration . get_messages_dir ( locale ) / filename files_written . update ( segment_pofile ( filename , segments ) ) return files_written | Segment all the pofiles for locale . |
234,128 | def segment_pofile ( filename , segments ) : reading_msg = "Reading {num} entries from {file}" writing_msg = "Writing {num} entries to {file}" source_po = polib . pofile ( filename ) LOG . info ( reading_msg . format ( file = filename , num = len ( source_po ) ) ) remaining_po = copy . deepcopy ( source_po ) remaining_... | Segment a . po file using patterns in segments . |
234,129 | def fix_header ( pofile ) : pofile . metadata_is_fuzzy = [ ] header = pofile . header fixes = ( ( 'SOME DESCRIPTIVE TITLE' , EDX_MARKER ) , ( 'Translations template for PROJECT.' , EDX_MARKER ) , ( 'YEAR' , str ( datetime . utcnow ( ) . year ) ) , ( 'ORGANIZATION' , 'edX' ) , ( "THE PACKAGE'S COPYRIGHT HOLDER" , "EdX" ... | Replace default headers with edX headers |
234,130 | def strip_key_strings ( pofile ) : newlist = [ entry for entry in pofile if not is_key_string ( entry . msgid ) ] del pofile [ : ] pofile += newlist | Removes all entries in PO which are key strings . These entries should appear only in messages . po not in any other po files . |
234,131 | def rename_source_file ( self , src , dst ) : try : os . rename ( self . source_msgs_dir . joinpath ( src ) , self . source_msgs_dir . joinpath ( dst ) ) except OSError : pass | Rename a file in the source directory . |
234,132 | def get_valid_commands ( ) : modules = [ m . basename ( ) . split ( '.' ) [ 0 ] for m in Path ( __file__ ) . dirname ( ) . files ( '*.py' ) ] commands = [ ] for modname in modules : if modname == 'main' : continue mod = importlib . import_module ( 'i18n.%s' % modname ) if hasattr ( mod , 'main' ) : commands . append ( ... | Returns valid commands . |
234,133 | def error_message ( ) : sys . stderr . write ( 'valid commands:\n' ) for cmd in get_valid_commands ( ) : sys . stderr . write ( '\t%s\n' % cmd ) return - 1 | Writes out error message specifying the valid commands . |
234,134 | def main ( ) : try : command = sys . argv [ 1 ] except IndexError : return error_message ( ) try : module = importlib . import_module ( 'i18n.%s' % command ) module . main . args = sys . argv [ 2 : ] except ( ImportError , AttributeError ) : return error_message ( ) return module . main ( ) | Executes the given command . Returns error_message if command is not valid . |
234,135 | def validate_po_files ( configuration , locale_dir , root_dir = None , report_empty = False , check_all = False ) : found_problems = False merged_files = configuration . generate_merge . keys ( ) for dirpath , __ , filenames in os . walk ( root_dir if root_dir else locale_dir ) : for name in filenames : __ , ext = os .... | Validate all of the po files found in the root directory that are not product of a merge . |
234,136 | def msgfmt_check_po_file ( locale_dir , filename ) : found_problems = False rfile = os . path . relpath ( filename , locale_dir ) out , err = call ( 'msgfmt -c -o /dev/null {}' . format ( rfile ) , working_directory = locale_dir ) if err : log . info ( u'\n' + out . decode ( 'utf8' ) ) log . warning ( u'\n' + err . dec... | Call GNU msgfmt - c on each . po file to validate its format . Any errors caught by msgfmt are logged to log . |
234,137 | def tags_in_string ( msg ) : def is_linguistic_tag ( tag ) : if tag . startswith ( "&" ) : return True if any ( x in tag for x in [ "<abbr>" , "<abbr " , "</abbr>" ] ) : return True return False __ , tags = Converter ( ) . detag_string ( msg ) return set ( t for t in tags if not is_linguistic_tag ( t ) ) | Return the set of tags in a message string . |
234,138 | def astral ( msg ) : utf32 = msg . encode ( "utf32" ) [ 4 : ] code_points = struct . unpack ( "%dI" % ( len ( utf32 ) / 4 ) , utf32 ) return any ( cp > 0xFFFF for cp in code_points ) | Does msg have characters outside the Basic Multilingual Plane? |
234,139 | def report_problems ( filename , problems ) : problem_file = filename . replace ( ".po" , ".prob" ) id_filler = textwrap . TextWrapper ( width = 79 , initial_indent = " msgid: " , subsequent_indent = " " * 9 ) tx_filler = textwrap . TextWrapper ( width = 79 , initial_indent = " --- , subsequent_indent = " " * 9 ) wit... | Report on the problems found in filename . |
234,140 | def merge ( configuration , locale , target = 'django.po' , sources = ( 'django-partial.po' , ) , fail_if_missing = True ) : LOG . info ( 'Merging %s locale %s' , target , locale ) locale_directory = configuration . get_messages_dir ( locale ) try : validate_files ( locale_directory , sources ) except Exception : if no... | For the given locale merge the sources files to become the target file . Note that the target file might also be one of the sources . |
234,141 | def merge_files ( configuration , locale , fail_if_missing = True ) : for target , sources in configuration . generate_merge . items ( ) : merge ( configuration , locale , target , sources , fail_if_missing ) | Merge all the files in locale as specified in config . yaml . |
234,142 | def clean_pofile ( pofile_path ) : pomsgs = pofile ( pofile_path ) pomsgs . metadata_is_fuzzy = False duplicate_entries = [ ] for entry in pomsgs : entry . occurrences = [ ( filename , None ) for filename , __ in entry . occurrences ] if 'fuzzy' in entry . flags : entry . flags = [ f for f in entry . flags if f != 'fuz... | Clean various aspect of a . po file . |
234,143 | def new_filename ( original_filename , new_locale ) : orig_file = Path ( original_filename ) new_file = orig_file . parent . parent . parent / new_locale / orig_file . parent . name / orig_file . name return new_file . abspath ( ) | Returns a filename derived from original_filename using new_locale as the locale |
234,144 | def run ( self , args ) : configuration = self . configuration source_messages_dir = configuration . source_messages_dir for locale , converter in zip ( configuration . dummy_locales , [ Dummy ( ) , Dummy2 ( ) , ArabicDummy ( ) ] ) : print ( 'Processing source language files into dummy strings, locale "{}"' . format ( ... | Generate dummy strings for all source po files . |
234,145 | def execute ( command , working_directory = config . BASE_DIR , stderr = sp . STDOUT ) : LOG . info ( "Executing in %s ..." , working_directory ) LOG . info ( command ) sp . check_call ( command , cwd = working_directory , stderr = stderr , shell = True ) | Executes shell command in a given working_directory . Command is a string to pass to the shell . Output is ignored . |
234,146 | def remove_file ( filename , verbose = True ) : if verbose : LOG . info ( 'Deleting file %s' , os . path . relpath ( filename , config . BASE_DIR ) ) if not os . path . exists ( filename ) : LOG . warning ( "File does not exist: %s" , os . path . relpath ( filename , config . BASE_DIR ) ) else : os . remove ( filename ... | Attempt to delete filename . log is boolean . If true removal is logged . Log a warning if file does not exist . Logging filenames are relative to config . BASE_DIR to cut down on noise in output . |
234,147 | def push ( * resources ) : cmd = 'tx push -s' if resources : for resource in resources : execute ( cmd + ' -r {resource}' . format ( resource = resource ) ) else : execute ( cmd ) | Push translation source English files to Transifex . |
234,148 | def pull_all_ltr ( configuration ) : print ( "Pulling all translated LTR languages from transifex..." ) for lang in configuration . ltr_langs : print ( 'rm -rf conf/locale/' + lang ) execute ( 'rm -rf conf/locale/' + lang ) execute ( 'tx pull -l ' + lang ) clean_translated_locales ( configuration , langs = configuratio... | Pulls all translations - reviewed or not - for LTR languages |
234,149 | def pull_all_rtl ( configuration ) : print ( "Pulling all translated RTL languages from transifex..." ) for lang in configuration . rtl_langs : print ( 'rm -rf conf/locale/' + lang ) execute ( 'rm -rf conf/locale/' + lang ) execute ( 'tx pull -l ' + lang ) clean_translated_locales ( configuration , langs = configuratio... | Pulls all translations - reviewed or not - for RTL languages |
234,150 | def clean_translated_locales ( configuration , langs = None ) : if not langs : langs = configuration . translated_locales for locale in langs : clean_locale ( configuration , locale ) | Strips out the warning from all translated po files about being an English source file . |
234,151 | def clean_locale ( configuration , locale ) : dirname = configuration . get_messages_dir ( locale ) if not dirname . exists ( ) : return for filename in dirname . files ( '*.po' ) : clean_file ( configuration , dirname . joinpath ( filename ) ) | Strips out the warning from all of a locale s translated po files about being an English source file . Iterates over machine - generated files . |
234,152 | def clean_file ( configuration , filename ) : pofile = polib . pofile ( filename ) if pofile . header . find ( EDX_MARKER ) != - 1 : new_header = get_new_header ( configuration , pofile ) new = pofile . header . replace ( EDX_MARKER , new_header ) pofile . header = new pofile . save ( ) | Strips out the warning from a translated po file about being an English source file . Replaces warning with a note about coming from Transifex . |
234,153 | def get_new_header ( configuration , pofile ) : team = pofile . metadata . get ( 'Language-Team' , None ) if not team : return TRANSIFEX_HEADER . format ( configuration . TRANSIFEX_URL ) return TRANSIFEX_HEADER . format ( team ) | Insert info about edX into the po file headers |
234,154 | def detag_string ( self , string ) : counter = itertools . count ( 0 ) count = lambda m : '<%s>' % next ( counter ) tags = self . tag_pattern . findall ( string ) tags = [ '' . join ( tag ) for tag in tags ] ( new , nfound ) = self . tag_pattern . subn ( count , string ) if len ( tags ) != nfound : raise Exception ( 't... | Extracts tags from string . |
234,155 | def options ( self ) : arg = self . get ( 0 ) if arg . startswith ( '-' ) and not self . is_asking_for_help : return arg [ 1 : ] return '' . join ( x for x in arg if x in 'dgktz' ) | Train tickets query options . |
234,156 | def trains ( self ) : for row in self . _rows : train_no = row . get ( 'station_train_code' ) initial = train_no [ 0 ] . lower ( ) if not self . _opts or initial in self . _opts : train = [ train_no , '\n' . join ( [ colored . green ( row . get ( 'from_station_name' ) ) , colored . red ( row . get ( 'to_station_name' )... | Filter rows according to headers |
234,157 | def pretty_print ( self ) : pt = PrettyTable ( ) if len ( self ) == 0 : pt . _set_field_names ( [ 'Sorry,' ] ) pt . add_row ( [ TRAIN_NOT_FOUND ] ) else : pt . _set_field_names ( self . headers ) for train in self . trains : pt . add_row ( train ) print ( pt ) | Use PrettyTable to perform formatted outprint . |
234,158 | def _valid_date ( self ) : date = self . _parse_date ( self . date ) if not date : exit_after_echo ( INVALID_DATE ) try : date = datetime . strptime ( date , '%Y%m%d' ) except ValueError : exit_after_echo ( INVALID_DATE ) offset = date - datetime . today ( ) if offset . days not in range ( - 1 , 50 ) : exit_after_echo ... | Check and return a valid query date . |
234,159 | def _parse_date ( date ) : result = '' . join ( re . findall ( '\d' , date ) ) l = len ( result ) if l in ( 2 , 3 , 4 ) : year = str ( datetime . today ( ) . year ) return year + result if l in ( 6 , 7 , 8 ) : return result return '' | Parse from the user input date . |
234,160 | def _build_params ( self ) : d = OrderedDict ( ) d [ 'purpose_codes' ] = 'ADULT' d [ 'queryDate' ] = self . _valid_date d [ 'from_station' ] = self . _from_station_telecode d [ 'to_station' ] = self . _to_station_telecode return d | Have no idea why wrong params order can t get data . So use OrderedDict here . |
234,161 | def date_range ( self ) : try : days = int ( self . days ) except ValueError : exit_after_echo ( QUERY_DAYS_INVALID ) if days < 1 : exit_after_echo ( QUERY_DAYS_INVALID ) start = datetime . today ( ) end = start + timedelta ( days = days ) return ( datetime . strftime ( start , '%Y-%m-%d' ) , datetime . strftime ( end ... | Generate date range according to the days user input . |
234,162 | def query ( params ) : r = requests_get ( QUERY_URL , verify = True ) return HospitalCollection ( r . json ( ) , params ) | params is a city name or a city name + hospital name . |
234,163 | def cli ( ) : if args . is_asking_for_help : exit_after_echo ( cli . __doc__ , color = None ) elif args . is_querying_lottery : from . lottery import query result = query ( ) elif args . is_querying_movie : from . movies import query result = query ( ) elif args . is_querying_lyric : from . lyrics import query result =... | Various information query via command line . |
234,164 | def query ( ) : r = requests_get ( QUERY_URL ) try : rows = r . json ( ) [ 'subject_collection_items' ] except ( IndexError , TypeError ) : rows = [ ] return MoviesCollection ( rows ) | Query hot movies infomation from douban . |
234,165 | def action_draft ( self ) : for rec in self : if not rec . state == 'cancelled' : raise UserError ( _ ( 'You need to cancel it before reopening.' ) ) if not ( rec . am_i_owner or rec . am_i_approver ) : raise UserError ( _ ( 'You are not authorized to do this.\r\n' 'Only owners or approvers can reopen Change Requests.'... | Set a change request as draft |
234,166 | def action_to_approve ( self ) : template = self . env . ref ( 'document_page_approval.email_template_new_draft_need_approval' ) approver_gid = self . env . ref ( 'document_page_approval.group_document_approver_user' ) for rec in self : if rec . state != 'draft' : raise UserError ( _ ( "Can't approve pages in '%s' stat... | Set a change request as to approve |
234,167 | def action_approve ( self ) : for rec in self : if rec . state not in [ 'draft' , 'to approve' ] : raise UserError ( _ ( "Can't approve page in '%s' state." ) % rec . state ) if not rec . am_i_approver : raise UserError ( _ ( 'You are not authorized to do this.\r\n' 'Only approvers with these groups can approve this: '... | Set a change request as approved . |
234,168 | def action_cancel ( self ) : self . write ( { 'state' : 'cancelled' } ) for rec in self : rec . message_post ( subtype = 'mt_comment' , body = _ ( 'Change request <b>%s</b> has been cancelled by %s.' ) % ( rec . display_name , self . env . user . name ) ) | Set a change request as cancelled . |
234,169 | def _compute_am_i_owner ( self ) : for rec in self : rec . am_i_owner = ( rec . create_uid == self . env . user ) | Check if current user is the owner |
234,170 | def _compute_page_url ( self ) : for page in self : base_url = self . env [ 'ir.config_parameter' ] . sudo ( ) . get_param ( 'web.base.url' , default = 'http://localhost:8069' ) page . page_url = ( '{}/web#db={}&id={}&view_type=form&' 'model=document.page.history' ) . format ( base_url , self . env . cr . dbname , page... | Compute the page url . |
234,171 | def _compute_diff ( self ) : history = self . env [ 'document.page.history' ] for rec in self : domain = [ ( 'page_id' , '=' , rec . page_id . id ) , ( 'state' , '=' , 'approved' ) ] if rec . approved_date : domain . append ( ( 'approved_date' , '<' , rec . approved_date ) ) prev = history . search ( domain , limit = 1... | Shows a diff between this version and the previous version |
234,172 | def action_add_url ( self ) : if not self . env . context . get ( 'active_model' ) : return attachment_obj = self . env [ 'ir.attachment' ] for form in self : url = parse . urlparse ( form . url ) if not url . scheme : url = parse . urlparse ( '%s%s' % ( 'http://' , form . url ) ) for active_id in self . env . context ... | Adds the URL with the given name as an ir . attachment record . |
234,173 | def _compute_is_approval_required ( self ) : for page in self : res = page . approval_required if page . parent_id : res = res or page . parent_id . is_approval_required page . is_approval_required = res | Check if the document required approval based on his parents . |
234,174 | def _compute_approver_group_ids ( self ) : for page in self : res = page . approver_gid if page . parent_id : res = res | page . parent_id . approver_group_ids page . approver_group_ids = res | Compute the approver groups based on his parents . |
234,175 | def _compute_am_i_approver ( self ) : for rec in self : rec . am_i_approver = rec . can_user_approve_this_page ( self . env . user ) | Check if the current user can approve changes to this page . |
234,176 | def can_user_approve_this_page ( self , user ) : self . ensure_one ( ) if not self . is_approval_required : return True if user . has_group ( 'document_page.group_document_manager' ) : return True if not user . has_group ( 'document_page_approval.group_document_approver_user' ) : return False if not self . approver_gro... | Check if a user can approve this page . |
234,177 | def status ( self ) : response = requests . get ( "https://tccna.honeywell.com/WebAPI/emea/api/v1/" "location/%s/status?includeTemperatureControlSystems=True" % self . locationId , headers = self . client . _headers ( ) ) response . raise_for_status ( ) data = response . json ( ) for gw_data in data [ 'gateways' ] : ga... | Retrieves the location status . |
234,178 | def set_dhw_on ( self , until = None ) : if until is None : data = { "Mode" : "PermanentOverride" , "State" : "On" , "UntilTime" : None } else : data = { "Mode" : "TemporaryOverride" , "State" : "On" , "UntilTime" : until . strftime ( '%Y-%m-%dT%H:%M:%SZ' ) } self . _set_dhw ( data ) | Sets the DHW on until a given time or permanently . |
234,179 | def set_dhw_off ( self , until = None ) : if until is None : data = { "Mode" : "PermanentOverride" , "State" : "Off" , "UntilTime" : None } else : data = { "Mode" : "TemporaryOverride" , "State" : "Off" , "UntilTime" : until . strftime ( '%Y-%m-%dT%H:%M:%SZ' ) } self . _set_dhw ( data ) | Sets the DHW off until a given time or permanently . |
234,180 | def schedule ( self ) : response = requests . get ( "https://tccna.honeywell.com/WebAPI/emea/api/v1" "/%s/%s/schedule" % ( self . zone_type , self . zoneId ) , headers = self . client . _headers ( ) ) response . raise_for_status ( ) mapping = [ ( 'dailySchedules' , 'DailySchedules' ) , ( 'dayOfWeek' , 'DayOfWeek' ) , (... | Gets the schedule for the given zone |
234,181 | def set_schedule ( self , zone_info ) : try : json . loads ( zone_info ) except ValueError as error : raise ValueError ( "zone_info must be valid JSON: " , error ) headers = dict ( self . client . _headers ( ) ) headers [ 'Content-Type' ] = 'application/json' response = requests . put ( "https://tccna.honeywell.com/Web... | Sets the schedule for this zone |
234,182 | def temperatures ( self , force_refresh = False ) : self . _populate_full_data ( force_refresh ) for device in self . full_data [ 'devices' ] : set_point = 0 status = "" if 'heatSetpoint' in device [ 'thermostat' ] [ 'changeableValues' ] : set_point = float ( device [ 'thermostat' ] [ 'changeableValues' ] [ "heatSetpoi... | Retrieve the current details for each zone . Returns a generator . |
234,183 | def get_modes ( self , zone ) : self . _populate_full_data ( ) device = self . _get_device ( zone ) return device [ 'thermostat' ] [ 'allowedModes' ] | Returns the set of modes the device can be assigned . |
234,184 | def set_temperature ( self , zone , temperature , until = None ) : if until is None : data = { "Value" : temperature , "Status" : "Hold" , "NextTime" : None } else : data = { "Value" : temperature , "Status" : "Temporary" , "NextTime" : until . strftime ( '%Y-%m-%dT%H:%M:%SZ' ) } self . _set_heat_setpoint ( zone , data... | Sets the temperature of the given zone . |
234,185 | def _set_dhw ( self , status = "Scheduled" , mode = None , next_time = None ) : data = { "Status" : status , "Mode" : mode , "NextTime" : next_time , "SpecialModes" : None , "HeatSetpoint" : None , "CoolSetpoint" : None } self . _populate_full_data ( ) dhw_zone = self . _get_dhw_zone ( ) if dhw_zone is None : raise Exc... | Set DHW to On Off or Auto either indefinitely or until a specified time . |
234,186 | def set_dhw_on ( self , until = None ) : time_until = None if until is None else until . strftime ( '%Y-%m-%dT%H:%M:%SZ' ) self . _set_dhw ( status = "Hold" , mode = "DHWOn" , next_time = time_until ) | Set DHW to on either indefinitely or until a specified time . |
234,187 | def _headers ( self ) : if not self . access_token or not self . access_token_expires : self . _basic_login ( ) elif datetime . now ( ) > self . access_token_expires - timedelta ( seconds = 30 ) : self . _basic_login ( ) return { 'Accept' : HEADER_ACCEPT , 'Authorization' : 'bearer ' + self . access_token } | Ensure the Authorization Header has a valid Access Token . |
234,188 | def _basic_login ( self ) : _LOGGER . debug ( "No/Expired/Invalid access_token, re-authenticating..." ) self . access_token = self . access_token_expires = None if self . refresh_token : _LOGGER . debug ( "Trying refresh_token..." ) credentials = { 'grant_type' : "refresh_token" , 'scope' : "EMEA-V1-Basic EMEA-V1-Anony... | Obtain a new access token from the vendor . |
234,189 | def user_account ( self ) : self . account_info = None url = 'https://tccna.honeywell.com/WebAPI/emea/api/v1/userAccount' response = requests . get ( url , headers = self . _headers ( ) ) response . raise_for_status ( ) self . account_info = response . json ( ) return self . account_info | Return the user account information . |
234,190 | def installation ( self ) : self . locations = [ ] url = ( "https://tccna.honeywell.com/WebAPI/emea/api/v1/location" "/installationInfo?userId=%s" "&includeTemperatureControlSystems=True" % self . account_info [ 'userId' ] ) response = requests . get ( url , headers = self . _headers ( ) ) response . raise_for_status (... | Return the details of the installation . |
234,191 | def full_installation ( self , location = None ) : url = ( "https://tccna.honeywell.com/WebAPI/emea/api/v1/location" "/%s/installationInfo?includeTemperatureControlSystems=True" % self . _get_location ( location ) ) response = requests . get ( url , headers = self . _headers ( ) ) response . raise_for_status ( ) return... | Return the full details of the installation . |
234,192 | def gateway ( self ) : url = 'https://tccna.honeywell.com/WebAPI/emea/api/v1/gateway' response = requests . get ( url , headers = self . _headers ( ) ) response . raise_for_status ( ) return response . json ( ) | Return the detail of the gateway . |
234,193 | def temperatures ( self ) : self . location . status ( ) if self . hotwater : yield { 'thermostat' : 'DOMESTIC_HOT_WATER' , 'id' : self . hotwater . dhwId , 'name' : '' , 'temp' : self . hotwater . temperatureStatus [ 'temperature' ] , 'setpoint' : '' } for zone in self . _zones : zone_info = { 'thermostat' : 'EMEA_ZON... | Return a generator with the details of each zone . |
234,194 | def zone_schedules_backup ( self , filename ) : _LOGGER . info ( "Backing up schedules from ControlSystem: %s (%s)..." , self . systemId , self . location . name ) schedules = { } if self . hotwater : _LOGGER . info ( "Retrieving DHW schedule: %s..." , self . hotwater . zoneId ) schedule = self . hotwater . schedule ( ... | Backup all zones on control system to the given file . |
234,195 | def zone_schedules_restore ( self , filename ) : _LOGGER . info ( "Restoring schedules to ControlSystem %s (%s)..." , self . systemId , self . location ) _LOGGER . info ( "Reading from backup file: %s..." , filename ) with open ( filename , 'r' ) as file_input : schedule_db = file_input . read ( ) schedules = json . lo... | Restore all zones on control system from the given file . |
234,196 | def cli ( env , package_keyname , keyword , category ) : table = formatting . Table ( COLUMNS ) manager = ordering . OrderingManager ( env . client ) _filter = { 'items' : { } } if keyword : _filter [ 'items' ] [ 'description' ] = { 'operation' : '*= %s' % keyword } if category : _filter [ 'items' ] [ 'categories' ] = ... | List package items used for ordering . |
234,197 | def sort_items ( items ) : sorted_items = { } for item in items : category = lookup ( item , 'itemCategory' , 'categoryCode' ) if sorted_items . get ( category ) is None : sorted_items [ category ] = [ ] sorted_items [ category ] . append ( item ) return sorted_items | sorts the items into a dictionary of categories with a list of items |
234,198 | def cli ( env , sortby , datacenter , number , name , limit ) : mgr = SoftLayer . NetworkManager ( env . client ) table = formatting . Table ( COLUMNS ) table . sortby = sortby vlans = mgr . list_vlans ( datacenter = datacenter , vlan_number = number , name = name , limit = limit ) for vlan in vlans : table . add_row (... | List VLANs . |
234,199 | def cli ( env ) : account = env . client [ 'Account' ] nas_accounts = account . getNasNetworkStorage ( mask = 'eventCount,serviceResource[datacenter.name]' ) table = formatting . Table ( [ 'id' , 'datacenter' , 'size' , 'server' ] ) for nas_account in nas_accounts : table . add_row ( [ nas_account [ 'id' ] , utils . lo... | List NAS accounts . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.