def comparer_blanc_noir(self, blanc, noir): #todo faire un debug affichable if self.Augmentation_coup_possible_adv_dans_zone( self.plateau, noir, ZONE_COIN) <= 0: #Ok on peut envisager de jouer noir coeff_blanc, coeff_noir = [], [] coeff_blanc.append( self.Augmentation_pion_stable_dans_zone( self.plateau, self.cote, ZONE_TOUT, blanc)) coeff_noir.append( self.Augmentation_pion_stable_dans_zone( self.plateau, self.cote, ZONE_TOUT, noir)) coeff_blanc.append(self.Nombre_pion_retourne(self.plateau, blanc)) coeff_noir.append(self.Nombre_pion_retourne(self.plateau, noir)) outils.ajouter_coeff_alea(coeff_blanc, coeff_noir) cfg.debug("##Cas particu noir {} est mieux que blanc {}".format( noir, blanc)) if est_superieur(coeff_blanc, coeff_noir): return blanc else: return noir return blanc
def faireTour(self): """Faire un tour de jeu.""" self.actions_annulees = [] self.tour = self.rang % self.plateau.nombre_de_joueurs joueur_actif = self.joueurs[self.tour] # Joueur à qui c'est le tour. cfg.debug("C'est au tour du joueur: " + str(joueur_actif)) self.plateau.charger(self.tour) # Nécessaire pour tous les joueurs. if self.panneau: self.afficher() self.rang += 1 if len(self.plateau.mouvements ) > 0: # Si des mouvements sont possibles. choix_du_joueur = joueur_actif.jouer(deepcopy(self.plateau), self.panneau) if not choix_du_joueur: return None cfg.debug("Le choix du joueur est {}".format(str(choix_du_joueur))) self.plateau.insererPion(choix_du_joueur, joueur_actif.cote) self.animer(choix_du_joueur) self.plateau.conquerir(choix_du_joueur, joueur_actif.cote) # Sauvegarde l'historique du jeu. self.historique.append( [self.plateau.grille, joueur_actif.cote, choix_du_joueur]) else: # Sinon aucun mouvement n'est possible et on passe au tour suivant. pass # Mot clé Python pour indiquer de ne rien faire.
def grabApp(pkg): app = {"gtime": time.time()} try: page = urllib2.urlopen("https://play.google.com/store/apps/details?id=" + pkg) debug("Start open page for pkg[%s]: Found it." % pkg) dom = pq(page.read().decode("utf-8")) app["type"] = 2 app["name"] = dom("#body-content .document-title").text() app["category"] = dom("#body-content .document-subtitle.category").attr("href") app["rating_count"] = dom('[itemprop="ratingCount"]').attr("content") app["developer"] = dom('#body-content [itemprop="name"]').text() app["downloads"] = dom('#body-content [itemprop="numDownloads"]').text() app["filesize"] = dom('#body-content [itemprop="fileSize"]').text() app["publish_date"] = dom('#body-content [itemprop="datePublished"]').text() app["version"] = dom('#body-content [itemprop="softwareVersion"]').text() app["system_require"] = dom('#body-content [itemprop="operatingSystems"]').text() app["rating_badge"] = dom('#body-content [itemprop="contentRating"]').text() app["category"] = [] categories = dom("#body-content .document-subtitle.category") if categories.size() > 1: for index in range(categories.size()): app["category"].append(categories.eq(index).attr("href")) else: app["category"].append(categories.attr("href")) app["category"] = json.dumps(app["category"]) del dom, page except urllib2.URLError, e: debug("Start open page for pkg[%s]: 404 not found it." % pkg) app["type"] = 1
def __get_customize_page(self): debug("Fetching Customize Page [%s]" % self.blogname) opener = self._make_opener() resp = opener.open('http://www.tumblr.com/customize/%s' % self.blogname) if resp.code != 200: debug(" !! Failed to fetch '/customize/%s': Error [%s]" % (self.blogname, resp.code)) return None html = resp.fp.read() # find the "user_form_key" m = re.search(r'Tumblr\.Customize\.user_form_key\s?=\s?[\'\"]([^\'\"]+)[\'\"];', html) if not m: debug(" !! Failed to parse Theme: Could not find [user_form_key]") return None userFormKey = m.group(1) m = re.search(r'Tumblr\.Customize\.blog\.set\((.+)(?=\);\n)', html) if not m: debug(" !! Failed to parse Theme: Could not find JSON object in Tumblr.Customize.blog.set()") return None themeInfo = m.group(1) themeInfo = jsonlib.loads(themeInfo) themeInfo['user_form_key'] = userFormKey themeInfo['id'] = themeInfo['name'] debug(' <3 Theme parsed') return themeInfo
def presenterPionsStables(self, fenetre): # Obsolète """Présente les pions stables a l'ecran en les trouvant, cela s'effectue avec la fenêtre. """ self.afficher() fenetre.coller(self.surface, 0) fenetre.afficher() fenetre.flip() tous_les_pions = [] for i in range(2): pions = self.obtenirTousLesPionsDefinitivementStables(i, fenetre) tous_les_pions.append(pions) self.presenter( pions, self.pieces_couleur[i], fenetre, message="pions stables", pause=True, ) cfg.debug("Pions définitivement stables:", tous_les_pions) fenetre.clear() plateau.afficher(fenetre) for i in range(2): plateau.presenter( tous_les_pions[i], self.pieces_couleur[i], fenetre, message="pions stables", clear=False, ) if tous_les_pions.count([]) != 2: fenetre.attendre() # Par défaut la fenêtre attend 1 seconde.
def socionet(author='', title='', keywords='', year1='', year2=''): config.debug('Socionet') config.write_log('Socionet: начал работу') if title: keywords = title + ' ' + keywords try: r = requests.post( base_url, data={ 'author-name': author, 'justtext': keywords, # ключевые слова 'fulltext': 'fulltext', # fulltext 'tr1': year1, 'tr2': year2, # 14 марта 1971 'accept-charset': 'utf-8', }) except requests.exceptions.ConnectionError: config.write_log('Socionet: ошибка при выполнении запроса') return 0 config.write_log('Socionet: запрос:' + str(r.url)) config.to_json({'BaseUrlParser': {'url_socio': r.url}}) html = r.text names_urls = get_urls(html, author, title) if names_urls: for name, url in names_urls: download_file(name, url, 'Socionet') config.write_log('Socionet: работа завершена') else: config.write_log('Socionet: материалы не найдены')
def pobierz(self,ocena): debug("Pobieram %s" % ocena.przedmiot) ret = self.c.execute("SELECT * FROM oceny WHERE \ przedmiot = ? \ AND typ = ? \ AND url = ? \ AND kod = ?",(ocena.przedmiot,ocena.typ,ocena.url,ocena.kod) ).fetchone() if ret: return USOS_Ocena(ret[0],ret[1],ret[2], ret[3]=="True", ret[4], ret[5])
def comparer_rouge_vert(self, rouge, vert): #todo revoir ca + debug affichage if not (self.position_stable_pour_cote(self.plateau, vert, self.cote)): if self.position_stable_pour_cote(self.plateau, rouge, self.cote): cfg.debug( "##Cas particulier, le rouge {} est mieux que le vert {}". format(rouge, vert)) return rouge return vert
def main(self, plateau): self.reinitialiser( plateau) # Il faut prednre en compte le nouveau plateau coups_bourbier = self.obtenir_coups_bourbier(self.plateau, self.cote) if coups_bourbier != []: cfg.debug("##Coup Bourbier !") return self.compa_diago(self.comparer, *coups_bourbier) else: return self.compa_diago(self.comparer, *self.mouvements_possibles)
def updateApp(pkg): app = grabApp(pkg) setsql = [] for field, value in app.items(): setsql.append("%s = '%s'" % (field, value)) setsql = ",".join(setsql) debug("Start save pkg[%s] to database." % pkg) cursor.execute("UPDATE appinfo SET %s WHERE pkg = '%s'" % (setsql, pkg))
def dodaj(self,ocena): debug("Dodaje %s" % ocena.przedmiot) self.c.execute("INSERT INTO oceny VALUES (?,?,?,?,?,?)", (ocena.przedmiot, ocena.kod, ocena.typ, ocena.do_sredniej, ocena.url, ocena.oceny) ) self.conn.commit()
def ustaw_login(self,mech): debug("Pobieram login..."); ret = self.c.execute("SELECT * FROM config WHERE klucz = ?", ("cookies", )).fetchone() if ret: mech._ua_handlers['_cookies'].cookiejar = pickle.loads(str(ret[1])) return True else: return False
def comparer_blanc_vert(self, blanc, vert): #todo faire un debug affichable if self.position_stable_pour_cote(self.plateau, blanc, self.cote): if not (self.position_stable_pour_cote(self.plateau, vert, self.cote)): if self.Nombre_pion_retourne( self.plateau, blanc) >= self.Nombre_pion_retourne( self.plateau, vert): cfg.debug("##Cas particulier {} est mieux que {}") return blanc return vert
def do_sredniej(self,url,typ_zajec): tree = html.fromstring(self.open(url).read()) tabele = tree.xpath('//table [@class="grey" and ' +'contains(.,"'+unicode(typ_zajec)+'")]') if len(tabele)==0: tabele = tree.xpath('//table [@class="grey"]') for tabela in tabele: if t(tabela.xpath('.//tr [contains (.,"Czy ocena")]/td[2]//*')[0])=='TAK': return True else: return False debug("do_sredniej(): Tu nie powinien wejsc! url=%s" % url)
def sound_play(note): if G.mute: return fname = get_sound_file(G.instrument, note) if not os.path.isfile(fname): G.error('File not found: ' + fname) return channel = pygame.mixer.Channel(G.index_from_note[note]) sound = pygame.mixer.Sound(fname) sound.set_volume(G.volume) channel.play(sound) G.output('Play %s' % (note)) G.debug("start %s on channel %d at volume %.1f" % (fname, G.index_from_note[note], 11.0 * G.volume))
def fetch(self, uriFrag): debug("Fetching www.tumblr.com/%s" % uriFrag) opener = self._make_opener() resp = opener.open('http://www.tumblr.com/%s' % uriFrag) if resp.code != 200: debug(" !! Failed to fetch: Error [%s]" % (resp.code)) return None html = resp.fp.read() return html
def aktualizuj(self,ocena): debug("Aktualizuje %s" % ocena.przedmiot) self.c.execute("UPDATE oceny SET ocena = ? WHERE \ przedmiot = ? \ AND kod = ? \ AND typ = ? \ AND do_sredniej = ? \ AND url = ?", (ocena.oceny, ocena.przedmiot, ocena.kod, ocena.typ, ocena.do_sredniej, ocena.url)) self.conn.commit()
def scholar(author='', title='', keywords='', year1='', year2=''): config.debug('Scholar') config.write_log('Scholar: начал работу') query = { 'allintitle': '"' + title + '"', 'author': '"' + author + '"', } params = { 'q': keywords + ' ' + ' '.join([k + ':' + v for k, v in query.items() if v[1:-1]]), 'as_vis': 1, # без цитат 'as_ylo': year1, # год 1 'as_yhi': year2, # год 2 'hl': 'ru', 'start': 0, # страницы 10 20 ...80 } while params['start'] <= 60: sleep(2) try: r = requests.get(base_url, params=params) except requests.exceptions.ConnectionError: config.write_log('Scholar: ошибка при выполнении запроса') break config.write_log('Scholar: запрос: ' + str(r.url)) config.to_json({'BaseUrlParser': {'url_scholar': r.url}}) html = r.text name_urls = get_urls(html, author) if name_urls: for name, url in name_urls: download_file(name, url, 'Scholar') else: config.write_log('Scholar: работа завершена') break params['start'] += 10
def cyberleninka(author='', title='', keywords='', year1='', year2=''): config.debug('Cyberleninka') config.write_log('Cyberleninka: начал работу') query = { '@author': author, '@name': title, # название статьи '@keywords': keywords, # ключевые слова '@year': year1 or year2, # поиск по году точный } params = { 'q': ' '.join([k+' '+v for k, v in query.items() if v]), 'page': 1 } try: r = requests.get(base_url+'/search', params=params) except requests.exceptions.ConnectionError: config.write_log('Cyberleninka: ошибка при выполнении запроса') return 0 config.write_log('Cyberleninka: запрос: ' + str(r.url)) config.to_json({ 'BaseUrlParser': { 'url_cyberleninka': r.url } }) html = r.text pages = count_pages(html) if pages: get_data_fom_page(html, author) for i in range(2, pages+1): params['page'] = i try: html = requests.get(base_url+'/search', params=params).text except requests.exceptions.ConnectionError: config.write_log('Cyberleninka: ошибка при выполнении запроса') return 0 get_data_fom_page(html) config.write_log('Cyberleninka: работа завершена')
def __save_customize_page(self, themeInfo): # HTTP Post is done with Mime-type 'application/json' postData = jsonlib.dumps(themeInfo) postHandler = HTTPPostHandler('application/json') debug("Editing Theme HTML...") opener = self._make_opener() opener.add_handler(postHandler) opener.addheaders.append(('Referer', 'http://www.tumblr.com/customize/%s' % self.blogname)) opener.addheaders.append(('Accept', 'application/json, text/javascript, */*; q=0.01')) opener.addheaders.append(('Accept-Charset', 'UTF-8,*;q=0.5')) opener.addheaders.append(('X-Requested-With', 'XMLHttpRequest')) opener.addheaders.append(('Origin', 'http://www.tumblr.com')) opener.addheaders.append(('Pragma', 'no-cache')) opener.addheaders.append(('Cache-Control', 'no-cache')) try: resp = opener.open('http://www.tumblr.com/customize_api/blog/%s' % self.blogname, data = postData) except Exception as e: debug(" !! Failed to edit HTML") return None newThemeInfo = resp.fp.read() newThemeInfo = jsonlib.loads(newThemeInfo) debug(" <3 Theme Saved.") return newThemeInfo
def connect(env, dbname=None): if hasattr(env, 'get'): # we have a dictionary with connection info url = env.get('url') debug = env.get('debug') if dbname is None: dbname = env.get('dbname') else: url = config.get(env, 'url') debug = config.debug(env) if dbname is None: dbname = config.get(env, 'dbname') username = config.username(env) password = config.password(env) server = Server(url, username, password) logger.info('Connecting to: %s' % url ) logger.info('Using database: %s' % dbname ) db = server.connect(dbname) db.env = env db.check_views() return db
def zapisz_login(self,mech): debug("Zapisuje login..."); tresc = pickle.dumps(mech._ua_handlers['_cookies'].cookiejar) ret = self.c.execute("SELECT * FROM config WHERE klucz = ?", ("cookies", )).fetchone() if ret: debug("Juz cos jest.") self.c.execute("UPDATE config SET tresc = ? WHERE klucz = ?", (tresc, "cookies")).fetchone() self.conn.commit() return True else: debug("Jeszcze nic nie ma...") self.c.execute("INSERT INTO config VALUES (?,?)" , ("cookies", tresc)) self.conn.commit() return True
def new_fct(*args, **kwargs): config.debug("~{}({},{})".format(fonction.__name__, args, kwargs)) result = fonction(*args, **kwargs) config.debug("$", result) return result
def main(self, plateau): """"Methode à surcharger""" cfg.debug("Random actif, Robot.main n'a pas ete surcharge") return self.jouerAleatoire(plateau)
def image(self): display.set("assets/forest.png") return "ok" @cherrypy.expose def image2(self): display.set("assets/graves.png") return "ok" @cherrypy.expose def generate(self, length=8): return "hi from {}".format(length) if __name__ == '__main__': conf = { '/': { 'tools.sessions.on': True, 'tools.staticdir.root': os.path.abspath(os.getcwd()) }, '/assets': { 'tools.staticdir.on': True, 'tools.staticdir.dir': './assets' } } config.load_config('./config.yml') config.debug() cherrypy.server.socket_host = '0.0.0.0' cherrypy.server.socket_port = 8082 cherrypy.server.shutdown_timeout = 1 cherrypy.quickstart(Page(), '/', conf)
if categories.size() > 1: for index in range(categories.size()): app["category"].append(categories.eq(index).attr("href")) else: app["category"].append(categories.attr("href")) app["category"] = json.dumps(app["category"]) del dom, page except urllib2.URLError, e: debug("Start open page for pkg[%s]: 404 not found it." % pkg) app["type"] = 1 return app debug("Start...") connection = connection.MySQLConnection(**dbconfig) cursor = connection.cursor() cursor.execute("SET NAMES utf8") cursor.execute("SELECT pkg FROM appinfo WHERE type = 0 LIMIT 50") appinfo = cursor.fetchall() debug("Find %d appinfos." % len(appinfo)) threads = [] for pkg in appinfo: thread = Thread(target=updateApp, args=(pkg[0],)) # thread.setDaemon(True) thread.start() threads.append(thread) for thread in threads: thread.join()
# @todo: # 有几个建议: # 1. config 数据库配置最好能根据环境变量的方式获取,或者写在 # 执行的命令行后 当做参数; # 2. dom('#action-dropdown-children-類別'.decode('utf-8')) # 里面有繁体字,上线估计是有问题的; # 3. 抓取完最好有更新记录,下次定时多久再更新。 from urllib2 import urlopen from pyquery import PyQuery as pq from config import dbconfig, debug from mysql.connector import (connection) import time debug("Start open category page.") page = urlopen('https://play.google.com/store/apps') content = page.read() categoryList = [] dom = pq(content.decode('utf-8')) category = dom('#action-dropdown-children-類別'.decode('utf-8')) for menu in category('ul.submenu-item-wrapper').items(): if len(menu('.parent-submenu-link')): parentName = menu('.parent-submenu-link').text() parentKey = menu('.parent-submenu-link').attr('href') children = [] for child in menu('.child-submenu-link').items(): childName = child.text()
def sound_stop(note): channel = pygame.mixer.Channel(G.index_from_note[note]) channel.stop() G.output('Stop %s' % (note)) G.debug("stop channel %d" % (G.index_from_note[note]))
@router.get( "/discord/redirect", tags=["auth"], status_code=307, ) async def redirect_to_discord_oauth_portal(request: Request, callback: HttpUrl = None): """Redirect user to correct oauth link depending on specified domain and requested scopes.""" callback = callback or (str(request.base_url) + "api/v1/auth/discord/callback") return RedirectResponse(get_redirect(callback=callback, scopes=SCOPES), status_code=307) if config.debug(): @router.get( "/discord/callback", tags=["auth"], response_model=CallbackResponse, response_description="GET Discord OAuth Callback", ) async def get_discord_oauth_callback(request: Request, code: str, callback: HttpUrl = None): """ Callback endpoint for finished discord authorization flow. """ callback = callback or (str(request.base_url) + "api/v1/auth/discord/callback")
from werkzeug.utils import secure_filename from io import BytesIO import base64 from aws_helpers import upload_file_s3, get_all_files_s3, delete_file_s3 from aws_helpers import get_file_url, get_signal_name, get_image_url from config import s3_file_bucket, s3_image_bucket import config from simpls.SIMPLS import SIMPLS_Chart # See aws_helpers.py for details on config file not in Git # instantiate the app app = Flask(__name__) app.config.from_object(__name__) app.secret_key = config.app_secret_key() app.debug = config.debug() # enable CORS CORS(app, resources={r'/*': {'origins': '*'}}) @app.route('/files', methods=['POST']) def upload_file(): if 'file' not in request.files: flash('No file part') return make_response(jsonify({'result': 'error'})) file = request.files['file'] if file.filename == '': flash('No file selected for uploading') return make_response(jsonify({'result': 'no file selected'})) if file:
from flask import Flask, abort, url_for, request, jsonify from webargs.flaskparser import parser from flask_cors import CORS from config import debug from resources.lookup import LookupView app = Flask(__name__, template_folder='templates') CORS(app, supports_credentials=True) app.jinja_env.globals = {'debug': debug(), 'url_for': url_for} app.jinja_env.auto_reload = True app.config['TEMPLATES_AUTO_RELOAD'] = True LookupView.register(app) @app.before_request def before_request(): # Wipe Jinja2 cache for local development with every request. if 'localhost' in request.host_url or '0.0.0.0' in request.host_url: app.jinja_env.cache = {} @parser.error_handler def handle_request_parsing_error(err): abort(jsonify(error_code='validation_error', message=err.messages)) if __name__ == '__main__':
def playsong_aux(fname): infile = open(fname, 'r') tempo = 120 # andante prev_tones = [] line = '' while G.gui and G.gui.button_demo.get(): line = line.strip() #G.output('parse line: "%s"' % (line)) if (not len(line)): line = infile.readline() if ('' == line): pygame.mixer.stop() # turn itself off gui-side G.gui.buttom_demo.set(0) G.gui.draw_keyboard() return None elif re.match(r'#', line): G.debug(line) line = '' elif re.match(r'\\tempo ([1-9][0-9]*)\s*$', line): # Yay! I get to pointlessly repeat myself because python doesn't trust the programmer with assignments that evaluate to a value! matches = re.match(r'\\tempo ([1-9][0-9]*)\s*$', line) try: tempo = int(matches.group(1)) G.output('Tempo = %s' % (tempo)) except: G.error("Can't happen. Invalid tempo: \"" + line + '"') line = '' elif re.match(r'\\instrument (.*)', line): matches = re.match(r'\\instrument (.*)', line) player.set_instrument(matches.group(1)) line = '' # instruments can have spaces, so this command always uses the entire line elif re.match(r'\\key (.*)', line): matches = re.match(r'\\key (.*)', line) player.set_key(matches.group(1), 0) line = '' # instruments can have spaces, so this command always uses the entire line elif re.match(r'\(([~A-G0-8b ]*)\)([1-9][0-9]*\.?)(.*)', line): matches = re.match(r'\(([~A-G0-8b ]*)\)([1-9][0-9]*\.?)(.*)', line) # Does admit a few notes that aren't on the keyboard, like G8, but those will get caught by sound_play() # Also admits things like (C4~3 A)3. If I can nest groups, I *could* catch those, but again, sound_play will handle it. # The checks here just need to make sure it doesn't do anything that could escape the SOUNDS_DIR tones = matches.group(1).split() try: s = matches.group(2) duration = 4.0 / float(s) # now equals number of quarter notes if '.' == s[len(s) - 1]: # dotted note duration = duration * 1.5; # Stop the previous set of notes for tone in prev_tones: if ('~' + tone) not in tones: player.sound_stop(tone) G.gui.key_up(tone) # Play this set for (i, tone) in enumerate(tones): if ('~' != tone[0]): # If it's a tie, we don't start it over player.sound_play(tone) G.gui.key_down(tone) else: tones[i] = tone[1:len(tone)] # prev_tones won't care if it was already a tie prev_tones = tones # (duration beats) / (tempo beats/minute) * 60 s/min* 1000 ms/s = x ms ms = int(1000 * 60 * duration / tempo) pygame.time.delay(ms) line = matches.group(3) except: G.error('Invalid note: "' + line + '"') print sys.exc_info() traceback.print_tb(sys.exc_info()[2]) print '' line = '' else: G.error('Syntax error: "' + line + '"') line = '' pygame.mixer.stop()
from config import plik_bazy,login,haslo,debug,powiadom if __name__ == '__main__': baza = USOS_Baza(plik_bazy) usos = USOS() if not baza.ustaw_login(usos): usos.login(login,haslo) baza.zapisz_login(usos) oceny = [] try: oceny = usos.pobierz_oceny() debug("Pobranie ocen udane") except Exception,e: if str(e[0]).count("Blad logowania")>0: print("Potrzebuje ponownie sie zalogowac..."), usos.login(login,haslo) baza.zapisz_login(usos) oceny = usos.pobierz_oceny() else: raise for ocena in oceny: z_bazy = baza.pobierz(ocena) if z_bazy == ocena: continue print ".", ; sys.stdout.flush()
# -*- coding: utf-8 -*- # author: liuxu import logging import config logger = logging.getLogger("dmr") logger.setLevel(logging.DEBUG) formatter = logging.Formatter( '[%(asctime)s][%(levelname)s][%(name)s] %(message)s') fh = logging.FileHandler(config.getLogPath()) fh.setFormatter(formatter) if (config.debug()): fh.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) ch.setFormatter(formatter) logger.addHandler(ch) else: fh.setLevel(logging.INFO) logger.addHandler(fh) logger.propagate = config.debug() def d(msg): logger.log(logging.DEBUG, msg)
def _login(self): debug("Logging in [%s / %s]" % (self.login, self.blogname)) opener = self._make_opener() # If we have cookies, let's see if we are logged in: if len(self.cookieJar): debug(" >> Testing cookies...") resp0 = opener.open('https://www.tumblr.com') if resp0.code != 200: debug(" !! Failed to fetch '/': Error [%s]" % resp0.code) raise LoginError('Could not fetch www.tumblr.com') html0 = resp0.fp.read() if 'id="logged_in"' in html0 and not 'id="logged_out"' in html0: debug(" <3 Good - already logged in.") self.logged_in = True if not self.logged_in: debug(" >> Fetching /login Page...") # OK, we need to login, Fetch the login page first resp1 = opener.open('https://www.tumblr.com/login') if resp1.code != 200: debug(" !! Failed to fetch '/login': Error [%s]" % resp1.code) raise LoginError('Could not fetch www.tumblr.com/login') debug(" >> Sending Login info...") # login is POSTed with Mime-Type 'application/x-www-form-urlencoded' loginInfo = {'user[email]' : self.login, 'user[password]' : self.password } loginInfo = encode_urlencoded_formdata(loginInfo) #origHeaders = [h for h in opener.addheaders] opener2 = self._make_opener() opener2.addheaders.append(('Content-Type', 'application/x-www-form-urlencoded')) resp2 = opener2.open('https://www.tumblr.com/login', data = loginInfo) html2 = resp2.fp.read() #opener.addheaders = origHeaders # Some hacky heuristics to determine if the login was a Success codeOK = resp2.code == 200 hasRefresh = '<meta http-equiv="Refresh" content="0;url=/dashboard">' in html2 hasNoErrors = 'SignupProcess.errors =' not in html2 if codeOK and hasRefresh and hasNoErrors: debug(" <3 Success - logged in.") else: debug(" !! Login Failed: Error [%s]" % resp2.code) raise LoginError('Login failed') #//end if self.save_cookies() self.logged_in = True return True
def dbinfo(env): info = {} for key in ['url', 'dbname']: info[key] = config.get(env, key) info['debug'] = config.debug(env) return info
#standard libs from threading import Thread from subprocess import Popen, PIPE import sys import logging import site site.addsitedir("../libs") #own libs import config from dhash import DistributedHash log = logging.getLogger("verifyta_statusreader") if config.debug(): log.setLevel(logging.DEBUG) else: log.setLevel(logging.INFO) class JobStreamReader: def __init__(self, stream, uid): self._stream = stream self._uid = uid self._loadtable = DistributedHash("uppaal_load") self._throughputtable = DistributedHash("uppaal_throughput") self._finalresult = "" def startreading(self): log.info("Started reading output from verifyta with id: {}" .format(self._uid))
def get_date(): if config.debug(): return datetime.today().second return datetime.today().day
def __mark_photo_private(self, postID, editPage): debug(' >> Parsing Edit Page') soup = BeautifulSoup(editPage) form = {} # Build caption m = re.search(r'<textarea.*?id="post_two".*?>(.*?)</textarea>', editPage, re.I | re.M | re.DOTALL) if not m: debug(' !! Couldn\'t find caption!') return caption = m.group(1) caption = re.sub('<', '<', caption) caption = re.sub('>', '>', caption) caption = re.sub('&', '&', caption) caption = re.sub(' ', '\r', caption) # Build the form data for posting form['UPLOAD_IDENTIFIER'] = soup.select('#upload_id')[0]['value'] form['post[state]'] = 'private' form['post[publish_on]'] = '' form['post[draft_status]'] = '' form['post[date]'] = soup.select('#post_date')[0].get('value') or '' form['post[source_url]'] = soup.select('#post_source_url')[0].get('value') or '' form['post[tags]'] = soup.select('#post_tags')[0].get('value') or '' form['post[slug]'] = '' form['custom_tweet'] = 'Photo: [URL]' form['custom_tweet_changed'] = '0' form['is_rich_text[one]'] = '0' form['is_rich_text[two]'] = '1' form['is_rich_text[three]'] = '0' form['form_key'] = soup.select('#form_key')[0]['value'] form['photo_raw'] = '' form['images'] = ('', '') form['photo_src'] = '' form['MAX_FILE_SIZE'] = '10485760' form['post[two]'] = caption form['post[three]'] = soup.select('#post_three')[0].get('value') or '' form['post[type]'] = 'photo' form['post[id]'] = str(postID) form['post[promotion_data][message]'] = '(No message)' form['post[promotion_data][icon]'] = '/images/highlighted_posts/icons/bolt_white.png' form['post[promotion_data][color]'] = '#bb3434' postData = encode_multipart_formdata(form) multipartHandler = HTTPPostHandler(postData[1]) debug(" >> Editing post to 'Private'") opener = self._make_opener() opener.add_handler(multipartHandler) opener.addheaders.append(('Referer', 'http://www.tumblr.com/edit/%s' % postID)) opener.addheaders.append(('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')) opener.addheaders.append(('Accept-Charset', 'UTF-8,*;q=0.5')) resp = opener.open('http://www.tumblr.com/edit/%s' % postID, data = postData[0]) html = resp.fp.read() # hacky heuristic: # After a successful edit, we should be returned to the Dashboard if '<body id="dashboard_index"' in html: debug(' >> Success!') return True else: debug(' !! Failed! Something went wrong!') return False
display.set("assets/forest.png") return "ok" @cherrypy.expose def image2(self): display.set("assets/graves.png") return "ok" @cherrypy.expose def generate(self, length=8): return "hi from {}".format(length) if __name__ == '__main__': conf = { '/': { 'tools.sessions.on': True, 'tools.staticdir.root': os.path.abspath(os.getcwd()) }, '/assets': { 'tools.staticdir.on': True, 'tools.staticdir.dir': './assets' } } config.load_config('./config.yml') config.debug() cherrypy.server.socket_host = '0.0.0.0' cherrypy.server.socket_port = 8082 cherrypy.server.shutdown_timeout = 1 cherrypy.quickstart(Page(), '/', conf)