code
stringlengths
1
18.2k
def _get_key_index(self, row): """Get the key that should be used as the first interpolation value""" # Don't bother with empty tracks if len(self.keys) == 0: return -1 # No track values are defined yet if row < self.keys[0].row: return -1 # Get the insertion index index = bisect.bisect_left(self.keys, row) # Index is ...
def load(self, filepath): """Load the track file""" with open(filepath, 'rb') as fd: num_keys = struct.unpack(">i", fd.read(4))[0] for i in range(num_keys): row, value, kind = struct.unpack('>ifb', fd.read(9)) self.keys.append(TrackKey(row, value, kind))
def save(self, path): """Save the track""" name = Track.filename(self.name) with open(os.path.join(path, name), 'wb') as fd: fd.write(struct.pack('>I', len(self.keys))) for k in self.keys: fd.write(struct.pack('>ifb', k.row, k.value, k.kind))
def iri2uri(uri): """Convert an IRI to a URI. Note that IRIs must be passed in a unicode strings. That is, do not utf-8 encode the IRI before passing it into the function.""" assert uri != None, 'iri2uri must be passed a non-none string!' original = uri if isinstance(uri ,str): (scheme, authority, path, query, fragment...
in if it has been removed. if original.endswith("?") and not uri.endswith("?"): uri = uri+"?" return uri
def validate_host_parameters(self, host_list, remote_user): ''' Validate and set the host list and remote user parameters. ''' if host_list is None: host_list = self.host_list if remote_user is None: remote_user = self.remote_user if host_list is None or remote_user is None: print "Host list [%s], remote user [%s] are ...
def validate_results(self, results, checks=None): ''' Valdiate results from the Anisble Run. ''' results['status'] = 'PASS' failed_hosts = [] ################################################### # First validation is to make sure connectivity to # all the hosts was ok. ###################################################...
pairs that should be matched. ################################################## if checks is None: #print "No additional checks validated" return results, failed_hosts for check in checks: key = check.keys()[0] value = check.values()[0] for node in results['contacted'].keys(): if key in results['contacted'][node].keys...
def ansible_perform_operation(self, host_list=None, remote_user=None, remote_pass=None, module=None, complex_args=None, module_args='', environment=None, check=False, sudo=False, sudo_user=None, sudo_pass=None, forks=20): ''' Perform any ansible operation. ''' (host_list, remote_user) = \ self.validate_host_parameters(...
def header(self, sheet, name): """ Write sheet header. Args: sheet: (xlwt.Worksheet.Worksheet) instance of xlwt sheet. name: (unicode) name of sheet. """ header = sheet.row(0) for i, column in enumerate(self.headers[name]): header.write(i, self.headers[name][i])
def output(self): """ Create full path for excel file to save parsed translations strings. Returns: unicode: full path for excel file to save parsed translations strings. """ path, src = os.path.split(self.src) src, ext = os.path.splitext(src) return os.path.join(path, "{src}.xls".format(**{"src": src, }))
def strings(self): """ Write strings sheet. """ sheet = self.result.add_sheet("strings") self.header(sheet, "strings") n_row = 1 # row number for entry in self.po: row = sheet.row(n_row) row.write(0, entry.msgid) row.write(1, entry.msgstr) n_row += 1 sheet.flush_row_data()
def metadata(self): """ Write metadata sheet. """ sheet = self.result.add_sheet("metadata") self.header(sheet, "metadata") n_row = 1 # row number for k in self.po.metadata: row = sheet.row(n_row) row.write(0, k) row.write(1, self.po.metadata[k]) n_row += 1 sheet.flush_row_data()
def convert(self, *args, **kwargs): """ Yes it is, thanks captain. """ self.strings() self.metadata() # save file self.result.save(self.output())
def _parser(): """Parse command-line options.""" launcher = 'pip%s-utils' % sys.version_info.major parser = argparse.ArgumentParser( description='%s.' % __description__, epilog='See `%s COMMAND --help` for help ' 'on a specific subcommand.' % launcher, prog=launcher) parser.add_argument( '--version', action='version', ...
add_help=False, help='list outdated packages that may be updated') parser_outdated.add_argument( '-b', '--brief', action='store_true', help='show package name only') group = parser_outdated.add_mutually_exclusive_group() group.add_argument( '-a', '--all', action='store_true', help='list all outdated packages') group.ad...
def main(args=None): """Start application.""" parser = _parser() # Python 2 will error 'too few arguments' if no subcommand is supplied. # No such error occurs in Python 3, which makes it feasible to check # whether a subcommand was provided (displaying a help message if not). # argparse internals vary significantly ov...
def sync_from_remote(org, syncer, remote): """ Sync local instance against a single remote object :param * org: the org :param * syncer: the local model syncer :param * remote: the remote object :return: the outcome (created, updated or deleted) """ identity = syncer.identify_remote(remote) with syncer.lock(org, identi...
SyncOutcome.ignored
def sync_local_to_set(org, syncer, remote_set): """ Syncs an org's set of local instances of a model to match the set of remote objects. Local objects not in the remote set are deleted. :param org: the org :param * syncer: the local model syncer :param remote_set: the set of remote objects :return: tuple of number of l...
def sync_local_to_changes(org, syncer, fetches, deleted_fetches, progress_callback=None): """ Sync local instances against iterators which return fetches of changed and deleted remote objects. :param * org: the org :param * syncer: the local model syncer :param * fetches: an iterator returning fetches of modified remot...
deleted_fetches: for deleted_remote in deleted_fetch: identity = syncer.identify_remote(deleted_remote) with syncer.lock(org, identity): existing = syncer.fetch_local(org, identity) if existing: syncer.delete_local(existing) outcome_counts[SyncOutcome.deleted] += 1 num_synced += len(deleted_fetch) if progress_callback:...
def fetch_local(self, org, identity): """ Fetches the local model instance with the given identity, returning none if it doesn't exist :param org: the org :param identity: the unique identity :return: the instance or none """ qs = self.fetch_all(org=org).filter(**{self.local_id_attr: identity}) if self.select_related: ...
def fetch_all(self, org): """ Fetches all local objects :param org: the org :return: the queryset """ qs = self.model.objects.filter(org=org) if self.local_backend_attr is not None: qs = qs.filter(**{self.local_backend_attr: self.backend}) return qs
def fsto(self): """sto operation. """ a = float(self.tmpopslist.pop()) var = self.opslist.pop() if isinstance(var, basestring): self.variables.update({var: a}) return a else: print("Can only sto into a variable.") return 'ERROR'
def solve(self): """Solve rpn expression, return None if not valid.""" popflag = True self.tmpopslist = [] while True: while self.opslist and popflag: op = self.opslist.pop() if self.is_variable(op): op = self.variables.get(op) if self.is_operator(op): popflag = False break self.tmpopslist.append(op) # operations tmpr ...
def build_sort(): '''Build sort query paramter from kwargs''' sorts = request.args.getlist('sort') sorts = [sorts] if isinstance(sorts, basestring) else sorts sorts = [s.split(' ') for s in sorts] return [{SORTS[s]: d} for s, d in sorts if s in SORTS]
def index(advice): '''Index/Reindex a CADA advice''' topics = [] for topic in advice.topics: topics.append(topic) parts = topic.split('/') if len(parts) > 1: topics.append(parts[0]) try: es.index(index=es.index_name, doc_type=DOCTYPE, id=advice.id, body={ 'id': advice.id, 'administration': advice.administration, 'type'...
def initialize(self): '''Create or update indices and mappings''' if es.indices.exists(self.index_name): es.indices.put_mapping(index=self.index_name, doc_type=DOCTYPE, body=MAPPING) else: es.indices.create(self.index_name, { 'mappings': {'advice': MAPPING}, 'settings': {'analysis': ANALSYS}, })
def show_list_translations(context, item): """ Return the widget to select the translations we want to order or delete from the item it's being edited :param context: :param item: :return: """ if not item: return manager = Manager() manager.set_master(item) ct_item = ContentType.objects.get_for_model(item) item_languag...
def _xml_pretty_print(self, data): """Pretty print xml data """ raw_string = xtree.tostring(data, 'utf-8') parsed_string = minidom.parseString(raw_string) return parsed_string.toprettyxml(indent='\t')
def _create_table_xml_file(self, data, fname=None): """Creates a xml file of the table """ content = self._xml_pretty_print(data) if not fname: fname = self.name with open(fname+".xml", 'w') as f: f.write(content)
def _init_table_elementTree(self, xml=True, db_table=True): """Create a table """ # <table> tag object t_table = xtree.Element('table') # <table xmlns='' securityLevel='' htpps=''> if not self.table_attr : self.table_attr = self._TAB_ATTR for attr in self.table_attr.items() : t_table.set(*attr) # <meta> t_meta = xtree....
def save(self, name=None, path=None): """Save file as xml """ if path : name = os.path.join(path,name) try: self._create_table_xml_file(self.etree, name) except (Exception,) as e: print(e) return False return True
def addBinder(self, binder): """Adds a binder to the file """ root = self.etree bindings = root.find('bindings') bindings.append(binder.etree) return True
def removeBinder(self, name): """Remove a binder from a table """ root = self.etree t_bindings = root.find('bindings') t_binder = t_bindings.find(name) if t_binder : t_bindings.remove(t_binder) return True return False
def if_url(context, url_name, yes, no): """ Example: %li{ class:"{% if_url 'contacts.contact_read' 'active' '' %}" } """ current = context["request"].resolver_match.url_name return yes if url_name == current else no
def post(self, request, *args, **kwargs): """ Returns a token identifying the user in Centrifugo. """ current_timestamp = "%.0f" % time.time() user_id_str = u"{0}".format(request.user.id) token = generate_token(settings.CENTRIFUGE_SECRET, user_id_str, "{0}".format(current_timestamp), info="") # we get all the channels ...
def index_queryset(self, using=None): """ Used when the entire index for model is updated. """ return self.get_model().objects.filter(date_creation__lte=datetime.datetime.now())
def addFunction(self, func_code, from_file=''): """Add function """ if from_file: with open(from_file) as f: func_code = f.read() root = self.etree t_execute = root.find('execute') if not t_execute : t_execute = ctree.SubElement(root, 'execute') t_execute.text = "\n\t![CDATA]{0:>5}]]\n\t".format(func_code.ljust(4)) ret...
def removeFunction(self): """Remove function tag """ root = self.etree t_execute = root.find('execute') try: root.remove(t_execute) return True except (Exception,) as e: print(e) return False
def _buildElementTree(self,): """Turns object into a Element Tree """ t_binder = ctree.Element(self.name) for k,v in self.__dict__.items(): if k not in ('name', 'urls', 'inputs', 'paging') and v : t_binder.set(k,v) self.etree = t_binder return t_binder
def addUrl(self, url): """Add url to binder """ if url not in self.urls: self.urls.append(url) root = self.etree t_urls = root.find('urls') if not t_urls: t_urls = ctree.SubElement(root, 'urls') t_url = ctree.SubElement(t_urls, 'url') t_url.text = url return True
def removeUrl(self, url): """Remove passed url from a binder """ root = self.etree t_urls = root.find('urls') if not t_urls: return False for t_url in t_urls.findall('url'): if t_url.text == url.strip(): t_urls.remove(t_url) if url in self.urls: self.urls.remove(url) return True return False
def addInput(self, key): """Add key to input : key, value or map """ if key not in self.inputs: self.inputs.append(key) root = self.etree t_inputs = root.find('inputs') if not t_inputs : t_inputs = ctree.SubElement(root, 'inputs') t_inputs.append(key.etree) return True
def removeInput(self, key_id, input_type='key'): """Remove key (key, value, map) from Input key_id : id of the input element i.e <key id='artist' /> input_type : type of the input ; key, value or map """ root = self.etree t_inputs = root.find('inputs') if not t_inputs: return False keys = t_inputs.findall(input_type) k...
def addPaging(self,paging): """Add paging to Binder """ if not vars(self).get('paging', None): self.paging = paging root = self.etree try: root.append(paging.etree) return True except (Exception,) as e: print(e) return False
def removePaging(self,): """Remove paging from Binder """ root = self.etree t_paging = root.find('paging') try: root.remove(t_paging) return True except (Exception,) as e: print(e) return False
def _buildElementTree(self,): """Turn object into an ElementTree """ t_elt = ctree.Element(self.name) for k,v in [ (key,value) for key,value in self.__dict__.items() if key != 'name']: # Excluding name from list of items if v and v != 'false' : t_elt.set(k if k != 'like' else 'as', str(v).lower()) self._etree = t_elt r...
def _buildElementTree(self,): """Turn object into an Element Tree """ t_paging = ctree.Element('paging') t_paging.set('model', self.model) for key in self.__dict__.keys(): if key != 'model': t_tag = ctree.SubElement(t_paging, key) for item in self.__dict__[key].items(): t_tag.set(*item) self.etree = t_paging return t_p...
def get_application_choices(): """ Get the select options for the application selector :return: """ result = [] keys = set() for ct in ContentType.objects.order_by('app_label', 'model'): try: if issubclass(ct.model_class(), TranslatableModel) and ct.app_label not in keys: result.append(('{}'.format(ct.app_label), '{}'....
def get_model_choices(): """ Get the select options for the model selector :return: """ result = [] for ct in ContentType.objects.order_by('app_label', 'model'): try: if issubclass(ct.model_class(), TranslatableModel): result.append( ('{} - {}'.format(ct.app_label, ct.model.lower()), '{} - {}'.format(ct.app_label.capit...
def get_num_words(text): """ Counts and returns the number of words found in a given text :param text: :return: """ try: word_regexp_pattern = re.compile(r"[a-zA-Záéíóúñ]+") num_words = re.findall(word_regexp_pattern, text) return len(num_words) except TypeError: return 0
def has_field(mc, field_name): """ detect if a model has a given field has :param field_name: :param mc: :return: """ try: mc._meta.get_field(field_name) except FieldDoesNotExist: return False return True
def reader(f): '''CSV Reader factory for CADA format''' return unicodecsv.reader(f, encoding='utf-8', delimiter=b',', quotechar=b'"')
def writer(f): '''CSV writer factory for CADA format''' return unicodecsv.writer(f, encoding='utf-8', delimiter=b',', quotechar=b'"')
def from_row(row): '''Create an advice from a CSV row''' subject = (row[5][0].upper() + row[5][1:]) if row[5] else row[5] return Advice.objects.create( id=row[0], administration=cleanup(row[1]), type=row[2], session=datetime.strptime(row[4], '%d/%m/%Y'), subject=cleanup(subject), topics=[t.title() for t in cleanup(row[...
def to_row(advice): '''Serialize an advice into a CSV row''' return [ advice.id, advice.administration, advice.type, advice.session.year, advice.session.strftime('%d/%m/%Y'), advice.subject, ', '.join(advice.topics), ', '.join(advice.tags), ', '.join(advice.meanings), ROMAN_NUMS.get(advice.part, ''), advice.content, ]
def clean_dict(data): """Remove None-valued keys from a dictionary, recursively.""" if is_mapping(data): out = {} for k, v in data.items(): if v is not None: out[k] = clean_dict(v) return out elif is_sequence(data): return [clean_dict(d) for d in data if d is not None] return data
def keys_values(data, *keys): """Get an entry as a list from a dict. Provide a fallback key.""" values = [] if is_mapping(data): for key in keys: if key in data: values.extend(ensure_list(data[key])) return values
def solve_simple_captcha(self, pathfile=None, filedata=None, filename=None): """ Upload a image (from disk or a bytearray), and then block until the captcha has been solved. Return value is the captcha result. either pathfile OR filedata should be specified. Filename is ignored (and is only kept for compatibility with ...
def solve_recaptcha(self, google_key, page_url, timeout = 15 * 60): ''' Solve a recaptcha on page `page_url` with the input value `google_key`. Timeout is `timeout` seconds, defaulting to 60 seconds. Return value is either the `g-recaptcha-response` value, or an exceptionj is raised (generally `CaptchaSolverFailure`) '...
def userinput(prompttext="", times=1): """ Get the input of the user via a universally secure method. :type prompttext: string :param prompttext: The text to display while receiving the data. :type times: integer :param times: The amount of times to ask the user. If value is not 1, a list will be returned. Default is 1...
def shellinput(initialtext='>> ', splitpart=' '): """ Give the user a shell-like interface to enter commands which are returned as a multi-part list containing the command and each of the arguments. :type initialtext: string :param initialtext: Set the text to be displayed as the prompt. :type splitpart: string :param ...
def splitstring(string, splitcharacter=' ', part=None): """ Split a string based on a character and get the parts as a list. :type string: string :param string: The string to split. :type splitcharacter: string :param splitcharacter: The character to split for the string. :type part: integer :param part: Get a specific...
of the splitted text with a specific part return str(string).split(splitcharacter)[part]
def pykeyword(operation='list', keywordtotest=None): """ Check if a keyword exists in the Python keyword dictionary. :type operation: string :param operation: Whether to list or check the keywords. Possible options are 'list' and 'in'. :type keywordtotest: string :param keywordtotest: The keyword to check. :return: The...
ValueError("Invalid operation specified.")
def binboolflip(item): """ Convert 0 or 1 to False or True (or vice versa). The converter works as follows: - 0 > False - False > 0 - 1 > True - True > 1 :type item: integer or boolean :param item: The item to convert. >>> binboolflip(0) False >>> binboolflip(False) 0 >>> binboolflip(1) True >>> binboolflip(True) 1 >>>...
def warnconfig(action='default'): """ Configure the Python warnings. :type action: string :param action: The configuration to set. Options are: 'default', 'error', 'ignore', 'always', 'module' and 'once'. """ # If action is 'default' if action.lower() == 'default': # Change warning settings warnings.filterwarnings('def...
def happybirthday(person): """ Sing Happy Birthday """ print('Happy Birthday To You') time.sleep(2) print('Happy Birthday To You') time.sleep(2) print('Happy Birthday Dear ' + str(person[0].upper()) + str(person[1:])) time.sleep(2) print('Happy Birthday To You')
def cowsay(text='', align='centre'): """ Simulate an ASCII cow saying text. :type text: string :param text: The text to print out. :type align: string :param algin: Where to align the cow. Can be 'left', 'centre' or 'right' """ # Make align lowercase align = align.lower() # Set the cowtext cowtext = str(text) # Set top...
" " * (int(len(topbar) / 2) + 1) # If align is left elif align == 'left': # Set spacing to a single space spacing = ' ' # If align is right elif align == 'right': # Set the spacing to the length of the text plus 2 spacing = " " * (len(text) + 2) else: # Raise a runtime warning raise ValueError("Invalid alignment provid...
def convertbinary(value, argument): """ Convert text to binary form or backwards. :type value: string :param value: The text or the binary text :type argument: string :param argument: The action to perform on the value. Can be "to" or "from". """ if argument == 'to': return bin(value) elif argument == 'from': return fo...
def reversetext(contenttoreverse, reconvert=True): """ Reverse any content :type contenttoreverse: string :param contenttoreverse: The content to be reversed :type reeval: boolean :param reeval: Wether or not to reconvert the object back into it's initial state. Default is "True". """ # If reconvert is specified if rec...
def convertascii(value, command='to'): """ Convert an ASCII value to a symbol :type value: string :param value: The text or the text in ascii form. :type argument: string :param argument: The action to perform on the value. Can be "to" or "from". """ command = command.lower() if command == 'to': return chr(value) elif ...
def availchars(charactertype): """ Get all the available characters for a specific type. :type charactertype: string :param charactertype: The characters to get. Can be 'letters', 'lowercase, 'uppercase', 'digits', 'hexdigits', 'punctuation', 'printable', 'whitespace' or 'all'. >>> availchars("lowercase") 'abcdefghijkl...
character type is 'hexdigits' elif charactertype.lower() == 'hexdigits': # Return the result return string.hexdigits # If the lowercase version of the character type is 'punctuation' elif charactertype.lower() == 'punctuation': # Return the result return string.punctuation # If the lowercase version of the character ty...
def textbetween(variable, firstnum=None, secondnum=None, locationoftext='regular'): """ Get The Text Between Two Parts """ if locationoftext == 'regular': return variable[firstnum:secondnum] elif locationoftext == 'toend': return variable[firstnum:] elif locationoftext == 'tostart': return variable[:secondnum]
def letternum(letter): """ Get The Number Corresponding To A Letter """ if not isinstance(letter, str): raise TypeError("Invalid letter provided.") if not len(letter) == 1: raise ValueError("Invalid letter length provided.") letter = letter.lower() alphaletters = string.ascii_lowercase for i in range(len(alphaletters))...
def wordvalue(word): """ Get the value of each letter of a string's position in the alphabet added up :type word: string :param word: The word to find the value of """ # Set total to 0 total = 0 # For each character of word for i in enumerate(word): # Add it's letter value to total total += letternum(word[i[0]]) # Retu...
def spacelist(listtospace, spacechar=" "): """ Convert a list to a string with all of the list's items spaced out. :type listtospace: list :param listtospace: The list to space out. :type spacechar: string :param spacechar: The characters to insert between each list item. Default is: " ". """ output = '' space = '' out...
def numlistbetween(num1, num2, option='list', listoption='string'): """ List Or Count The Numbers Between Two Numbers """ if option == 'list': if listoption == 'string': output = '' output += str(num1) for currentnum in range(num1 + 1, num2 + 1): output += ',' output += str(currentnum) elif listoption == 'list': output...
def textalign(text, maxlength, align='left'): """ Align Text When Given Full Length """ if align == 'left': return text elif align == 'centre' or align == 'center': spaces = ' ' * (int((maxlength - len(text)) / 2)) elif align == 'right': spaces = (maxlength - len(text)) else: raise ValueError("Invalid alignment specifi...
def shapesides(inputtocheck, inputtype='shape'): """ Get the sides of a shape. inputtocheck: The amount of sides or the shape to be checked, depending on the value of inputtype. inputtype: The type of input provided. Can be: 'shape', 'sides'. """ # Define the array of sides to a shape shapestosides = { 'triangle': 3, '...
sidestoshapes = dictflip(shapestosides) # If the lowercase version of the input type is 'shape' if inputtype.lower() == 'shape': # If the lowercase version of the shape is in the array if inputtocheck.lower() in shapestosides: # Return the corresponding sides return shapestosides[inputtocheck.lower()] # Return 'n' retu...
def autosolve(equation): """ Automatically solve an easy maths problem. :type equation: string :param equation: The equation to calculate. >>> autosolve("300 + 600") 900 """ try: # Try to set a variable to an integer num1 = int(equation.split(" ")[0]) except ValueError: # Try to set a variable to a decimal num1 = float...
"minus", "subtract"]: # Return the answer return num1 - num2 # If the lowercase version of the operator is '*', 'times', 'multiply' elif equation.split(" ")[1].lower() in ["*", "times", "multiply"]: # Return the answer return num1 * num2 # If the lowercase version of the operator is '/', 'divide' or 'quotient' elif equ...
def autohard(equation): """ Automatically solve a hard maths problem. :type equation: string :param equation: The equation to solve. >>> autohard("log 10") 2.302585092994046 """ try: # Try to set a variable to an integer num1 = int(equation.split(" ")[1]) except ValueError: # Try to set a variable to a decimal num1 = f...
== "atan": # Return the answer return math.atan(num1) # If the lowercase version of the operation equals 'cos' elif equation.split(" ")[0].lower() == "cos": # Return the answer return math.cos(num1) # If the lowercase version of the operation equals 'hypot' elif equation.split(" ")[0].lower() == "hypot": try: # Try to ...
operation entered.")
def equation(operation, firstnum, secondnum): """ Solve a simple maths equation manually """ if operation == 'plus': return firstnum + secondnum elif operation == 'minus': return firstnum - secondnum elif operation == 'multiply': return firstnum * secondnum elif operation == 'divide': if not secondnum == 0: return firs...
def scientific(number, operation, number2=None, logbase=10): """ Solve scientific operations manually """ if operation == 'log': return math.log(number, logbase) elif operation == 'acos': return math.acos(number) elif operation == 'asin': return math.asin(number) elif operation == 'atan': return math.atan(number) elif ...
def fracsimplify(numerator, denominator): """ Simplify a fraction. :type numerator: integer :param numerator: The numerator of the fraction to simplify :type denominator: integer :param denominator: The denominator of the fraction to simplify :return: The simplified fraction :rtype: list """ # If the numerator is the s...
the limit minus i checknum = limit - i # If the number is divisible by the numerator and denominator if numerator % checknum == 0 and denominator % checknum == 0: # Set the numerator to half of the number numerator = numerator / checknum # Set the denominator to half of the number denominator = denominator / checknum #...
def circleconvert(amount, currentformat, newformat): """ Convert a circle measurement. :type amount: number :param amount: The number to convert. :type currentformat: string :param currentformat: The format of the provided value. :type newformat: string :param newformat: The intended format of the value. >>> circleconv...
math.pi # Raise a warning raise ValueError("Invalid new format provided.") # If the lowercase version of the current format is 'diameter' elif currentformat.lower() == 'diameter': # If the lowercase version of the new format is 'radius' if newformat.lower() == 'radius': # Return the converted value return amount / 2 # ...
of the new format is 'diameter' elif newformat.lower() == 'diameter': # Return the converted value return amount / math.pi
def amountdiv(number, minnum, maxnum): """ Get the amount of numbers divisable by a number. :type number: number :param number: The number to use. :type minnum: integer :param minnum: The minimum number to check. :type maxnum: integer :param maxnum: The maximum number to check. >>> amountdiv(20, 1, 15) 5 """ # Set the ...
def constant(constanttype): """ Get A Constant """ constanttype = constanttype.lower() if constanttype == 'pi': return math.pi elif constanttype == 'e': return math.e elif constanttype == 'tau': return math.tau elif constanttype == 'inf': return math.inf elif constanttype == 'nan': return math.nan elif constanttype in ...