idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
236,300
def substitute_minor_for_major ( progression , substitute_index , ignore_suffix = False ) : ( roman , acc , suff ) = parse_string ( progression [ substitute_index ] ) res = [ ] if suff == 'm' or suff == 'm7' or suff == '' and roman in [ 'II' , 'III' , 'VI' ] or ignore_suffix : n = skip ( roman , 2 ) a = interval_diff (...
Substitute minor chords for its major equivalent .
236,301
def substitute_diminished_for_diminished ( progression , substitute_index , ignore_suffix = False ) : ( roman , acc , suff ) = parse_string ( progression [ substitute_index ] ) res = [ ] if suff == 'dim7' or suff == 'dim' or suff == '' and roman in [ 'VII' ] or ignore_suffix : if suff == '' : suff = 'dim' last = roman ...
Substitute a diminished chord for another diminished chord .
236,302
def interval_diff ( progression1 , progression2 , interval ) : i = numeral_intervals [ numerals . index ( progression1 ) ] j = numeral_intervals [ numerals . index ( progression2 ) ] acc = 0 if j < i : j += 12 while j - i > interval : acc -= 1 j -= 1 while j - i < interval : acc += 1 j += 1 return acc
Return the number of half steps progression2 needs to be diminished or augmented until the interval between progression1 and progression2 is interval .
236,303
def skip ( roman_numeral , skip = 1 ) : i = numerals . index ( roman_numeral ) + skip return numerals [ i % 7 ]
Skip the given places to the next roman numeral .
236,304
def add_note ( self , note , octave = None , dynamics = { } ) : if type ( note ) == str : if octave is not None : note = Note ( note , octave , dynamics ) elif len ( self . notes ) == 0 : note = Note ( note , 4 , dynamics ) else : if Note ( note , self . notes [ - 1 ] . octave ) < self . notes [ - 1 ] : note = Note ( n...
Add a note to the container and sorts the notes from low to high .
236,305
def add_notes ( self , notes ) : if hasattr ( notes , 'notes' ) : for x in notes . notes : self . add_note ( x ) return self . notes elif hasattr ( notes , 'name' ) : self . add_note ( notes ) return self . notes elif type ( notes ) == str : self . add_note ( notes ) return self . notes for x in notes : if type ( x ) =...
Feed notes to self . add_note .
236,306
def from_chord_shorthand ( self , shorthand ) : self . empty ( ) self . add_notes ( chords . from_shorthand ( shorthand ) ) return self
Empty the container and add the notes in the shorthand .
236,307
def from_interval ( self , startnote , shorthand , up = True ) : return self . from_interval_shorthand ( startnote , shorthand , up )
Shortcut to from_interval_shorthand .
236,308
def from_interval_shorthand ( self , startnote , shorthand , up = True ) : self . empty ( ) if type ( startnote ) == str : startnote = Note ( startnote ) n = Note ( startnote . name , startnote . octave , startnote . dynamics ) n . transpose ( shorthand , up ) self . add_notes ( [ startnote , n ] ) return self
Empty the container and add the note described in the startnote and shorthand .
236,309
def remove_note ( self , note , octave = - 1 ) : res = [ ] for x in self . notes : if type ( note ) == str : if x . name != note : res . append ( x ) else : if x . octave != octave and octave != - 1 : res . append ( x ) else : if x != note : res . append ( x ) self . notes = res return res
Remove note from container .
236,310
def remove_notes ( self , notes ) : if type ( notes ) == str : return self . remove_note ( notes ) elif hasattr ( notes , 'name' ) : return self . remove_note ( notes ) else : map ( lambda x : self . remove_note ( x ) , notes ) return self . notes
Remove notes from the containers .
236,311
def remove_duplicate_notes ( self ) : res = [ ] for x in self . notes : if x not in res : res . append ( x ) self . notes = res return res
Remove duplicate and enharmonic notes from the container .
236,312
def transpose ( self , interval , up = True ) : for n in self . notes : n . transpose ( interval , up ) return self
Transpose all the notes in the container up or down the given interval .
236,313
def get_note_names ( self ) : res = [ ] for n in self . notes : if n . name not in res : res . append ( n . name ) return res
Return a list with all the note names in the current container .
236,314
def determine ( notes ) : notes = set ( notes ) res = [ ] for key in keys : for scale in _Scale . __subclasses__ ( ) : if scale . type == 'major' : if ( notes <= set ( scale ( key [ 0 ] ) . ascending ( ) ) or notes <= set ( scale ( key [ 0 ] ) . descending ( ) ) ) : res . append ( scale ( key [ 0 ] ) . name ) elif scal...
Determine the scales containing the notes .
236,315
def degree ( self , degree_number , direction = 'a' ) : if degree_number < 1 : raise RangeError ( "degree '%s' out of range" % degree_number ) if direction == 'a' : notes = self . ascending ( ) [ : - 1 ] return notes [ degree_number - 1 ] elif direction == 'd' : notes = reversed ( self . descending ( ) ) [ : - 1 ] retu...
Return the asked scale degree .
236,316
def begin_track ( tuning , padding = 2 ) : names = [ x . to_shorthand ( ) for x in tuning . tuning ] basesize = len ( max ( names ) ) + 3 res = [ ] for x in names : r = ' %s' % x spaces = basesize - len ( r ) r += ' ' * spaces + '||' + '-' * padding res . append ( r ) return res
Helper function that builds the first few characters of every bar .
236,317
def add_headers ( width = 80 , title = 'Untitled' , subtitle = '' , author = '' , email = '' , description = '' , tunings = [ ] ) : result = [ '' ] title = str . upper ( title ) result += [ str . center ( ' ' . join ( title ) , width ) ] if subtitle != '' : result += [ '' , str . center ( str . title ( subtitle ) , wi...
Create a nice header in the form of a list of strings using the information that has been filled in .
236,318
def from_Note ( note , width = 80 , tuning = None ) : if tuning is None : tuning = default_tuning result = begin_track ( tuning ) min = 1000 ( s , f ) = ( - 1 , - 1 ) if hasattr ( note , 'string' ) and hasattr ( note , 'fret' ) : n = tuning . get_Note ( note . string , note . fret ) if n is not None and int ( n ) == in...
Return a string made out of ASCII tablature representing a Note object or note string .
236,319
def from_Track ( track , maxwidth = 80 , tuning = None ) : result = [ ] width = _get_width ( maxwidth ) if not tuning : tuning = track . get_tuning ( ) lastlen = 0 for bar in track : r = from_Bar ( bar , width , tuning , collapse = False ) barstart = r [ 1 ] . find ( '||' ) + 2 if ( len ( r [ 0 ] ) + lastlen ) - barsta...
Convert a mingus . containers . Track object to an ASCII tablature string .
236,320
def from_Composition ( composition , width = 80 ) : instr_tunings = [ ] for track in composition : tun = track . get_tuning ( ) if tun : instr_tunings . append ( tun ) else : instr_tunings . append ( default_tuning ) result = add_headers ( width , composition . title , composition . subtitle , composition . author , co...
Convert a mingus . containers . Composition to an ASCII tablature string .
236,321
def from_Suite ( suite , maxwidth = 80 ) : subtitle = str ( len ( suite . compositions ) ) + ' Compositions' if suite . subtitle == '' else suite . subtitle result = os . linesep . join ( add_headers ( maxwidth , suite . title , subtitle , suite . author , suite . email , suite . description , ) ) hr = maxwidth * '=' n...
Convert a mingus . containers . Suite to an ASCII tablature string complete with headers .
236,322
def _get_qsize ( tuning , width ) : names = [ x . to_shorthand ( ) for x in tuning . tuning ] basesize = len ( max ( names ) ) + 3 barsize = ( ( width - basesize ) - 2 ) - 1 return max ( 0 , int ( barsize / 4.5 ) )
Return a reasonable quarter note size for tuning and width .
236,323
def _get_width ( maxwidth ) : width = maxwidth / 3 if maxwidth <= 60 : width = maxwidth elif 60 < maxwidth <= 120 : width = maxwidth / 2 return width
Return the width of a single bar when width of the page is given .
236,324
def triad ( note , key ) : return [ note , intervals . third ( note , key ) , intervals . fifth ( note , key ) ]
Return the triad on note in key as a list .
236,325
def triads ( key ) : if _triads_cache . has_key ( key ) : return _triads_cache [ key ] res = map ( lambda x : triad ( x , key ) , keys . get_notes ( key ) ) _triads_cache [ key ] = res return res
Return all the triads in key .
236,326
def augmented_triad ( note ) : return [ note , intervals . major_third ( note ) , notes . augment ( intervals . major_fifth ( note ) ) ]
Build an augmented triad on note .
236,327
def seventh ( note , key ) : return triad ( note , key ) + [ intervals . seventh ( note , key ) ]
Return the seventh chord on note in key .
236,328
def sevenths ( key ) : if _sevenths_cache . has_key ( key ) : return _sevenths_cache [ key ] res = map ( lambda x : seventh ( x , key ) , keys . get_notes ( key ) ) _sevenths_cache [ key ] = res return res
Return all the sevenths chords in key in a list .
236,329
def dominant_flat_ninth ( note ) : res = dominant_ninth ( note ) res [ 4 ] = intervals . minor_second ( note ) return res
Build a dominant flat ninth chord on note .
236,330
def dominant_sharp_ninth ( note ) : res = dominant_ninth ( note ) res [ 4 ] = notes . augment ( intervals . major_second ( note ) ) return res
Build a dominant sharp ninth chord on note .
236,331
def eleventh ( note ) : return [ note , intervals . perfect_fifth ( note ) , intervals . minor_seventh ( note ) , intervals . perfect_fourth ( note ) ]
Build an eleventh chord on note .
236,332
def dominant_flat_five ( note ) : res = dominant_seventh ( note ) res [ 2 ] = notes . diminish ( res [ 2 ] ) return res
Build a dominant flat five chord on note .
236,333
def from_shorthand ( shorthand_string , slash = None ) : if type ( shorthand_string ) == list : res = [ ] for x in shorthand_string : res . append ( from_shorthand ( x ) ) return res if shorthand_string in [ 'NC' , 'N.C.' ] : return [ ] shorthand_string = shorthand_string . replace ( 'min' , 'm' ) shorthand_string = sh...
Take a chord written in shorthand and return the notes in the chord .
236,334
def determine ( chord , shorthand = False , no_inversions = False , no_polychords = False ) : if chord == [ ] : return [ ] elif len ( chord ) == 1 : return chord elif len ( chord ) == 2 : return [ intervals . determine ( chord [ 0 ] , chord [ 1 ] ) ] elif len ( chord ) == 3 : return determine_triad ( chord , shorthand ...
Name a chord .
236,335
def determine_triad ( triad , shorthand = False , no_inversions = False , placeholder = None ) : if len ( triad ) != 3 : return False def inversion_exhauster ( triad , shorthand , tries , result ) : intval1 = intervals . determine ( triad [ 0 ] , triad [ 1 ] , True ) intval2 = intervals . determine ( triad [ 0 ] , tria...
Name the triad ; return answers in a list .
236,336
def determine_seventh ( seventh , shorthand = False , no_inversion = False , no_polychords = False ) : if len ( seventh ) != 4 : return False def inversion_exhauster ( seventh , shorthand , tries , result , polychords ) : triads = determine_triad ( seventh [ : 3 ] , True , True ) intval3 = intervals . determine ( seven...
Determine the type of seventh chord ; return the results in a list ordered on inversions .
236,337
def determine_extended_chord5 ( chord , shorthand = False , no_inversions = False , no_polychords = False ) : if len ( chord ) != 5 : return False def inversion_exhauster ( chord , shorthand , tries , result , polychords ) : def add_result ( short ) : result . append ( ( short , tries , chord [ 0 ] ) ) triads = determi...
Determine the names of an extended chord .
236,338
def determine_extended_chord6 ( chord , shorthand = False , no_inversions = False , no_polychords = False ) : if len ( chord ) != 6 : return False def inversion_exhauster ( chord , shorthand , tries , result , polychords , ) : if tries == 1 and not no_polychords : polychords += determine_polychords ( chord , shorthand ...
Determine the names of an 6 note chord .
236,339
def determine_polychords ( chord , shorthand = False ) : polychords = [ ] function_list = [ determine_triad , determine_seventh , determine_extended_chord5 , determine_extended_chord6 , determine_extended_chord7 ] if len ( chord ) <= 3 : return [ ] elif len ( chord ) > 14 : return [ ] elif len ( chord ) - 3 <= 5 : func...
Determine the polychords in chord . This function can handle anything from polychords based on two triads to 6 note extended chords .
236,340
def from_Note ( note , process_octaves = True , standalone = True ) : if not hasattr ( note , 'name' ) : return False result = note . name [ 0 ] . lower ( ) for accidental in note . name [ 1 : ] : if accidental == '#' : result += 'is' elif accidental == 'b' : result += 'es' if process_octaves : oct = note . octave if o...
Get a Note object and return the LilyPond equivalent in a string .
236,341
def from_NoteContainer ( nc , duration = None , standalone = True ) : if nc is not None and not hasattr ( nc , 'notes' ) : return False if nc is None or len ( nc . notes ) == 0 : result = 'r' elif len ( nc . notes ) == 1 : result = from_Note ( nc . notes [ 0 ] , standalone = False ) else : result = '<' for notes in nc ...
Get a NoteContainer object and return the LilyPond equivalent in a string .
236,342
def from_Bar ( bar , showkey = True , showtime = True ) : if not hasattr ( bar , 'bar' ) : return False if showkey : key_note = Note ( bar . key . key [ 0 ] . upper ( ) + bar . key . key [ 1 : ] ) key = '\\key %s \\%s ' % ( from_Note ( key_note , False , standalone = False ) , bar . key . mode ) result = key else : res...
Get a Bar object and return the LilyPond equivalent in a string .
236,343
def from_Track ( track ) : if not hasattr ( track , 'bars' ) : return False lastkey = Key ( 'C' ) lasttime = ( 4 , 4 ) result = '' for bar in track . bars : if lastkey != bar . key : showkey = True else : showkey = False if lasttime != bar . meter : showtime = True else : showtime = False result += from_Bar ( bar , sho...
Process a Track object and return the LilyPond equivalent in a string .
236,344
def from_Composition ( composition ) : if not hasattr ( composition , 'tracks' ) : return False result = '\\header { title = "%s" composer = "%s" opus = "%s" } ' % ( composition . title , composition . author , composition . subtitle ) for track in composition . tracks : result += from_Track ( track ) + ' ' return resu...
Return the LilyPond equivalent of a Composition in a string .
236,345
def save_string_and_execute_LilyPond ( ly_string , filename , command ) : ly_string = '\\version "2.10.33"\n' + ly_string if filename [ - 4 : ] in [ '.pdf' , '.png' ] : filename = filename [ : - 4 ] try : f = open ( filename + '.ly' , 'w' ) f . write ( ly_string ) f . close ( ) except : return False command = 'lilypond...
A helper function for to_png and to_pdf . Should not be used directly .
236,346
def determine ( value ) : i = - 2 for v in base_values : if value == v : return ( value , 0 , 1 , 1 ) if value < v : break i += 1 scaled = float ( value ) / 2 ** i if scaled >= 0.9375 : return ( base_values [ i ] , 0 , 1 , 1 ) elif scaled >= 0.8125 : return ( base_values [ i + 1 ] , 0 , 7 , 4 ) elif scaled >= 17 / 24.0...
Analyse the value and return a tuple containing the parts it s made of .
236,347
def init ( sf2 , driver = None , file = None ) : global midi , initialized if not initialized : if file is not None : midi . start_recording ( file ) else : midi . start_audio_output ( driver ) if not midi . load_sound_font ( sf2 ) : return False midi . fs . program_reset ( ) initialized = True return True
Initialize the audio .
236,348
def start_recording ( self , file = 'mingus_dump.wav' ) : w = wave . open ( file , 'wb' ) w . setnchannels ( 2 ) w . setsampwidth ( 2 ) w . setframerate ( 44100 ) self . wav = w
Initialize a new wave file for recording .
236,349
def load_sound_font ( self , sf2 ) : self . sfid = self . fs . sfload ( sf2 ) return not self . sfid == - 1
Load a sound font .
236,350
def create ( self , group_type , config_file , group_name = None , region = None , profile_name = None ) : logging . info ( "[begin] create command using group_types:{0}" . format ( self . group_types ) ) config = GroupConfigFile ( config_file = config_file ) if config . is_fresh ( ) is False : raise ValueError ( "Conf...
Create a Greengrass group in the given region .
236,351
def _create_subscription_definition ( gg_client , group_type , config ) : logging . info ( '[begin] Configuring routing subscriptions' ) sub_info = gg_client . create_subscription_definition ( Name = "{0}_routing" . format ( group_type . type_name ) ) logging . info ( 'Created subscription definition: {0}' . format ( s...
Configure routing subscriptions for a Greengrass group .
236,352
def clean_core ( self , config_file , region = None , profile_name = None ) : config = GroupConfigFile ( config_file = config_file ) if region is None : region = self . _region core_cert_id = config [ 'core' ] [ 'cert_id' ] core_cert_arn = config [ 'core' ] [ 'cert_arn' ] core_thing_name = config [ 'core' ] [ 'thing_na...
Clean all Core related provisioned artifacts from both the local file and the AWS Greengrass service .
236,353
def clean_devices ( self , config_file , region = None , profile_name = None ) : config = GroupConfigFile ( config_file = config_file ) if region is None : region = self . _region devices = config [ 'devices' ] if 'device_thing_name' in devices : logging . info ( 'Configured devices already clean' ) return policy_name ...
Clean all device related provisioned artifacts from both the local file and the AWS Greengrass service .
236,354
def clean_file ( config_file ) : logging . info ( '[begin] Cleaning config file' ) config = GroupConfigFile ( config_file = config_file ) if config . is_fresh ( ) is True : raise ValueError ( "Config is already clean." ) config . make_fresh ( ) logging . info ( '[end] Cleaned config file:{0}' . format ( config_file ) )
Clean all provisioned artifacts from the local config file .
236,355
def clean_all ( self , config_file , region = None , profile_name = None ) : logging . info ( '[begin] Cleaning all provisioned artifacts' ) config = GroupConfigFile ( config_file = config_file ) if config . is_fresh ( ) is True : raise ValueError ( "Config is already clean." ) if region is None : region = self . _regi...
Clean all provisioned artifacts from both the local file and the AWS Greengrass service .
236,356
def deploy ( self , config_file , region = None , profile_name = None ) : config = GroupConfigFile ( config_file = config_file ) if config . is_fresh ( ) : raise ValueError ( "Config not yet tracking a group. Cannot deploy." ) if region is None : region = self . _region gg_client = _get_gg_session ( region = region , p...
Deploy the configuration and Lambda functions of a Greengrass group to the Greengrass core contained in the group .
236,357
def create_core ( self , thing_name , config_file , region = None , cert_dir = None , account_id = None , policy_name = 'ggc-default-policy' , profile_name = None ) : config = GroupConfigFile ( config_file = config_file ) if config . is_fresh ( ) is False : raise ValueError ( "Config file already tracking previously cr...
Using the thing_name value creates a Thing in AWS IoT attaches and downloads new keys & certs to the certificate directory then records the created information in the local config file for inclusion in the Greengrass Group as a Greengrass Core .
236,358
def create_devices ( self , thing_names , config_file , region = None , cert_dir = None , append = False , account_id = None , policy_name = 'ggd-discovery-policy' , profile_name = None ) : logging . info ( "create_devices thing_names:{0}" . format ( thing_names ) ) config = GroupConfigFile ( config_file = config_file ...
Using the thing_names values creates Things in AWS IoT attaches and downloads new keys & certs to the certificate directory then records the created information in the local config file for inclusion in the Greengrass Group as Greengrass Devices .
236,359
def associate_devices ( self , thing_names , config_file , region = None , profile_name = None ) : logging . info ( "associate_devices thing_names:{0}" . format ( thing_names ) ) config = GroupConfigFile ( config_file = config_file ) if region is None : region = self . _region devices = config [ 'devices' ] if type ( t...
Using the thing_names values associate existing Things in AWS IoT with the config of another Greengrass Group for use as Greengrass Devices .
236,360
def send_data ( self , message ) : data = json . dumps ( message ) . encode ( 'utf-8' ) + b'\n' self . transport . write ( data )
Given an object encode as JSON and transmit to the server .
236,361
async def got_who_reply ( self , nick = None , real_name = None , ** kws ) : nick = nick [ 2 : ] if nick [ 0 : 2 ] == 'E_' else nick host , ports = real_name . split ( ' ' , 1 ) self . servers . remove ( nick ) logger . debug ( "Found: '%s' at %s with port list: %s" , nick , host , ports ) self . results [ host . lower...
Server replied to one of our WHO requests with details .
236,362
async def _keepalive ( self ) : while self . protocol : vers = await self . RPC ( 'server.version' ) logger . debug ( "Server version: " + repr ( vers ) ) await asyncio . sleep ( 600 )
Keep our connect to server alive forever with some pointless traffic .
236,363
def _send_request ( self , method , params = [ ] , is_subscribe = False ) : self . next_id += 1 req_id = self . next_id msg = { 'id' : req_id , 'method' : method , 'params' : params } if is_subscribe : waitQ = asyncio . Queue ( ) self . subscriptions [ method ] . append ( waitQ ) fut = asyncio . Future ( loop = self . ...
Send a new request to the server . Serialized the JSON and tracks id numbers and optional callbacks .
236,364
def _got_response ( self , msg ) : resp_id = msg . get ( 'id' , None ) if resp_id is None : method = msg . get ( 'method' , None ) if not method : logger . error ( "Incoming server message had no ID nor method in it" , msg ) return result = msg . get ( 'params' , None ) logger . debug ( "Traffic on subscription: %s" % ...
Decode and dispatch responses from the server .
236,365
def from_json ( self , fname ) : with open ( fname , 'rt' ) as fp : for row in json . load ( fp ) : nn = ServerInfo . from_dict ( row ) self [ str ( nn ) ] = nn
Read contents of a CSV containing a list of servers .
236,366
def from_irc ( self , irc_nickname = None , irc_password = None ) : if have_bottom : from . findall import IrcListener bot = IrcListener ( irc_nickname = irc_nickname , irc_password = irc_password ) results = bot . loop . run_until_complete ( bot . collect_data ( ) ) bot . loop . close ( ) self . update ( results ) els...
Connect to the IRC channel and find all servers presently connected .
236,367
def save_json ( self , fname = 'servers.json' ) : rows = sorted ( self . keys ( ) ) with open ( fname , 'wt' ) as fp : json . dump ( [ self [ k ] for k in rows ] , fp , indent = 1 )
Write out to a CSV file .
236,368
def select ( self , ** kws ) : lst = [ i for i in self . values ( ) if i . select ( ** kws ) ] random . shuffle ( lst ) return lst
Find all servers with indicated protocol support . Shuffled .
236,369
def _post_patched_request ( consumers , lti_key , body , url , method , content_type ) : oauth_server = LTIOAuthServer ( consumers ) oauth_server . add_signature_method ( SignatureMethod_HMAC_SHA1_Unicode ( ) ) lti_consumer = oauth_server . lookup_consumer ( lti_key ) lti_cert = oauth_server . lookup_cert ( lti_key ) s...
Authorization header needs to be capitalized for some LTI clients this function ensures that header is capitalized
236,370
def post_message ( consumers , lti_key , url , body ) : content_type = 'application/xml' method = 'POST' ( _ , content ) = _post_patched_request ( consumers , lti_key , body , url , method , content_type , ) is_success = b"<imsx_codeMajor>success</imsx_codeMajor>" in content log . debug ( "is success %s" , is_success )...
Posts a signed message to LTI consumer
236,371
def post_message2 ( consumers , lti_key , url , body , method = 'POST' , content_type = 'application/xml' ) : ( response , _ ) = _post_patched_request ( consumers , lti_key , body , url , method , content_type , ) is_success = response . status == 200 log . debug ( "is success %s" , is_success ) return is_success
Posts a signed message to LTI consumer using LTI 2 . 0 format
236,372
def verify_request_common ( consumers , url , method , headers , params ) : log . debug ( "consumers %s" , consumers ) log . debug ( "url %s" , url ) log . debug ( "method %s" , method ) log . debug ( "headers %s" , headers ) log . debug ( "params %s" , params ) oauth_server = LTIOAuthServer ( consumers ) oauth_server ...
Verifies that request is valid
236,373
def generate_request_xml ( message_identifier_id , operation , lis_result_sourcedid , score ) : root = etree . Element ( u'imsx_POXEnvelopeRequest' , xmlns = u'http://www.imsglobal.org/services/' u'ltiv1p1/xsd/imsoms_v1p0' ) header = etree . SubElement ( root , 'imsx_POXHeader' ) header_info = etree . SubElement ( head...
Generates LTI 1 . 1 XML for posting result to LTI consumer .
236,374
def is_role ( self , role ) : log . debug ( "is_role %s" , role ) roles = self . session [ 'roles' ] . split ( ',' ) if role in LTI_ROLES : role_list = LTI_ROLES [ role ] roles = set ( role_list ) & set ( roles ) is_user_role_there = len ( roles ) >= 1 log . debug ( "is_role roles_list=%s role=%s in list=%s" , role_lis...
Verify if user is in role
236,375
def _check_role ( self ) : role = u'any' if 'role' in self . lti_kwargs : role = self . lti_kwargs [ 'role' ] log . debug ( "check_role lti_role=%s decorator_role=%s" , self . role , role ) if not ( role == u'any' or self . is_role ( self , role ) ) : raise LTIRoleException ( 'Not authorized.' )
Check that user is in role specified as wrapper attribute
236,376
def post_grade ( self , grade ) : message_identifier_id = self . message_identifier_id ( ) operation = 'replaceResult' lis_result_sourcedid = self . lis_result_sourcedid score = float ( grade ) if 0 <= score <= 1.0 : xml = generate_request_xml ( message_identifier_id , operation , lis_result_sourcedid , score ) ret = p...
Post grade to LTI consumer using XML
236,377
def _consumers ( self ) : app_config = self . lti_kwargs [ 'app' ] . config config = app_config . get ( 'PYLTI_CONFIG' , dict ( ) ) consumers = config . get ( 'consumers' , dict ( ) ) return consumers
Gets consumer s map from app config
236,378
def response_url ( self ) : url = "" url = self . session [ 'lis_outcome_service_url' ] app_config = self . lti_kwargs [ 'app' ] . config urls = app_config . get ( 'PYLTI_URL_FIX' , dict ( ) ) for prefix , mapping in urls . items ( ) : if url . startswith ( prefix ) : for _from , _to in mapping . items ( ) : url = url ...
Returns remapped lis_outcome_service_url uses PYLTI_URL_FIX map to support edX dev - stack
236,379
def _consumers ( self ) : consumers = { } for env in os . environ : if env . startswith ( 'CONSUMER_KEY_SECRET_' ) : key = env [ 20 : ] consumers [ key ] = { "secret" : os . environ [ env ] , "cert" : None } if not consumers : raise LTIException ( "No consumers found. Chalice stores " "consumers in Lambda environment v...
Gets consumers from Lambda environment variables prefixed with CONSUMER_KEY_SECRET_ . For example given a consumer key of foo and a shared secret of bar you should have an environment variable CONSUMER_KEY_SECRET_foo = bar .
236,380
def verify_request ( self ) : request = self . lti_kwargs [ 'app' ] . current_request if request . method == 'POST' : parsed_url = request . raw_body . decode ( ) parsed_qs = parse_qs ( parsed_url , keep_blank_values = True ) params = { k : v [ 0 ] for k , v in parsed_qs . items ( ) } else : params = request . query_pa...
Verify LTI request
236,381
def get_queryset ( self ) : return Event . objects . filter ( Q ( startTime__gte = timezone . now ( ) - timedelta ( days = 90 ) ) & ( Q ( series__isnull = False ) | Q ( publicevent__isnull = False ) ) ) . annotate ( count = Count ( 'eventregistration' ) ) . annotate ( ** self . get_annotations ( ) ) . exclude ( Q ( cou...
Recent events are listed in link form .
236,382
def get_context_data ( self , ** kwargs ) : self . set_return_page ( 'viewregistrations' , _ ( 'View Registrations' ) , event_id = self . object . id ) context = { 'event' : self . object , 'registrations' : EventRegistration . objects . filter ( event = self . object , cancelled = False ) . order_by ( 'registration__c...
Add the list of registrations for the given series
236,383
def get_context_data ( self , ** kwargs ) : context = super ( SubmissionRedirectView , self ) . get_context_data ( ** kwargs ) redirect_url = unquote ( self . request . GET . get ( 'redirect_url' , '' ) ) if not redirect_url : redirect_url = self . get_return_page ( ) . get ( 'url' , '' ) if not redirect_url : try : re...
The URL to redirect to can be explicitly specified or it can come from the site session history or it can be the default admin success page as specified in the site settings .
236,384
def get ( self , request , * args , ** kwargs ) : user_has_validation_string = self . get_object ( ) . validationString user_has_permissions = request . user . has_perm ( 'core.view_all_invoices' ) if request . GET . get ( 'v' , None ) == user_has_validation_string or user_has_permissions : return super ( ViewInvoiceVi...
Invoices can be viewed only if the validation string is provided unless the user is logged in and has view_all_invoice permissions
236,385
def dispatch ( self , request , * args , ** kwargs ) : if 'pk' in self . kwargs : try : self . invoices = Invoice . objects . filter ( pk = self . kwargs . get ( 'pk' ) ) [ : ] except ValueError : raise Http404 ( ) if not self . invoices : raise Http404 ( ) else : ids = request . GET . get ( 'invoices' , '' ) try : sel...
Get the set of invoices for which to permit notifications
236,386
def get_form_kwargs ( self ) : kwargs = super ( InvoiceNotificationView , self ) . get_form_kwargs ( ) kwargs [ 'invoices' ] = self . toNotify return kwargs
Pass the set of invoices to the form for creation
236,387
def dispatch ( self , request , * args , ** kwargs ) : ids = request . GET . get ( 'customers' ) groups = request . GET . get ( 'customergroup' ) self . customers = None if ids or groups : filters = Q ( id__isnull = True ) if ids : filters = filters | Q ( id__in = [ int ( x ) for x in ids . split ( ',' ) ] ) if groups ...
If a list of customers or groups was passed then parse it
236,388
def get_form_kwargs ( self , ** kwargs ) : numMonths = 12 lastStart = ( Event . objects . annotate ( Min ( 'eventoccurrence__startTime' ) ) . order_by ( '-eventoccurrence__startTime__min' ) . values_list ( 'eventoccurrence__startTime__min' , flat = True ) . first ( ) ) if lastStart : month = lastStart . month year = la...
Get the list of recent months and recent series to pass to the form
236,389
def get_initial ( self ) : initial = super ( SendEmailView , self ) . get_initial ( ) form_data = self . request . session . get ( EMAIL_VALIDATION_STR , { } ) . get ( 'form_data' , { } ) if form_data : initial . update ( form_data ) return initial
If the user already submitted the form and decided to return from the confirmation page then re - populate the form
236,390
def form_valid ( self , form ) : form . cleaned_data . pop ( 'template' , None ) self . request . session [ EMAIL_VALIDATION_STR ] = { 'form_data' : form . cleaned_data } return HttpResponseRedirect ( reverse ( 'emailConfirmation' ) )
Pass form data to the confirmation view
236,391
def form_valid ( self , form ) : startDate = form . cleaned_data . get ( 'startDate' ) repeatEvery = form . cleaned_data . get ( 'repeatEvery' ) periodicity = form . cleaned_data . get ( 'periodicity' ) quantity = form . cleaned_data . get ( 'quantity' ) endDate = form . cleaned_data . get ( 'endDate' ) if periodicity ...
For each object in the queryset create the duplicated objects
236,392
def recentEvents ( self ) : return Event . objects . filter ( Q ( pk__in = self . individualEvents . values_list ( 'pk' , flat = True ) ) | Q ( session__in = self . eventSessions . all ( ) ) | Q ( publicevent__category__in = self . eventCategories . all ( ) ) | Q ( series__category__in = self . seriesCategories . all (...
Get the set of recent and upcoming events to which this list applies .
236,393
def currentEvent ( self ) : currentEvent = self . recentEvents . filter ( endTime__gte = timezone . now ( ) ) . order_by ( 'startTime' ) . first ( ) if not currentEvent : currentEvent = self . recentEvents . filter ( endTime__lte = timezone . now ( ) ) . order_by ( '-endTime' ) . first ( ) return currentEvent
Return the first event that hasn t ended yet or if there are no future events the last one to end .
236,394
def appliesToEvent ( self , event ) : return ( event in self . individualEvents . all ( ) or event . session in self . eventSessions . all ( ) or event . category in self . seriesCategories . all ( ) or event . category in self . eventCategories . all ( ) )
Check whether this guest list is applicable to an event .
236,395
def getDayStart ( self , dateTime ) : return ensure_localtime ( dateTime ) . replace ( hour = 0 , minute = 0 , second = 0 , microsecond = 0 )
Ensure local time and get the beginning of the day
236,396
def getListForEvent ( self , event = None ) : names = list ( self . guestlistname_set . annotate ( guestType = Case ( When ( notes__isnull = False , then = F ( 'notes' ) ) , default = Value ( ugettext ( 'Manually Added' ) ) , output_field = models . CharField ( ) ) ) . values ( 'firstName' , 'lastName' , 'guestType' ) ...
Get the list of names associated with a particular event .
236,397
def clean ( self ) : if not self . staffCategory and not self . staffMember : raise ValidationError ( _ ( 'Either staff category or staff member must be specified.' ) ) if self . staffCategory and self . staffMember : raise ValidationError ( _ ( 'Specify either a staff category or a staff member, not both.' ) )
Either staffCategory or staffMember must be filled in but not both .
236,398
def updateSeriesAttributes ( request ) : if request . method == 'POST' and request . POST . get ( 'event' ) : series_option = request . POST . get ( 'event' ) or None seriesClasses = EventOccurrence . objects . filter ( event__id = series_option ) seriesTeachers = SeriesTeacher . objects . filter ( event__id = series_o...
This function handles the filtering of available series classes and seriesteachers when a series is chosen on the Substitute Teacher reporting form .
236,399
def processCheckIn ( request ) : if request . method == 'POST' : event_id = request . POST . get ( 'event_id' ) reg_ids = request . POST . getlist ( 'reg_id' ) if not event_id : return HttpResponse ( _ ( "Error at start." ) ) all_eventreg = list ( EventRegistration . objects . filter ( event__id = event_id ) ) for this...
This function handles the Ajax call made when a user is marked as checked in