def greater_than_equal(self, item, splitonly=False): try: if self.indexstrings: if not isinstance(item, str): item = str(item) except: self.indexstrings = False if item not in self.list: if self.list: if self.indexstrings: if Index(item) < Item(self.list[0]): #for when the entire list is greater than the item if splitonly: return 0 return self.list return [x for x in self.list if Index(x) >= Index(item)] else: if item < self.list[0]: if splitonly: return 0 return self.list if splitonly: return 0 return [] splitpoint = self.find(item)[1] if not splitonly: return self.list[splitpoint:] return splitpoint
def greater_than(self, item, splitonly=False): try: if self.indexstrings: if not isinstance(item, str): item = str(item) except: self.indexstrings = False if item not in self.list: if self.list: if self.indexstrings: if Index(item) < Index(self.list[0]): if splitonly: return 0 return self.list return [x for x in self.list if Index(x) > Index(item)] else: if item < self.list[0]: if splitonly: return 0 return self.list return [x for x in self.list if x > item] if splitonly: return 0 return [] splitpoint = self.find(item)[1] if not splitonly: return self.list[splitpoint + 1:] return splitpoint + 1
def lesser_than(self, item, splitonly=False): try: if self.indexstrings: if not isinstance(item, str): item = str(item) except: self.indexstrings = False if item not in self.list: if self.list: if self.indexstrings: if Index(item) > Index(self.list[-1]): if splitonly: return 0 return self.list else: return [x for x in self.list if Index(x) < Index(item)] else: if item > self.list[-1]: if splitonly: return 0 return self.list else: return [x for x in self.list if x < item] if splitonly: return 0 return [] splitpoint = self.find(item)[1] if not splitonly: return self.list[0:splitpoint] return splitpoint
def add(self, index, onlypositive=True): """Adds an index to list""" if isinstance(index, str): index = Index(index) if index >= Index(0) or not onlypositive: self.all.append(index) self.length = len(self.all)
def load_project_into_DB(self, project=None, all_projects=None): try: defaultkeys = all_projects[project]['defaultkeys'] except: print(project, ':', 'defaultkeys FAILED') defaultkeys = [] try: indexes = all_projects[project]['indexes'] except: print(project, ':', 'index FAILED') indexes = OrderedList() try: lastup = all_projects[project]['position'][0] except: print(project, ':', 'lastup FAILED') lastup = Index(2) try: uptohere = uptohere = all_projects[project]['position'][1] except: print(project, ':', 'uptohere FAILED') uptohere = Index(2) try: mainterm = mainterm = all_projects[project]['going'][0] except: print(project, ':', 'mainterm FAILED') mainterm = 'quit' try: series_enter = series_enter = all_projects[project]['going'][1] except: print(project, ':', 'series enter FAILED') series_enter = '' try: date = all_projects[project]['date'] except: date = [str(str(datetime.datetime.now()))] self.initiate_project(project_name=project, defaultkeys=defaultkeys, lastup=lastup, indexes=indexes, uptohere=uptohere, mainterm=mainterm, series_enter=series_enter, date=date, opened=False)
def add(self, item): if not self.sequence_type or type(item) != self.sequence_type: self.sequence_type = get_type(self.list + [item]) if self.sequence_type == "INCONSISTENT": self.sequence_type = get_type(self.list) if self.sequence_type == "INCONSISTENT": self.sequence_type = get_majority_type(self.list) if self.sequence_type is None: self.sequence_type = type(item) item = convert_to_type(item, self.sequence_type) if item: try: if self.indexstrings: if not isinstance(item, str): item = str(item) if not self.list: self.list = [item] elif not self.find(item)[0]: if Index(item) < Index(self.list[0]): self.list = [item] + self.list elif Index(item) > Index(self.list[-1]): self.list = self.list + [item] else: index = self.find(item)[1] self.list = self.list[0:index] + [ item ] + self.list[index:] except: self.indexstrings = False if not self.indexstrings: if not self.list: self.list = [item] elif not self.find(item)[0]: if item < self.list[0]: self.list = [item] + self.list elif item > self.list[-1]: self.list = self.list + [item] else: index = self.find(item)[1] self.list = self.list[0:index] + [item ] + self.list[index:]
def reset_indexes(self, indexes=None, project=None, db_only=False): if not project: project = self.current if not db_only and not self.db_only: if not indexes: self.projects[project]['indexes'] = OrderedList() elif isinstance(indexes, list): self.projects[project]['indexes'] = OrderedList( sorted(indexes, key=lambda x_temp: Index(x_temp))) if self.using_database: self.delete_all_indexes_DB(project=project) for temp_index in sorted(indexes, key=lambda x_temp: Index(x_temp)): self.add_index_DB(project=project, index=temp_index)
def get_project(self, project=None): if not project: project = self.current if self.using_database: temp_keys = self.get_keys_DB(project=project) temp_indexes = sorted(self.get_indexes_DB(project=project), key=lambda x_temp: Index(x_temp)) temp_dates = sorted(self.get_dates_DB(project=project)) temp_simple = self.get_simple_DB(project=project) lastup, uptohere, mainterm, series_enter, opened = temp_simple[ 0], temp_simple[1], temp_simple[2], temp_simple[ 3], temp_simple[4] temp_dict = {} temp_dict['defaultkeys'] = temp_keys temp_dict['position'] = (lastup, uptohere) temp_dict['going'] = (mainterm, series_enter) temp_dict['date'] = temp_dates temp_dict['indexes'] = OrderedList(temp_indexes) temp_dict['status'] = { 'started': temp_dates[0], 'open': opened, 'lastmodified': temp_dates } return temp_dict if project in self.projects: return self.projects[project]
def dict_format(x_temp): """formats output of the list of search results""" if self.for_indexes: shown_indexes = rangelist.range_find( [Index(a_temp) for a_temp in x_temp[1]], reduce=True) else: shown_indexes = formkeys({ abridge(index_reduce(x_temp), maxlength=20) for x_temp in x_temp[1] }) if len(shown_indexes) < 20: return (abridge(x_temp[0], maxlength=20) + VERTLINE + shown_indexes) returnlist = [] sp_temp = split_up_range(shown_indexes, seg_length=3) returnlist.append( abridge(x_temp[0], maxlength=20) + VERTLINE + sp_temp[0]) for s_temp in sp_temp[1:]: returnlist.append(VERTLINE + s_temp) return returnlist
def get(self, func_name=None, item=None, item2=None): try: if self.indexstrings: if not isinstance(item, str): item = str(item) if not isinstance(item2, str): item2 = str(item2) except: pass # For a single item if func_name == '?': #to return all values return self.list if not func_name or not item: return [] if func_name == '=': #to return one value return [item] # With two items if item2: # to get a range item2 = convert_to_type(item2, type(item)) return [ x_temp for x_temp in self.greater_than_equal(item) if x_temp <= item2 ] temp_list = [ convert_to_type(x, type(item)) for x in self.list if convert_to_type(x, type(item)) ] if func_name == '>=': if not self.indexstrings: return [x for x in temp_list if x >= item] else: return [x for x in temp_list if Index(x) >= Index(item)] elif func_name == '<=': if not self.indexstrings: return [x for x in temp_list if x <= item] else: return [x for x in stemp_list if Index(x) <= Index(item)] elif func_name == '>': if not self.indexstrings: return [x for x in temp_list if x > item] else: return [x for x in temp_list if Index(x) > Index(item)] elif func_name == '<': if not self.indexstrings: return [x for x in temp_list if x < item] else: return [x for x in temp_list if Index(x) < Index(item)]
def delete(self, index): """Deletes an index from the list.""" if isinstance(index, str): index = Index(index) if index in self.all: self.all.remove(index) self.length = len(self.all)
def deconvert(x): if isinstance(x, float): return x if x.startswith('<<DATE>>'): return is_date(x[8:]) if x.startswith('<<INDEX>>'): return Index(x[9:]) return x
def get_all_indexes(self, project=None): if self.using_database: temp_indexes = self.get_indexes_DB(project=project) return sorted(temp_indexes, key=lambda x_temp: Index(x_temp)) if not project: project = self.current return self.projects[project]['indexes'].list
def convert(x): if type(x) == str: return x if type(x) == float: return x if type(x) == type(datetime.datetime.now()): return '<<DATE>>' + str(x) if type(x) == type(Index(0)): return '<<INDEX>>' + str(x) return str(x)
def __str__(self): if len(self.list) > 0: if isinstance(self.list[-1], str): return ', '.join( ["'" + str(x_temp) + "'" for x_temp in self.list]) elif type(self.list[-1]) == type(Index(0)): return ', '.join( ["Index('" + str(x_temp) + "')" for x_temp in self.list]) else: return ', '.join([str(x_temp) for x_temp in self.list]) return ''
def all_date_strings(): for x_temp in self.list: if isinstance(x_temp,(float,int)) \ or type(x_temp)==type(datetime.date(1970,1,7)) \ or type(x_temp)==type(Index(0)): return False if isinstance(x_temp,str) and not is_date(x_temp) \ and not is_date((x_temp+'-01')) \ and not is_date((x_temp+'-01-01')): return False return True
def convert_to_type(item, is_type): return_item = None try: if type(item) == is_type: return_item = item elif is_type == str: return_item = str(item) elif is_type == type(datetime.date(1972, 3, 13)) and isinstance( item, str): return_item = is_date(item, returndate=True) elif is_type == float and isinstance(item, str) and isfloat(item): return_item = float(item) elif is_type == int and isinstance(item, str) and item.isnumeric(): return_item = int(item) elif is_type == type(Index(0)) and isinstance(item, str) and isindex(item): return_item = Index(item) elif is_type == float and isinstance(item, int): return_item = float(item) except: pass return return_item
def find_within(self, item1, item2, fromequal=False, toequal=False): try: if self.indexstrings: if not isinstance(item1, str): item1 = str(item1) if not isinstance(item2, str): item2 = str(item2) if Index(item1) > Index(item2): item1, item2 = item2, item1 except: self.indexstrings = False if not self.indexstrings: if item1 > item2: item1, item2 = item2, item1 fromfound, from_temp = self.find(item1) tofound, to_temp = self.find(item2) if fromfound and not fromequal: from_temp += 1 if tofound and toequal: to_temp += 1 if from_temp == -1: from_temp = 0 if to_temp == -1: return [] if to_temp != -2 or to_temp <= len(self.list): return self.list[from_temp:to_temp] else: return self.list[from_temp:]
def __init__(self, orderfuncs=( suc_one, suc_two, ), sortfunc=lambda x: Index(x)): if orderfuncs and isinstance(orderfuncs, (list, tuple, set)): self.orderfuncs = orderfuncs elif orderfuncs: self.orderfuncs = (orderfuncs, ) self.sortfunc = sortfunc self.resultlist = []
def move(self): """Advance forward according to the speed""" if not self.all: return Index(1) if not self.random: if self.tilt == 0: for a_temp in range(self.speed): here = self.get() return here here = self.return_point() was_here = here for x_temp in range(10): if self.direction == 1: if self.tilt == 1: here = here.next() if self.tilt == 2: here = here.child() elif self.direction == -1: if self.tilt == 1: here = here.previous() if self.tilt == 2: here = here.parent() if here in self.all: self.current = self.all.index(here) return here if self.running_up > 2: if self.tilt == 2: self.tilt = 0 if self.tilt == 1: self.tilt = 2 self.running_up = 0 self.running_up += 1 return was_here if not self.all: self.all = list(self.all_backup) random_point = random.randint(0, len(self.all) - 1) i_temp = self.all.pop(random_point) return i_temp
def __init__(self, entrylist=None, indexstrings=False): if entrylist and indexstrings: self.indexstrings = True self.list = sorted([str(x_temp) for x_temp in entrylist], key=lambda x_temp: Index(str(x_temp))) elif entrylist and not indexstrings: try: self.list = sorted(set(entrylist)) except: self.list = entrylist self.indexstrings = False else: self.list = [] self.indexstrings = indexstrings self.sequence_type = None
def combine_sequence_values(keylist): """combines sequence keys into ranges. used with const_dict """ from indexclass import Index sequence_key_dict = {} other_key_set = set() returnlist = [] def all_numeric(l): for x in l: if not x.isnumeric(): return False else: return True def all_float(l): for x in l: if not x.replace('.', '').isnumeric() or x.count('.') > 1: return False else: return True for key in keylist: if ATSIGN in key: if ATSIGN + UNDERLINE in key: value = key.split(ATSIGN + UNDERLINE)[1] elif ATSIGN + POUND in key: value = key.split(ATSIGN + POUND)[1] elif ATSIGN in key: value = key.split(ATSIGN)[1] if value: head = key.split(value)[0] else: head = key value = '' if value.endswith('.0'): value = value[:-2] if value: if head not in sequence_key_dict: sequence_key_dict[head] = {value} else: sequence_key_dict[head].add(value) else: other_key_set.add(key) for head in sequence_key_dict: if UNDERLINE not in head and POUND not in head and all_numeric( sequence_key_dict[head]): all_values = range_find(list(sequence_key_dict[head]), breaker=';') returnlist.append(head + all_values) elif UNDERLINE not in head and POUND not in head and all_float( sequence_key_dict[head]): ordered_indexes = ind_ord.format( [Index(x) for x in sequence_key_dict[head]]) returnlist.append(head + ordered_indexes) elif UNDERLINE in head: ordered_indexes = ind_ord.format( [Index(x) for x in sequence_key_dict[head]]) returnlist.append(head + ordered_indexes) elif POUND in head: ## ordered_dates = ind_ord.format([datetime.datetime([int(y) for y in x.split('-')]) for x in sequence_key_dict[head]]) ## returnlist.append(head+ordered_indexes) pass returnlist += list(other_key_set) return sorted(returnlist)
def fetch_value(self, index): #Fetches the appropriate information from the note in the notebase #corresponding to the given index. return_list = [] temp_note = self.fetchfunction(index) temp_sequence_dict = {} for keyword in temp_note.keyset: #Extracts values for sequence keywords in the keyset of note if '@#' in keyword: #For a date sequence keyword head, value = keyword.split('@#') temp_sequence_dict[head] = is_date(value) elif '@_' in keyword: #For an index sequence keyword head, value = keyword.split('@_') temp_sequence_dict[head] = Index(value) elif '@' in keyword: #For others, in which case the type has to be #determined from the sequence register head, value = keyword.split('@') if head in self.sequenceobject.query(action='get'): value_type = self.sequenceobject.query(term1='#TYPE#', term2=head, action='get') #TO convert into types if value_type in [float, int]: temp_sequence_dict[head] = float(value) elif value_type == str: temp_sequence_dict[head] = value elif value_type == type(upper_str('f')): temp_sequence_dict[head] = upper_str(value) for v in self.full_sort_schema: # Applies the sort schema to the given note val = v[0] spec = v[1] reverse = 1 if type(val) == str and val.startswith('~'): val = val[1:] reverse = -1 if type(spec) == str and spec.startswith('~'): spec = spec[1:] reverse = -1 if spec in [ int, float, str, type(datetime.date(1972, 3, 13)), type(upper_str('f')), type(Index('1')) ]: #IF the sorting criterion is a sequence keyword if val in temp_sequence_dict: if spec in [int, float]: return_list.append(temp_sequence_dict[val] * reverse) elif spec in [str, type(upper_str('f'))]: temp_result = temp_sequence_dict[val] if spec == type(upper_str('f')): temp_result = temp_result.upper( ) #Class not really so useful. Oh well! temp_result = tuple( [ord(x) * reverse for x in temp_result]) return_list.append(temp_result) elif spec in [type(Index('1'))]: return_list.append( temp_sequence_dict[val] * reverse ) #NOTE no reverse yet for date or indextype else: #For a date sequence return_list.append( (temp_sequence_dict[val].year * reverse, temp_sequence_dict[val].month * reverse, temp_sequence_dict[val].day * reverse)) else: #For there is no sequence keyword corresponding to the criterion if spec in [float, int]: return_list.append(-10000000000000 * reverse) elif spec in [type(Index('1'))]: return_list.append(Index('0')) elif spec in [str, type(upper_str('f'))]: return_list.append(tuple([0])) elif spec == type(datetime.date(1972, 3, 13)): return_list.append( (-100000000 * reverse, 1 * reverse, 1 * reverse)) elif spec in [ 'DATE', 'USER', 'SIZE', 'KEYCOUNT', 'INDEX', 'TEXTLENGTH' ]: #For general sorting criterion if spec in ['DATE', 'USER', 'SIZE' ] and spec.lower() in temp_note.meta: return_list.append(temp_note.meta[spec.lower()]) elif spec == 'KEYCOUNT': return_list.append(len(temp_note.keyset) * reverse) elif spec == 'TEXTLENGTH': return_list.append(len(temp_note.text) * reverse) else: return_list.append(index * reverse) elif val in ['K', 'KW', 'T', 'TC', 'TW', 'TCW']: #To sort by the number of found elements in keywordset or text total_weighted_value = 0 if isinstance(spec, dict): for k in spec: if 'K' in val: total_weighted_value += ( k in temp_note.keyset) * spec[k] elif 'TC' in val: total_weighted_value += ( k in temp_note.text) * spec[k] elif 'T' in val: total_weighted_value += temp_note.text.count( k) * spec[k] return_list.append(total_weighted_value * reverse) else: return_list.append(index) return_list = tuple(return_list) return tuple(return_list)
def get_range(self, entryterm, sort=True, orequal=True, complete=False, indexes=False): """gets a range of indexes from a string of index ranges IR1, IR2, IR3... Each indexrange is formated INDEXFROM-INDEXTO or -INDEXFROM/-INDEXTO. orequal True is less than equal to upper range. if complete true find top level indexes between top-level form of entered indexes. Sort is true to sort output. Many is true if term includes a number of ranges """ term = entryterm # For more than one range of indexes returnrange = [] bigterm = term for term in bigterm.split(COMMA): if term.strip(): term = term.strip() if (term[0]!=DASH and (SLASH in term or DASH in term)) \ or (term[0]==DASH and (SLASH in term[1:] or DASH in term[1:])): if DASH + DASH in term: term = term.replace(DASH+DASH, SLASH+DASH) if SLASH not in term: if term[0] != DASH: term = term.replace(DASH, SLASH) else: term = term[0] + term[1:].replace(DASH,SLASH) if POUND not in term: termfrom = Index(index_expand(term.split(SLASH)[0])) termto = Index(index_expand(term.split(SLASH)[1])) else: termfrom = term.split(SLASH)[0] termto = term.split(SLASH)[1] returnrange += [str(x) for x in self.notebook.find_within(termfrom, termto, orequal=orequal)] else: if indexes: returnrange += [Index(term)] else: returnrange += [str(term)] if complete and returnrange == []: if indexes: returnrange = [Index(a_temp) for a_temp in range(int(termfrom), int(termto)+1)] else: returnrange = [str(a_temp) for a_temp in range(int(termfrom), int(termto)+1)] if sort: return sorted(returnrange, key=lambda x_temp: Index(str(x_temp))) return set(returnrange) if sort: return set(sorted(returnrange, key=lambda x_temp: Index(str(x_temp)))) return set(returnrange)
def evaluate_term (self, term): """Returns a set of indexes for a given atomic element""" def is_index_range (y): #tests if a term is an index range for x in ['0','1','2','3','4','5','6','7','8','9','-',',','/','.','^','~']: y=y.replace(x,'') return y=='' negative = False variable = False returnset = set() if term and term[0] == '~': negative = True term = term[1:] if not term: return returnset if is_index_range(term): returnset = self.get_range(term) elif term == 'MARKED': returnset = set(self.default_dictionary['marked']) elif term == 'UNMARKED': returnset = {str(x) for x in self.default_dictionary['indexlist'].list if not str(x) in self.default_dictionary['marked']} elif term == 'ALL': returnset = {str(x) for x in self.default_dictionary['indexlist'].list} elif term in ['POSITIVE','POS']: returnset = {str(x) for x in self.default_dictionary['indexlist'].list if x>=Index(0)} elif term in ['NEGATIVE','NEG']: returnset = {str(x) for x in self.default_dictionary['indexlist'].list if x<Index(0)} elif term in ['FLIPBOOK','FB']: returnset = {str(x) for x in self.default_dictionary['flipbook']} elif term in self.variables: #For a variable returnset = {str(x).strip() for x in self.variables[term].split(',')} elif term in self.default_dictionary['projects'].get_all_projects(): #For a project returnset = {str(x) for x in self.default_dictionary['projects'].get_all_indexes(project=term)} if not negative: return returnset else: return {str(x) for x in self.default_dictionary['indexlist'].list if not str(x) in returnset}
def transform(complexobject,start=True,indexstrings=True): """ copies dictionary, and applies tranformations """ def dummy (y): return y if start: complexobject = copy.deepcopy(complexobject) start = False if isinstance(complexobject,dict): for x in list(complexobject.keys()): complexobject[x]=transform(complexobject[x],start=start) return complexobject elif isinstance(complexobject,list): newlist = [] for x in complexobject: newlist += [transform(x,start=start)] return newlist elif isinstance(complexobject,set): newset = set() for x in complexobject: newset.add(transform(x,start=start)) return newset elif isinstance(complexobject,tuple): newlist = [] for x in complexobject: newlist += [transform(x,start=start)] return tuple(newlist) else: if type(complexobject) == type(Index(0)): return '<'+str(complexobject)+'>' elif isinstance(complexobject,str) and len(complexobject)>4\ and complexobject[0:2] == '<<'\ and complexobject[-2:] == '>>': return OrderedList(eval(complexobject[2:-2]),indexstrings=indexstrings) elif isinstance(complexobject,str) and len(complexobject)>2\ and complexobject[0] == '<' \ and complexobject[-1] == '>': return Index(complexobject[1:-1]) elif isinstance(complexobject,str) and len(complexobject)>6\ and complexobject[0:3] == '###'\ and complexobject[-3:] == '###'\ and complexobject[3:-3] in ['float','str','date']: return {'float':type(1.2), 'str':type('st'), 'date':type(datetime.datetime.now())}[complexobject[3:-3]] elif type(complexobject) == type(datetime.datetime.now()): return str(complexobject) elif isinstance(complexobject,str) and COLON in complexobject and DASH in complexobject and PERIOD in complexobject and \ complexobject.replace(DASH,EMPTYCHAR).replace(PERIOD,EMPTYCHAR).replace(COLON,EMPTYCHAR).replace(BLANK,EMPTYCHAR).isnumeric(): return is_date(complexobject,returndate=True) ## elif isinstance(complexobject,str) and complexobject.startswith('datetime.datetime'): ## return eval(complexobject) elif type(complexobject) == type(ordlist_example): return '<<['+str(complexobject)+']>>' elif isinstance(complexobject,str) and complexobject in ['b#True','b#False']: if complexobject == 'b#True': return True return False elif isinstance(complexobject,bool): if complexobject: return 'b#True' return 'b#False' else: return complexobject
def s_input(prompt='', inputtext=None, typeflag=None, conditions=None, must_be_in=None, returnvalue=EMPTYCHAR): """ solicits input with prompt if inputtext is not empty, otherwise returns inputtext """ if typeflag is None and conditions is None: if not inputtext or inputtext in [EMPTYCHAR, QUESTIONMARK]: inputtext = input(prompt) return inputtext if typeflag not in ['str','float','int','index']: return returnvalue else: not_ok = True condition_met = False query = '' counter = 0 while counter<5 and (not_ok or (conditions and not condition_met) or (must_be_in and not condition_met)): if (not_ok and counter > 0) or (conditions and not condition_met and counter>0) \ or (must_be_in and not condition_met and counter>0) \ or not inputtext or inputtext in [EMPTYCHAR, QUESTIONMARK]: inputtext = input(prompt) not_found_in = False value = inputtext if typeflag: if typeflag == 'str': not_ok = False elif typeflag == 'int': try: value = int(inputtext) not_ok = False except: query = 'Input value must be integer ' elif typeflag == 'float': try: value = float(inputtext) not_ok = False except: query = 'Input value must be floating point ' elif typeflag == 'index': try: value = Index(inputtext) not_ok = False except: query = 'Input value must be an index ' if not not_ok \ and ((conditions and isinstance(conditions,(list,tuple)) and \ len(conditions) > 1 and \ (isinstance(conditions[0],(str,int,float)) or type(conditions[0])==type(Index(0))) and \ (isinstance(conditions[1],(str,int,float)) or type(conditions[1])==type(Index(0)))) or (must_be_in and isinstance(must_be_in,(str,list,set,tuple)))): if must_be_in and isinstance(must_be_in,(str,list,set,tuple)): if inputtext in must_be_in: condition_met = True else: query += '\nInput value must be in ' + conv(must_be_in) not_found_in = True if not not_found_in and (conditions and isinstance(conditions,(list,tuple)) and \ len(conditions) > 1 and \ (isinstance(conditions[0],(str,int,float)) or type(conditions[0])==type(Index(0))) and \ (isinstance(conditions[1],(str,int,float)) or type(conditions[1])==type(Index(0)))): if value >= conditions[0] and value <= conditions[1]: condition_met = True else: query += '\n Input value must be between ' + str(conditions[0]) + ' and ' + str(conditions[1]) if not_ok or (not condition_met and (conditions or must_be_in)): print('ATTENTION',query) counter += 1 if not inputtext: inputtext = returnvalue if (not_ok or (conditions and not condition_met) or (must_be_in and not condition_met)): if (not_ok and counter > 0) or (conditions and not condition_met and counter>0) \ or (must_be_in and not condition_met and counter>0): return returnvalue return inputtext
def find(self, item): try: if self.indexstrings: if not isinstance(item, str): item = str(item) if not self.list: # if the list is empty return False, -1 if len( self.list ) == 1: #if only one value in list which is equal to item if Index(self.list[0]) == Index(item): return True, 0 else: if Index(item) > Index(self.list[0]): return False, -2 # if one value in list, greater than item else: return False, -1 #... less than item elif Index(item) < Index(self.list[0]): return False, -1 # if the item is smaller than the least value of the list elif Index(item) > Index(self.list[-1]): return False, -2 # if the item is greater than the least value of the list else: # is the item is within the list # search algorithm lowest = 0 highest = len(self.list) middle = int((lowest + highest) / 2) while True: if Index(self.list[middle]) == Index(item): return True, middle if middle in [lowest, highest]: break if Index(self.list[middle]) < Index(item): lowest = middle else: highest = middle middle = int((lowest + highest) / 2) return False, middle + 1 # if the item is not found except: # if the ordered list does not in fact consist in indexstrings self.indexstrings = False if not self.list: return False, -1 # if the list is entry if len(self.list) == 1: # for a list with one item if self.list[0] == item: return True, 0 else: if item > self.list[0]: return False, -2 # if item is greater than else: return False, -1 # is less then if item < self.list[0]: return False, -1 # it item is less than elif item > self.list[-1]: return False, -2 # if great then else: # search algorithm lowest = 0 highest = len(self.list) middle = int((lowest + highest) / 2) while True: if self.list[middle] == item: return True, middle if middle in [lowest, highest]: break if self.list[middle] < item: lowest = middle else: highest = middle middle = int((lowest + highest) / 2) return False, middle + 1 # if not found
def range_find(pageset, reduce=True, compact=True, breaker=', '): """Tranforms a list of pages into a formatted range Reduce to give indexes in a reduced form! """ if compact: def integer_part(x): if '.' in str(x): return int(str(x).split('.')[0]) else: return int(x) pages = set() pair_list = [] integer_pages = set() for page in pageset: ip_temp = integer_part(page) integer_pages.add(ip_temp) all_indexes = sorted(integer_pages) del integer_pages try: starting = all_indexes[0] except: starting = 0 ending = starting if len(all_indexes) > 0: for ind in all_indexes[1:]: if ind == ending + 1: ending = ind elif ind > ending + 1: pair_list.append((starting, ending)) starting = ind ending = ind else: pass if (len(pair_list) > 0 and pair_list[-1] != (starting, ending)) or len(pair_list) == 0: pair_list.append((starting, ending)) result = '' for pair in pair_list: starting, ending = pair[0], pair[1] if ending > starting: result += str(starting) + LONGDASH + str(ending) + breaker else: result += str(starting) + breaker if len(result) > len(breaker): return result[0:-len(breaker)] else: return '' else: return '' pagerangelist = [] for page in sorted(pageset): if isinstance(page, int): if page in pageset and page - 1 in pageset: pagerangelist[-1].append(str(page)) elif page in pageset and not page - 1 in pageset: pagerangelist.append([str(page)]) elif isinstance(page, str): if page.isnumeric(): if page in pageset and str(int(page) - 1) in pageset: pagerangelist[-1].append(str(page)) elif page in pageset and not str(int(page) - 1) in pageset: pagerangelist.append([str(page)]) elif type(page) == type(Index(0)): if page in pageset and page - Index(1) in pageset: pagerangelist[-1].append(str(page)) elif page in pageset and not page - Index(1) in pageset: pagerangelist.append([str(page)]) def redux(x): if reduce: return index_reduce(x) else: return x pagerangestringlist = [] for pagerange in pagerangelist: if len(pagerange) == 1: pagerangestringlist.append(redux(str(pagerange[0]))) else: pagerangestringlist.append( redux(str(pagerange[0])) + LONGDASH + redux(str(pagerange[-1]))) return COMMABLANK.join(pagerangestringlist)