def growlnotify(title=None, message=None, app=None, sticky=False, icon=None, image=None, url=None): if title and not isstring(title): title = str(title) if not message: message = "" if message and not isstring(message): message = str(message) # if message and isstring(message): # message = message.encode("utf-8") if title and title[0] == "-": title = "\\" + title # if title and isstring(title): # title = title.encode("utf-8") if not message and not title: title = "" args = [] if title: args += ["-t", title] if app: args += ["-a", app] if icon: args += ["--icon", icon] if image: args += ["--image", fullpath(image)] if sticky: args += ["-s"] if url: args += ["--url", url] stdin = message # need first growlnotify arg for correct app icon args = ["growlnotify"] + args _open() _run(args, stdin)
def write(path, content): """write to file and return fullpath""" path = fullpath(path) if content is None: content = "" if isinstance(content, dict): content = json.dumps(content) if not isstring(content): content = str(content) if str(content.__class__) == "<class 'bytes'>": try: content = str(content, "utf-8") # python3 except TypeError: # TypeError: str() takes at most 1 argument (2 given) content = str(content) # python2 # if encoding: # content=content.encode(encoding) folder = os.path.dirname(path) if folder and not os.path.exists(folder): os.makedirs(folder) try: unicode() if isinstance(content, unicode): content = content.encode("utf-8") open(path, "w").write(content) except NameError: # NameError: name 'unicode' is not defined open(path, "w", encoding="utf-8").write(content) return path
def userpath(path): home = os.environ["HOME"] if not isstring(path): path = str(path) if path.find(home) == 0: path = type(path)("~") + path.replace(home, "", 1) return path
def ispublic(obj, module=None): if not obj: return False if not module: module = inspect.getmodule(obj) if not module: err = "%s module is None" % obj raise TypeError(err) __all__ = module.__dict__.get("__all__", None) name = None if hasattr(obj, "__name__"): name = obj.__name__ else: if isstring(obj): name = obj else: for _name, member in inspect.getmembers(module): if member == obj: name = _name continue if not name: err = "unknown name for %s" % obj raise TypeError(err) if __all__: return name in __all__ return name.find("_") != 0
def readfile(**kwargs): global promej_dict from tkinter.filedialog import askopenfilename filename = askopenfilename() if filename != '': filename_new = filename[:filename.rfind('.')] + '.crf' file_in = open(filename_new, 'r') main_str = file_in.read() file_in.close() raw_str_1 = main_str[:main_str.find('/')] raw_str_2 = main_str[main_str.find('/') + 1:main_str.find('|')] y = int(raw_str_1[:raw_str_1.find(' ')]) g = int(raw_str_1[raw_str_1.find(' ') + 1:raw_str_1.rfind(' ')]) r = int(raw_str_2[:raw_str_2.find(' ')]) s = int(raw_str_2[raw_str_2.find(' ') + 1:]) #print(r,s) promej_dict = (int(r), int(s), int(y), int(g)) p = int(p_entry.get()) q = int(q_entry.get()) #print(r,s,y,g,p,q) check = dsa(filename, mode='check', p=p, q=q, r=r, s=s, y=y, g=g) if not isstring.isstring(check): if check.get('params')[0] == r: VerPhoto('img/ver.png', 100, 80, 0.1, 0.6) else: VerPhoto('img/unver.png', 100, 80, 0.1, 0.6) else: from tkinter import messagebox messagebox.showerror('Error', check)
def fullpath(path): if not path: return None if not isstring(path): path = str(path) path = os.path.expanduser(path) if not os.path.isabs(path): path = os.path.abspath(path) return path
def subopen(args, stdin=None, shell=False, cwd=None, env=None): temp = None pid = None close_fds = True rstrip = True try: if stdin is not None and isstring(stdin): temp = tempfile() write(temp, stdin) stdin = open(temp) args = tolist(args) for i, arg in enumerate(args): if not isinstance(arg, int): if PY3: args[i] = str(arg) # python3 else: args[i] = __builtin__.unicode(arg) # python2 if not env: env = os.environ.copy() process = subprocess.Popen(args, stdin=stdin, stderr=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=close_fds, shell=shell, cwd=cwd, env=env, universal_newlines=False # , # startupinfo=startupinfo#, # creationflags=creationflags ) pid = process.pid stdoutdata, stderrdata = process.communicate() if PY3: # python3. process.communicate returns bytes stdoutdata = str(stdoutdata, "utf-8") # stdoutdata stderrdata = str(stderrdata, "utf-8") # stderrdata # rstrip if rstrip and stdoutdata: stdoutdata = stdoutdata.rstrip() if rstrip and stderrdata: stderrdata = stderrdata.rstrip() returncode = process.returncode return (returncode, stdoutdata, stderrdata) # raise CalledProcessError(returncode,args,err) # if returncode!=0: # raise CalledProcessError(returncode,args,stderrdata) # return stdoutdata finally: try: if pid: os.killpg(pid, signal.SIGTERM) except Exception: pass # print(format_exc()) rm(temp)
def tolist(obj): """convert object to list""" if obj is None: return [] if isstring(obj): return [obj] if isiterable(obj): return list(obj) else: return [obj]
def argquote(text, lstrip=True, rstrip=True): if not text: return text if not isstring(text): text = str(text) if lstrip: text = text.lstrip() if rstrip: text = text.rstrip() if text.find(" ") >= 0: text = '"%s"' % text return text
def getprintable(string, replace=""): result = [] if not isstring(string): string = str(string) for s in string: try: if s in string.printable: result.append(s) else: result.append(replace) except Exception: pass return type(string)("".join(result))
def isoverloaded(obj, cls=None): if not obj: return False if not cls: cls = getclass(obj) if not cls: return False name = None if hasattr(obj, "__name__"): name = obj.__name__ if isstring(obj): name = obj if not name: return False if isinherited(obj, cls): return name in cls.__dict__ return False
def writeinfile(file, dict): from tkinter import messagebox #(need_dict, file) if not isstring.isstring(dict): if file != '': pos_of_dot = file.rfind('.') if pos_of_dot != -1: signed_file = file[:pos_of_dot] + '.crf' list1 = dict.get('result', 0) list2 = dict.get('params', 0) hash = dict.get('hash', 0) #(list1) if all([list1, list2, hash]): out_file = open(signed_file, 'w') i = 0 for elem in list1: out_file.write(str(elem)) if i < len(list1) - 1: out_file.write(' ') i += 1 out_file.write('/') i = 0 for elem in list2: out_file.write(str(elem)) if i < len(list2) - 1: out_file.write(' ') i += 1 out_file.write('|') out_file.write(str(hash)) out_file.close() else: messagebox.showerror('Error', 'Wrong file path') else: messagebox.showerror('Error', 'Wrong filename') else: messagebox.showerror('Error', dict)
def openFile(**kwargs): from tkinter import messagebox from tkinter.filedialog import askopenfilename filename = askopenfilename() if filename != '': kek = True try: p = int(p_entry.get()) q = int(q_entry.get()) x = int(x_entry.get()) h = int(h_entry.get()) k = int(k_entry.get()) except: messagebox.showerror('Error', 'One of parameters is missing') kek = False if kek: global need_dict global filename123 filename123 = filename need_dict = dsa(filename, p=p, q=q, x=x, k=k, h=h, mode='signature') if not isstring.isstring(need_dict): label_6['text'] = 'Hash: ' + str(need_dict.get( 'hash', 0))[:17] + '...' label_7['text'] = 'Y: ' + str( need_dict.get('result', 0)[0]) label_8['text'] = 'G: ' + str( need_dict.get('result', 0)[1]) else: messagebox.showerror('Error', need_dict) else: messagebox.showerror('Error', 'One of parametrs is false') else: messagebox.showerror('File.Error', 'Wrong file name!')
def ismatch(string, pattern): if string == pattern: return True if pattern is None: return False for s in list(set(tolist(string))): if s == pattern: return True if not isstring(s): s = str(s) for p in tolist(pattern): if s == p: return True if isregex(p): return bool(p.match(s)) if inspect.isfunction(p): return p(s) if fnmatch.fnmatch(s, str(p)): return True return False
def objectname(obj, fullname=False): """ return object fullname with dot """ if obj and isstring(obj): return _str_name(obj, fullname) if isinstance(obj, property): return _prop_name(obj, fullname) if not obj or not hasattr(obj, "__name__"): return name = obj.__name__ names = [] module = inspect.getmodule(obj) if not inspect.ismodule(obj) and module: names.append(os.path.basename(module.__name__)) cls = getclass(obj) if cls and obj != cls: name = _cls_attr_name(cls, obj) names.append(cls.__name__) names.append(name) return _str_name(".".join(names), fullname)
def iswildcard(string): """Check string is Unix shell-style wildcards Returns: true if string is pattern, false else """ # https://docs.python.org/2/library/fnmatch.html if not string: return False if not isstring(string): return False if "*" in string: return True if "?" in string: return True if bool(re.match('(.*)\[([^]]*)\](.*)', string)): # [seq] return True if bool(re.match('(.*)\[\!([^]]*)\](.*)', string)): # [!seq] return True return False
def add_friend(): #Adding new friend naam = raw_input("Please add your friend's name: ") salutation = raw_input("Are they Mr. or Ms.?: ") age = input("Age?") rating = input("Spy rating?") #validity check if len(naam) > 0 and age > 12 and isstring(naam): frd = Spy(naam, salutation, age, rating) friends.append(frd) print 'Friend Added!' #writing to a csv with open('friends.csv', 'a') as friends_data: writer = csv.writer(friends_data) writer.writerow([ frd.spy_name, frd.spy_salutation, frd.spy_age, frd.spy_rating ]) else: print 'Sorry! Invalid entry. We can\'t add spy with the details you provided' return len(friends)
def formatvalue(value): if value is None: return "=None" if isstring(value): return "='%s'" % value.replace("\n", "").replace("/", ":") if inspect.isclass(value): if inspect.getmodule(value) != builtins: return "=%s" % objectname(value, fullname=True) else: return "=%s" % value.__name__ if isfilehandler(value): value = value.name if isregex(value): value = 'r"%s"' % value.pattern if "instance at" in str(value) or "object at" in str(value): cls = objectname(value.__class__, fullname=True) cls = cls.replace("__builtin__.", "") value = "<%s instance>" % cls if inspect.isfunction(value): if inspect.isbuiltin(value): return "=%s" % value.__name__ else: return "=%s" % objectname(value, fullname=True) return "=%s" % str(value)
def isprintable(string): if isstring(string): for s in string: if s not in printable: return False return True
return False # Retrieving Information from the CSV and Forming the JSON Config Files for i in range( len(index) ): #This loop runs for every row in the CSV File hence creating a seperate JSON File for each json_dict = {} #Empty dict that will contain the JSON data for x in keys: single_data = ( csv_data.iloc[[i]] ) #Taking the Pandas DataFrame of Information for the single file being created #Checking the Recieved Data in Cases: First Case with Strings #Checking every Column (Key) and updating the JSON file with the right type if isstring(single_data.ix[0, x]): if isFloat((single_data.ix[0, x])): if math.isnan((single_data.ix[0, x])): continue else: #Checking Cases: First Case for Lists if (single_data.ix[0, x])[0] == '[': list_data = single_data.ix[0, x] #_____Removing any extra characters_______# list_data = list_data.replace("\"", "").replace( "\'", "").replace(" ", "") #_________________________________________#
while show_menu: menu_choices = "What do you want to do? \n 1. Add a status update \n 2. Add a friend \n 3. Send a secret message \n 4. Read a secret message \n 5. Read Chats from a user \n 6. Close Application \n" menu_choice = input(menu_choices) if menu_choice == 1: current_status_message = add_status(current_status_message) else: show_menu = False else: print 'Abhi tumhari umr na hai babua' if existing == "Y": start_chat(spy_name,spy_age, spy_rating) #working on default value else: spy_name = '' #making values null for new value spy_salutation = '' spy_age = 0 spy_rating = 0.0 spy_online = False spy_name = raw_input("Welcome to spy chat, what's your name: ") #checking for a valid name if len(spy_name) > 0 and isstring(spy_name): spy_salutation = raw_input("Should I call you Mr. or Ms.?: ") spy_age = input("What is your age?") spy_rating = input("What is your spy rating?") spy_online = True start_chat(spy_name, spy_age, spy_rating) else: print 'Please add a valid spy name'