def logger_name(self, logger_name): name_len = len(logger_name) + 1 if self.max_string_len < name_len: raise ArgumentError("Logger name %s is too long" % logger_name) props = self._props logger = c_wchar_p(addressof(props.contents) + props.contents.logger_name_offset) memmove(logger, c_wchar_p(logger_name), sizeof(c_wchar) * name_len)
def pass_encrypt(self, data): """ Encrypts the given data with the given passphrase. :return: output array """ out = create_string_buffer( len(data) + TOX_PASS_ENCRYPTION_EXTRA_LENGTH) tox_err_encryption = c_int() self.libtoxencryptsave.tox_pass_encrypt( c_char_p(data), c_size_t(len(data)), c_char_p(bytes(self._passphrase, 'utf-8')), c_size_t(len(self._passphrase)), out, byref(tox_err_encryption)) tox_err_encryption = tox_err_encryption.value if tox_err_encryption == TOX_ERR_ENCRYPTION['OK']: return out[:] elif tox_err_encryption == TOX_ERR_ENCRYPTION['NULL']: raise ArgumentError( 'Some input data, or maybe the output pointer, was null.') elif tox_err_encryption == TOX_ERR_ENCRYPTION['KEY_DERIVATION_FAILED']: raise RuntimeError( 'The crypto lib was unable to derive a key from the given passphrase, which is usually a' ' lack of memory issue. The functions accepting keys do not produce this error.' ) elif tox_err_encryption == TOX_ERR_ENCRYPTION['FAILED']: raise RuntimeError('The encryption itself failed.')
def convert(data, data_type: type): try: return data_type(data) except ValueError: raise ArgumentError( "Can't convert %s '%s' to %s!" % (type(data).__name__, data, data_type.__name__))
def manage_thread_info(args): if len(args) == 0: raise ArgumentError("No option specified!") elif args[0] == "clear": from dsres.commands import DSR_NEST arg = args[1:] if len(args) > 1 else DSR_NEST["meta"]["processes"]["clear"].keys() DarkSouls.clear_saved_func(arg) elif args[0] == "list": if not bool(DarkSouls.STATIC_FUNC): print(Fore.LIGHTBLUE_EX + "No commands to re-execute" + Fore.RESET) else: print(Fore.LIGHTBLUE_EX + "\nTo be re-executed:\n") for command in DarkSouls.STATIC_FUNC: print(Fore.LIGHTCYAN_EX + "\t" + command[0] + Fore.LIGHTYELLOW_EX + " " + " ".join([str(arg).lower() for arg in DarkSouls.STATIC_FUNC[command]])) print(Fore.RESET) if not bool(DarkSouls.WAITING_FUNC): print(Fore.LIGHTBLUE_EX + "No commands are waiting for event flags" + Fore.RESET) else: print(Fore.LIGHTBLUE_EX + "\nWaiting for event flags:\n") for evt_hash in DarkSouls.WAITING_FUNC: entry = DarkSouls.WAITING_FUNC[evt_hash] flag_id = entry["val"][0] flag_state = entry["val"][1] command = entry["arg"][0] args = entry["arg"][1:] print(Fore.YELLOW + "\t" + str(flag_id).zfill(8) + " → " + ((Fore.LIGHTGREEN_EX + "ON") if flag_state else (Fore.LIGHTRED_EX + "OFF")) + Fore.LIGHTCYAN_EX + "\t" + command + Fore.LIGHTYELLOW_EX + " " + " ".join(args)) print(Fore.RESET)
def create_custom_item(args: list, func): try: i_cat, i_id, i_count = DarkSouls.ITEM_CATEGORIES[args[0]], args[1], args[2] func(i_cat, i_id, i_count) print(Fore.GREEN + ("Created new item, ID: %s" % i_id) + Fore.RESET) except IndexError: raise ArgumentError("No item ID/count specified!")
def __init__(self, tox_pointer): """ Start new A/V session. There can only be only one session per Tox instance. :param tox_pointer: pointer to Tox instance """ toxav_err_new = c_int() ToxAV.libtoxav.toxav_new.restype = POINTER(c_void_p) self._toxav_pointer = ToxAV.libtoxav.toxav_new(tox_pointer, byref(toxav_err_new)) toxav_err_new = toxav_err_new.value if toxav_err_new == TOXAV_ERR_NEW['NULL']: raise ArgumentError( 'One of the arguments to the function was NULL when it was not expected.' ) elif toxav_err_new == TOXAV_ERR_NEW['MALLOC']: raise MemoryError( 'Memory allocation failure while trying to allocate structures required for the A/V ' 'session.') elif toxav_err_new == TOXAV_ERR_NEW['MULTIPLE']: raise RuntimeError( 'Attempted to create a second session for the same Tox instance.' ) self.call_state_cb = None self.audio_receive_frame_cb = None self.video_receive_frame_cb = None self.call_cb = None
def call_control(self, friend_number, control): """ Sends a call control command to a friend. :param friend_number: The friend number of the friend this client is in a call with. :param control: The control command to send. :return: True on success. """ toxav_err_call_control = c_int() result = ToxAV.libtoxav.toxav_call_control( self._toxav_pointer, c_uint32(friend_number), c_int(control), byref(toxav_err_call_control)) toxav_err_call_control = toxav_err_call_control.value if toxav_err_call_control == TOXAV_ERR_CALL_CONTROL['OK']: return bool(result) elif toxav_err_call_control == TOXAV_ERR_CALL_CONTROL['SYNC']: raise RuntimeError('Synchronization error occurred.') elif toxav_err_call_control == TOXAV_ERR_CALL_CONTROL[ 'FRIEND_NOT_FOUND']: raise ArgumentError( 'The friend_number passed did not designate a valid friend.') elif toxav_err_call_control == TOXAV_ERR_CALL_CONTROL[ 'FRIEND_NOT_IN_CALL']: raise RuntimeError( 'This client is currently not in a call with the friend. Before the call is answered, ' 'only CANCEL is a valid control.') elif toxav_err_call_control == TOXAV_ERR_CALL_CONTROL[ 'INVALID_TRANSITION']: raise RuntimeError( 'Happens if user tried to pause an already paused call or if trying to resume a call ' 'that is not paused.')
def read(self, full_shape=None): file = open(self._file_path, 'r') str_in = [] if self._type == 'csv' or self._type == 'txt': for row in csv.reader(file): if len(row) != 0: str_in.append(row) else: raise ArgumentError(self._type + ' file is not supported by TensorReader.') file.close() order = len(str_in[0]) - 1 entry_count = len(str_in) value = np.zeros(entry_count) idx = np.zeros(shape=(entry_count, order), dtype=int) for row in range(entry_count): entry = str_in[row] idx[row] = np.array([int(entry[mode]) for mode in range(order)]) value[row] = float(entry[-1]) if full_shape == None: max_dim = np.max(idx, axis=0) + np.ones(order).astype(int) else: max_dim = full_shape self._sparse_data = tf.SparseTensor(indices=idx, values=value, dense_shape=max_dim) self._full_data = tf.sparse_tensor_to_dense(self._sparse_data, validate_indices=False)
def add_agent(self, position): """ Adds a new agent with default properties to the simulation. Args: position (Vector2): The two-dimensional starting position of this agent. Returns: int: The number of the agent, or -1 when the agent defaults have not been set. """ if self.default_agent_ is None: raise ArgumentError( 'Default agent not set. Call set_agent_defaults first.') agent = Agent(self) agent.id_ = len(self.agents_) agent.max_neighbors_ = self.default_agent_.max_neighbors_ agent.max_speed_ = self.default_agent_.max_speed_ agent.neighbor_dist_ = self.default_agent_.neighbor_dist_ agent.position_ = position agent.radius_ = self.default_agent_.radius_ agent.time_horizon_ = self.default_agent_.time_horizon_ agent.time_horizon_obst_ = self.default_agent_.time_horizon_obst_ agent.velocity_ = self.default_agent_.velocity_ self.agents_.append(agent) return agent.id_
def set_accelerometer_sensitivity(self, value): """ Sets the accelerometer sensitivity to 2, 4, 8 or 16 according to the given value. Throws an ArgumentError if the value provided is not valid. :param value: the target sensitivity. """ # note that this implicitly disables the self tests on each axis # i.e. the full byte is actually 000[accel]000 where the 1st 3 are the accelerometer self tests, the next two # values are the actual sensitivity and the last 3 are unused # the 2 [accel] bits are translated by the device as follows; 00 = 2g, 01 = 4g, 10 = 8g, 11 = 16g # in binary we get 2 = 0, 4 = 1000, 8 = 10000, 16 = 11000 # so the 1st 3 bits are always 0 try: self.i2c_io.write(self.MPU6050_ADDRESS, self.MPU6050_RA_ACCEL_CONFIG, { 2: 0, 4: 8, 8: 16, 16: 24 }[value]) self._acceleration_factor = value / 32768.0 self.accelerometer_sensitivity = value logger.warning(f"Set accelerometer sensitivity = {value}") except KeyError: raise ArgumentError(value + " is not a valid sensitivity (2,4,8,18)")
def raise_warp_error(b_full_name: str): from dsres.commands import DSR_NEST if not b_full_name.strip() or b_full_name.lower() == DSRCmd.default: raise ArgumentError("No arguments given!") area_name = b_full_name.split()[0] if area_name not in DSR_NEST["warp"].keys(): raise ArgumentError("Unknown area name: %s" % DarkSouls.get_name_from_arg(area_name)) else: if len(b_full_name.split()) < 2: raise ArgumentError("No bonfire name specified!") bonfire_name = b_full_name.split()[1] if bonfire_name not in DSR_NEST["warp"][area_name]: raise ArgumentError("Unknown bonfire name for area '%s': %s" % ( DarkSouls.get_name_from_arg(area_name), bonfire_name )) raise AssertionError("Error processing arguments: %s | Can't determine the reason of failure" % b_full_name)
def SetLogFileName(self, logger_name): """Set the current log file name stored in the buffer.""" name_len = len(logger_name) + 1 if self.max_string_len < name_len: raise ArgumentError("Name too long") memmove(self.GetLogFileName(), c_wchar_p(logger_name), sizeof(c_wchar) * name_len)
def video_send_frame(self, friend_number, width, height, y, u, v): """ Send a video frame to a friend. Y - plane should be of size: height * width U - plane should be of size: (height/2) * (width/2) V - plane should be of size: (height/2) * (width/2) :param friend_number: The friend number of the friend to which to send a video frame. :param width: Width of the frame in pixels. :param height: Height of the frame in pixels. :param y: Y (Luminance) plane data. :param u: U (Chroma) plane data. :param v: V (Chroma) plane data. """ toxav_err_send_frame = c_int() result = self.libtoxav.toxav_video_send_frame( self._toxav_pointer, c_uint32(friend_number), c_uint16(width), c_uint16(height), c_char_p(y), c_char_p(u), c_char_p(v), byref(toxav_err_send_frame)) toxav_err_send_frame = toxav_err_send_frame.value if toxav_err_send_frame == TOXAV_ERR_SEND_FRAME['OK']: return bool(result) elif toxav_err_send_frame == TOXAV_ERR_SEND_FRAME['NULL']: raise ArgumentError('One of Y, U, or V was NULL.') elif toxav_err_send_frame == TOXAV_ERR_SEND_FRAME['FRIEND_NOT_FOUND']: raise ArgumentError( 'The friend_number passed did not designate a valid friend.') elif toxav_err_send_frame == TOXAV_ERR_SEND_FRAME[ 'FRIEND_NOT_IN_CALL']: raise RuntimeError( 'This client is currently not in a call with the friend.') elif toxav_err_send_frame == TOXAV_ERR_SEND_FRAME['SYNC']: raise RuntimeError('Synchronization error occurred.') elif toxav_err_send_frame == TOXAV_ERR_SEND_FRAME['INVALID']: raise ArgumentError( 'One of the frame parameters was invalid. E.g. the resolution may be too small or too ' 'large, or the audio sampling rate may be unsupported.') elif toxav_err_send_frame == TOXAV_ERR_SEND_FRAME[ 'PAYLOAD_TYPE_DISABLED']: raise RuntimeError( 'Either friend turned off audio or video receiving or we turned off sending for the said' 'payload.') elif toxav_err_send_frame == TOXAV_ERR_SEND_FRAME['RTP_FAILED']: RuntimeError('Failed to push frame through rtp interface.')
def create_item(self, i_name: str, i_count: int, func): if i_name not in self.items.keys(): raise ArgumentError("Item '%s' doesn't exist!" % DarkSouls.get_name_from_arg(i_name)) else: item = self.items[i_name] i_id = item.get_id() i_cat = item.get_category() func(i_cat, i_id, i_count) print(Fore.GREEN + ("Created new item, ID: %d" % i_id) + Fore.RESET)
def start(self, name): with self._lock: if self._closed: assert False, "Already closed" try: s = self.service_node_launches[name] except KeyError: raise ArgumentError(f"Invalid service requested: {name}") if name not in self._subprocesses: self._do_start(s)
def ask_flag(): flag_id = input_dialog( title="Enter a flag ID", text="Event flag to listen to:" ).run() if flag_id is None or not flag_id.strip(): raise ArgumentError("No flag ID specified!") if not flag_id.isnumeric(): raise ArgumentError("Can't convert %s '%s' to int!" % (type(flag_id).__name__, flag_id)) state = radiolist_dialog( title="Select flag state", text="Desired state of event flag %s" % flag_id, values=[ (True, "ON"), (False, "OFF") ] ).run() if state is None: raise ArgumentError("No state specified!") return int(flag_id), state
def audio_send_frame(self, friend_number, pcm, sample_count, channels, sampling_rate): """ Send an audio frame to a friend. The expected format of the PCM data is: [s1c1][s1c2][...][s2c1][s2c2][...]... Meaning: sample 1 for channel 1, sample 1 for channel 2, ... For mono audio, this has no meaning, every sample is subsequent. For stereo, this means the expected format is LRLRLR... with samples for left and right alternating. :param friend_number: The friend number of the friend to which to send an audio frame. :param pcm: An array of audio samples. The size of this array must be sample_count * channels. :param sample_count: Number of samples in this frame. Valid numbers here are ((sample rate) * (audio length) / 1000), where audio length can be 2.5, 5, 10, 20, 40 or 60 milliseconds. :param channels: Number of audio channels. Sulpported values are 1 and 2. :param sampling_rate: Audio sampling rate used in this frame. Valid sampling rates are 8000, 12000, 16000, 24000, or 48000. """ toxav_err_send_frame = c_int() result = ToxAV.libtoxav.toxav_audio_send_frame(self._toxav_pointer, c_uint32(friend_number), cast(pcm, c_void_p), c_size_t(sample_count), c_uint8(channels), c_uint32(sampling_rate), byref(toxav_err_send_frame)) toxav_err_send_frame = toxav_err_send_frame.value if toxav_err_send_frame == TOXAV_ERR_SEND_FRAME['OK']: return bool(result) elif toxav_err_send_frame == TOXAV_ERR_SEND_FRAME['NULL']: raise ArgumentError('The samples data pointer was NULL.') elif toxav_err_send_frame == TOXAV_ERR_SEND_FRAME['FRIEND_NOT_FOUND']: raise ArgumentError('The friend_number passed did not designate a valid friend.') elif toxav_err_send_frame == TOXAV_ERR_SEND_FRAME['FRIEND_NOT_IN_CALL']: raise RuntimeError('This client is currently not in a call with the friend.') elif toxav_err_send_frame == TOXAV_ERR_SEND_FRAME['SYNC']: raise RuntimeError('Synchronization error occurred.') elif toxav_err_send_frame == TOXAV_ERR_SEND_FRAME['INVALID']: raise ArgumentError('One of the frame parameters was invalid. E.g. the resolution may be too small or too ' 'large, or the audio sampling rate may be unsupported.') elif toxav_err_send_frame == TOXAV_ERR_SEND_FRAME['PAYLOAD_TYPE_DISABLED']: raise RuntimeError('Either friend turned off audio or video receiving or we turned off sending for the said' 'payload.') elif toxav_err_send_frame == TOXAV_ERR_SEND_FRAME['RTP_FAILED']: RuntimeError('Failed to push frame through rtp interface.')
def call(self, friend_number, audio_bit_rate, video_bit_rate): """ Call a friend. This will start ringing the friend. It is the client's responsibility to stop ringing after a certain timeout, if such behaviour is desired. If the client does not stop ringing, the library will not stop until the friend is disconnected. Audio and video receiving are both enabled by default. :param friend_number: The friend number of the friend that should be called. :param audio_bit_rate: Audio bit rate in Kb/sec. Set this to 0 to disable audio sending. :param video_bit_rate: Video bit rate in Kb/sec. Set this to 0 to disable video sending. :return: True on success. """ toxav_err_call = c_int() result = self.libtoxav.toxav_call(self._toxav_pointer, c_uint32(friend_number), c_uint32(audio_bit_rate), c_uint32(video_bit_rate), byref(toxav_err_call)) toxav_err_call = toxav_err_call.value if toxav_err_call == TOXAV_ERR_CALL['OK']: return bool(result) elif toxav_err_call == TOXAV_ERR_CALL['MALLOC']: raise MemoryError( 'A resource allocation error occurred while trying to create the structures required for ' 'the call.') elif toxav_err_call == TOXAV_ERR_CALL['SYNC']: raise RuntimeError('Synchronization error occurred.') elif toxav_err_call == TOXAV_ERR_CALL['FRIEND_NOT_FOUND']: raise ArgumentError( 'The friend number did not designate a valid friend.') elif toxav_err_call == TOXAV_ERR_CALL['FRIEND_NOT_CONNECTED']: raise ArgumentError( 'The friend was valid, but not currently connected.') elif toxav_err_call == TOXAV_ERR_CALL['FRIEND_ALREADY_IN_CALL']: raise ArgumentError( 'Attempted to call a friend while already in an audio or video call with them.' ) elif toxav_err_call == TOXAV_ERR_CALL['INVALID_BIT_RATE']: raise ArgumentError('Audio or video bit rate is invalid.')
def generate_noise_2d( shape, feature_size=4, octaves=1, x_offsets: np.array = None, y_offsets: np.array = None, seed=None, ) -> np.array: if x_offsets is not None and x_offsets.shape != shape: raise ArgumentError( f"x_offsets.shape != shape {shape}!={x_offsets.shape}") if y_offsets is not None and y_offsets.shape != shape: raise ArgumentError( f"y_offsets.shape != shape {shape}!={y_offsets.shape}") offset_max = 4096**2 if not seed: offsets = (random.randrange(offset_max), random.randrange(offset_max)) else: offsets = (seed, seed) width = shape[1] height = shape[0] arr = np.ones((width, height)) for y in range(height): for x in range(width): # arr[y,x] = simplex.noise2d((x + offsets[0]) / feature_size,(y + # offsets[1]) / feature_size) xx = (x + offsets[0] + (x_offsets[y, x] if x_offsets is not None else 0) ) / feature_size yy = (y + offsets[1] + (y_offsets[y, x] if y_offsets is not None else 0) ) / feature_size arr[y, x] = pnoise2( xx, yy, octaves, ) return arr
def answer(self, friend_number, audio_bit_rate, video_bit_rate): """ Accept an incoming call. If answering fails for any reason, the call will still be pending and it is possible to try and answer it later. Audio and video receiving are both enabled by default. :param friend_number: The friend number of the friend that is calling. :param audio_bit_rate: Audio bit rate in Kb/sec. Set this to 0 to disable audio sending. :param video_bit_rate: Video bit rate in Kb/sec. Set this to 0 to disable video sending. :return: True on success. """ toxav_err_answer = c_int() result = self.libtoxav.toxav_answer(self._toxav_pointer, c_uint32(friend_number), c_uint32(audio_bit_rate), c_uint32(video_bit_rate), byref(toxav_err_answer)) toxav_err_answer = toxav_err_answer.value if toxav_err_answer == TOXAV_ERR_ANSWER['OK']: return bool(result) elif toxav_err_answer == TOXAV_ERR_ANSWER['SYNC']: raise RuntimeError('Synchronization error occurred.') elif toxav_err_answer == TOXAV_ERR_ANSWER['CODEC_INITIALIZATION']: raise RuntimeError( 'Failed to initialize codecs for call session. Note that codec initiation will fail if ' 'there is no receive callback registered for either audio or video.' ) elif toxav_err_answer == TOXAV_ERR_ANSWER['FRIEND_NOT_FOUND']: raise ArgumentError( 'The friend number did not designate a valid friend.') elif toxav_err_answer == TOXAV_ERR_ANSWER['FRIEND_NOT_CALLING']: raise ArgumentError( 'The friend was valid, but they are not currently trying to initiate a call. This is ' 'also returned if this client is already in a call with the friend.' ) elif toxav_err_answer == TOXAV_ERR_ANSWER['INVALID_BIT_RATE']: raise ArgumentError('Audio or video bit rate is invalid.')
def __init__( self, octaves: float, feature_size: float, x0: float = 0, y0: float = 0, seed: int = 0, ) -> None: if feature_size <= 0: raise ArgumentError("feature_size must be > 0") self.x0 = x0 self.y0 = y0 self.octaves = octaves self.feature_size = feature_size self.seed = seed
def pass_decrypt(self, data): """ Decrypts the given data with the given passphrase. :return: output array """ out = create_string_buffer( len(data) - TOX_PASS_ENCRYPTION_EXTRA_LENGTH) tox_err_decryption = c_int() self.libtoxencryptsave.tox_pass_decrypt( c_char_p(bytes(data)), c_size_t(len(data)), c_char_p(bytes(self._passphrase, 'utf-8')), c_size_t(len(self._passphrase)), out, byref(tox_err_decryption)) tox_err_decryption = tox_err_decryption.value if tox_err_decryption == TOX_ERR_DECRYPTION['OK']: return out[:] elif tox_err_decryption == TOX_ERR_DECRYPTION['NULL']: raise ArgumentError( 'Some input data, or maybe the output pointer, was null.') elif tox_err_decryption == TOX_ERR_DECRYPTION['INVALID_LENGTH']: raise ArgumentError( 'The input data was shorter than TOX_PASS_ENCRYPTION_EXTRA_LENGTH bytes' ) elif tox_err_decryption == TOX_ERR_DECRYPTION['BAD_FORMAT']: raise ArgumentError( 'The input data is missing the magic number (i.e. wasn\'t created by this module, or is' ' corrupted)') elif tox_err_decryption == TOX_ERR_DECRYPTION['KEY_DERIVATION_FAILED']: raise RuntimeError( 'The crypto lib was unable to derive a key from the given passphrase, which is usually a' ' lack of memory issue. The functions accepting keys do not produce this error.' ) elif tox_err_decryption == TOX_ERR_DECRYPTION['FAILED']: raise RuntimeError( 'The encrypted byte array could not be decrypted. Either the data was corrupt or the ' 'password/key was incorrect.')
def get_upgrade_value_pyro_flame(item: DSRItem): is_pyro_asc = item.get_upgrade_type() == DSRItem.Upgrade.PYRO_FLAME_ASCENDED max_upgrade = 5 if is_pyro_asc else 15 upgrade = input_dialog( title="Enter upgrade value for %s" % DarkSouls.get_name_from_arg(item.get_name()), text="Item type: %sPyromancy Flame" % "Ascended " if is_pyro_asc else "" ).run() try: if int(upgrade) > max_upgrade or int(upgrade) < 0: print(Fore.RED + ("Can't upgrade %sPyromancy Flame to +%s" % ( "Ascended " if is_pyro_asc else "", upgrade)) + Fore.RESET) return None except ValueError: raise ArgumentError("Can't convert %s '%s' to int!" % (type(upgrade).__name__, upgrade)) return upgrade
def get_upgrade_value_armor_or_unique(item: DSRItem): is_unique = item.get_upgrade_type() == DSRItem.Upgrade.UNIQUE max_upgrade = 5 if is_unique else 10 upgrade = input_dialog( title="Enter upgrade value for %s" % DarkSouls.get_name_from_arg(item.get_name()), text="Item type: %s" % "Unique" if is_unique else "Armor" ).run() try: if int(upgrade) > max_upgrade or int(upgrade) < 0: print(Fore.RED + ("Can't upgrade %s to +%s" % ( "Unique" if is_unique else "Armor", upgrade)) + Fore.RESET) return None except ValueError: raise ArgumentError("Can't convert %s '%s' to int!" % (type(upgrade).__name__, upgrade)) return upgrade
def sample(self, location): """ Given sample locations in BigBrain space, the sampler centers a fixed-size box near the given location in BigBrain cortex and extracts layerwise grayvalue statistics. The center is found by identifying the closest point in Layer IV which is inside a specified maximum distance (default 1mm) from the given point. If the location is not close enough to the cortical midsurface, the data sample will be empty and a warning will be printed. Parameters ---------- location: Point, or PointSet Candidate location(s) for sampling Return ------ List of dicts, one per sample point, with keys: - 'center': the physical coordinate of the cube used as a region of interest - 'boxsize': sidelenght in mm f the cube used as a region of interest - 'space': name of the space (bigbrain) - 'layers': Dict of layer-wise statistics with mean gray value, standard deviation, and volume in mm """ if location.space != self.space: logger.info( f"Warping sample locations from {location.space.name} to {self.space.name}" ) loc_bb = location.warp(self.space) else: loc_bb = location result = [] if isinstance(loc_bb, Point): result.append(self._sample_single_point(loc_bb)) elif isinstance(loc_bb, PointSet): for p in tqdm( loc_bb, total=len(loc_bb), unit="locations", desc=f"Sampling from {len(loc_bb)} locations", disable=logger.level > 20, ): result.append(self._sample_single_point(p)) else: raise ArgumentError( f"Invalid location specification {location.__class__.__name__} BigBrain sampling." ) return result
def get_event_flag_offset(flag_id): id_str = str(flag_id).zfill(8) if len(id_str) == 8: group = id_str[0:1] area = id_str[1:4] section = int(id_str[4:5]) number = int(id_str[5:8]) if group in DSProcess.EVENT_FLAG_GROUPS.keys( ) and area in DSProcess.EVENT_FLAG_AREAS.keys(): offset = DSProcess.EVENT_FLAG_GROUPS[group] offset += DSProcess.EVENT_FLAG_AREAS[area] * 0x500 offset += section * 128 offset += int((number - (number % 32)) / 8) mask = 0x80000000 >> (number % 32) return offset, mask raise ArgumentError("Unknown event flag ID: %d" % flag_id)
def get_upgrade_value_infusable(infusions: list, item: DSRItem): infusion = radiolist_dialog( title="Select infusion type", text="How would you like %s to be upgraded?" % DarkSouls.get_name_from_arg(item.get_name()), values=infusions ).run() if infusion is None: return None upgrade = input_dialog( title="Enter upgrade value", text="Item type: Normal [%s]" % infusion.upper() ).run() try: int(upgrade) except ValueError: raise ArgumentError("Can't convert %s '%s' to int" % (type(upgrade).__name__, upgrade)) return upgrade, infusion
def add_obstacle(self, vertices): """ Adds a new obstacle to the simulation. Args: vertices (list): List of the vertices of the polygonal obstacle in counterclockwise order. Returns: int: The number of the first vertex of the obstacle, or -1 when the number of vertices is less than two. Remarks: To add a "negative" obstacle, e.g. a bounding polygon around the environment, the vertices should be listed in clockwise order. """ if len(vertices) < 2: raise ArgumentError('Must have at least 2 vertices.') obstacleNo = len(self.obstacles_) for i in range(len(vertices)): obstacle = Obstacle() obstacle.point_ = vertices[i] if i != 0: obstacle.previous_ = self.obstacles_[len(self.obstacles_) - 1] obstacle.previous_.next_ = obstacle if i == len(vertices) - 1: obstacle.next_ = self.obstacles_[obstacleNo] obstacle.next_.previous_ = obstacle obstacle.direction_ = rvo_math.normalize( vertices[0 if i == len(vertices) - 1 else i + 1] - vertices[i]) if len(vertices) == 2: obstacle.convex_ = True else: obstacle.convex_ = rvo_math.left_of( vertices[len(vertices) - 1 if i == 0 else i - 1], vertices[i], vertices[0 if i == len(vertices) - 1 else i + 1]) >= 0.0 obstacle.id_ = len(self.obstacles_) self.obstacles_.append(obstacle) return obstacleNo
def upgrade_item(self, i_name: str, i_count: int): if i_name not in self.items.keys(): raise ArgumentError("Item '%s' doesn't exist!" % DarkSouls.get_name_from_arg(i_name)) else: item = self.items[i_name] i_id = item.get_id() i_category = item.get_category() if item.get_upgrade_type() == DSItem.Upgrade.NONE: print(Fore.RED + "Can't upgrade this item!" + Fore.RESET) return elif item.get_upgrade_type() in (DSItem.Upgrade.ARMOR, DSItem.Upgrade.UNIQUE): upgrade = DarkSouls.get_upgrade_value_armor_or_unique(item) if upgrade is None: return i_id += int(upgrade) elif item.get_upgrade_type() in ( DSItem.Upgrade.PYRO_FLAME, DSItem.Upgrade.PYRO_FLAME_ASCENDED): upgrade = DarkSouls.get_upgrade_value_pyro_flame(item) if upgrade is None: return i_id += int(upgrade) * 100 elif item.get_upgrade_type() in ( DSItem.Upgrade.INFUSABLE, DSItem.Upgrade.INFUSABLE_RESTRICTED): values = [(self.infusions[key].get_name(), self.infusions[key].get_name().upper()) for key in self.infusions.keys()] upgrade, infusion = DarkSouls.get_upgrade_value_infusable( values, item) if upgrade is None: return i_id = self.infusions[infusion].infuse(item, int(upgrade)) else: raise AssertionError( "Can't determine the upgrade type for item '%s'!" % DarkSouls.get_name_from_arg(i_name)) if i_id >= item.get_id(): self.item_get(i_category, i_id, i_count) print(Fore.GREEN + "Upgrade successful" + Fore.RESET)
def set_gyro_sensitivity(self, value): """ Sets the gyro sensitivity to 250, 500, 1000 or 2000 according to the given value (and implicitly disables the self tests) :param value: the target sensitivity. """ try: self.i2c_io.write(self.MPU6050_ADDRESS, self.MPU6050_RA_GYRO_CONFIG, { 250: 0, 500: 8, 1000: 16, 2000: 24 }[value]) self._gyro_factor = value / 32768.0 self.gyro_sensitivity = value logger.warning(f"Set gyro sensitivity = {value}") except KeyError: raise ArgumentError( value + " is not a valid sensitivity (250,500,1000,2000)")