def send_prescence(self): data={"id":common.get_id(),"local_ip":spkwifi.get_ip_adress()} if common.get_id() is not None: if self.channel_thread.token==None: if self.channel_thread.bad_token!=None: data["bad_token"]=self.channel_thread.bad_token data["get_token"]=True if self.routine!=None: data["routine"]=self.routine.type data["current_cut_job"]=self.routine.job_id data["can_stop"]=self.routine.status.can_stop data["stop_requested"]=self.routine.status.stop_requested data["cut_fase"]=self.routine.status.fase if self.last_job_status is not None: data["last_job_status"]=self.last_job_status.as_dict() self.last_job_status=None if self.message is not None: data["popup_message"]=self.message self.message=None try: #print data response_object=common.send_data(data) #print data #print response_object except Exception as error: print error response_object={} time.sleep(1) #durmamos 10 segundos, hubo un error con el servidor return response_object
def build_graph(lemma_cmd, proof_cmds): lemma_name = lemma_name_from_statement(getAddBody(lemma_cmd)) graph = ProofGraph(getAddBody(lemma_cmd)) next_node_id = 1 states = [(get_id(lemma_cmd), graph.start_node)] state_map = {} for cmd in proof_cmds: if isAdd(cmd): most_recent_state, most_recent_node = states[-1] if shouldFilterCommand(cmd): state_map[get_id(cmd)] = most_recent_state continue states.append((get_id(cmd), graph.mkNode(sanitizeTactic(getAddBody(cmd)), datetime.fromtimestamp(get_time(cmd)), most_recent_node))) next_node_id += 1 if isFinishingProofCmd(getAddBody(cmd)): for statenum, node in states: graph.setNodeColor(node, "blue") if isFailed(cmd): most_recent_state, most_recent_node = states[-1] graph.setNodeColor(most_recent_node, "red") if isCancel(cmd): cancel_dest = getCancelDest(cmd) cancel_dest = state_map.get(cancel_dest, cancel_dest) while len(states) > 0 and states[-1][0] != cancel_dest: states.pop() assert len(states) > 0 if not os.path.exists("graphs"): os.mkdir("graphs") graph_filename = "graphs/" + lemma_name + ".svg" graph.draw(graph_filename) return graph
def send_prescence(self): data = {"id": common.get_id(), "local_ip": spkwifi.get_ip_adress()} if common.get_id() is not None: if self.channel_thread.token == None: if self.channel_thread.bad_token != None: data["bad_token"] = self.channel_thread.bad_token data["get_token"] = True if self.routine != None: data["routine"] = self.routine.type data["current_cut_job"] = self.routine.job_id data["can_stop"] = self.routine.status.can_stop data["stop_requested"] = self.routine.status.stop_requested data["cut_fase"] = self.routine.status.fase if self.last_job_status is not None: data["last_job_status"] = self.last_job_status.as_dict() self.last_job_status = None if self.message is not None: data["popup_message"] = self.message self.message = None try: #print data response_object = common.send_data(data) #print data #print response_object except Exception as error: print error response_object = {} time.sleep(1) #durmamos 10 segundos, hubo un error con el servidor return response_object
def run(self): self.check_version() self.channel_thread = ChannelApiThread(self.channel_api_message) self.channel_thread.start() print u"Cliente conectado con servidor" while not self.kill: self.required_post = False response = self.send_prescence() self.manage_response(response) time.sleep(1) for _ in range(200): if common.get_id() is not None or self.kill: break time.sleep( 5 ) #cuando no hay id, esperamos 5 segundos y solo mandamos el ip paque nos configuren while self.kill == False and self.required_post == False and ( self.channel_thread.connected == True or self.channel_thread.connecting == True): time.sleep(0.1) pass if self.required_post == True: time.sleep( 0.1 ) #para que si se marco el required post antes de que acabara de hacer cosas otro thread, las acabe
def expand_twitter( accum_ids, asset_def, embeds_dct, override_link ): asset_name = asset_def["asset_name"] # get id... htmlid = common.get_id(asset_name,accum_ids) accum_ids.append( htmlid ) # get parms... x = get_attr( 'x', asset_name, asset_def, embeds_dct ) y = get_attr( 'y', asset_name, asset_def, embeds_dct ) z = get_attr( 'z', asset_name, asset_def, embeds_dct,'0') if override_link: link = override_link else: link = get_attr( 'link', asset_name, asset_def, embeds_dct,'http://www.twitter.com') link = common.site_replace(link) # get template and replace vars... f = open("embeds/twitter.txt",'r') tmpl = f.read() f.close() txt = tmpl.replace("HTMLID",htmlid) txt = txt.replace("LINK",link ) # produce html parts... style = "#%s { position:absolute;top:%dpx;left:%dpx;z-index:%d;} " % (asset_name, int(y), int(x), int(z) ) content = txt scriptlet_dct = { "on":"", "off":"", "init":"" } return [ style, content, "", scriptlet_dct ]
def expand_item( accum_ids, asset_def, embeds_dct ): # get the asset definition... asset_name = asset_def["asset_name"] print "ed->", embeds_dct item_def = embeds_dct[asset_name][0] # get id... htmlid = common.get_id(asset_name,accum_ids) accum_ids.append( htmlid ) # get basic properties... codeval = item_def['code'] if codeval.startswith("file"): idx = codeval.find(":") + 1 filename = codeval[idx:] path = os.path.join(EMBEDS_DIR, filename) f = open(path,'r') code = f.read() f.close() # insert id... print "CODEVAL-->%s<--" % code, code.startswith("<div ") if ( code.startswith("<div ") ): code = code[0:5] + " id=%s " % htmlid + code[5:] print "REPLACE 1!!", code else: print "ERROR: Invalid code value" sys.exit(1) x = get_attr( 'x', asset_name, asset_def, embeds_dct ) y = get_attr( 'y', asset_name, asset_def, embeds_dct ) z = get_attr( 'z', asset_name, asset_def, embeds_dct,'0') # style... style = "" style += common.emit_line( "#%s {" % htmlid ) style += common.emit_line( "position: absolute;") style += common.emit_line( "left: %dpx;" % int(x) ) style += common.emit_line( "top: %dpx;" % int(y) ) style += common.emit_line( "z-index: %d;" % int(z) ) # content... content = common.emit_line( code ) scriptlet_dct = {} scriptlet_dct['on'] = "document.getElementById('%s').style.visibility = '%s';" % (htmlid, 'visible' ) scriptlet_dct['off'] = "document.getElementById('%s').style.visibility = '%s';" % (htmlid, 'hidden' ) scriptlet_dct['init'] = "document.getElementById('%s').style.visibility = '%s';" % (htmlid, 'visible' ) return [ style, content, "", scriptlet_dct ]
def expand_pinterest( accum_ids, asset_def, embeds_dct, images_dct = None, override_link=None, override_image=None ): asset_name = asset_def["asset_name"] # get id... htmlid = common.get_id(asset_name,accum_ids) accum_ids.append( htmlid ) # get parms... x = get_attr( 'x', asset_name, asset_def, embeds_dct ) y = get_attr( 'y', asset_name, asset_def, embeds_dct ) z = get_attr( 'z', asset_name, asset_def, embeds_dct,'0') if override_link: link = override_link else: link = get_attr( 'link', asset_name, asset_def, embeds_dct,'http://www.pinterest.com') link = common.site_replace(link) if override_image: image = override_image else: image = get_attr( 'image', asset_name, asset_def, embeds_dct, 'http://thestudio.codetodesign.com/content_7_6_2012/main_logo4.png' ) image = common.site_replace( image ) # possibly use img path... br1 = image.find("[") br2 = image.find("]") if (br1>=0) and (br2>=0): imgref = image[br1:(br2+1)] imgref = imgref[1:-1] print images_dct pathimg = get_img_path( imgref, images_dct ) image = image[0:br1] + pathimg + image[br2+1:] print "ref->",imgref, pathimg, image else: image = common.path_replace( image) f = open("embeds/pinterest.txt",'r') tmpl = f.read() f.close() txt = tmpl.replace("HTMLID",htmlid) link = urllib2.quote(link) link = link.replace( "/", "%2F" ) txt = txt.replace("LINK",link) image = urllib2.quote(image) image = image.replace( "/", "%2F" ) txt = txt.replace("IMAGE", image) style = "#%s { position:absolute;top:%dpx;left:%dpx;z-index:%d;} " % (asset_name, int(y), int(x), int(z) ) content = txt scriptlet_dct = { "on":"", "off":"", "init":"" } return [ style, content, "", scriptlet_dct ]
def expand_caption( accum_ids, asset_def ): print "IMAGE SET EXPAND CAPTION", asset_def # get the asset definition... asset_name = asset_def["asset_name"] + "_cap" item_def = asset_def # get id... htmlid = common.get_id(asset_name,accum_ids) accum_ids.append( htmlid ) # get cap path... cap_path = asset_def['cap_path'] capfile = asset_def['cap_file'] print "caps->", cap_path, capfile capsrc = os.path.join( cap_path, capfile ) capsrc = common.path_replace(capsrc) # compute the coord... centerx = 1067 centery = 371 capw = asset_def['cap_width'] caph = asset_def['cap_height'] x = centerx - (int)(capw*1.0/2) y = centery - (int)(caph*1.0/2) # get z... z = 3 # style... style = "" style += common.emit_line( "#%s {" % htmlid ) style += common.emit_line( "position: absolute;") style += common.emit_line( "left: %dpx;" % int(x) ) style += common.emit_line( "top: %dpx;" % int(y) ) style += common.emit_line( "z-index: %d;" % int(z) ) style += common.emit_line( "}" ) # content... content = "" content += common.emit_line( "<img id=%s src=\"%s\" alt=\"TheStudio\" >" % (htmlid, capsrc) ) scriptlet_dct = {} scriptlet_dct['on'] = "document.getElementById('%s').style.visibility = '%s';" % (htmlid, 'visible' ) scriptlet_dct['off'] = "document.getElementById('%s').style.visibility = '%s';" % (htmlid, 'hidden' ) scriptlet_dct['init'] = "document.getElementById('%s').style.visibility = '%s';" % (htmlid, 'visible' ) return [ style, content, "", scriptlet_dct ]
def expand_brightcove_item( accum_ids, asset_def, images_dct, movies_dct ): # get the movie asset name... asset_name = asset_def["asset_name"] # get the base def of the item... item_def = movies_dct[asset_name][0] # get an html id for video element... htmlid = common.get_id( asset_name, accum_ids ) accum_ids.append(htmlid) # path is url... url = item_def["path"] # must have width and height... width = item_def['width'] height = item_def['height'] # get coords for def... x = int(asset_def['x']) y = int(asset_def['y']) z = asset_def['z'] # content from template... f = open( BRIGHTCOVE_EMBED, 'r') txt = f.read() f.close() content = txt.replace("URL",url) content = content.replace("HTMLID",htmlid) content = content.replace("WIDTH", width) content = content.replace("HEIGHT",height) content = content.replace("STYLE","position:absolute;visibility:inherit;top:%dpx;left:%dpx;z-index:4;" % (y,x) ) # style... style = "" # dct... scriptlet_dct = {} #scriptlet_dct['on'] = "document.getElementById('%s').style.visibility='visible';" % htmlid #scriptlet_dct['off'] = "document.getElementById('%s').style.visibility='hidden';" % htmlid #scriptlet_dct['init'] = "document.getElementById('%s').style.visibility='visible';" % htmlid scriptlet_dct['on'] = "" scriptlet_dct['off'] = "" scriptlet_dct['init'] = "" return [ style, content, scriptlet_dct ]
def pop_proof(cmds): states = [] proof_cmds = [] while len(cmds) > 0: cmd = cmds.pop(0) proof_cmds.append(cmd) if isAdd(cmd): states.append(get_id(cmd)) if isEndingProofCmd(getAddBody(cmd)): return proof_cmds if isCancel(cmd): cancel_dest = getCancelDest(cmd) while len(states) > 0 and states[-1] != cancel_dest: state_num = states.pop() if len(states) == 0: return proof_cmds return proof_cmds
def get_cancel_lengths(cmds): states = [] cancel_lengths = collections.Counter() for dat in cmds: if isAdd(dat): states.append(get_id(dat)-1) if isCancel(dat): cancel_length = 0 cancel_dest = getCancelDest(dat) if len(states) == 0: return collections.Counter() while states[-1] != cancel_dest: cancel_length += 1 states.pop() if len(states) == 0: return collections.Counter() cancel_lengths[cancel_length] += 1 return cancel_lengths
def add_question(cursor, site_input): values = [common.get_id('question'), common.get_submission_time(), 0, 0, site_input[0], site_input[1], '', site_input[2]] cursor.execute(""" INSERT INTO question(id, submission_time, view_number, vote_number, title, message, image,user_id) VALUES(%(id)s, %(submission_time)s, %(view_number)s, %(vote_number)s, %(title)s, %(message)s, %(image)s,%(user_id)s) """, {'id': values[0], 'submission_time': values[1], 'view_number': values[2], 'vote_number': values[3], 'title': values[4], 'message': values[5], 'image': values[6], 'user_id': values[7]})
def cpo_expand_caption_item( accum_ids, parent, asset_def, cp_dct, cpo_dct, images_dct, init_item, action_scripts ): print "CPO EXPAND CAPTION->", asset_def, cpo_dct.keys() typ = asset_def["type"] x = int(asset_def['x']) y = int(asset_def['y']) z = int(asset_def['z']) name = asset_def['asset_name'] hid = common.get_id( name, accum_ids ) # get the individual images and create ids... img_init_asset = images_dct[init_item][0] path = img_init_asset['path'] fname = img_init_asset['filename'] src = os.path.join(path,fname) src = common.path_replace( src ) src = common.create_path( src ) print "init src->", src # style... style = "" style += common.emit_line("#%s {" % hid ) style += common.emit_line(" position: absolute;") style += common.emit_line(" top: %dpx;" % y ) style += common.emit_line(" left: %dpx;" % x ) style += common.emit_line(" z-index: %d;" % (z+1) ) style += common.emit_line(" border:none;" ) style += common.emit_line(" visibility: hidden;" ) style += common.emit_line("}") # content... content = "<img id=\"%s\" src=\"%s\" alt=\"TheStudio\" />\n" % (hid, src) # scriptlet dct... scriptlet_dct = {} scriptlet_dct['on'] = "document.getElementById('%s').style.visibility='visible';" % hid scriptlet_dct['off'] = "document.getElementById('%s').style.visibility='hidden';" % hid scriptlet_dct['init'] = "document.getElementById('%s').style.visibility='visible';" % hid return [ style, content, scriptlet_dct ]
def run(self): self.check_version() self.channel_thread=ChannelApiThread(self.channel_api_message) self.channel_thread.start() print u"Cliente conectado con servidor" while not self.kill: self.required_post=False response=self.send_prescence() self.manage_response(response) time.sleep(1) for _ in range(200): if common.get_id() is not None or self.kill: break time.sleep(5) #cuando no hay id, esperamos 5 segundos y solo mandamos el ip paque nos configuren while self.kill==False and self.required_post==False and (self.channel_thread.connected==True or self.channel_thread.connecting==True): time.sleep(0.1) pass if self.required_post==True: time.sleep(0.1) #para que si se marco el required post antes de que acabara de hacer cosas otro thread, las acabe
def cpo_expand_preview_item(accum_ids, parent, asset_def, cp_dct, cpo_dct, images_dct, init_item, action_scripts): print "CPO EXPAND PREVIEW->", asset_def, cpo_dct.keys() typ = asset_def["type"] x = int(asset_def["x"]) y = int(asset_def["y"]) z = int(asset_def["z"]) name = asset_def["asset_name"] hid = common.get_id(name, accum_ids) # get the individual images and create ids... img_init_asset = images_dct[init_item][0] path = img_init_asset["path"] fname = img_init_asset["filename"] src = os.path.join(path, fname) src = common.path_replace(src) src = common.create_path(src) # style... style = "" style += common.emit_line("#%s {" % hid) style += common.emit_line(" position: absolute;") style += common.emit_line(" top: %dpx;" % y) style += common.emit_line(" left: %dpx;" % x) style += common.emit_line(" z-index: %d;" % (z + 1)) style += common.emit_line(" border:none;") style += common.emit_line(" visibility: hidden;") style += common.emit_line("}") # content... content = '<img id="%s" src="%s" alt="TheStudio" />\n' % (hid, src) # scriptlet dct... scriptlet_dct = {} scriptlet_dct["on"] = "document.getElementById('%s').style.visibility='visible';" % hid scriptlet_dct["off"] = "document.getElementById('%s').style.visibility='hidden';" % hid scriptlet_dct["init"] = "document.getElementById('%s').style.visibility='visible';" % hid return [style, content, scriptlet_dct]
def get_stats(proof_cmds): all_tactics = collections.Counter() cancelled_tactics = collections.Counter() failed_tactics = collections.Counter() num_tactics = 0 num_cancellations = 0 num_failures = 0 history_stack = [] for cmd in proof_cmds: if isAdd(cmd): tactic = getAddBody(cmd) history_stack.append((get_id(cmd), tactic)) if isVernacCmd(tactic): continue if isGoalPunctuation(tactic): continue num_tactics += 1 stem = get_stem(tactic) all_tactics[stem] += 1 if isCancel(cmd): cancel_dest = getCancelDest(cmd) cancellation_size = 0 while len( history_stack) > 0 and history_stack[-1][0] != cancel_dest: state_num, tactic = history_stack.pop() if isVernacCmd(tactic): continue if isGoalPunctuation(tactic): continue if isFailed(cmd): failed_tactics[get_stem(tactic)] += 1 cancelled_tactics[get_stem(tactic)] += 1 cancellation_size += 1 if isFailed(cmd): num_failures += cancellation_size num_cancellations += cancellation_size assert len(history_stack) > 0 return ProofMetadata(1, num_tactics, num_cancellations, num_failures, all_tactics, cancelled_tactics, failed_tactics)
families = config['families'] t0 = time.time() logging.info('Reading and parsing gedcom') try: people = Gedcom(fn) except Exception, e: logging.error('<h1>FATALT fel vid import av Gedcom</h1>') exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback) sys.exit() logging.info('Time %s', time.time() - t0) contributionFile = fn #TEMP #FIX #Handle versions contributionId = common.get_id('A') config['originalData'].insert({ 'type': 'admin', 'created': time.time(), 'file': contributionFile, 'cId': contributionId }) #modify Gedcom links by adding unique contributionId to them noChange = ('INDI', 'FAM', 'FAMS', 'FAMC', 'CHIL') patRepl = re.compile(r'@([^@]+)@') def fixGedcom(l): if l.value().startswith('@') and l.tag() not in noChange: l._value = patRepl.sub('@' + contributionId + r'-\1@', l.value(), 1)
def expand_item( accum_ids, asset_def, images_dct, movies_dct ): print "mov->", movies_dct.keys() # get the movie asset name... asset_name = asset_def["asset_name"] # get the base def of the item... item_def = movies_dct[asset_name][0] # get type... typ = "file" if item_def.has_key("type"): typ = item_def["type"] # if video type, branch here... if typ == "vimeo": return expand_vimeo_item( accum_ids, asset_def, images_dct, movies_dct ) elif typ == "brightcove": return expand_brightcove_item( accum_ids, asset_def, images_dct, movies_dct ) # get the alt movie asset name, if any... alt_name = "" if asset_def.has_key("alt"): alt_name = asset_def["alt"] # get an html id for video element... htmlid = common.get_id( asset_name, accum_ids ) accum_ids.append(htmlid) # get the poster path, if any... poster_path = "" if item_def["poster"].strip()!="": poster = item_def["poster"].strip() poster_path = gen_images.get_item_path( poster, images_dct ) poster_path = common.create_path( poster_path ) # get the alternate movie path src, if any... alt_path = "" if alt_name != "": alt_path = get_item_path( alt_name, movies_dct ) alt_path = common.create_path( alt_path ) # finally, get the primary movie path src... movie_path = get_item_path( asset_name, movies_dct ) movie_path = common.create_path( movie_path ) # get coords for def... x = asset_def['x'] y = asset_def['y'] z = asset_def['z'] # create the style... style = "" style += common.emit_line( "#%s {" % htmlid ) style += common.emit_line( "position: absolute;") style += common.emit_line( "left: %dpx;" % int(x) ) style += common.emit_line( "top: %dpx;" % int(y) ) style += common.emit_line( "z-index: %d;" % int(z) ) style += common.emit_line( "visibility: hidden;" ) style += common.emit_line( "}" ) if poster_path == "": content = common.emit_line( "<video controls id=%s ><source src=\"%s\" />CANNOT LOAD</video>" % (htmlid, movie_path) ) else: if alt_path != "": content = common.emit_line( "<video controls id=%s poster=\"%s\" >" % ( htmlid, poster_path ) ) content += common.emit_line( "<source src=\"%s\" />" % movie_path ) content += common.emit_line( "<source src=\"%s\" />" % alt_path ) content += common.emit_line( "</video>" ) else: content = common.emit_line( "<video controls id=%s poster=\"%s\" ><source src=\"%s\" /></video>" % (htmlid, poster_path, movie_path) ) scriptlet_dct = {} scriptlet_dct['on'] = "document.getElementById('%s').style.visibility='visible';" % htmlid scriptlet_dct['off'] = "document.getElementById('%s').style.visibility='hidden';" % htmlid scriptlet_dct['init'] = "document.getElementById('%s').style.visibility='visible';" % htmlid return [ style, content, scriptlet_dct ]
def do_POST(self): # if self.path=="/send_web": # # form = cgi.FieldStorage( # fp=self.rfile, # headers=self.headers, # environ={'REQUEST_METHOD':'POST', # 'CONTENT_TYPE':self.headers['Content-Type'], # }) # self.send_response(200) # self.end_headers() # textout = ["Nombre red: %s", # "Pswd: %s\n", # "Tu raspberry se esta conectando...", # "Si cometiste algun error, conectate al cable de Ethernet recarga la pagina y repite los pasos.", # ] # # self.wfile.write("SPKClient:. \n\n" + "\n".join(textout) % (form["ssid"].value,form["psk"].value)) # # if not spkwifi.set_wifi_network(form["ssid"].value.strip(), form["psk"].value.strip()): # self.wfile.write("Algo salio mal...") # # # return # if self.path=="/send_cncid": # form = cgi.FieldStorage( # fp=self.rfile, # headers=self.headers, # environ={'REQUEST_METHOD':'POST', # 'CONTENT_TYPE':self.headers['Content-Type'], # }) # # cncid= form["cncid"].value # # try: # if cncid.startswith("sudo"): # cncid = cncid.split("\"")[1] # # f = open(main.NEWCNCIDFILENAME,"w") # f.write(cncid) # f.close # # self.send_response(200) # self.end_headers() # # textout = ["ID: %s\n", # "Recarga la pagina en unos momentos.", # "Tu raspberry se esta reiniciando...", # "Revisa tu nueva maquina en el taller correspondiente." # ] # self.wfile.write("SPKClient:. \n\n" + "\n".join(textout) % (cncid)) # # common.restart_please() # #system("reboot") # #execl(sys.executable, *([sys.executable]+sys.argv)) # # except: # self.send_response(200) # self.end_headers() # self.wfile.write("Error, revisa el contenido de tu id") # # # return # if self.path=="/reset_client": # form = cgi.FieldStorage( # fp=self.rfile, # headers=self.headers, # environ={'REQUEST_METHOD':'POST', # 'CONTENT_TYPE':self.headers['Content-Type'], # }) # # # self.send_response(200) # self.end_headers() # self.wfile.write("El script de spkclient se esta reiniciando, ve a la pagina principal y recargala.") # common.restart_please() # return # if self.path=="/reset_pi": # form = cgi.FieldStorage( # fp=self.rfile, # headers=self.headers, # environ={'REQUEST_METHOD':'POST', # 'CONTENT_TYPE':self.headers['Content-Type'], # }) # # # self.send_response(200) # self.end_headers() # self.wfile.write("La raspberrypi se reiniciara...") # system("reboot") # return # if self.path == "/spkwizardsetup": data = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': self.headers['Content-Type'], }) action = data.getfirst("action", None) origin = self.headers.get("Origin", None) if not origin in ALLOWED_CONFIG_ORIGINS: self.send_response(403) return self.send_response(200) self.send_header('Content-type', "application/json") self.send_header('Access-Control-Allow-Origin', origin) self.end_headers() if action == "marco": if common.get_id() != None: self.wfile.write( json.dumps({"status": "already_configured"})) else: self.wfile.write( json.dumps({ "status": "polo", "current_network": spkwifi.get_current_connected_network() })) elif action == "get_network_status": self.wfile.write( json.dumps({ "status": "success", "available_networks": [n.ssid for n in spkwifi.get_available_networks()], "current_network": spkwifi.get_current_connected_network() })) elif action == "set_wifi_network": ssid = data.getfirst("ssid", None) password = data.getfirst("password", None) if spkwifi.set_wifi_network(ssid, password): self.wfile.write( json.dumps({ "status": "success", "current_network": spkwifi.get_current_connected_network() })) else: self.wfile.write( json.dumps({ "status": "error", "current_network": spkwifi.get_current_connected_network() })) elif action == "send_workshop": config_data = json.loads(data.getfirst("config_data", "{}")) response = common.send_config_info(config_data) if "extra_info" in response: self.wfile.write( json.dumps({ "status": "success", "extra_info": response["extra_info"] })) else: self.wfile.write( json.dumps({ "status": "error", "reason": response.get("reason", "") })) else: self.wfile.write(json.dumps({"status": "error"})) elif self.path == "/spkcnclocalcommandreceiver": data = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': self.headers['Content-Type'], }) origin = self.headers.get("Origin", None) local_token = data.getfirst("_local_token", None) prev_local_token = data.getfirst("_prev_local_token", None) if not origin in ALLOWED_CONFIG_ORIGINS or local_token == None or ( local_token != local_connection_token != prev_local_token): self.send_response(403) return self.send_response(200) self.send_header('Content-type', "application/json") self.send_header('Access-Control-Allow-Origin', origin) self.end_headers() message = json.loads(data.getfirst("message", None)) command = message.get("command", None) if command == "checking_same_network": self.wfile.write(json.dumps({"status": "sure :)"})) elif command == "lifeline": time.sleep(60) self.wfile.write(json.dumps({"status": "sure :)"})) elif command == "get_network_status": self.wfile.write( json.dumps({ "status": "success", "available_networks": [n.ssid for n in spkwifi.get_available_networks()], "current_network": spkwifi.get_current_connected_network() })) elif command == "get_current_network": self.wfile.write( json.dumps({ "status": "success", "current_network": spkwifi.get_current_connected_network() })) elif command == "set_wifi_network": ssid = message.get("ssid", None) password = message.get("password", None) if spkwifi.set_wifi_network(ssid, password): self.wfile.write( json.dumps({ "status": "success", "current_network": spkwifi.get_current_connected_network() })) else: self.wfile.write( json.dumps({ "status": "error", "current_network": spkwifi.get_current_connected_network() })) elif command == "get_script_status_change": while True: if common.internet_thread.routine is None or common.internet_thread.routine.status.as_dict( ) != message.get("last_status", None): break else: time.sleep(.01) if common.internet_thread.routine is not None: self.wfile.write( json.dumps({ "status": common.internet_thread.routine.status.as_dict() })) else: self.wfile.write( json.dumps({ "status": common.internet_thread.last_job_status.as_dict() if common.internet_thread.last_job_status is not None else None })) elif command == "send_console_line": if common.internet_thread.routine is None: try: self.console_manager.writeline(message.get("line", "")) except: pass self.wfile.write(json.dumps({})) elif command == "console_line_poll": try: lines = None lastid = message.get("lastlineid", None) counter = 0 response = {"status": "success"} while common.internet_thread.routine is None and lines is None and counter < 3: if message.get("i_think_there_is_no_serial", False): response["parser"] = common.get_parser() break #para que se quite el mensaje de que no hay serial lastid, lines = self.console_manager.readlines(lastid) counter += 1 response["lines"] = lines response["lastlineid"] = lastid self.wfile.write(json.dumps(response)) except DeadSerialException: self.wfile.write( json.dumps({ "status": "error", "reason": "no-serial" })) except: self.wfile.write(json.dumps({"status": "error"})) elif command == "jog_pressed_key": global current_jogging global jogging_cancel_timer try: if common.internet_thread.routine is None: key = message.get("key", None) pressed = message.get("pressed", None) possibles = { 38: "Y", 40: "Y-", 37: "X-", 39: "X", 33: "Z", 34: "Z-" } #http://keycode.info/ usb = ThreadsafeSerial.get() parser = common.get_parser() if key in possibles and pressed is not None: if jogging_cancel_timer is not None: jogging_cancel_timer.cancel() if not pressed or (current_jogging is not None and current_jogging != key): if parser == "tiny-g": usb.write("!%\n") #grbl mandar (! y ctrl x? cuando se frene?) current_jogging = None else: if message.get( "new_pressed", False) and current_jogging is None: if parser == "tiny-g": usb.write("G91 G0 " + possibles[key] + "1000\nG90\n") #grbl mandar lo mismo? current_jogging = key jogging_cancel_timer = threading.Timer( 0.5, lambda: usb.write("!%\n" if parser == "tiny-g" else "")) jogging_cancel_timer.start() usb.flushInput() except DeadSerialException: pass self.wfile.write(json.dumps({})) else: common.internet_thread.manage_response(message) self.wfile.write(json.dumps({}))
def emit_item(accum_ids, item, template_dct, template_assets_dct ): _nm = item["abbrev"] nm = common.get_id(_nm, accum_ids) x = int( item["x"] ) y = int( item["y"] ) z = 0 if item["z"]!="": z = int( item["z"] ) eltype = item["type"] file_location = item["file_location"] file_name = item["file_name"] fpath = os.path.join(file_location,file_name) fpath = fpath.replace( "CONTENT76", "../content_7_6_2012" ) # emit style... html = "" style = "" style += "#%s {\n" % nm style += "position: absolute;" style += "left: %dpx;\n" % x style += "top: %dpx;\n" % y style += "z-index: %d;\n" % z style += "overflow: hidden;\n" style += "border: 0px;\n" #html += "border: 1px dashed #333;" if eltype == 'imganim': style += "visibility: hidden;\n" style += "}\n" #style += "#%s.hover { border: 1px dashed #333; }\n" % nm # get link... link = item["link"] # get mouseover script, if any... mover = "" if item["mouseover"] != "": anim = item["mouseover"].split(":") mover = anim_script_item( anim, nm, template_dct, template_assets_dct ) # get mouseout script, if any... mout = "" if item["mouseover"] != "": anim = item["mouseout"].split(":") mout = anim_script_item( anim, nm, template_dct, template_assets_dct ) mc = "" # emit the item... if eltype=="imgmovie": pass elif mc!="": pass elif link and link!="0": if link.startswith("mailto:"): html += '<a href="%s">\n' % (link) else: html += '<a href="%s">\n' % (link+'.html') if (mover!="") and (mout!=""): html += '<img id=\"%s\" src="%s" onmouseover="%s" onmouseout="%s" alt=\"TheStudio\" />\n' % (nm,fpath,mover,mout) else: html += '<img id=\"%s\" src="%s" alt=\"TheStudio\" />\n' % (nm,fpath) html += '</a>\n' else: html += '<img id=\"%s\" src="%s" alt=\"TheStudio\" />\n' % (nm,fpath) return [ style, html ]
def cpo_expand_option_item( accum_ids, parent, asset_def, cpo_dct, images_dct, init_option, action_scripts ): print "CPO EXPAND->", asset_def, cpo_dct.keys() typ = asset_def["type"] x = int(asset_def['x']) y = int(asset_def['y']) z = int(asset_def['z']) name = asset_def['asset_name'] hid = common.get_id( name, accum_ids ) # get the option asset... cpo_asset = cpo_dct[ name ][0] # get the individual images and create ids... img_desel = cpo_asset['deselected'] desel_id = "%s_desel" % hid img_sel = cpo_asset['selected'] sel_id = "%s_sel" % hid img_preview = cpo_asset['preview'] # desel style... style = "" style += common.emit_line("#%s {" % desel_id ) style += common.emit_line(" position: absolute;") style += common.emit_line(" top: %dpx;" % y ) style += common.emit_line(" left: %dpx;" % x ) style += common.emit_line(" z-index: %d;" % (z+1) ) style += common.emit_line(" border:none;" ) style += common.emit_line(" visibility: hidden;" ) style += common.emit_line("}") # sel style... style += common.emit_line("#%s {" % sel_id ) style += common.emit_line(" position: absolute;") style += common.emit_line(" top: %dpx;" % y ) style += common.emit_line(" left: %dpx;" % x ) style += common.emit_line(" z-index: %d;" % z ) style += common.emit_line(" border:none;" ) style += common.emit_line(" visibility: hidden;" ) style += common.emit_line("}") # create scriptlet dcts... master_scr_dct = [] scriptlet_dct = {} scriptlet_dct['on'] = "document.getElementById('%s').style.visibility='visible';" % desel_id scriptlet_dct['off'] = "document.getElementById('%s').style.visibility='hidden';" % desel_id scriptlet_dct['init'] = "document.getElementById('%s').style.visibility='visible';" % desel_id master_scr_dct.append( scriptlet_dct ) scriptlet_dct = {} scriptlet_dct['on'] = "document.getElementById('%s').style.visibility='visible';" % sel_id scriptlet_dct['off'] = "document.getElementById('%s').style.visibility='hidden';" % sel_id scriptlet_dct['init'] = "document.getElementById('%s').style.visibility='visible';" % sel_id master_scr_dct.append( scriptlet_dct ) # create the content... content = "" # desel... img_desel_asset = images_dct[img_desel][0] path = img_desel_asset['path'] fname = img_desel_asset['filename'] src = os.path.join(path,fname) src = common.path_replace( src ) content += "<a href=\"#\" >\n" #content += "<img id=\"%s\" src=\"%s\" alt=\"TheStudio\" onclick=\"%s;\" onmouseover=\"%s;\" onmouseout=\"%s;\" />\n" % \ #(desel_id, src, "%s_click()" % desel_id, "%s_mouseover()" % desel_id, "%s_mouseout()" % desel_id ) content += "<img id=\"%s\" src=\"%s\" alt=\"TheStudio\" onclick=\"%s;\" />\n" % \ (desel_id, src, "%s_click()" % desel_id ) content += "</a>\n" # sel... img_sel_asset = images_dct[img_sel][0] path = img_sel_asset['path'] fname = img_sel_asset['filename'] src = os.path.join(path,fname) src = common.path_replace( src ) content += "<a href=\"#\" >\n" #content += "<img id=\"%s\" src=\"%s\" alt=\"TheStudio\" onclick=\"%s;\" onmouseover=\"%s;\" onmouseout=\"%s;\" />\n" % \ #(sel_id, src, "%s_click()" % sel_id, "%s_mouseover()" % sel_id, "%s_mouseout()" % sel_id ) content += "<img id=\"%s\" src=\"%s\" alt=\"TheStudio\" onclick=\"%s;\" />\n" % \ (sel_id, src, "%s_click()" % sel_id ) content += "</a>\n" return [ style, content, master_scr_dct ]
def expand_item( accum_ids, asset_def, images_dct, onclick=None, init_vis=None, ahref=None, exturl=False ): print "IMAGE EXPAND" # get the asset definition... asset_name = asset_def["asset_name"] item_def = images_dct[asset_name][0] # get id... htmlid = common.get_id(asset_name,accum_ids) accum_ids.append( htmlid ) # get basic properties... image_path = get_item_path( asset_name, images_dct ) x = get_attr( 'x', asset_name, asset_def, images_dct ) y = get_attr( 'y', asset_name, asset_def, images_dct ) z = get_attr( 'z', asset_name, asset_def, images_dct,'0') # init vis param override... #init = get_attr( 'init', asset_name, asset_def, images_dct ) #if init and not init_vis: #init_vis = init # mouseover... mouseover = get_attr( 'mouseover', asset_name, asset_def, images_dct ) onmouseover = "" if mouseover: onmouseover = mouse_script_item( htmlid, mouseover, images_dct ) # mouseout... mouseout = get_attr( 'mouseout', asset_name, asset_def, images_dct ) onmouseout = "" if mouseout: onmouseout = mouse_script_item( htmlid, mouseout, images_dct ) # onclick param override... click = get_attr('click', asset_name, asset_def, images_dct, '') if click!='' and onclick==None: onclick = click_script_items( click ) #parts = click.split(":") #onclick = click_script_item(parts[0], parts[1], parts[2], images_dct ) # style... style = "" style += common.emit_line( "#%s {" % htmlid ) style += common.emit_line( "position: absolute;") style += common.emit_line( "left: %dpx;" % int(x) ) style += common.emit_line( "top: %dpx;" % int(y) ) style += common.emit_line( "z-index: %d;" % int(z) ) style += common.emit_line( "border:none; " ) style += common.emit_line( "visibility: hidden;") #if init_vis!=None: #if init_vis: #style += common.emit_line( "visibility: %s;" % init_vis ) #else: #style += common.emit_line( "visibility: %s;" % init_vis ) style += common.emit_line( "}" ) # content... content = "" # a href... if ahref: if exturl: content += common.emit_line("<a href=%s target=\"_blank\" >\n" % ahref ) else: content += common.emit_line("<a href=%s >\n" % ahref ) else: content += common.emit_line("<a href=# >\n" ) # onclick script... if onclick: content += common.emit_line( "<img id=\"%s\" src=\"%s\" onclick=\"%s\" onmouseover=\"%s\" onmouseout=\"%s\" alt=\"TheStudio\" >" % \ (htmlid,image_path, onclick, onmouseover, onmouseout) ) else: content += common.emit_line( "<img id=\"%s\" src=\"%s\" onmouseover=\"%s\" onmouseout=\"%s\" alt=\"TheStudio\" >" % \ (htmlid,image_path, onmouseover, onmouseout ) ) # end a href... if ahref: content += common.emit_line("</a>\n" ) else: content += common.emit_line("</a>\n" ) if ( asset_name.find("caption_big") > 0 ): print "content->", content print "style->", style scriptlet_dct = {} scriptlet_dct['on'] = "document.getElementById('%s').style.visibility = '%s';" % (htmlid, 'visible' ) scriptlet_dct['off'] = "document.getElementById('%s').style.visibility = '%s';" % (htmlid, 'hidden' ) #if init_vis!=None: #scriptlet_dct['init'] = "document.getElementById('%s').style.visibility = '%s';" % (htmlid, init_vis) #else: scriptlet_dct['init'] = "document.getElementById('%s').style.visibility = 'visible';" % (htmlid) return [ style, content, "", scriptlet_dct ]
def do_POST(self): # if self.path=="/send_web": # # form = cgi.FieldStorage( # fp=self.rfile, # headers=self.headers, # environ={'REQUEST_METHOD':'POST', # 'CONTENT_TYPE':self.headers['Content-Type'], # }) # self.send_response(200) # self.end_headers() # textout = ["Nombre red: %s", # "Pswd: %s\n", # "Tu raspberry se esta conectando...", # "Si cometiste algun error, conectate al cable de Ethernet recarga la pagina y repite los pasos.", # ] # # self.wfile.write("SPKClient:. \n\n" + "\n".join(textout) % (form["ssid"].value,form["psk"].value)) # # if not spkwifi.set_wifi_network(form["ssid"].value.strip(), form["psk"].value.strip()): # self.wfile.write("Algo salio mal...") # # # return # if self.path=="/send_cncid": # form = cgi.FieldStorage( # fp=self.rfile, # headers=self.headers, # environ={'REQUEST_METHOD':'POST', # 'CONTENT_TYPE':self.headers['Content-Type'], # }) # # cncid= form["cncid"].value # # try: # if cncid.startswith("sudo"): # cncid = cncid.split("\"")[1] # # f = open(main.NEWCNCIDFILENAME,"w") # f.write(cncid) # f.close # # self.send_response(200) # self.end_headers() # # textout = ["ID: %s\n", # "Recarga la pagina en unos momentos.", # "Tu raspberry se esta reiniciando...", # "Revisa tu nueva maquina en el taller correspondiente." # ] # self.wfile.write("SPKClient:. \n\n" + "\n".join(textout) % (cncid)) # # common.restart_please() # #system("reboot") # #execl(sys.executable, *([sys.executable]+sys.argv)) # # except: # self.send_response(200) # self.end_headers() # self.wfile.write("Error, revisa el contenido de tu id") # # # return # if self.path=="/reset_client": # form = cgi.FieldStorage( # fp=self.rfile, # headers=self.headers, # environ={'REQUEST_METHOD':'POST', # 'CONTENT_TYPE':self.headers['Content-Type'], # }) # # # self.send_response(200) # self.end_headers() # self.wfile.write("El script de spkclient se esta reiniciando, ve a la pagina principal y recargala.") # common.restart_please() # return # if self.path=="/reset_pi": # form = cgi.FieldStorage( # fp=self.rfile, # headers=self.headers, # environ={'REQUEST_METHOD':'POST', # 'CONTENT_TYPE':self.headers['Content-Type'], # }) # # # self.send_response(200) # self.end_headers() # self.wfile.write("La raspberrypi se reiniciara...") # system("reboot") # return # if self.path=="/spkwizardsetup": data = cgi.FieldStorage( fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-Type'], }) action= data.getfirst("action", None) origin= self.headers.get("Origin",None) if not origin in ALLOWED_CONFIG_ORIGINS: self.send_response(403) return self.send_response(200) self.send_header('Content-type',"application/json") self.send_header('Access-Control-Allow-Origin',origin) self.end_headers() if action=="marco": if common.get_id()!=None: self.wfile.write(json.dumps({"status":"already_configured"})) else: self.wfile.write(json.dumps({"status":"polo","current_network":spkwifi.get_current_connected_network()})) elif action=="get_network_status": self.wfile.write(json.dumps({"status":"success","available_networks":[n.ssid for n in spkwifi.get_available_networks()],"current_network":spkwifi.get_current_connected_network()})) elif action=="set_wifi_network": ssid= data.getfirst("ssid", None) password= data.getfirst("password", None) if spkwifi.set_wifi_network(ssid, password): self.wfile.write(json.dumps({"status":"success","current_network":spkwifi.get_current_connected_network()})) else: self.wfile.write(json.dumps({"status":"error","current_network":spkwifi.get_current_connected_network()})) elif action=="send_workshop": config_data= json.loads(data.getfirst("config_data", "{}")) response=common.send_config_info(config_data) if "extra_info" in response: self.wfile.write(json.dumps({"status":"success","extra_info":response["extra_info"]})) else: self.wfile.write(json.dumps({"status":"error","reason":response.get("reason","")})) else: self.wfile.write(json.dumps({"status":"error"})) elif self.path=="/spkcnclocalcommandreceiver": data = cgi.FieldStorage( fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-Type'], }) origin= self.headers.get("Origin",None) local_token= data.getfirst("_local_token", None) prev_local_token= data.getfirst("_prev_local_token", None) if not origin in ALLOWED_CONFIG_ORIGINS or local_token==None or (local_token!=local_connection_token!=prev_local_token): self.send_response(403) return self.send_response(200) self.send_header('Content-type',"application/json") self.send_header('Access-Control-Allow-Origin',origin) self.end_headers() message= json.loads(data.getfirst("message", None)) command=message.get("command",None) if command=="checking_same_network": self.wfile.write(json.dumps({"status":"sure :)"})) elif command=="lifeline": time.sleep(60) self.wfile.write(json.dumps({"status":"sure :)"})) elif command=="get_network_status": self.wfile.write(json.dumps({"status":"success","available_networks":[n.ssid for n in spkwifi.get_available_networks()],"current_network":spkwifi.get_current_connected_network()})) elif command=="get_current_network": self.wfile.write(json.dumps({"status":"success","current_network":spkwifi.get_current_connected_network()})) elif command=="set_wifi_network": ssid= message.get("ssid", None) password= message.get("password", None) if spkwifi.set_wifi_network(ssid, password): self.wfile.write(json.dumps({"status":"success","current_network":spkwifi.get_current_connected_network()})) else: self.wfile.write(json.dumps({"status":"error","current_network":spkwifi.get_current_connected_network()})) elif command=="get_script_status_change": while True: if common.internet_thread.routine is None or common.internet_thread.routine.status.as_dict()!=message.get("last_status",None): break else: time.sleep(.01) if common.internet_thread.routine is not None: self.wfile.write(json.dumps({"status":common.internet_thread.routine.status.as_dict()})) else: self.wfile.write(json.dumps({"status":common.internet_thread.last_job_status.as_dict() if common.internet_thread.last_job_status is not None else None})) elif command=="send_console_line": if common.internet_thread.routine is None: try: self.console_manager.writeline(message.get("line","")) except: pass self.wfile.write(json.dumps({})) elif command=="console_line_poll": try: lines=None lastid=message.get("lastlineid",None) counter=0 response={"status":"success"} while common.internet_thread.routine is None and lines is None and counter <3: if message.get("i_think_there_is_no_serial",False): response["parser"]=common.get_parser() break #para que se quite el mensaje de que no hay serial lastid,lines=self.console_manager.readlines(lastid) counter+=1 response["lines"]=lines response["lastlineid"]=lastid self.wfile.write(json.dumps(response)) except DeadSerialException: self.wfile.write(json.dumps({"status":"error","reason":"no-serial"})) except: self.wfile.write(json.dumps({"status":"error"})) elif command =="jog_pressed_key": global current_jogging global jogging_cancel_timer try: if common.internet_thread.routine is None: key=message.get("key",None) pressed=message.get("pressed",None) possibles={38:"Y",40:"Y-",37:"X-",39:"X",33:"Z",34:"Z-"} #http://keycode.info/ usb=ThreadsafeSerial.get() parser=common.get_parser() if key in possibles and pressed is not None: if jogging_cancel_timer is not None: jogging_cancel_timer.cancel() if not pressed or (current_jogging is not None and current_jogging!=key): if parser=="tiny-g": usb.write("!%\n") #grbl mandar (! y ctrl x? cuando se frene?) current_jogging=None else: if message.get("new_pressed",False) and current_jogging is None: if parser=="tiny-g": usb.write("G91 G0 "+possibles[key]+"1000\nG90\n") #grbl mandar lo mismo? current_jogging=key jogging_cancel_timer=threading.Timer(0.5,lambda: usb.write("!%\n" if parser=="tiny-g" else "")) jogging_cancel_timer.start() usb.flushInput() except DeadSerialException: pass self.wfile.write(json.dumps({})) else: common.internet_thread.manage_response(message) self.wfile.write(json.dumps({}))
def main(): def addToTacPairCount(table, tac1, tac2): if re.match("[-+*\{\}]", tac1) or re.match("[-+*\{\}]", tac2): return if isVernacCmd(tac1) or isVernacCmd(tac2): return stem1 = get_stem(tac1) stem2 = get_stem(tac2) table[(stem1, stem2)] += 1 def addToTacticCount(table, tactic): if re.match("[-+*\{\}]", tactic): return if isVernacCmd(tactic): return stem = get_stem(tactic) table[stem] += 1 with open("users.txt", 'r') as usersfile: profiles = loads(usersfile.read()) all_tactics_count = collections.Counter() prev_count = collections.Counter() failed_prevs_count = collections.Counter() next_count = collections.Counter() cancelled_replaced_pairs = collections.Counter() cancel_lengths = collections.Counter() previous_tactic = '' just_cancelled = False just_failed = False total_cancels = 0 total_failures = 0 full_matching_cancels = 0 matching_stem_cancels = 0 for user in get_users(logdir): for session in get_sessions(logdir, user): cmds = get_commands(logdir, user, session) is_interactive = sublist_contained(cmds, [isCancel, lambda entry: not isCancel(entry)]) if not is_interactive: continue preprocessed_cmds = preprocess_vernac_backtrack( preprocess_failures(profiles, cmds)) cancel_lengths += get_cancel_lengths(preprocessed_cmds) history = [] for dat in preprocessed_cmds: if isAdd(dat): added_tactic = getAddBody(dat) if not isVernacCmd(added_tactic) and \ not isGoalPunctuation(added_tactic): stem = get_stem(added_tactic) assert not isVernacKeyword(stem), added_tactic assert stem.strip() != "", added_tactic all_tactics_count[stem] += 1 if just_cancelled: addToTacticCount(next_count, added_tactic) addToTacPairCount(cancelled_replaced_pairs, previous_tactic, added_tactic) if previous_tactic.strip() == added_tactic.strip(): full_matching_cancels += 1 try: if get_stem(previous_tactic) == get_stem(added_tactic): matching_stem_cancels += 1 except: pass just_cancelled = False previous_tactic = added_tactic history.append((get_id(dat)-1, added_tactic)) if isCancel(dat): total_cancels += 1 just_cancelled = True cancel_dest = getCancelDest(dat) while len(history) > 0 and history[-1][0] != cancel_dest: state_num, tactic = history.pop() addToTacticCount(prev_count, tactic) if isFailed(dat): total_failures += 1 addToTacticCount(failed_prevs_count, previous_tactic) print(cancel_lengths) print(f"Of {total_cancels} cancels, {total_failures} were failures ({100 * total_failures / total_cancels:3.2f}%)") print(f"Of those cancels, {full_matching_cancels} " f"({100 * full_matching_cancels / total_cancels:3.2f}%) " f"were replaced with the exact same tactic, " f"and {matching_stem_cancels} " f"({100 * matching_stem_cancels / total_cancels:3.2f}%) " f"were replaced by a tactic with the same stem") print("All tactics:") for tactic, count in all_tactics_count.most_common(50): print(f"{tactic}: {count} occurances") print("Tactics before cancel:") for tactic, count in prev_count.most_common(25): print(f"{tactic}: {count} cancels, {failed_prevs_count[tactic]} failures ({100 * failed_prevs_count[tactic] / count:3.2f}%)") print("Tactics after cancel:") for tactic, count in next_count.most_common(25): print(f"{tactic}: {count} run after cancel") print(cancelled_replaced_pairs.most_common(25))
def expand_item( accum_ids, page_item, images_dct, movies_dct, movie_panels_dct, embeds_dct ): asset_name = page_item["asset_name"] item_def = movie_panels_dct[asset_name] tot_style = "" tot_content = "" scriptlet_dct = {} scriptlet_dct['on'] = '' scriptlet_dct['off'] = '' scriptlet_dct['init'] = '' htmlid = common.get_id( asset_name, accum_ids ) accum_ids.append( htmlid ) for item in item_def: asn = item["asset_name"] if asn.startswith("mov"): style, content, scr_dct = gen_movies.expand_item( accum_ids, item, images_dct, movies_dct ) tot_style += style tot_content += content scriptlet_dct['on'] += scr_dct['on'] scriptlet_dct['off'] += scr_dct['off'] scriptlet_dct['init'] += scr_dct['init'] elif asn.startswith("img"): # determine the script, if any... script = None ahref = None exturl = None if item.has_key("link") and item["link"]!="": link = item["link"] if link.startswith("option:"): ltype,parm = link.split(":") funcname = "func_%s_%s" % (menu_name, parm) test = action_scripts[funcname] script = "%s ();" % funcname elif link.startswith("url:"): idx = link.find(":") + 1 ahref = link[idx:] print "MENUS AHREF->", ahref elif link.startswith("nurl:"): idx = link.find(":") + 1 ahref = link[idx:] exturl = True else: print "ERROR: gen_movie_panels: Unknown link type", asset_name, item sys.exit(1) style, content, foo, scr_dct = gen_images.expand_item( accum_ids, item, images_dct, script, None, ahref, exturl ) tot_style += style tot_content += content scriptlet_dct['on'] += scr_dct['on'] scriptlet_dct['off'] += scr_dct['off'] scriptlet_dct['init'] += scr_dct['init'] elif asn.startswith("embed"): style, content, foo, scr_dct = gen_embeds.expand_item( accum_ids, item, embeds_dct, images_dct, None, None) tot_style += style tot_content += content scriptlet_dct['on'] += scr_dct['on'] scriptlet_dct['off'] += scr_dct['off'] scriptlet_dct['init'] += scr_dct['init'] else: print "ERROR: gen_movie_panels: Cannot process->", item sys.exit(1) return [ tot_style, tot_content, scriptlet_dct ]
import common print(common.get_id())