idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
250,800
def decodeLength ( length ) : bytes_length = len ( length ) if bytes_length < 2 : offset = b'\x00\x00\x00' XOR = 0 elif bytes_length < 3 : offset = b'\x00\x00' XOR = 0x8000 elif bytes_length < 4 : offset = b'\x00' XOR = 0xC00000 elif bytes_length < 5 : offset = b'' XOR = 0xE0000000 else : raise ConnectionError ( 'Unabl...
Decode length based on given bytes .
250,801
def writeSentence ( self , cmd , * words ) : encoded = self . encodeSentence ( cmd , * words ) self . log ( '<---' , cmd , * words ) self . transport . write ( encoded )
Write encoded sentence .
250,802
def read ( self , length ) : data = bytearray ( ) while len ( data ) != length : data += self . sock . recv ( ( length - len ( data ) ) ) if not data : raise ConnectionError ( 'Connection unexpectedly closed.' ) return data
Read as many bytes from socket as specified in length . Loop as long as every byte is read unless exception is raised .
250,803
def parseWord ( word ) : mapping = { 'yes' : True , 'true' : True , 'no' : False , 'false' : False } _ , key , value = word . split ( '=' , 2 ) try : value = int ( value ) except ValueError : value = mapping . get ( value , value ) return ( key , value )
Split given attribute word to key value pair .
250,804
def composeWord ( key , value ) : mapping = { True : 'yes' , False : 'no' } if type ( value ) == int : value = str ( value ) else : value = mapping . get ( value , str ( value ) ) return '={}={}' . format ( key , value )
Create a attribute word from key value pair . Values are casted to api equivalents .
250,805
def login_token ( api , username , password ) : sentence = api ( '/login' ) token = tuple ( sentence ) [ 0 ] [ 'ret' ] encoded = encode_password ( token , password ) tuple ( api ( '/login' , ** { 'name' : username , 'response' : encoded } ) )
Login using pre routeros 6 . 43 authorization method .
250,806
def check_relations ( self , relations ) : for rel in relations : if not rel : continue fields = rel . split ( '.' , 1 ) local_field = fields [ 0 ] if local_field not in self . fields : raise ValueError ( 'Unknown field "{}"' . format ( local_field ) ) field = self . fields [ local_field ] if not isinstance ( field , B...
Recursive function which checks if a relation is valid .
250,807
def format_json_api_response ( self , data , many ) : ret = self . format_items ( data , many ) ret = self . wrap_response ( ret , many ) ret = self . render_included_data ( ret ) ret = self . render_meta_document ( ret ) return ret
Post - dump hook that formats serialized data as a top - level JSON API object .
250,808
def _do_load ( self , data , many = None , ** kwargs ) : many = self . many if many is None else bool ( many ) self . included_data = data . get ( 'included' , { } ) self . document_meta = data . get ( 'meta' , { } ) try : result = super ( Schema , self ) . _do_load ( data , many , ** kwargs ) except ValidationError as...
Override marshmallow . Schema . _do_load for custom JSON API handling .
250,809
def _extract_from_included ( self , data ) : return ( item for item in self . included_data if item [ 'type' ] == data [ 'type' ] and str ( item [ 'id' ] ) == str ( data [ 'id' ] ) )
Extract included data matching the items in data .
250,810
def inflect ( self , text ) : return self . opts . inflect ( text ) if self . opts . inflect else text
Inflect text if the inflect class Meta option is defined otherwise do nothing .
250,811
def format_errors ( self , errors , many ) : if not errors : return { } if isinstance ( errors , ( list , tuple ) ) : return { 'errors' : errors } formatted_errors = [ ] if many : for index , errors in iteritems ( errors ) : for field_name , field_errors in iteritems ( errors ) : formatted_errors . extend ( [ self . fo...
Format validation errors as JSON Error objects .
250,812
def format_error ( self , field_name , message , index = None ) : pointer = [ '/data' ] if index is not None : pointer . append ( str ( index ) ) relationship = isinstance ( self . declared_fields . get ( field_name ) , BaseRelationship , ) if relationship : pointer . append ( 'relationships' ) elif field_name != 'id' ...
Override - able hook to format a single error message as an Error object .
250,813
def format_item ( self , item ) : if not item : return None ret = self . dict_class ( ) ret [ TYPE ] = self . opts . type_ attributes = { ( get_dump_key ( self . fields [ field ] ) or field ) : field for field in self . fields } for field_name , value in iteritems ( item ) : attribute = attributes [ field_name ] if att...
Format a single datum as a Resource object .
250,814
def format_items ( self , data , many ) : if many : return [ self . format_item ( item ) for item in data ] else : return self . format_item ( data )
Format data as a Resource object or list of Resource objects .
250,815
def get_top_level_links ( self , data , many ) : self_link = None if many : if self . opts . self_url_many : self_link = self . generate_url ( self . opts . self_url_many ) else : if self . opts . self_url : self_link = data . get ( 'links' , { } ) . get ( 'self' , None ) return { 'self' : self_link }
Hook for adding links to the root of the response data .
250,816
def get_resource_links ( self , item ) : if self . opts . self_url : ret = self . dict_class ( ) kwargs = resolve_params ( item , self . opts . self_url_kwargs or { } ) ret [ 'self' ] = self . generate_url ( self . opts . self_url , ** kwargs ) return ret return None
Hook for adding links to a resource object .
250,817
def wrap_response ( self , data , many ) : ret = { 'data' : data } if many or data : top_level_links = self . get_top_level_links ( data , many ) if top_level_links [ 'self' ] : ret [ 'links' ] = top_level_links return ret
Wrap data and links according to the JSON API
250,818
def extract_value ( self , data ) : errors = [ ] if 'id' not in data : errors . append ( 'Must have an `id` field' ) if 'type' not in data : errors . append ( 'Must have a `type` field' ) elif data [ 'type' ] != self . type_ : errors . append ( 'Invalid `type` specified' ) if errors : raise ValidationError ( errors ) i...
Extract the id key and validate the request structure .
250,819
def fill_package_digests ( generated_project : Project ) -> Project : for package_version in chain ( generated_project . pipfile_lock . packages , generated_project . pipfile_lock . dev_packages ) : if package_version . hashes : continue if package_version . index : scanned_hashes = package_version . index . get_packag...
Temporary fill package digests stated in Pipfile . lock .
250,820
def fetch_digests ( self , package_name : str , package_version : str ) -> dict : report = { } for source in self . _sources : try : report [ source . url ] = source . get_package_hashes ( package_name , package_version ) except NotFound as exc : _LOGGER . debug ( f"Package {package_name} in version {package_version} n...
Fetch digests for the given package in specified version from the given package index .
250,821
def random_passphrase_from_wordlist ( phrase_length , wordlist ) : passphrase_words = [ ] numbytes_of_entropy = phrase_length * 2 entropy = list ( dev_random_entropy ( numbytes_of_entropy , fallback_to_urandom = True ) ) bytes_per_word = int ( ceil ( log ( len ( wordlist ) , 2 ) / 8 ) ) if ( phrase_length * bytes_per_w...
An extremely entropy efficient passphrase generator .
250,822
def reverse_hash ( hash , hex_format = True ) : if not hex_format : hash = hexlify ( hash ) return "" . join ( reversed ( [ hash [ i : i + 2 ] for i in range ( 0 , len ( hash ) , 2 ) ] ) )
hash is in hex or binary format
250,823
def get_num_words_with_entropy ( bits_of_entropy , wordlist ) : entropy_per_word = math . log ( len ( wordlist ) ) / math . log ( 2 ) num_words = int ( math . ceil ( bits_of_entropy / entropy_per_word ) ) return num_words
Gets the number of words randomly selected from a given wordlist that would result in the number of bits of entropy specified .
250,824
def create_passphrase ( bits_of_entropy = None , num_words = None , language = 'english' , word_source = 'wiktionary' ) : wordlist = get_wordlist ( language , word_source ) if not num_words : if not bits_of_entropy : bits_of_entropy = 80 num_words = get_num_words_with_entropy ( bits_of_entropy , wordlist ) return ' ' ....
Creates a passphrase that has a certain number of bits of entropy OR a certain number of words .
250,825
def serialize_input ( input , signature_script_hex = '' ) : if not ( isinstance ( input , dict ) and 'transaction_hash' in input and 'output_index' in input ) : raise Exception ( 'Required parameters: transaction_hash, output_index' ) if is_hex ( str ( input [ 'transaction_hash' ] ) ) and len ( str ( input [ 'transacti...
Serializes a transaction input .
250,826
def serialize_output ( output ) : if not ( 'value' in output and 'script_hex' in output ) : raise Exception ( 'Invalid output' ) return '' . join ( [ hexlify ( struct . pack ( '<Q' , output [ 'value' ] ) ) , hexlify ( variable_length_int ( len ( output [ 'script_hex' ] ) / 2 ) ) , output [ 'script_hex' ] ] )
Serializes a transaction output .
250,827
def serialize_transaction ( inputs , outputs , lock_time = 0 , version = 1 ) : serialized_inputs = '' . join ( [ serialize_input ( input ) for input in inputs ] ) serialized_outputs = '' . join ( [ serialize_output ( output ) for output in outputs ] ) return '' . join ( [ hexlify ( struct . pack ( '<I' , version ) ) , ...
Serializes a transaction .
250,828
def deserialize_transaction ( tx_hex ) : tx = bitcoin . deserialize ( str ( tx_hex ) ) inputs = tx [ "ins" ] outputs = tx [ "outs" ] ret_inputs = [ ] ret_outputs = [ ] for inp in inputs : ret_inp = { "transaction_hash" : inp [ "outpoint" ] [ "hash" ] , "output_index" : int ( inp [ "outpoint" ] [ "index" ] ) , } if "seq...
Given a serialized transaction return its inputs outputs locktime and version
250,829
def variable_length_int ( i ) : if not isinstance ( i , ( int , long ) ) : raise Exception ( 'i must be an integer' ) if i < ( 2 ** 8 - 3 ) : return chr ( i ) elif i < ( 2 ** 16 ) : return chr ( 253 ) + struct . pack ( '<H' , i ) elif i < ( 2 ** 32 ) : return chr ( 254 ) + struct . pack ( '<I' , i ) elif i < ( 2 ** 64 ...
Encodes integers into variable length integers which are used in Bitcoin in order to save space .
250,830
def make_pay_to_address_script ( address ) : hash160 = hexlify ( b58check_decode ( address ) ) script_string = 'OP_DUP OP_HASH160 %s OP_EQUALVERIFY OP_CHECKSIG' % hash160 return script_to_hex ( script_string )
Takes in an address and returns the script
250,831
def make_op_return_script ( data , format = 'bin' ) : if format == 'hex' : assert ( is_hex ( data ) ) hex_data = data elif format == 'bin' : hex_data = hexlify ( data ) else : raise Exception ( "Format must be either 'hex' or 'bin'" ) num_bytes = count_bytes ( hex_data ) if num_bytes > MAX_BYTES_AFTER_OP_RETURN : raise...
Takes in raw ascii data to be embedded and returns a script .
250,832
def create_bitcoind_service_proxy ( rpc_username , rpc_password , server = '127.0.0.1' , port = 8332 , use_https = False ) : protocol = 'https' if use_https else 'http' uri = '%s://%s:%s@%s:%s' % ( protocol , rpc_username , rpc_password , server , port ) return AuthServiceProxy ( uri )
create a bitcoind service proxy
250,833
def get_unspents ( address , blockchain_client = BlockchainInfoClient ( ) ) : if isinstance ( blockchain_client , BlockcypherClient ) : return blockcypher . get_unspents ( address , blockchain_client ) elif isinstance ( blockchain_client , BlockchainInfoClient ) : return blockchain_info . get_unspents ( address , block...
Gets the unspent outputs for a given address .
250,834
def broadcast_transaction ( hex_tx , blockchain_client ) : if isinstance ( blockchain_client , BlockcypherClient ) : return blockcypher . broadcast_transaction ( hex_tx , blockchain_client ) elif isinstance ( blockchain_client , BlockchainInfoClient ) : return blockchain_info . broadcast_transaction ( hex_tx , blockcha...
Dispatches a raw hex transaction to the network .
250,835
def make_send_to_address_tx ( recipient_address , amount , private_key , blockchain_client = BlockchainInfoClient ( ) , fee = STANDARD_FEE , change_address = None ) : private_key_obj , from_address , inputs = analyze_private_key ( private_key , blockchain_client ) if not change_address : change_address = from_address o...
Builds and signs a send to address transaction .
250,836
def make_op_return_tx ( data , private_key , blockchain_client = BlockchainInfoClient ( ) , fee = OP_RETURN_FEE , change_address = None , format = 'bin' ) : private_key_obj , from_address , inputs = analyze_private_key ( private_key , blockchain_client ) if not change_address : change_address = from_address outputs = m...
Builds and signs an OP_RETURN transaction .
250,837
def send_to_address ( recipient_address , amount , private_key , blockchain_client = BlockchainInfoClient ( ) , fee = STANDARD_FEE , change_address = None ) : signed_tx = make_send_to_address_tx ( recipient_address , amount , private_key , blockchain_client , fee = fee , change_address = change_address ) response = bro...
Builds signs and dispatches a send to address transaction .
250,838
def embed_data_in_blockchain ( data , private_key , blockchain_client = BlockchainInfoClient ( ) , fee = OP_RETURN_FEE , change_address = None , format = 'bin' ) : signed_tx = make_op_return_tx ( data , private_key , blockchain_client , fee = fee , change_address = change_address , format = format ) response = broadcas...
Builds signs and dispatches an OP_RETURN transaction .
250,839
def sign_all_unsigned_inputs ( hex_privkey , unsigned_tx_hex ) : inputs , outputs , locktime , version = deserialize_transaction ( unsigned_tx_hex ) tx_hex = unsigned_tx_hex for index in xrange ( 0 , len ( inputs ) ) : if len ( inputs [ index ] [ 'script_sig' ] ) == 0 : tx_hex = sign_transaction ( str ( unsigned_tx_hex...
Sign a serialized transaction s unsigned inputs
250,840
def calculate_merkle_root ( hashes , hash_function = bin_double_sha256 , hex_format = True ) : if hex_format : hashes = hex_to_bin_reversed_hashes ( hashes ) while len ( hashes ) > 1 : hashes = calculate_merkle_pairs ( hashes , hash_function ) merkle_root = hashes [ 0 ] if hex_format : return bin_to_hex_reversed ( merk...
takes in a list of binary hashes returns a binary hash
250,841
def b58check_encode ( bin_s , version_byte = 0 ) : bin_s = chr ( int ( version_byte ) ) + bin_s num_leading_zeros = len ( re . match ( r'^\x00*' , bin_s ) . group ( 0 ) ) bin_s = bin_s + bin_checksum ( bin_s ) hex_s = hexlify ( bin_s ) b58_s = change_charset ( hex_s , HEX_KEYSPACE , B58_KEYSPACE ) return B58_KEYSPACE [...
Takes in a binary string and converts it to a base 58 check string .
250,842
def make_pay_to_address_outputs ( to_address , send_amount , inputs , change_address , fee = STANDARD_FEE ) : return [ { "script_hex" : make_pay_to_address_script ( to_address ) , "value" : send_amount } , { "script_hex" : make_pay_to_address_script ( change_address ) , "value" : calculate_change_amount ( inputs , send...
Builds the outputs for a pay to address transaction .
250,843
def make_op_return_outputs ( data , inputs , change_address , fee = OP_RETURN_FEE , send_amount = 0 , format = 'bin' ) : return [ { "script_hex" : make_op_return_script ( data , format = format ) , "value" : send_amount } , { "script_hex" : make_pay_to_address_script ( change_address ) , "value" : calculate_change_amou...
Builds the outputs for an OP_RETURN transaction .
250,844
def add_timezone ( value , tz = None ) : tz = tz or timezone . get_current_timezone ( ) try : if timezone . is_naive ( value ) : return timezone . make_aware ( value , tz ) except AttributeError : dt = datetime . datetime . combine ( value , datetime . time ( ) ) return timezone . make_aware ( dt , tz ) return value
If the value is naive then the timezone is added to it .
250,845
def get_active_entry ( user , select_for_update = False ) : entries = apps . get_model ( 'entries' , 'Entry' ) . no_join if select_for_update : entries = entries . select_for_update ( ) entries = entries . filter ( user = user , end_time__isnull = True ) if not entries . exists ( ) : return None if entries . count ( ) ...
Returns the user s currently - active entry or None .
250,846
def get_month_start ( day = None ) : day = add_timezone ( day or datetime . date . today ( ) ) return day . replace ( day = 1 )
Returns the first day of the given month .
250,847
def get_setting ( name , ** kwargs ) : if hasattr ( settings , name ) : return getattr ( settings , name ) if 'default' in kwargs : return kwargs [ 'default' ] if hasattr ( defaults , name ) : return getattr ( defaults , name ) msg = '{0} must be specified in your project settings.' . format ( name ) raise AttributeErr...
Returns the user - defined value for the setting or a default value .
250,848
def get_week_start ( day = None ) : day = add_timezone ( day or datetime . date . today ( ) ) days_since_monday = day . weekday ( ) if days_since_monday != 0 : day = day - relativedelta ( days = days_since_monday ) return day
Returns the Monday of the given week .
250,849
def get_year_start ( day = None ) : day = add_timezone ( day or datetime . date . today ( ) ) return day . replace ( month = 1 ) . replace ( day = 1 )
Returns January 1 of the given year .
250,850
def to_datetime ( date ) : return datetime . datetime ( date . year , date . month , date . day )
Transforms a date or datetime object into a date object .
250,851
def report_estimation_accuracy ( request ) : contracts = ProjectContract . objects . filter ( status = ProjectContract . STATUS_COMPLETE , type = ProjectContract . PROJECT_FIXED ) data = [ ( 'Target (hrs)' , 'Actual (hrs)' , 'Point Label' ) ] for c in contracts : if c . contracted_hours ( ) == 0 : continue pt_label = "...
Idea from Software Estimation Demystifying the Black Art McConnel 2006 Fig 3 - 3 .
250,852
def get_context_data ( self , ** kwargs ) : context = super ( ReportMixin , self ) . get_context_data ( ** kwargs ) form = self . get_form ( ) if form . is_valid ( ) : data = form . cleaned_data start , end = form . save ( ) entryQ = self . get_entry_query ( start , end , data ) trunc = data [ 'trunc' ] if entryQ : val...
Processes form data to get relevant entries & date_headers .
250,853
def get_entry_query ( self , start , end , data ) : incl_billable = data . get ( 'billable' , True ) incl_nonbillable = data . get ( 'non_billable' , True ) incl_leave = data . get ( 'paid_leave' , True ) if not any ( ( incl_billable , incl_nonbillable , incl_leave ) ) : return None basicQ = Q ( end_time__gte = start ,...
Builds Entry query from form data .
250,854
def get_headers ( self , date_headers , from_date , to_date , trunc ) : date_headers = list ( date_headers ) if date_headers and date_headers [ 0 ] < from_date : date_headers [ 0 ] = from_date if date_headers and trunc != 'day' : count = len ( date_headers ) range_headers = [ 0 ] * count for i in range ( count - 1 ) : ...
Adjust date headers & get range headers .
250,855
def get_previous_month ( self ) : end = utils . get_month_start ( ) - relativedelta ( days = 1 ) end = utils . to_datetime ( end ) start = utils . get_month_start ( end ) return start , end
Returns date range for the previous full month .
250,856
def convert_context_to_csv ( self , context ) : content = [ ] date_headers = context [ 'date_headers' ] headers = [ 'Name' ] headers . extend ( [ date . strftime ( '%m/%d/%Y' ) for date in date_headers ] ) headers . append ( 'Total' ) content . append ( headers ) summaries = context [ 'summaries' ] summary = summaries ...
Convert the context dictionary into a CSV file .
250,857
def defaults ( self ) : ( start , end ) = get_week_window ( timezone . now ( ) - relativedelta ( days = 7 ) ) return { 'from_date' : start , 'to_date' : end , 'billable' : True , 'non_billable' : False , 'paid_leave' : False , 'trunc' : 'day' , 'projects' : [ ] , }
Default filter form data when no GET data is provided .
250,858
def get_hours_data ( self , entries , date_headers ) : project_totals = get_project_totals ( entries , date_headers , total_column = False ) if entries else [ ] data_map = { } for rows , totals in project_totals : for user , user_id , periods in rows : for period in periods : day = period [ 'day' ] if day not in data_m...
Sum billable and non - billable hours across all users .
250,859
def add_parameters ( url , parameters ) : if parameters : sep = '&' if '?' in url else '?' return '{0}{1}{2}' . format ( url , sep , urlencode ( parameters ) ) return url
Appends URL - encoded parameters to the base URL . It appends after & if ? is found in the URL ; otherwise it appends using ? . Keep in mind that this tag does not take into account the value of existing params ; it is therefore possible to add another value for a pre - existing parameter .
250,860
def get_max_hours ( context ) : progress = context [ 'project_progress' ] return max ( [ 0 ] + [ max ( p [ 'worked' ] , p [ 'assigned' ] ) for p in progress ] )
Return the largest number of hours worked or assigned on any project .
250,861
def get_uninvoiced_hours ( entries , billable = None ) : statuses = ( 'invoiced' , 'not-invoiced' ) if billable is not None : billable = ( billable . lower ( ) == u'billable' ) entries = [ e for e in entries if e . activity . billable == billable ] hours = sum ( [ e . hours for e in entries if e . status not in statuse...
Given an iterable of entries return the total hours that have not been invoiced . If billable is passed as billable or nonbillable limit to the corresponding entries .
250,862
def humanize_hours ( total_hours , frmt = '{hours:02d}:{minutes:02d}:{seconds:02d}' , negative_frmt = None ) : seconds = int ( float ( total_hours ) * 3600 ) return humanize_seconds ( seconds , frmt , negative_frmt )
Given time in hours return a string representing the time .
250,863
def _timesheet_url ( url_name , pk , date = None ) : url = reverse ( url_name , args = ( pk , ) ) if date : params = { 'month' : date . month , 'year' : date . year } return '?' . join ( ( url , urlencode ( params ) ) ) return url
Utility to create a time sheet URL with optional date parameters .
250,864
def reject_user_timesheet ( request , user_id ) : form = YearMonthForm ( request . GET or request . POST ) user = User . objects . get ( pk = user_id ) if form . is_valid ( ) : from_date , to_date = form . save ( ) entries = Entry . no_join . filter ( status = Entry . VERIFIED , user = user , start_time__gte = from_dat...
This allows admins to reject all entries instead of just one
250,865
def _is_requirement ( line ) : line = line . strip ( ) return line and not ( line . startswith ( "-r" ) or line . startswith ( "#" ) )
Returns whether the line is a valid package requirement .
250,866
def render_to_response ( self , context ) : if self . redirect_if_one_result : if self . object_list . count ( ) == 1 and self . form . is_bound : return redirect ( self . object_list . get ( ) . get_absolute_url ( ) ) return super ( SearchMixin , self ) . render_to_response ( context )
When the user makes a search and there is only one result redirect to the result s detail page rather than rendering the list .
250,867
def clean_start_time ( self ) : start = self . cleaned_data . get ( 'start_time' ) if not start : return start active_entries = self . user . timepiece_entries . filter ( start_time__gte = start , end_time__isnull = True ) for entry in active_entries : output = ( 'The start time is on or before the current entry: ' '%s...
Make sure that the start time doesn t come before the active entry
250,868
def clean ( self ) : active = utils . get_active_entry ( self . user ) start_time = self . cleaned_data . get ( 'start_time' , None ) end_time = self . cleaned_data . get ( 'end_time' , None ) if active and active . pk != self . instance . pk : if ( start_time and start_time > active . start_time ) or ( end_time and en...
If we re not editing the active entry ensure that this entry doesn t conflict with or come after the active entry .
250,869
def clock_in ( request ) : user = request . user active_entry = utils . get_active_entry ( user , select_for_update = True ) initial = dict ( [ ( k , v ) for k , v in request . GET . items ( ) ] ) data = request . POST or None form = ClockInForm ( data , initial = initial , user = user , active = active_entry ) if form...
For clocking the user into a project .
250,870
def toggle_pause ( request ) : entry = utils . get_active_entry ( request . user ) if not entry : raise Http404 entry . toggle_paused ( ) entry . save ( ) action = 'paused' if entry . is_paused else 'resumed' message = 'Your entry, {0} on {1}, has been {2}.' . format ( entry . activity . name , entry . project , action...
Allow the user to pause and unpause the active entry .
250,871
def reject_entry ( request , entry_id ) : return_url = request . GET . get ( 'next' , reverse ( 'dashboard' ) ) try : entry = Entry . no_join . get ( pk = entry_id ) except : message = 'No such log entry.' messages . error ( request , message ) return redirect ( return_url ) if entry . status == Entry . UNVERIFIED or e...
Admins can reject an entry that has been verified or approved but not invoiced to set its status to unverified for the user to fix .
250,872
def delete_entry ( request , entry_id ) : try : entry = Entry . no_join . get ( pk = entry_id , user = request . user ) except Entry . DoesNotExist : message = 'No such entry found.' messages . info ( request , message ) url = request . GET . get ( 'next' , reverse ( 'dashboard' ) ) return HttpResponseRedirect ( url ) ...
Give the user the ability to delete a log entry with a confirmation beforehand . If this method is invoked via a GET request a form asking for a confirmation of intent will be presented to the user . If this method is invoked via a POST request the entry will be deleted .
250,873
def get_hours_per_week ( self , user = None ) : try : profile = UserProfile . objects . get ( user = user or self . user ) except UserProfile . DoesNotExist : profile = None return profile . hours_per_week if profile else Decimal ( '40.00' )
Retrieves the number of hours the user should work per week .
250,874
def get_hours_for_week ( self , week_start = None ) : week_start = week_start if week_start else self . week_start week_end = week_start + relativedelta ( days = 7 ) return ProjectHours . objects . filter ( week_start__gte = week_start , week_start__lt = week_end )
Gets all ProjectHours entries in the 7 - day period beginning on week_start .
250,875
def get_users_from_project_hours ( self , project_hours ) : name = ( 'user__first_name' , 'user__last_name' ) users = project_hours . values_list ( 'user__id' , * name ) . distinct ( ) . order_by ( * name ) return users
Gets a list of the distinct users included in the project hours entries ordered by name .
250,876
def check_all ( self , all_entries , * args , ** kwargs ) : all_overlaps = 0 while True : try : user_entries = all_entries . next ( ) except StopIteration : return all_overlaps else : user_total_overlaps = self . check_entry ( user_entries , * args , ** kwargs ) all_overlaps += user_total_overlaps
Go through lists of entries find overlaps among each return the total
250,877
def check_entry ( self , entries , * args , ** kwargs ) : verbosity = kwargs . get ( 'verbosity' , 1 ) user_total_overlaps = 0 user = '' for index_a , entry_a in enumerate ( entries ) : if index_a == 0 : if args and verbosity >= 1 or verbosity >= 2 : self . show_name ( entry_a . user ) user = entry_a . user for index_b...
With a list of entries check each entry against every other
250,878
def find_start ( self , ** kwargs ) : week = kwargs . get ( 'week' , False ) month = kwargs . get ( 'month' , False ) year = kwargs . get ( 'year' , False ) days = kwargs . get ( 'days' , 0 ) start = timezone . now ( ) - relativedelta ( months = 1 , day = 1 ) if week : start = utils . get_week_start ( ) if month : star...
Determine the starting point of the query using CLI keyword arguments
250,879
def find_users ( self , * args ) : if args : names = reduce ( lambda query , arg : query | ( Q ( first_name__icontains = arg ) | Q ( last_name__icontains = arg ) ) , args , Q ( ) ) users = User . objects . filter ( names ) else : users = User . objects . all ( ) if not users . count ( ) and args : if len ( args ) == 1 ...
Returns the users to search given names as args . Return all users if there are no args provided .
250,880
def find_entries ( self , users , start , * args , ** kwargs ) : forever = kwargs . get ( 'all' , False ) for user in users : if forever : entries = Entry . objects . filter ( user = user ) . order_by ( 'start_time' ) else : entries = Entry . objects . filter ( user = user , start_time__gte = start ) . order_by ( 'star...
Find all entries for all users from a given starting point . If no starting point is provided all entries are returned .
250,881
def cbv_decorator ( function_decorator ) : def class_decorator ( View ) : View . dispatch = method_decorator ( function_decorator ) ( View . dispatch ) return View return class_decorator
Allows a function - based decorator to be used on a CBV .
250,882
def date_totals ( entries , by ) : date_dict = { } for date , date_entries in groupby ( entries , lambda x : x [ 'date' ] ) : if isinstance ( date , datetime . datetime ) : date = date . date ( ) d_entries = list ( date_entries ) if by == 'user' : name = ' ' . join ( ( d_entries [ 0 ] [ 'user__first_name' ] , d_entries...
Yield a user s name and a dictionary of their hours
250,883
def get_project_totals ( entries , date_headers , hour_type = None , overtime = False , total_column = False , by = 'user' ) : totals = [ 0 for date in date_headers ] rows = [ ] for thing , thing_entries in groupby ( entries , lambda x : x [ by ] ) : name , thing_id , date_dict = date_totals ( thing_entries , by ) date...
Yield hour totals grouped by user and date . Optionally including overtime .
250,884
def validate ( self , validation_instances , metrics , iteration = None ) : if not validation_instances or not metrics : return { } split_id = 'val%s' % iteration if iteration is not None else 'val' train_results = evaluate . evaluate ( self , validation_instances , metrics = metrics , split_id = split_id ) output . ou...
Evaluate this model on validation_instances during training and output a report .
250,885
def predict_and_score ( self , eval_instances , random = False , verbosity = 0 ) : if hasattr ( self , '_using_default_separate' ) and self . _using_default_separate : raise NotImplementedError self . _using_default_combined = True return ( self . predict ( eval_instances , random = random , verbosity = verbosity ) , s...
Return most likely outputs and scores for the particular set of outputs given in eval_instances as a tuple . Return value should be equivalent to the default implementation of
250,886
def load ( self , infile ) : model = pickle . load ( infile ) self . __dict__ . update ( model . __dict__ )
Deserialize a model from a stored file .
250,887
def iter_batches ( iterable , batch_size ) : sourceiter = iter ( iterable ) while True : batchiter = islice ( sourceiter , batch_size ) yield chain ( [ batchiter . next ( ) ] , batchiter )
Given a sequence or iterable yield batches from that iterable until it runs out . Note that this function returns a generator and also each batch will be a generator .
250,888
def gen_batches ( iterable , batch_size ) : def batches_thunk ( ) : return iter_batches ( iterable , batch_size ) try : length = len ( iterable ) except TypeError : return batches_thunk ( ) num_batches = ( length - 1 ) // batch_size + 1 return SizedGenerator ( batches_thunk , length = num_batches )
Returns a generator object that yields batches from iterable . See iter_batches for more details and caveats .
250,889
def inverted ( self ) : return Instance ( input = self . output , output = self . input , annotated_input = self . annotated_output , annotated_output = self . annotated_input , alt_inputs = self . alt_outputs , alt_outputs = self . alt_inputs , source = self . source )
Return a version of this instance with inputs replaced by outputs and vice versa .
250,890
def get_data_or_download ( dir_name , file_name , url = '' , size = 'unknown' ) : dname = os . path . join ( stanza . DATA_DIR , dir_name ) fname = os . path . join ( dname , file_name ) if not os . path . isdir ( dname ) : assert url , 'Could not locate data {}, and url was not specified. Cannot retrieve data.' . form...
Returns the data . if the data hasn t been downloaded then first download the data .
250,891
def add ( self , word , count = 1 ) : if word not in self : super ( Vocab , self ) . __setitem__ ( word , len ( self ) ) self . _counts [ word ] += count return self [ word ]
Add a word to the vocabulary and return its index .
250,892
def subset ( self , words ) : v = self . __class__ ( unk = self . _unk ) unique = lambda seq : len ( set ( seq ) ) == len ( seq ) assert unique ( words ) for w in words : if w in self : v . add ( w , count = self . count ( w ) ) return v
Get a new Vocab containing only the specified subset of words .
250,893
def _index2word ( self ) : compute_index2word = lambda : self . keys ( ) try : self . _index2word_cache except AttributeError : self . _index2word_cache = compute_index2word ( ) if len ( self . _index2word_cache ) != len ( self ) : self . _index2word_cache = compute_index2word ( ) return self . _index2word_cache
Mapping from indices to words .
250,894
def from_dict ( cls , word2index , unk , counts = None ) : try : if word2index [ unk ] != 0 : raise ValueError ( 'unk must be assigned index 0' ) except KeyError : raise ValueError ( 'word2index must have an entry for unk.' ) vals = set ( word2index . values ( ) ) n = len ( vals ) bijection = ( len ( word2index ) == n ...
Create Vocab from an existing string to integer dictionary .
250,895
def to_file ( self , f ) : for word in self . _index2word : count = self . _counts [ word ] f . write ( u'{}\t{}\n' . format ( word , count ) . encode ( 'utf-8' ) )
Write vocab to a file .
250,896
def backfill_unk_emb ( self , E , filled_words ) : unk_emb = E [ self [ self . _unk ] ] for i , word in enumerate ( self ) : if word not in filled_words : E [ i ] = unk_emb
Backfills an embedding matrix with the embedding for the unknown token .
250,897
def best_gpu ( max_usage = USAGE_THRESHOLD , verbose = False ) : try : proc = subprocess . Popen ( "nvidia-smi" , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) output , error = proc . communicate ( ) if error : raise Exception ( error ) except Exception , e : sys . stderr . write ( "Couldn't run nvidia-smi ...
Return the name of a device to use either cpu or gpu0 gpu1 ... The least - used GPU with usage under the constant threshold will be chosen ; ties are broken randomly .
250,898
def evaluate ( learner , eval_data , metrics , metric_names = None , split_id = None , write_data = False ) : if metric_names is None : metric_names = [ ( metric . __name__ if hasattr ( metric , '__name__' ) else ( 'm%d' % i ) ) for i , metric in enumerate ( metrics ) ] split_prefix = split_id + '.' if split_id else ''...
Evaluate learner on the instances in eval_data according to each metric in metric and return a dictionary summarizing the values of the metrics .
250,899
def json2pb ( pb , js , useFieldNumber = False ) : for field in pb . DESCRIPTOR . fields : if useFieldNumber : key = field . number else : key = field . name if key not in js : continue if field . type == FD . TYPE_MESSAGE : pass elif field . type in _js2ftype : ftype = _js2ftype [ field . type ] else : raise ParseErro...
convert JSON string to google . protobuf . descriptor instance