def deactivate(panel_id): if Panel.find_one(id=panel_id): return db.run( "MATCH ()-[r]->() WHERE r.id=\"{}\" SET r.status=\"inactive\" RETURN r" .format(panel_id)).evaluate() log("Not found") return False
def print_stats(prefix, p1, c, t, avg_pos, avg_neg, avg_max, mAP): s1 = 'Correct: {0} / {1} - acc: {2:.4f} - mAP:{3:.4f}\n'.format( c, t, p1, mAP) s2 = 'AVG cosine sim (sq dist) values: pos: {0:.4f} ({1:.4f}), neg: {2:.4f} ({3:.4f}), max: {4:.4f} ({5:.4f})'.format( avg_pos, 2 - 2 * avg_pos, avg_neg, 2 - 2 * avg_neg, avg_max, 2 - 2 * avg_max) log(P, prefix + s1 + s2)
def reset_cvars(): """Walk over all modified cvar values and return them to their default expected values""" for var in CVARS["current"]: if DEBUG: print("Var: {0}, Value: {1}".format(var, CVARS["current"][var])) try: general.set_cvar(var, CVARS["current"][var]) except RuntimeError as exc: print( "Debug Views: WARNING - Unable to reset the CVAR {0} {1} due to error {2}".format( var, CVARS["current"][var], exc ) ) general.log( "Debug Views: WARNING - Unable to reset the CVAR {0} {1} due to error {2}".format( var, CVARS["current"][var], exc ) ) CVARS["current"].clear() CVARS["commands"] = None print("Debug Views: Reset To Default View Mode...") general.log("Debug Views: Resetting To Default View Mode...")
def create(source_id, destination_id, name, panel_type, num_of_ports, connector, height=-1): source_rack = Rack.find_one(by_id=source_id) destination_rack = Rack.find_one(by_id=destination_id) if not source_rack: log("Source rack not found") return False if not destination_rack: log("Destination rack not found") return False json_props = dict(id=uuid.uuid4(), name=name, panel_type=panel_type, num_of_ports=num_of_ports, connector=connector, status="active", height=height) source_rack_props = "{ id: \"" + str(source_id) + "\" }" destination_rack_props = "{ id: \"" + str(destination_id) + "\" }" cypher_query = """ MATCH (a:Rack {}), (b:Rack {}) CREATE (a)-[c:{} {}]->(b) RETURN c """.format(source_rack_props, destination_rack_props, panel_type.upper(), json_to_properties(json_props)) return db.run(cypher_query).evaluate()
def build_new_row(col="Hf"): disconnected = True releve = None while disconnected: try: releve = get_releve() except AttributeError: log("Web", "Hf connection failed", "New try in 60 seconds") reconnect() sleep(60) except requests.exceptions.ConnectionError: log("Web", "No internet for hf", "New try in 60 seconds") sleep(60) else: disconnected = False new_row = pd.DataFrame({ **{ "Date": [datetime.today().replace(second=0, microsecond=0)] }, **{ pseudo: [elem] for pseudo, elem in zip(releve["Pseudo"], releve[col]) } }) return new_row
def delete(panel_id): if Panel.find_one(id=panel_id): db.run("MATCH ()-[r]->() WHERE r.id=\"{}\" DELETE r".format( panel_id)).evaluate() return True log("Panel not found") return False
def update_hf_pickle(name="hunting_fields", save=True): name = "files/" + name archive = pd.read_pickle(name) new_row = build_new_row() archive = pd.concat([archive, new_row], axis=0, ignore_index=True) if save and not archive.iloc[-1, 1:].equals(archive.iloc[-2, 1:]): archive.to_pickle(name) log("Pickle", "Hunting fields", "Updated")
def add_cgfs(self): """spawn in each of our items from self.item_names and then select them""" num_cols = 25 x = 0 for idx, item in enumerate(self.cgf_files): if idx % num_cols == 0: # increment by some amount set by the last objects x width x += self.increment_amount ob = general.new_object("Brush", self.norm_path_for_ce(item), "", x, (idx % num_cols) * 0.23, 32) self.items.append(ob) general.select_object(ob) self.set_increment_amount() general.log("Added %s CGF Files to the map." % len(self.cgf_files))
def update_tech_pickle(name="tech", save=True): name = "files/" + name new_row = build_new_row("Tech") try: archive = pd.read_pickle(name) except FileNotFoundError: archive = new_row else: archive = pd.concat([archive, new_row], axis=0, ignore_index=True) if save: archive.to_pickle(name) log("Pickle", "Tech", "Updated")
def add_cgfs(self): """spawn in each of our items from self.item_names and then select them""" num_cols = 25 x = 0 for idx, item in enumerate(self.cgf_files): if idx % num_cols == 0: # increment by some amount set by the last objects x width x += self.increment_amount ob = general.new_object( "Brush", self.norm_path_for_ce(item), "", x, (idx % num_cols) * 0.23, 32 ) self.items.append(ob) general.select_object(ob) self.set_increment_amount() general.log("Added %s CGF Files to the map." % len(self.cgf_files))
def output_stats(train_type, P, test_print, test_net, net, testset_tuple, epoch, batch_count, is_final, loss, running_loss, score): disp_int = P.train_loss_int running_loss += loss if batch_count % disp_int == disp_int - 1: log( P, '[{0:d}, {1:5d}] loss: {2:.5f}'.format(epoch + 1, batch_count + 1, running_loss / disp_int)) running_loss = 0.0 test_int = P.train_test_int if ((test_int > 0 and batch_count % test_int == test_int - 1) or (test_int <= 0 and is_final)): score = test_print(train_type, P, net, testset_tuple, test_net, score, epoch + 1) return running_loss, score
def test_print_classif(train_type, P, net, testset_tuple, test_net, best_score=0, epoch=0): test_set, test_train_set = testset_tuple set_net_train(net, False) c, t = test_net(net, test_set) if (c > best_score): best_score = c prefix = '{0}, EPOCH:{1}, SCORE:{2}'.format(train_type, epoch, c) save_uuid(P, prefix) torch.save(net.state_dict(), path.join(P.save_dir, unique_str(P) + "_best_classif.pth.tar")) log(P, 'TEST - correct: {0} / {1} - acc: {2}'.format(c, t, float(c) / t)) c, t = test_net(net, test_train_set) torch.save(net.state_dict(), path.join(P.save_dir, "model_classif_" + str(epoch) + ".pth.tar")) log(P, 'TRAIN - correct: {0} / {1} - acc: {2}'.format(c, t, float(c) / t)) set_net_train(net, True, bn_train=P.train_bn) return best_score
def toggleCvarsValue(mode, cVars, onValue, offValue): currentValue = general.get_cvar(cVars) if type(onValue) is str: saveDefaultValue(cVars, currentValue) elif type(onValue) is int: saveDefaultValue(cVars, int(currentValue)) elif type(onValue) is float: saveDefaultValue(cVars, float(currentValue)) else: general.log('Failed to store default value for {0}'.format(cVars)) if currentValue == str(onValue): general.set_cvar(cVars, offValue) else: general.set_cvar(cVars, onValue)
def art(): """Art related debug views.""" if "e_debugdraw" not in CVARS["current"]: # Since it was desired to mix and match cvars, supporting additional cvar calls before we jump into cycling eDebugDraw if "r_wireframe" not in CVARS["current"]: try: general.set_cvar("r_wireframe", 1) CVARS["current"]["r_wireframe"] = 0 except RuntimeError as exc: print("Debug Views: WARNING - Unable to set r_wireframe 1") general.log( "Debug Views: WARNING - Unable to set r_wireframe 1") else: try: general.set_cvar("r_wireframe", 0) general.set_cvar("r_showlines", 2) CVARS["current"]["e_debugdraw"] = 0 except RuntimeError as exc: print("Debug Views: WARNING - Unable to set r_wireframe 1") general.log( "Debug Views: WARNING - Unable to set r_wireframe 1") else: # disabling any of the mixed cvars that could have been set above try: general.set_cvar("r_wireframe", 0) general.set_cvar("r_showlines", 0) except: pass eDebugDraw = cvar( "e_debugdraw", 0, "art", "E_DEBUGDRAW - Review Art Assets LODs \ Texture Memory \ Render Mat Count \ Phys Tri Count.", ) # NOTE: I removed e_debugdraw 1 because it was crashing after the 3.6 integration eDebugDraw.add_value(4, "Texture memory total for each object.") eDebugDraw.add_value(5, "Renderable material counts for each object.") eDebugDraw.add_value(19, "Physics triangle count for each object.") eDebugDraw.add_value( 22, "Current LOD index and its corrisponding vertex count for each object." ) eDebugDraw.next_value()
def art(): """Art related debug views.""" if "e_debugdraw" not in CVARS["current"]: # Since it was desired to mix and match cvars, supporting additional cvar calls before we jump into cycling eDebugDraw if "r_wireframe" not in CVARS["current"]: try: general.set_cvar("r_wireframe", 1) CVARS["current"]["r_wireframe"] = 0 except RuntimeError as exc: print("Debug Views: WARNING - Unable to set r_wireframe 1") general.log("Debug Views: WARNING - Unable to set r_wireframe 1") else: try: general.set_cvar("r_wireframe", 0) general.set_cvar("r_showlines", 2) CVARS["current"]["e_debugdraw"] = 0 except RuntimeError as exc: print("Debug Views: WARNING - Unable to set r_wireframe 1") general.log("Debug Views: WARNING - Unable to set r_wireframe 1") else: # disabling any of the mixed cvars that could have been set above try: general.set_cvar("r_wireframe", 0) general.set_cvar("r_showlines", 0) except: pass eDebugDraw = cvar( "e_debugdraw", 0, "art", "E_DEBUGDRAW - Review Art Assets LODs \ Texture Memory \ Render Mat Count \ Phys Tri Count.", ) # NOTE: I removed e_debugdraw 1 because it was crashing after the 3.6 integration eDebugDraw.add_value(4, "Texture memory total for each object.") eDebugDraw.add_value(5, "Renderable material counts for each object.") eDebugDraw.add_value(19, "Physics triangle count for each object.") eDebugDraw.add_value( 22, "Current LOD index and its corrisponding vertex count for each object." ) eDebugDraw.next_value()
def send_pm(player_name=None, subject="", text="No text"): if player_name is None: player_name = get_identifiants_fmz()[0] url = "http://s1.fourmizzz.fr/messagerie.php?defaut=Ecrire&destinataire=" + player_name cookies = {'PHPSESSID': get_identifiants_fmz()[-1]} options = webdriver.ChromeOptions() options.add_argument('--headless') options.add_argument("--start-maximized") driver = webdriver.Chrome(options=options) try: driver.get(url) for key, value in cookies.items(): driver.add_cookie({'name': key, 'value': value}) driver.get(url) # write object wait_for_elem( driver, "/html/body/div[4]/div[1]/div[6]/div[1]/div[2]/span/input", By.XPATH, 5).click() wait_for_elem(driver, "/html/body/div[4]/div[1]/div[6]/div[1]/div[2]/span/input", By.XPATH, 5)\ .send_keys(subject) # write main text wait_for_elem( driver, "/html/body/div[4]/div[1]/div[6]/div[1]/div[3]/span/textarea", By.XPATH, 5).click() wait_for_elem(driver, "/html/body/div[4]/div[1]/div[6]/div[1]/div[3]/span/textarea", By.XPATH, 5)\ .send_keys(text) # send pm wait_for_elem( driver, "/html/body/div[4]/div[1]/div[6]/div[1]/div[4]/span[1]/input", By.XPATH, 50).click() finally: driver.close() driver.quit() log("Web", "Mp sent", "Mp sent to " + player_name)
def find_all_between_racks(rack1_id, rack2_id): if not Rack.find_one(by_id=rack1_id): log("Rack 1 not found") return False if not Rack.find_one(by_id=rack2_id): log("Rack 2 not found") return False cypher_query = """ MATCH (a)-[r]->(b) WHERE a.id=\"{}\" AND b.id=\"{}\" return r """.format(rack1_id, rack2_id) r1 = db.run(cypher_query).data() cypher_query = """ MATCH (a)-[r]->(b) WHERE a.id=\"{}\" AND b.id=\"{}\" return r """.format(rack2_id, rack1_id) r2 = db.run(cypher_query).data() if r1 and r2: return [i["r"] for i in r1] + [i["r"] for i in r2] if r1: return [i["r"] for i in r1] return [i["r"] for i in r2]
def reset_cvars(): """Walk over all modified cvar values and return them to their default expected values""" for var in CVARS["current"]: if DEBUG: print("Var: {0}, Value: {1}".format(var, CVARS["current"][var])) try: general.set_cvar(var, CVARS["current"][var]) except RuntimeError as exc: print( "Debug Views: WARNING - Unable to reset the CVAR {0} {1} due to error {2}" .format(var, CVARS["current"][var], exc)) general.log( "Debug Views: WARNING - Unable to reset the CVAR {0} {1} due to error {2}" .format(var, CVARS["current"][var], exc)) CVARS["current"].clear() CVARS["commands"] = None print("Debug Views: Reset To Default View Mode...") general.log("Debug Views: Resetting To Default View Mode...")
def update_convoys(new_convoys=None): if new_convoys is None: disconnected = True new_convoys = None while disconnected: try: new_convoys = get_new_convoys() except TimeoutException: log("Web", "Convoys connection failed", "New try in 60 seconds") reconnect() sleep(60) except InvalidCookieDomainException: log("Web", "No internet for convoys", "New try in 60 seconds") sleep(60) else: disconnected = False old_convoys = pd.read_pickle("files/convoys") old_convoys = old_convoys.append(new_convoys).reset_index().drop("index", axis=1) old_convoys["Date"] = pd.to_datetime(old_convoys["Date"], format='%Y-%m-%d %H:%M:%S') old_convoys.drop_duplicates(inplace=True) old_convoys.sort_values(by="Date", inplace=True) old_convoys.to_pickle("files/convoys") log("Pickle", "Convoys", "Updated")
def reconnect(): pseudo, mdp, cook = get_identifiants_fmz() url = "http://s1.fourmizzz.fr" cookies = {'PHPSESSID': cook} options = webdriver.ChromeOptions() options.add_argument('--headless') options.add_argument("--start-maximized") driver = webdriver.Chrome(options=options) try: driver.get(url) for key, value in cookies.items(): driver.add_cookie({'name': key, 'value': value}) driver.get(url) wait_for_elem(driver, "//*[@id='loginForm']/table/tbody/tr[2]/td[2]/input", By.XPATH).click() wait_for_elem(driver, "//*[@id='loginForm']/table/tbody/tr[2]/td[2]/input", By.XPATH).send_keys(pseudo) wait_for_elem(driver, "//*[@id='loginForm']/table/tbody/tr[3]/td[2]/input", By.XPATH).click() wait_for_elem(driver, "//*[@id='loginForm']/table/tbody/tr[3]/td[2]/input", By.XPATH).send_keys(mdp) wait_for_elem(driver, "//*[@id='loginForm']/input[2]", By.XPATH).click() except TimeoutException: log("Web", "Reconnection", "Reconnection failed") finally: driver.close() driver.quit()
def next_value(self): if not self.values: return for value, desc in self.values: if value == self.curValue: curIdx = self.values.index((value, desc)) if curIdx + 1 == len(self.values): reset_cvars() return try: valueNext, descNext = self.values[curIdx + 1] if DEBUG: print( "NextValue: {0} Next Label: {1}".format(valueNext, descNext) ) self.set_value(valueNext, descNext) general.log( "Debug Views: Now Showing {0}, {1}".format(valueNext, descNext) ) return except Exception as exc: if DEBUG: print("ERROR: Exception Met: {0}".format(exc)) reset_cvars() return try: valueNext, descNext = self.values[0] self.set_value(valueNext, descNext) general.log(" ") general.log( "Debug Views: Starting Debug View Mode: {0}, This Mode Is Driven By The CVar: {1}".format( self.category, self.name ) ) general.log( "Debug Views: Now Showing {0} {1}, {2}".format( self.name, valueNext, descNext ) ) except Exception as exc: if DEBUG: print("ERROR: Exception Met: {0}".format(exc)) reset_cvars()
def next_value(self): if not self.values: return for value, desc in self.values: if value == self.curValue: curIdx = self.values.index((value, desc)) if curIdx + 1 == len(self.values): reset_cvars() return try: valueNext, descNext = self.values[curIdx + 1] if DEBUG: print("NextValue: {0} Next Label: {1}".format( valueNext, descNext)) self.set_value(valueNext, descNext) general.log("Debug Views: Now Showing {0}, {1}".format( valueNext, descNext)) return except Exception as exc: if DEBUG: print("ERROR: Exception Met: {0}".format(exc)) reset_cvars() return try: valueNext, descNext = self.values[0] self.set_value(valueNext, descNext) general.log(" ") general.log( "Debug Views: Starting Debug View Mode: {0}, This Mode Is Driven By The CVar: {1}" .format(self.category, self.name)) general.log("Debug Views: Now Showing {0} {1}, {2}".format( self.name, valueNext, descNext)) except Exception as exc: if DEBUG: print("ERROR: Exception Met: {0}".format(exc)) reset_cvars()
def update(rack_id=None, name=None, site=None, building=None, room=None): if rack_id: if not Rack.find_one(by_id=rack_id): log("Rack not found") return False props = [] if name: props.append("a.name=\"{}\"".format(name)) if site: props.append("a.site=\"{}\"".format(site)) if building: props.append("a.building=\"{}\"".format(building)) if room: props.append("a.room=\"{}\"".format(room)) if props: props_str = "SET " + ", ".join(props) else: log("Nothing to update") return False cypher_query = "MATCH (a: Rack { id: \"" + str(rack_id) + "\"}" + ") {} RETURN a".format(props_str) return db.run(cypher_query).evaluate() log("Must provide rack id") return False
def update(panel_id, **kwargs): props = [] p = Panel.find_one(id=panel_id) if not p: log("Panel not found") return False for key, value in kwargs.iteritems(): if key in dict(p): if key == "id": log("Panel id is not changeable") continue if type(value) in [int, float]: props.append("r.{}={}".format(key, value)) else: props.append("r.{}=\"{}\"".format(key, value)) if props: props_str = ", ".join(props) cypher_query = """ MATCH ()-[r]->() WHERE r.id=\"{}\" SET {} RETURN r """.format(panel_id, props_str) return db.run(cypher_query).evaluate() log("No updates were made") return False
import json import falcon from requests import codes from requests.exceptions import ConnectionError from general import log, getEnvVar, isDocker from falcon_app_template import app SERVICE_TYPE = "apigateway" logger = log(SERVICE_TYPE).logger if getEnvVar('MTLS', False): PROT = 'https' from muServSec import ServiceCert, Requests serviceCert = ServiceCert(logger, SERVICE_TYPE, True) requests = Requests(serviceCert) else: PROT = 'http' import requests if isDocker(): USERS_SERVICE_URL = '%s://%s:%s/' % (PROT, "users", 80) ACCOUNTS_SERVICE_URL = '%s://%s:%s/' % (PROT, "accounts", 80) TRANSACTIONS_SERVICE_URL = '%s://%s:%s/' % (PROT, "transactions", 80) PAYMENT_SERVICE_URL = '%s://%s:%s/' % (PROT, "payment", 80) else: USERS_SERVICE_URL = '%s://%s:%s/' % (PROT, '0.0.0.0', 9081) ACCOUNTS_SERVICE_URL = '%s://%s:%s/' % (PROT, '0.0.0.0', 9082) TRANSACTIONS_SERVICE_URL = '%s://%s:%s/' % (PROT, '0.0.0.0', 9083)
import time import xbmc import xbmcaddon import sys import general if __name__ == '__main__': general.log("SyncPlay start: " + str(time.time()) + str(sys.argv), level=xbmc.LOGNOTICE) monitor = xbmc.Monitor() addon_id = 'plugin.video.syncplay' selfAddon = xbmcaddon.Addon(addon_id) autostart = selfAddon.getSetting('autostart').lower() == 'true' ip1 = selfAddon.getSetting('ip1') ip2 = selfAddon.getSetting('ip2') ip3 = selfAddon.getSetting('ip3') ip4 = selfAddon.getSetting('ip4') ips = [ip1, ip2, ip3, ip4] general.log("Autostart: " + str(autostart) + str(ips), level=xbmc.LOGNOTICE) if autostart: #check for autostart videos = general.get_videos(ips, True) general.log("Found Videos: " + str(videos), level=xbmc.LOGNOTICE) if videos is not None and len(videos) > 0:
def get_new_convoys(): """Returns a dataframe with all the convoys in 'SDC_Convois'""" url = "http://s1.fourmizzz.fr/alliance.php?forum_menu" cookies = {'PHPSESSID': get_identifiants_fmz()[-1]} forum_id = "forum61251.categorie_forum" # Opens webDriver options = webdriver.ChromeOptions() options.add_argument('--headless') options.add_argument("--start-maximized") driver = webdriver.Chrome(options=options) try: driver.get(url) for key, value in cookies.items(): driver.add_cookie({'name': key, 'value': value}) driver.get(url) # Click on the forum name wait_for_elem(driver, forum_id, By.CLASS_NAME).click() sleep(2) df_convois = pd.DataFrame( columns=["Date", "Livreur", "Destinataire", "Quantite"]) # Mark every subforum as read i = 2 while i > 0: try: # if it's an "important" topic or there are no messages // or it's locked, if len(driver.find_elements_by_xpath("//*[@id='form_cat']/table/tbody/tr["+str(i)+"]/td[1]/img")) > 0 \ or int(wait_for_elem(driver, "//*[@id='form_cat']/table/tbody/tr["+str(i+1)+"]/td/div/strong", By.XPATH, 2).text) == 0: # or (len(driver.find_elements_by_xpath("//*[@id='form_cat']/table/tbody/tr[" # + str(i) + "]/td[2]/img")) > 0 # and wait_for_elem(driver,"//*[@id='form_cat']/table/tbody/tr["+str(i)+"]/td[2]/img", By.XPATH, # 2).get_attribute('alt') == "Fermé"): i += 2 continue # Click to open the sub forum wait_for_elem( driver, "//*[@id='form_cat']/table/tbody/tr[" + str(i) + "]/td[2]/a", By.XPATH, 2).click() sleep(2) # Wait for the page to load # Reset the forum driver.get(url) # Click on the forum name try: wait_for_elem(driver, forum_id, By.CLASS_NAME).click() except TimeoutException: forum_id = forum_id.replace("categorie_forum", "ligne_paire") wait_for_elem(driver, forum_id, By.CLASS_NAME).click() sleep(1) # Waits if the element didn't load yet except (StaleElementReferenceException, IndexError): sleep(0.5) # Leave the loop if there is no more sub forum to read except TimeoutException: break # Go to the next sub forum else: i += 2 # Check every sub forum for convoys i = 2 while i > 0: try: # if it's an "important" topic or there are no messages // or it's locked, if len(driver.find_elements_by_xpath("//*[@id='form_cat']/table/tbody/tr["+str(i)+"]/td[1]/img")) > 0 \ or int(wait_for_elem(driver, "//*[@id='form_cat']/table/tbody/tr["+str(i+1)+"]/td/div/strong", By.XPATH, 2).text) == 0: # or (len(driver.find_elements_by_xpath("//*[@id='form_cat']/table/tbody/tr[" # + str(i) + "]/td[2]/img")) > 0 # and wait_for_elem(driver,"//*[@id='form_cat']/table/tbody/tr["+str(i)+"]/td[2]/img", By.XPATH, # 2).get_attribute('alt') == "Fermé"): i += 2 continue topic_name = wait_for_elem( driver, "//*[@id='form_cat']/table/tbody/tr[" + str(i) + "]/td[2]/a", By.XPATH, 2).text # Find the name of the requester and the amount requested try: destinataire, total_amount = topic_name.split(" - ")[1:3] except ValueError: continue total_amount = int( EngNumber( total_amount.replace(" ", "").replace("\u202f", ""))) # Click to open the sub forum wait_for_elem( driver, "//*[@id='form_cat']/table/tbody/tr[" + str(i) + "]/td[2]/a", By.XPATH, 2).click() sleep(2) # Wait for the page to load # Read every message inside the forum j = 2 while j > 0: try: # Read the date of the convoy annee = datetime.today().year # if it's a new message, adapt the Xpath if len( driver.find_elements_by_xpath( "//*[@id='forum']/div[" + str(j + 1) + "]/img")) > 0: date = wait_for_elem(driver, "//*[@id='forum']/div["+str(j+1)+"]/span[2]", By.XPATH, 1)\ .text.split() else: date = wait_for_elem(driver, "//*[@id='forum']/div["+str(j+1)+"]/span", By.XPATH, 1)\ .text.split() if len(date) == 5: annee = int(date[2]) del date[2] mois = [ "janv.", "févr.", "mars", "avril", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc." ] date = datetime( annee, mois.index(date[1]) + 1, int(date[0]), *(int(elem) for elem in date[3].split("h"))) if date > datetime.today(): date = datetime(date.year - 1, date.month, date.day, date.hour, date.minute) # Read the sender livreur = wait_for_elem( driver, "//*[@id='forum']/div[" + str(j + 1) + "]/a", By.XPATH, 2).text # Read the quantity quantite = wait_for_elem( driver, "//*[@id='forum']/div[" + str(j + 2) + "]", By.XPATH, 2).text try: quantite = [ int( match.replace("mat", "").replace("à", "").replace( "et", "")) for match in re.findall( "et[0-9]+mat|et[0-9]+à", quantite.replace(" ", "")) ] except AttributeError: log( "Web", "Convoy entry incorrect", "{} {} {} '" '{}' "'".format(date, livreur, destinataire, quantite)) else: # If everything is right, append the convoy to the dataframe if len(df_convois.index) > 0 \ and df_convois.at[df_convois.index[-1], "Date"].minute == date.minute: date += timedelta( seconds=df_convois.at[df_convois.index[-1], "Date"].second + 1) for s, match in enumerate(quantite): df_convois = df_convois.append( pd.DataFrame({ "Date": [date + timedelta(seconds=s)], "Livreur": [livreur], "Destinataire": [destinataire], "Quantite": [match] }), ignore_index=True) total_amount -= match # Leave the loop if there is no more message to read except TimeoutException: # Calculate the remaining amount if needed if wait_for_elem(driver, "//*[@id='forum']/div["+str(j-1)+"]/a", By.XPATH, 2).text \ != get_identifiants_fmz()[0] \ or len(quantite) > 0: convoy_link = get_convoy_link(destinataire) post_forum( "[url=" + convoy_link + "]" + destinataire + "[/url]\n\n" + "Reste: " + '{:,}'.format(total_amount).replace(",", " "), forum_id, topic_name) log("Forum", "Convoy countdown update", destinataire + "'s convoys updated") if total_amount <= 0: send_pm( get_identifiants_fmz()[0], "[Convoys finished]", destinataire + "'s convoys finished, activation requested" ) break # Go to the next message else: j += 2 # Reset the forum driver.get(url) # Click on the forum name wait_for_elem(driver, forum_id, By.CLASS_NAME).click() sleep(1) # Waits if the element didn't load yet except (StaleElementReferenceException, IndexError): sleep(0.5) # Leave the loop if there is no more sub forum to read except TimeoutException: break # Go to the next sub forum else: i += 2 finally: driver.close() driver.quit() # Reset the indices just in case df_convois.reset_index(inplace=True, drop=True) return df_convois
import os from flask import Flask, request, abort from requests import codes from requests.exceptions import ConnectionError from werkzeug.exceptions import NotFound, ServiceUnavailable from general import log, getEnvVar, isDocker, niceJson, allLinks # Use the name of the current directory as a service type serviceType = os.path.basename(os.getcwd()) logger = log(serviceType).logger # Setup MiSSFire try: PROT = 'http' if getEnvVar('MTLS', False) or getEnvVar('TOKEN', False): from MiSSFire import Requests requests = Requests() if getEnvVar('MTLS', False): PROT = 'https' if getEnvVar('TOKEN', False): from MiSSFire import jwt_conditional else: def jwt_conditional(reqs): def real_decorator(f): return f return real_decorator
'Materials/Special/green_screen.mtl') # set the physobj to be the selected brush object user_selection_brush = str(lodtools.getselected()) general.set_entity_geometry_file(PHYS_OBJECT_NAME, user_selection_brush) # 3. snap physobj to xform of selected object general.set_position(PHYS_OBJECT_NAME, int(obj_pos[0]), int(obj_pos[1]), int(obj_pos[2])) general.set_rotation(PHYS_OBJECT_NAME, int(obj_rot[0]), int(obj_rot[1]), int(obj_rot[2])) general.set_scale(PHYS_OBJECT_NAME, int(obj_scale[0]), int(obj_scale[1]), int(obj_scale[2])) # 5 Hide user selection object general.log("hiding " + user_selection) general.hide_object(user_selection) # 6. simulate physobj # select the physics object general.select_object(PHYS_OBJECT_NAME) # simulate it physics.simulate_selection() else: print('Converting Physics Object to Brush') # get the state of the physics objects physics.get_state(PHYS_OBJECT_NAME) # get the transforms of the simulated physics object phys_pos = general.get_position(PHYS_OBJECT_NAME) phys_rot = general.get_rotation(PHYS_OBJECT_NAME)