def sample_move(board) -> str: possible_moves = list(board.legal_moves) debug_print(f"Legal moves: {str(possible_moves)}") move = choice(possible_moves) debug_print(f"Move chosen: {move}") board.push(move) return board.uci(move)
def validate_activity(session_token: str) -> bool: """ Refreshes the last_seen timestamp for the given token. Also removes old sessions (auto logout) Raises ClientIpChangedException if client's ip address changed since last activity (possible mitm) :param session_token: str A valid session token :return: bool Success """ if not is_valid(session_token): debug_print( 'Auth: Session token is not valid: {}'.format(session_token)) return False session_record = get_session_record(session_token) if session_record['client_ip'] != get_client_ip(): raise ClientIpChangedException("IP was {}, but is {} now".format( session_record['client_ip'], get_client_ip())) session_record['last_seen'] = time.time() mc = get_memcache() key = _get_session_record_id(session_token) return mc.replace(key, _serialize_session_record(session_record)) != 0
def is_valid(session_token: str) -> bool: """ Returns a bool indicating whether the given session token is valid. A session token is valid if: 1) someone has logged in and the token was handed out to them AND 2) the timedelta from the last activity with this token to now doesn't exceed the session ttl AND 3) the token wasn't revoked (by logging out a user) Having a valid session token means you're allowed to do stuff However, this method should not be used to manually check if the current client has permissions, as it doesn't do IP pinning. Token validation is done automatically before each request is processed and if a client is accessing without permissions, the API automatically redirects. :param session_token: A session token :return: bool """ if type(session_token) != str: raise TypeError session_record = get_session_record(session_token) if session_record is None: debug_print('Auth: No session record found in MC.') return False if time.time() - session_record['last_seen'] > session_record['ttl']: invalidate(session_token) debug_print('Auth: Session token expired: {}'.format(session_token)) return False return True
def distancia_entre(A, B): debug_print(ARCHIVO, "distancia_entre", {"A": A, "B": B}) resultado = (((A[0] - B[0])**2) + ((A[1] - B[1])**2)) resultado = resultado**(1 / 2.0) debug_print(ARCHIVO, "distancia_entre", {"resultado": resultado}) return round(resultado, 5)
def invalidate_path_cache(path: str): """ Create a CDN invalidation for the specified path Args: path: distribution-relative path to the file to be invalidated Returns: """ cdn_id = get_config('cdn_distribution_id') if cdn_id: debug_print('Invalidate "%s" in "%s"' % (path, cdn_id)) try: client = boto3.client('cloudfront') reference = datetime.now().strftime('%Y%m%d%H%M%S') invalidation = client.create_invalidation(DistributionId=cdn_id, InvalidationBatch={ 'Paths': { 'Quantity': 1, 'Items': [path] }, 'CallerReference': 'beerbot_upload_' + reference }) print({'invalidation': invalidation}) debug_print('end invalidation') except Exception as e: print({'invalidation: Exception': e})
def fetch_items(self, item_ids, callback=None, min_delay=0): """ Fetch items for item ids Output format: {id1: {item1}, id2: {item2}, ...} Failed items might appear as LostItem instances instead of attribute dictionaries """ debug_print(">> fetch_items") items = {} for item_id in item_ids: # Skip items that have been recently updated, if requested if min_delay > 0: db_item = db.session.query(Item).get(item_id) if db_item is not None and min_delay > ( datetime.utcnow() - db_item.date_updated).total_seconds(): debug_print("Skipped item %d because it's too fresh" % item_id) continue api_item = self.fetch_item(item_id) items[item_id] = api_item if callback is not None: callback(api_item) return items
def new(party_id: int, party_type: PartyTypes = PartyTypes.DataClient, ttl: int = 1800) -> Optional[str]: """ Inserts a new session record for the party. Also pins the session to the clients IP to help with mitm attacks on session tokens. :param party_type: PartyTypes The type of Party whose session this is :param party_id: str The uuid of the associated party :param ttl: int Optional maximum time without activity before logout :return: bool Session token """ session_token = os.urandom(g._config['AUTH_SESSION_TOKEN_LENGTH']).hex() while is_valid(session_token): session_token = os.urandom( g._config['AUTH_SESSION_TOKEN_LENGTH']).hex() assert type(ttl) == int session_record = _build_session_record(party_id, party_type, ttl) debug_print("Auth: Inserting session record {}".format(session_record)) mc = get_memcache() if mc.set(_get_session_record_id(session_token), session_record) != 0: return session_token return None
def update(self, block_count, block_size, total_size): """Callback with count of blocks transferred so far, block size in bytes and the total size of the file in bytes.""" utils.debug_print("Download.update called with block_count: %s \ block_size: %s total_size: %s" % (block_count, block_size, total_size)) current_size = block_count * block_size if current_size > self.current_size: self.current_size = current_size self.old_total_size = self.total_size self.total_size = total_size current_bytes = float(block_count * block_size) / 1024 / 1024 total_bytes = float(total_size) / 1024 / 1024 try: percent_complete = 100 * current_bytes / total_bytes if percent_complete > self.percent_complete: self.percent_complete = percent_complete except ZeroDivisionError: self.percent_complete = 0 if self.percent_complete > 100: self.percent_complete = 100 if not self.has_started: self.has_started = True self.set_status(DOWNLOADING) if self.status != COMPLETED and self.percent_complete == 100: self.set_status(COMPLETED) utils.debug_print("Percent complete: %s" % self.percent_complete) self.emit("update", int(block_count), int(block_size), int(total_size))
def lista_to_dict(rutas): debug_print(ARCHIVO, "lista_to_dict") lista = [] for ruta in rutas: print(ruta.to_dict()) lista.append(ruta.to_dict()) return lista
def generate(self): model_path = os.path.expanduser(self.model_path) assert model_path.endswith( '.h5'), 'Keras model or weights must be a .h5 file.' # Load model, or construct model and load weights. num_anchors = len(self.anchors) num_classes = len(self.class_names) debug_print("num_anchors: %d, num_classes: %d" % (num_anchors, num_classes)) is_tiny_version = num_anchors == 6 # default setting try: self.yolo_model = load_model(model_path, compile=False) except: if is_tiny_version: self.yolo_model = tiny_yolo_body(Input(shape=(None, None, 3)), num_anchors // 2, num_classes) else: self.yolo_model = yolo_body(Input(shape=(None, None, 3)), num_anchors // 3, num_classes) # self.yolo_model = tiny_yolo_body(Input(shape=(None, None, 3)), # num_anchors//2, num_classes) \ # if is_tiny_version else yolo_body(Input(shape=(None, None, 3)), # num_anchors//3, num_classes) self.yolo_model.load_weights( self.model_path) # make sure model, anchors and classes match else: assert self.yolo_model.layers[-1].output_shape[-1] == \ num_anchors/len(self.yolo_model.output) * (num_classes + 5), \ 'Mismatch between model and given anchor and class sizes' debug_print( '{} model, anchors, and classes loaded.'.format(model_path)) # Generate colors for drawing bounding bboxes. hsv_tuples = [(x / len(self.class_names), 1., 1.) for x in range(len(self.class_names))] self.colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples)) self.colors = list( map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), self.colors)) np.random.seed(10101) # Fixed seed for consistent colors across runs. np.random.shuffle( self.colors) # Shuffle colors to decorrelate adjacent classes. np.random.seed(None) # Reset seed to default. # Generate output tensor targets for filtered bounding bboxes. self.input_image_shape = K.placeholder(shape=(2, )) if self.gpu_num >= 2: self.yolo_model = multi_gpu_model(self.yolo_model, gpus=self.gpu_num) bboxes, scores, classes = yolo_eval(self.yolo_model.output, self.anchors, len(self.class_names), self.input_image_shape, score_threshold=self.score, iou_threshold=self.iou) return bboxes, scores, classes
def fetch_top_story_ids(self): """ Fetch stories from top 100 items on front page Ordered by current front page rank """ debug_print(">> fetch_top_story_ids") return self.firebase.get('topstories', None)
def remove_disponible_by_id(self, id): debug_print(ARCHIVO, "remove_disponible_by_id", {"id": id}) for disponible in self.disponibles: if (disponible.id == id): self.disponibles.remove(disponible) debug_print(ARCHIVO, "remove_disponible_by_id", {"self.disponibles": self.disponibles})
def __init__(self, id, coordenadas): debug_print(ARCHIVO, "__init__", str({ "id": id, "coordenadas": coordenadas })) self.id = id self.coordenadas = coordenadas
def close(self): """do some operations when system is closing, like logging the blocks with the packets that have not been acked or sent.""" for block_id, packet_list in self.ack_blocks.items(): if self.is_sent_block(block_id): continue debug_print("block {} not finished!".format(block_id)) self.log_block(self.blocks_status[block_id]) return None
def close(self): """close all the application before closing this system.""" self.flush_log() for sender in self.senders: debug_print("sender {} wait_for_push_packets size {}".format( sender.id, len(sender.wait_for_push_packets))) if sender.application: sender.application.close(self.cur_time)
def init_divice(device, debug=False): try: device = evdev.InputDevice('/dev/input/event' + str(device)) utils.debug_print('Device file found', debug) return device except: utils.debug_print('No Device file found', debug) return None
def __save_xml(self): """Adds a header and indents the xml tree before saving it to disk.""" utils.debug_print("Saved download list to: %s" % self.download_file_path) file = open(self.download_file_path, "w") file.write(XML_HEADER) utils.indent(self.tree.getroot()) self.tree.write(file) file.close()
def set_status(self, status): self.old_status = self.status self.status = status utils.debug_print("Download status for %s changed to: %s (%s)" % (self, self.get_status_string(), status)) for download_obj in self.dbus_service.download_objects: if download_obj.download == self: download_obj.StatusChanged(STATUS_STRINGS[status]) self.emit("status-changed", status)
def __append_download(self, download): """Connects to the download signals we are interested in before adding the download object to the list of downloads.""" download.connect("update", self.__download_update) download.connect("status-changed", self.__download_status_changed) self.downloads.append(download) utils.debug_print("Appended download %s to list of downloads." % download) self.emit("download-added", (download))
def fetch_max_item_id(self): """ Fetch max item id available via HN Firebase API """ debug_print(">> fetch_max_item_id") max_id = self.firebase.get('maxitem', None) debug_print(max_id, '\n') return max_id
def leer_y_procesar_archivo(archivo): debug_print(ARCHIVO, "leer_y_procesar_archivo", str(archivo)) procesado = Archivo.procesar(archivo.split("\n")) return jsonify({ "puntosVenta": PuntoVenta.lista_to_dict(procesado.puntos), "centrosDistribucion": CentroDistribucion.lista_to_dict(procesado.centros) })
def __init__(self, centros, puntos): debug_print(ARCHIVO, "__init__", str({ "centros": centros, "puntos": puntos })) self.centros = centros self.puntos = puntos self.disponibles = puntos self.rutas = []
def read(device_id, debug=False): """Read from the card Reader :param debug: if True print debug msg :return: return the reading UUID """ rfid_code = read_rfid_reader(device_id, debug) rfid_uuid = utils.rfid_code_to_uuid(rfid_code, debug) utils.debug_print('RFID as UUID: ' + rfid_uuid, debug) return rfid_uuid
def to_dict(self): debug_print(ARCHIVO, "to_dict") return { "camion": self.camion, "capacidadRestante": self.capacidad_restante, "distanciaRecorrida": self.distancia_recorrida, "centroDistribucion": self.centro.id, "productos": self.cantidad_productos(), "ruta": [self.centro.to_dict()] + PuntoVenta.lista_to_dict(self.puntos) }
def __init__(self, id, coordenadas, productos=None): debug_print( ARCHIVO, "__init__", str({ "id": id, "coordenadas": coordenadas, "productos": productos })) self.id = id self.coordenadas = coordenadas self.productos = productos
def to_dict(self): debug_print(ARCHIVO, "to_dict") return { "id": self.id, "esCentroDistribucion": True, "coordenadas": { "x": self.coordenadas[0], "y": self.coordenadas[0], }, "productos": None, }
def remove_download(self, download): """Removes a download object from the list and xml tree.""" # Make sure the download is stopped before its removed if not download.is_canceled(): download.cancel() self.downloads.remove(download) download_element = self.__get_download_element(download) self.tree.getroot().remove(download_element) utils.debug_print("Removed download %s from list of downloads." % download) self.emit("download-removed", (download)) self.__save_xml()
def session_scope(): session = Session() try: yield session session.commit() except: session.rollback() debug_print('session_scope exception traceback:\n', traceback.format_exc()) raise finally: session.close()
def sino_remove_bragg_spots(sinogram, block_size=5, tolerance=0.05, sensitivity_low=1.5, sensitivity_high=0.2): """ If value is above some local threshold, replace by median. Removes dodgy highlights and shadows resulting from bragg peaks from large crystallites in diffracting orientations """ # Footprint for median value to replace bragg spots. # Usually the spots are contained to one projection, # so we sample above and below for good values. footprint = np.array( [[ False, True, False ], [ True, True, True ], [ False, False, False ], [ True, True, True ], [ False, True, False ]]) # Only consider pixels which differ from the local median by this offset. # Highlights and shadows will skew the arithmetic mean so use median. median_value = np.median(sinogram) offset_high = np.median(sinogram[sinogram>median_value]) offset_low = np.median(sinogram[sinogram<median_value]) utils.debug_print(median=median_value,offset_high=offset_high, offset_low=offset_low) mask_low = ~filters.threshold_adaptive( sinogram, block_size, method='median', offset=-sensitivity_low*(offset_low-median_value), ) mask_high = filters.threshold_adaptive( sinogram, block_size, method='median', offset=-sensitivity_high*(offset_high-median_value), ) if float(mask_high.sum()) > tolerance * mask_high.size: # Too many values marked as spots. Ignoring hilights. print('Found more than %s%% of values as hilights' % (tolerance * 100)) mask_high = np.zeros(shape=sinogram.shape, dtype=bool) if float(mask_low.sum()) > tolerance * mask_low.size: # Too many values marked as spots. Ignoring shadows. print('Found more than %s%% of values as shadows' % (tolerance * 100)) mask_low = np.zeros(shape=sinogram.shape, dtype=bool) mask = mask_low + mask_high # FIXME, only calculate values in mask. median = ndimage.median_filter(sinogram, footprint=footprint) ret = sinogram.copy() ret[mask==True] = median[mask==True] return ret
def unbuy(self, cat_name, prod_name): """ Remove our last offer only if it's the highest :param cat_name: category name :param prod_name: product name """ try: cat = Category.search_category(self._auct._categories, cat_name) auct = cat.search_auction(prod_name) auct.unbid(self.user) self.response(1) except CategoryException, e: debug_print(e) self.response(0)
def run(self): i = 0 start_time = time.time() while self.tree.height < TREE_HEIGHT_LIMIT: i += 1 node = self.select() node = self.expand(node=node) kwargs = self.simulate(node=node) self.backpropagate(**kwargs) if i % 50: current_time = time.time() - start_time debug_print( f"Index: {i}, Height {self.tree.height}, time = {current_time}" )
def save_item(self, item_data, update_max_id=False, front_page=False): """ Compile and save item to the database Each item is committed separately for better fault tolerance """ item = None # If item was lost if isinstance(item_data, LostItem): if not item_data.id: return None item = item_data db.session.add(item) debug_print("Lost %s because %s" % (item_data.id, item_data.reason), '\n') else: if 'id' not in item_data: debug_print('Skipping item because empty id', '\n') return None if item_data.get('type', None) in ('story', 'comment', 'poll', 'job', None): debug_print("Saving %d" % item_data['id'], '\n') compiled_data = self.compile_item_data(item_data, front_page) item = Item.create_or_update(compiled_data) else: debug_print("Skipping %s %d" % (item_data['type'], item_data['id']), '\n') if update_max_id: Status.set_max_item_id(item_data.id if isinstance(item_data, LostItem) else item_data['id']) db.session.commit() return item
def __init__(self, camion, centro, puntos): debug_print( ARCHIVO, "__init__", str({ "camion": camion, "centro": centro, "puntos": puntos })) self.camion = camion self.centro = centro self.puntos = puntos self.capacidad_restante = 1000 self.distancia_recorrida = 0 self.punto_actual = centro
def fetch_items(self, item_ids, callback=None, min_delay=0): """ Fetch items for item ids Output format: {id1: {item1}, id2: {item2}, ...} Failed items might appear as LostItem instances instead of attribute dictionaries """ debug_print(">> fetch_items") items = {} for item_id in item_ids: # Skip items that have been recently updated, if requested if min_delay > 0: db_item = db.session.query(Item).get(item_id) if db_item is not None and min_delay > (datetime.utcnow() - db_item.date_updated).total_seconds(): debug_print("Skipped item %d because it's too fresh" % item_id) continue api_item = self.fetch_item(item_id) items[item_id] = api_item if callback is not None: callback(api_item) return items
def fetch_item(self, item_id): """ Fetch item data by id Might return an instance of LostItem in case of API or HTTP error """ debug_print(">> fetch_item %d" % item_id) try: item = self.firebase.get('item', item_id) if item is None: item = LostItem(id=item_id, reason='null' ) return item except requests.exceptions.HTTPError as e: # If API error encountered, return a LostItem instead lost_item = db.session.query(LostItem).get(item_id) if lost_item is None: lost_item = LostItem(id=item_id, reason='HTTP/%s' % e.response.status_code, response=e.response.text, traceback=traceback.format_exc() ) return lost_item
def set_proxy(self, protocol, proxy): """Sets the proxy to use for the specified protocol.""" if protocol == "http": metalink.HTTP_PROXY = proxy utils.debug_print("HTTP proxy: %s" % metalink.HTTP_PROXY) elif protocol == "https": metalink.HTTPS_PROXY = proxy utils.debug_print("HTTPS proxy: %s" % metalink.HTTPS_PROXY) elif protocol == "ftp": metalink.FTP_PROXY = proxy utils.debug_print("FTP proxy: %s" % metalink.FTP_PROXY)
def distance(GPIO_ECHO,GPIO_TRIG,cars=0,should_print=True): #u.debug_print ("GPIO_TRIG = " + str(GPIO_TRIG) + ",GPIO_ECHO = " + str(GPIO_ECHO)) # Set GPIO Channels # ----------------- GPIO.setmode(GPIO.BCM) GPIO.setup(GPIO_ECHO, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.setwarnings(False) GPIO.setup(GPIO_TRIG, GPIO.OUT) GPIO.output(GPIO_TRIG, False) # A couple of variables # --------------------- EXIT = 0 # Infinite loop decpulsetrigger = 0.0001 # Trigger duration inttimeout = 2000 # Number of loop iterations before timeout called # Wait for 2 seconds to allow the ultrasonics to settle (probably not needed) # --------------------------------------------------------------------------- #print "Waiting for 2 seconds....." #time.sleep(2) # Go # -- #u.debug_print("Running....") min_dist = 100 # Never ending loop # ----------------- while EXIT < 10: # Trigger high for 0.0001s then low GPIO.output(GPIO_TRIG, True) time.sleep(decpulsetrigger) GPIO.output(GPIO_TRIG, False) # Wait for echo to go high (or timeout) i_countdown = inttimeout while (GPIO.input(GPIO_ECHO) == 0 and i_countdown > 0): i_countdown -= 1 # If echo is high than the i_countdown not zero if i_countdown > 0: # Start timer and init timeout countdown echostart = time.time() i_countdown = inttimeout # Wait for echo to go low (or timeout) while (GPIO.input(GPIO_ECHO) == 1 and i_countdown > 0): i_countdown -= 1 # Stop timer echoend = time.time() # Echo duration echoduration = echoend - echostart # Display distance if i_countdown > 0: i_distance = (echoduration*1000000)/58 if i_distance < car_detection_trashold and should_print: u.debug_print("Car number " + str(cars+1) + " was detected at " + str(i_distance) + "cm") min_dist = min(min_dist,i_distance) else: #u.debug_print("Distance - timeout") # Wait at least .01s before re trig (or in this case .1s) time.sleep(0.05) EXIT +=1 return min_dist
return min_dist # Which GPIO's are used [0]=BCM Port Number [1]=BCM Name [2]=Use [3]=Pin # ---------------------------------------------------------------------- GPIO_ECHO = 21 GPIO_TRIG = 20 #Global defines sleep_const = 0.1 #sleep period between each sampling green_light_interval = 5 #how long we will have the green light, in seconds car_detection_trashold = 25#if the distance is less than the trashold than a car was detected #__main__ u.debug_print("Hello Wer-O-Jam") while 1: i = 0 t_end = time.time() + green_light_interval print("Start counting\n") while time.time() < t_end: curDist = distance(GPIO_ECHO,GPIO_TRIG,i) #print("curDist is " + str(curDist) + "cm.\n") #u.debug_print("sleeping for " + str(sleep_const) + " seconds\n",True) time.sleep(sleep_const/10) if curDist < car_detection_trashold: i+=1 while curDist < car_detection_trashold: time.sleep(sleep_const) curDist = distance(GPIO_ECHO,GPIO_TRIG,i,False)
def start_download(self, download): """Starts a download in a new thread.""" utils.debug_print("Starting download %s" % download) thread.start_new_thread(self.__start_download, (download,)) self.emit("download-started", (download))