code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def image(self, processor=None, as_nparray=True) -> np.ndarray:
"""
Loads the image.
:param processor: Image processing like augmentations or cropping, if
not None. Defaults to None.
:param as_nparray: Whether to convert the image to a np array of uint8.
... |
Loads the image.
:param processor: Image processing like augmentations or cropping, if
not None. Defaults to None.
:param as_nparray: Whether to convert the image to a np array of uint8.
Defaults to True. If false, returns result of
... | image | python | autorope/donkeycar | donkeycar/pipeline/types.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/pipeline/types.py | MIT |
def _image_from_cache(self, as_nparray):
"""
Cache policy only supports numpy array format
:return: Numpy array from cache
"""
if not as_nparray:
return self._image
if self._cache_policy == CachePolicy.NOCACHE:
raise RuntimeError("Found cached ima... |
Cache policy only supports numpy array format
:return: Numpy array from cache
| _image_from_cache | python | autorope/donkeycar | donkeycar/pipeline/types.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/pipeline/types.py | MIT |
def __init__(self, seq_length: int, records: List[TubRecord]):
"""
:param seq_length: length of sequence
:param records: input record list
"""
self.records = records
self.seq_length = seq_length |
:param seq_length: length of sequence
:param records: input record list
| __init__ | python | autorope/donkeycar | donkeycar/pipeline/types.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/pipeline/types.py | MIT |
def is_continuous(rec_1: TubRecord, rec_2: TubRecord) -> bool:
"""
Checks if second record is next to first record
:param rec_1: first record
:param rec_2: second record
:return: if first record is followed by second record
"""
it_is = rec_1.underlying... |
Checks if second record is next to first record
:param rec_1: first record
:param rec_2: second record
:return: if first record is followed by second record
| is_continuous | python | autorope/donkeycar | donkeycar/pipeline/types.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/pipeline/types.py | MIT |
def __iter__(self) -> Iterator[List[TubRecord]]:
""" Iterable interface. Returns a generator as Iterator. """
it = iter(self.records)
for this_record in it:
seq = [this_record]
seq_it = copy(it)
for next_record in seq_it:
if self.is_continuous(... | Iterable interface. Returns a generator as Iterator. | __iter__ | python | autorope/donkeycar | donkeycar/pipeline/types.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/pipeline/types.py | MIT |
def drive(cfg):
'''
Construct a working robotic vehicle from many parts.
Each part runs as a job in the Vehicle loop, calling either
it's run or run_threaded method depending on the constructor flag `threaded`.
All parts are updated one after another at the framerate given in
cfg.DRIVE_LOOP_HZ a... |
Construct a working robotic vehicle from many parts.
Each part runs as a job in the Vehicle loop, calling either
it's run or run_threaded method depending on the constructor flag `threaded`.
All parts are updated one after another at the framerate given in
cfg.DRIVE_LOOP_HZ assuming each part finis... | drive | python | autorope/donkeycar | donkeycar/templates/arduino_drive.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/templates/arduino_drive.py | MIT |
def drive(cfg, model_path=None, model_type=None):
"""
Construct a minimal robotic vehicle from many parts. Here, we use a
single camera, web or joystick controller, autopilot and tubwriter.
Each part runs as a job in the Vehicle loop, calling either its run or
run_threaded method depending on the c... |
Construct a minimal robotic vehicle from many parts. Here, we use a
single camera, web or joystick controller, autopilot and tubwriter.
Each part runs as a job in the Vehicle loop, calling either its run or
run_threaded method depending on the constructor flag `threaded`. All
parts are updated one... | drive | python | autorope/donkeycar | donkeycar/templates/basic.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/templates/basic.py | MIT |
def calibrate(cfg):
"""
Construct an auxiliary robotic vehicle from only the RC controllers and
prints their values. The RC remote usually has a tuning pot for the throttle
and steering channel. In this loop we run the controllers and simply print
their values in order to allow centering the RC pwm ... |
Construct an auxiliary robotic vehicle from only the RC controllers and
prints their values. The RC remote usually has a tuning pot for the throttle
and steering channel. In this loop we run the controllers and simply print
their values in order to allow centering the RC pwm signals. If there is a
... | calibrate | python | autorope/donkeycar | donkeycar/templates/basic.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/templates/basic.py | MIT |
def drive(cfg, model_path=None, use_joystick=False, model_type=None,
camera_type='single', meta=[]):
"""
Construct a working robotic vehicle from many parts. Each part runs as a
job in the Vehicle loop, calling either it's run or run_threaded method
depending on the constructor flag `threaded`... |
Construct a working robotic vehicle from many parts. Each part runs as a
job in the Vehicle loop, calling either it's run or run_threaded method
depending on the constructor flag `threaded`. All parts are updated one
after another at the framerate given in cfg.DRIVE_LOOP_HZ assuming each
part finis... | drive | python | autorope/donkeycar | donkeycar/templates/complete.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/templates/complete.py | MIT |
def __init__(self, auto_record_on_throttle, record_in_autopilot):
"""
Donkeycar Part that manages the recording state.
"""
self.auto_record_on_throttle = auto_record_on_throttle
self.record_in_autopilot = record_in_autopilot
self.recording_latch: bool = None
self.... |
Donkeycar Part that manages the recording state.
| __init__ | python | autorope/donkeycar | donkeycar/templates/complete.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/templates/complete.py | MIT |
def run(self, mode: str, recording: bool):
"""
Set recording based on user/autopilot mode
:param mode: 'user'|'local_angle'|'local_pilot'
:param recording: current recording flag
:return: updated recording flag
"""
recording_in = recording
if recording_in ... |
Set recording based on user/autopilot mode
:param mode: 'user'|'local_angle'|'local_pilot'
:param recording: current recording flag
:return: updated recording flag
| run | python | autorope/donkeycar | donkeycar/templates/complete.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/templates/complete.py | MIT |
def run(self, mode,
user_steering, user_throttle,
pilot_steering, pilot_throttle):
"""
Main final steering and throttle values based on user mode
:param mode: 'user'|'local_angle'|'local_pilot'
:param user_steering: steering value in user (manual) mode
:pa... |
Main final steering and throttle values based on user mode
:param mode: 'user'|'local_angle'|'local_pilot'
:param user_steering: steering value in user (manual) mode
:param user_throttle: throttle value in user (manual) mode
:param pilot_steering: steering value in autopilot mod... | run | python | autorope/donkeycar | donkeycar/templates/complete.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/templates/complete.py | MIT |
def run(self, mode, user_image, pilot_image):
"""
Maintain run condition and which image to show in web ui
:param mode: 'user'|'local_angle'|'local_pilot'
:param user_image: image to show in manual (user) pilot
:param pilot_image: image to show in auto pilot
:return: tupl... |
Maintain run condition and which image to show in web ui
:param mode: 'user'|'local_angle'|'local_pilot'
:param user_image: image to show in manual (user) pilot
:param pilot_image: image to show in auto pilot
:return: tuple of (user-condition, autopilot-condition, web image)
... | run | python | autorope/donkeycar | donkeycar/templates/complete.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/templates/complete.py | MIT |
def add_user_controller(V, cfg, use_joystick, input_image='ui/image_array'):
"""
Add the web controller and any other
configured user input controller.
:param V: the vehicle pipeline.
On output this will be modified.
:param cfg: the configuration (from myconfig.py)
:return: the con... |
Add the web controller and any other
configured user input controller.
:param V: the vehicle pipeline.
On output this will be modified.
:param cfg: the configuration (from myconfig.py)
:return: the controller
| add_user_controller | python | autorope/donkeycar | donkeycar/templates/complete.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/templates/complete.py | MIT |
def add_camera(V, cfg, camera_type):
"""
Add the configured camera to the vehicle pipeline.
:param V: the vehicle pipeline.
On output this will be modified.
:param cfg: the configuration (from myconfig.py)
"""
logger.info("cfg.CAMERA_TYPE %s"%cfg.CAMERA_TYPE)
if camera_type ==... |
Add the configured camera to the vehicle pipeline.
:param V: the vehicle pipeline.
On output this will be modified.
:param cfg: the configuration (from myconfig.py)
| add_camera | python | autorope/donkeycar | donkeycar/templates/complete.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/templates/complete.py | MIT |
def add_odometry(V, cfg, threaded=True):
"""
If the configuration support odometry, then
add encoders, odometry and kinematics to the vehicle pipeline
:param V: the vehicle pipeline.
On output this may be modified.
:param cfg: the configuration (from myconfig.py)
"""
from donke... |
If the configuration support odometry, then
add encoders, odometry and kinematics to the vehicle pipeline
:param V: the vehicle pipeline.
On output this may be modified.
:param cfg: the configuration (from myconfig.py)
| add_odometry | python | autorope/donkeycar | donkeycar/templates/complete.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/templates/complete.py | MIT |
def drive(cfg, use_joystick=False, camera_type='single'):
'''
Construct a working robotic vehicle from many parts.
Each part runs as a job in the Vehicle loop, calling either
it's run or run_threaded method depending on the constructor flag
`threaded`. All parts are updated one after another at the... |
Construct a working robotic vehicle from many parts.
Each part runs as a job in the Vehicle loop, calling either
it's run or run_threaded method depending on the constructor flag
`threaded`. All parts are updated one after another at the framerate given
in cfg.DRIVE_LOOP_HZ assuming each part fini... | drive | python | autorope/donkeycar | donkeycar/templates/path_follow.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/templates/path_follow.py | MIT |
def test_circular_buffer_queue(self):
"""
enqueue items to head
dequeue items from tail
"""
queue:CircularBuffer = CircularBuffer(3, defaultValue="out-of-range")
self.assertEqual(3, queue.capacity)
self.assertEqual(0, queue.count)
queue.enqueue(0)
... |
enqueue items to head
dequeue items from tail
| test_circular_buffer_queue | python | autorope/donkeycar | donkeycar/tests/test_circular_buffer.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/tests/test_circular_buffer.py | MIT |
def test_circular_buffer_stack(self):
"""
push items to head
pop items from head
"""
stack:CircularBuffer = CircularBuffer(2, defaultValue="out-of-range")
self.assertEqual(2, stack.capacity)
self.assertEqual(0, stack.count)
self.assertEqual("out-of-range",... |
push items to head
pop items from head
| test_circular_buffer_stack | python | autorope/donkeycar | donkeycar/tests/test_circular_buffer.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/tests/test_circular_buffer.py | MIT |
def test_circular_buffer_array(self):
"""
append items to tail
set/get items by index
"""
array:CircularBuffer = CircularBuffer(2, defaultValue="out-of-range")
self.assertEqual(2, array.capacity)
self.assertEqual(0, array.count)
self.assertEqual("out-of-ra... |
append items to tail
set/get items by index
| test_circular_buffer_array | python | autorope/donkeycar | donkeycar/tests/test_circular_buffer.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/tests/test_circular_buffer.py | MIT |
def test_keras_vs_tflite_and_tensorrt(keras_pilot, tmp_dir):
""" This test cannot run for the 3D CNN model in tflite and the LSTM
model in """
k_keras, k_tflite, k_trt = create_models(keras_pilot, tmp_dir)
# prepare data
img = get_test_img(k_keras)
if keras_pilot is KerasIMU:
# simu... | This test cannot run for the 3D CNN model in tflite and the LSTM
model in | test_keras_vs_tflite_and_tensorrt | python | autorope/donkeycar | donkeycar/tests/test_keras.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/tests/test_keras.py | MIT |
def calc_center_of_rotation(wheelbase, front_wheel, orientation, steering_angle):
"""
Calculate the center of rotation for a bicycle turn.
Args:
wheelbase (float): The length of the bicycle wheelbase.
front_wheel (tuple): The x and y coordinates of the front wheel (x, y).
orientatio... |
Calculate the center of rotation for a bicycle turn.
Args:
wheelbase (float): The length of the bicycle wheelbase.
front_wheel (tuple): The x and y coordinates of the front wheel (x, y).
orientation (float): The orientation of the bicycle in radians.
steering_angle (float): The... | calc_center_of_rotation | python | autorope/donkeycar | donkeycar/tests/test_kinematics.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/tests/test_kinematics.py | MIT |
def calc_arc_end_point(center, radius, point, radians):
"""
Calculates the ending point on a circle given the center of the circle, the radius of the circle,
a point on the circle and a distance along the circle in radians from the given point.
Arguments:
center -- the center of the circle represen... |
Calculates the ending point on a circle given the center of the circle, the radius of the circle,
a point on the circle and a distance along the circle in radians from the given point.
Arguments:
center -- the center of the circle represented as a tuple (x, y) (tuple)
radius -- the radius of the c... | calc_arc_end_point | python | autorope/donkeycar | donkeycar/tests/test_kinematics.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/tests/test_kinematics.py | MIT |
def calc_bicycle_pose(wheelbase, front_wheel, orientation, steering_angle, distance):
"""
Calculate the ending pose for a bicycle with the given wheel base,
starting front wheel position, orientation, and steering angle that has
driven the given distance.
:param wheelbase:
:param front_wheel:
... |
Calculate the ending pose for a bicycle with the given wheel base,
starting front wheel position, orientation, and steering angle that has
driven the given distance.
:param wheelbase:
:param front_wheel:
:param orientation:
:param steering_angle:
:return: ending pose as tuple of (x, y, ... | calc_bicycle_pose | python | autorope/donkeycar | donkeycar/tests/test_kinematics.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/tests/test_kinematics.py | MIT |
def calc_line_length(p1, p2):
"""
Calculate the length of a line segment given its endpoints.
Args:
p1 (tuple): The x and y coordinates of the first endpoint (x1, y1).
p2 (tuple): The x and y coordinates of the second endpoint (x2, y2).
Returns:
float: The length of the line se... |
Calculate the length of a line segment given its endpoints.
Args:
p1 (tuple): The x and y coordinates of the first endpoint (x1, y1).
p2 (tuple): The x and y coordinates of the second endpoint (x2, y2).
Returns:
float: The length of the line segment.
| calc_line_length | python | autorope/donkeycar | donkeycar/tests/test_kinematics.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/tests/test_kinematics.py | MIT |
def test_controller_update_with_adjusted_max_throttle(self, serial):
'''
The adjusted MAX_FORWARD here should not affect the output throttle
value.
For example, when RC controller sending a 2000 value it means the user
want to go full speed. The throttle value should therefore be... |
The adjusted MAX_FORWARD here should not affect the output throttle
value.
For example, when RC controller sending a 2000 value it means the user
want to go full speed. The throttle value should therefore be 1.0. It is
the RoboHATDriver responsibility to translate this 1.0 to an... | test_controller_update_with_adjusted_max_throttle | python | autorope/donkeycar | donkeycar/tests/test_robohat.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/tests/test_robohat.py | MIT |
def test_controller_load_cfg(self):
'''
Make sure the controller load the value from config
'''
cfg.MM1_MAX_FORWARD = 1800
cfg.MM1_MAX_REVERSE = 1200
cfg.MM1_STOPPED_PWM = 1550
cfg.MM1_STEERING_MID = 1450
controller = RoboHATController(cfg)
asser... |
Make sure the controller load the value from config
| test_controller_load_cfg | python | autorope/donkeycar | donkeycar/tests/test_robohat.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/tests/test_robohat.py | MIT |
def config() -> Config:
""" Config for the test with relevant parameters"""
cfg = Config()
cfg.BATCH_SIZE = 2
cfg.TRAIN_TEST_SPLIT = 0.8
cfg.IMAGE_H = 120
cfg.IMAGE_W = 160
cfg.IMAGE_DEPTH = 3
cfg.PRINT_MODEL_SUMMARY = True
cfg.EARLY_STOP_PATIENCE = 1000
cfg.MAX_EPOCHS = 3
cf... | Config for the test with relevant parameters | config | python | autorope/donkeycar | donkeycar/tests/test_torch.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/tests/test_torch.py | MIT |
def car_dir(tmpdir_factory):
""" Creating car dir with sub dirs and extracting tub """
dir = tmpdir_factory.mktemp('mycar')
os.mkdir(os.path.join(dir, 'models'))
# extract tub.tar.gz into temp car_dir/tub
this_dir = os.path.dirname(os.path.abspath(__file__))
with tarfile.open(os.path.join(this_d... | Creating car dir with sub dirs and extracting tub | car_dir | python | autorope/donkeycar | donkeycar/tests/test_torch.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/tests/test_torch.py | MIT |
def test_train(config: Config, car_dir: str, data: Data) -> None:
"""
Testing convergence of the linear model
:param config: donkey config
:param car_dir: car directory (this is a temp dir)
:param data: test case data
:return: None
"""
from don... |
Testing convergence of the linear model
:param config: donkey config
:param car_dir: car directory (this is a temp dir)
:param data: test case data
:return: None
| test_train | python | autorope/donkeycar | donkeycar/tests/test_torch.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/tests/test_torch.py | MIT |
def test_training_pipeline(config: Config, model_type: str, car_dir: str) \
-> None:
"""
Testing consistency of the model interfaces and data used in training
pipeline.
:param config: donkey config
:param model_type: test specification of model type
:param ... |
Testing consistency of the model interfaces and data used in training
pipeline.
:param config: donkey config
:param model_type: test specification of model type
:param tub_dir: tub directory (car_dir/tub)
:return: None
| test_training_pipeline | python | autorope/donkeycar | donkeycar/tests/test_torch.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/tests/test_torch.py | MIT |
def test_train(config: Config, data: Data) -> None:
"""
Testing convergence of the above models
:param config: donkey config
:param data: test case data
:return: None
"""
def pilot_path(name):
pilot_name = f'pilot_{name}.savedmodel'
return o... |
Testing convergence of the above models
:param config: donkey config
:param data: test case data
:return: None
| test_train | python | autorope/donkeycar | donkeycar/tests/test_train.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/tests/test_train.py | MIT |
def test_training_pipeline(config: Config, model_type: str,
train_filter: Callable[[TubRecord], bool]) -> None:
"""
Testing consistency of the model interfaces and data used in training
pipeline.
:param config: donkey config
:param model_type: ... |
Testing consistency of the model interfaces and data used in training
pipeline.
:param config: donkey config
:param model_type: test specification of model type
:param train_filter: filter for records
:return: None
| test_training_pipeline | python | autorope/donkeycar | donkeycar/tests/test_train.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/tests/test_train.py | MIT |
def create_lbin(marker_index):
""" Create a linear binary array with value set """
l = [0] * 15
l[marker_index] = 1
return l | Create a linear binary array with value set | create_lbin | python | autorope/donkeycar | donkeycar/tests/test_util_data.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/tests/test_util_data.py | MIT |
def head(self):
"""
Non-destructive get of the entry at the head (index count-1)
return: if list is not empty, the head (most recently pushed/enqueued) entry.
if list is empty, the default value provided in the constructor
"""
if self.count > 0:
... |
Non-destructive get of the entry at the head (index count-1)
return: if list is not empty, the head (most recently pushed/enqueued) entry.
if list is empty, the default value provided in the constructor
| head | python | autorope/donkeycar | donkeycar/utilities/circular_buffer.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/utilities/circular_buffer.py | MIT |
def tail(self):
"""
Non-destructive get of the entry at the tail (index 0)
return: if list is not empty, the tail (least recently pushed/enqueued) entry.
if list is empty, the default value provided in the constructor
"""
if self.count > 0:
return self... |
Non-destructive get of the entry at the tail (index 0)
return: if list is not empty, the tail (least recently pushed/enqueued) entry.
if list is empty, the default value provided in the constructor
| tail | python | autorope/donkeycar | donkeycar/utilities/circular_buffer.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/utilities/circular_buffer.py | MIT |
def enqueue(self, value):
"""
Push a value onto the head of the buffer.
If the buffer is full, then the value
at the tail is dropped to make room.
"""
if self.count < self.capacity:
self.count += 1
else:
# drop entry at the tail
... |
Push a value onto the head of the buffer.
If the buffer is full, then the value
at the tail is dropped to make room.
| enqueue | python | autorope/donkeycar | donkeycar/utilities/circular_buffer.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/utilities/circular_buffer.py | MIT |
def dequeue(self):
"""
Remove value at tail of list and return it
return: if list not empty, value at tail
if list empty, the default value
"""
theValue = self.tail()
if self.count > 0:
self.count -= 1
self.tailIndex = (self.tailInd... |
Remove value at tail of list and return it
return: if list not empty, value at tail
if list empty, the default value
| dequeue | python | autorope/donkeycar | donkeycar/utilities/circular_buffer.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/utilities/circular_buffer.py | MIT |
def push(self, value):
"""
Push a value onto the head of the buffer.
If the buffer is full, then a IndexError
is raised.
"""
if self.count >= self.capacity:
raise IndexError("Attempt to push to a full buffer")
self.enqueue(value) |
Push a value onto the head of the buffer.
If the buffer is full, then a IndexError
is raised.
| push | python | autorope/donkeycar | donkeycar/utilities/circular_buffer.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/utilities/circular_buffer.py | MIT |
def pop(self):
"""
Remove value at head of list and return it
return: if list not empty, the value at head
if list empty, the default value
"""
theValue = self.head()
if self.count > 0:
self.count -= 1
return theValue |
Remove value at head of list and return it
return: if list not empty, the value at head
if list empty, the default value
| pop | python | autorope/donkeycar | donkeycar/utilities/circular_buffer.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/utilities/circular_buffer.py | MIT |
def append(self, value):
"""
append a value to the tail (index count-1) of the buffer.
If the buffer is at capacity, then this
will raise an IndexError.
"""
if self.count >= self.capacity:
raise IndexError("Attempt to append to a full buffer")
# make ... |
append a value to the tail (index count-1) of the buffer.
If the buffer is at capacity, then this
will raise an IndexError.
| append | python | autorope/donkeycar | donkeycar/utilities/circular_buffer.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/utilities/circular_buffer.py | MIT |
def get(self, i:int):
"""
Get value at given index where
head is index 0 and tail is is index count-1;
i: index from 0 to count-1 (head is zero)
return: value at index
or the default value if index is out of range
"""
if (i >= 0) and (i < self.coun... |
Get value at given index where
head is index 0 and tail is is index count-1;
i: index from 0 to count-1 (head is zero)
return: value at index
or the default value if index is out of range
| get | python | autorope/donkeycar | donkeycar/utilities/circular_buffer.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/utilities/circular_buffer.py | MIT |
def set(self, i:int, value):
"""
Set value at given index where
head is index 0 and tail is is index count-1;
"""
if (i >= 0) and (i < self.count):
self.buffer[(self.tailIndex + (self.count + i - 1)) % self.capacity] = value
return
raise IndexError... |
Set value at given index where
head is index 0 and tail is is index count-1;
| set | python | autorope/donkeycar | donkeycar/utilities/circular_buffer.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/utilities/circular_buffer.py | MIT |
def truncateTo(self, count):
"""
Truncate the list to the given number of values.
If the given number is greater than or equal to
the current count(), then nothing is changed.
If the given number is less than the
current count(), then elements are dropped
from th... |
Truncate the list to the given number of values.
If the given number is greater than or equal to
the current count(), then nothing is changed.
If the given number is less than the
current count(), then elements are dropped
from the tail to resize to the given number.
... | truncateTo | python | autorope/donkeycar | donkeycar/utilities/circular_buffer.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/utilities/circular_buffer.py | MIT |
def read_chip_id() -> str:
"""
Read the tegra chip id.
On non-tegra platforms this will be blank.
"""
try:
with open("/sys/module/tegra_fuse/parameters/tegra_chip_id", "r") as f:
return next(f)
except FileNotFoundError:
pass
return "" |
Read the tegra chip id.
On non-tegra platforms this will be blank.
| read_chip_id | python | autorope/donkeycar | donkeycar/utilities/dk_platform.py | https://github.com/autorope/donkeycar/blob/master/donkeycar/utilities/dk_platform.py | MIT |
def convert_to_tub_v2(paths, output_path):
"""
Convert from old tubs to new one
:param paths: legacy tub paths
:param output_path: new tub output path
:return: None
"""
empty_record = {'__empty__': True}
if type(paths) is str:
paths = [pa... |
Convert from old tubs to new one
:param paths: legacy tub paths
:param output_path: new tub output path
:return: None
| convert_to_tub_v2 | python | autorope/donkeycar | scripts/convert_to_tub_v2.py | https://github.com/autorope/donkeycar/blob/master/scripts/convert_to_tub_v2.py | MIT |
def show_pixel_values(image, x, y):
"""
Create text lines that show the value of the given pixel
The text lines are used in the main loop to draw text.
"""
text = []
if image is not None:
text.append(f"Pixel at x={x}, y={y}")
colorsRGB = image[y,x]
text.append(f"Pixel RG... |
Create text lines that show the value of the given pixel
The text lines are used in the main loop to draw text.
| show_pixel_values | python | autorope/donkeycar | scripts/hsv_picker.py | https://github.com/autorope/donkeycar/blob/master/scripts/hsv_picker.py | MIT |
def bgr_to_hsv(pixelRGB):
"""
Convert a single RGB pixel to HSV
"""
imgRGB = np.uint8([[pixelRGB]])
imgHSV = cv2.cvtColor(imgRGB, cv2.COLOR_BGR2HSV)
pixelHSV = imgHSV[0][0]
return pixelHSV |
Convert a single RGB pixel to HSV
| bgr_to_hsv | python | autorope/donkeycar | scripts/hsv_picker.py | https://github.com/autorope/donkeycar/blob/master/scripts/hsv_picker.py | MIT |
def list_templates(config: Config) -> None:
"""List available templates.
:param config: a :class:`.Config` object.
"""
config.print_stdout("Available templates:\n")
for tempname in config._get_template_path().iterdir():
with (tempname / "README").open() as readme:
synopsis = n... | List available templates.
:param config: a :class:`.Config` object.
| list_templates | python | sqlalchemy/alembic | alembic/command.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/command.py | MIT |
def init(
config: Config,
directory: str,
template: str = "generic",
package: bool = False,
) -> None:
"""Initialize a new scripts directory.
:param config: a :class:`.Config` object.
:param directory: string path of the target directory.
:param template: string name of the migration ... | Initialize a new scripts directory.
:param config: a :class:`.Config` object.
:param directory: string path of the target directory.
:param template: string name of the migration environment template to
use.
:param package: when True, write ``__init__.py`` files into the
environment locati... | init | python | sqlalchemy/alembic | alembic/command.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/command.py | MIT |
def revision(
config: Config,
message: Optional[str] = None,
autogenerate: bool = False,
sql: bool = False,
head: str = "head",
splice: bool = False,
branch_label: Optional[_RevIdType] = None,
version_path: Union[str, os.PathLike[str], None] = None,
rev_id: Optional[str] = None,
... | Create a new revision file.
:param config: a :class:`.Config` object.
:param message: string message to apply to the revision; this is the
``-m`` option to ``alembic revision``.
:param autogenerate: whether or not to autogenerate the script from
the database; this is the ``--autogenerate`` opti... | revision | python | sqlalchemy/alembic | alembic/command.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/command.py | MIT |
def check(config: "Config") -> None:
"""Check if revision command with autogenerate has pending upgrade ops.
:param config: a :class:`.Config` object.
.. versionadded:: 1.9.0
"""
script_directory = ScriptDirectory.from_config(config)
command_args = dict(
message=None,
autoge... | Check if revision command with autogenerate has pending upgrade ops.
:param config: a :class:`.Config` object.
.. versionadded:: 1.9.0
| check | python | sqlalchemy/alembic | alembic/command.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/command.py | MIT |
def merge(
config: Config,
revisions: _RevIdType,
message: Optional[str] = None,
branch_label: Optional[_RevIdType] = None,
rev_id: Optional[str] = None,
) -> Optional[Script]:
"""Merge two revisions together. Creates a new migration file.
:param config: a :class:`.Config` instance
:p... | Merge two revisions together. Creates a new migration file.
:param config: a :class:`.Config` instance
:param revisions: The revisions to merge.
:param message: string message to apply to the revision.
:param branch_label: string label name to apply to the new revision.
:param rev_id: hardcode... | merge | python | sqlalchemy/alembic | alembic/command.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/command.py | MIT |
def upgrade(
config: Config,
revision: str,
sql: bool = False,
tag: Optional[str] = None,
) -> None:
"""Upgrade to a later version.
:param config: a :class:`.Config` instance.
:param revision: string revision target or range for --sql mode. May be
``"heads"`` to target the most recent... | Upgrade to a later version.
:param config: a :class:`.Config` instance.
:param revision: string revision target or range for --sql mode. May be
``"heads"`` to target the most recent revision(s).
:param sql: if True, use ``--sql`` mode.
:param tag: an arbitrary "tag" that can be intercepted by c... | upgrade | python | sqlalchemy/alembic | alembic/command.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/command.py | MIT |
def downgrade(
config: Config,
revision: str,
sql: bool = False,
tag: Optional[str] = None,
) -> None:
"""Revert to a previous version.
:param config: a :class:`.Config` instance.
:param revision: string revision target or range for --sql mode. May
be ``"base"`` to target the first re... | Revert to a previous version.
:param config: a :class:`.Config` instance.
:param revision: string revision target or range for --sql mode. May
be ``"base"`` to target the first revision.
:param sql: if True, use ``--sql`` mode.
:param tag: an arbitrary "tag" that can be intercepted by custom
... | downgrade | python | sqlalchemy/alembic | alembic/command.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/command.py | MIT |
def show(config: Config, rev: str) -> None:
"""Show the revision(s) denoted by the given symbol.
:param config: a :class:`.Config` instance.
:param rev: string revision target. May be ``"current"`` to show the
revision(s) currently applied in the database.
"""
script = ScriptDirectory.from_... | Show the revision(s) denoted by the given symbol.
:param config: a :class:`.Config` instance.
:param rev: string revision target. May be ``"current"`` to show the
revision(s) currently applied in the database.
| show | python | sqlalchemy/alembic | alembic/command.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/command.py | MIT |
def history(
config: Config,
rev_range: Optional[str] = None,
verbose: bool = False,
indicate_current: bool = False,
) -> None:
"""List changeset scripts in chronological order.
:param config: a :class:`.Config` instance.
:param rev_range: string revision range.
:param verbose: output... | List changeset scripts in chronological order.
:param config: a :class:`.Config` instance.
:param rev_range: string revision range.
:param verbose: output in verbose mode.
:param indicate_current: indicate current revision.
| history | python | sqlalchemy/alembic | alembic/command.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/command.py | MIT |
def heads(
config: Config, verbose: bool = False, resolve_dependencies: bool = False
) -> None:
"""Show current available heads in the script directory.
:param config: a :class:`.Config` instance.
:param verbose: output in verbose mode.
:param resolve_dependencies: treat dependency version as dow... | Show current available heads in the script directory.
:param config: a :class:`.Config` instance.
:param verbose: output in verbose mode.
:param resolve_dependencies: treat dependency version as down revisions.
| heads | python | sqlalchemy/alembic | alembic/command.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/command.py | MIT |
def branches(config: Config, verbose: bool = False) -> None:
"""Show current branch points.
:param config: a :class:`.Config` instance.
:param verbose: output in verbose mode.
"""
script = ScriptDirectory.from_config(config)
for sc in script.walk_revisions():
if sc.is_branch_point:
... | Show current branch points.
:param config: a :class:`.Config` instance.
:param verbose: output in verbose mode.
| branches | python | sqlalchemy/alembic | alembic/command.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/command.py | MIT |
def current(config: Config, verbose: bool = False) -> None:
"""Display the current revision for a database.
:param config: a :class:`.Config` instance.
:param verbose: output in verbose mode.
"""
script = ScriptDirectory.from_config(config)
def display_version(rev, context):
if verb... | Display the current revision for a database.
:param config: a :class:`.Config` instance.
:param verbose: output in verbose mode.
| current | python | sqlalchemy/alembic | alembic/command.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/command.py | MIT |
def stamp(
config: Config,
revision: _RevIdType,
sql: bool = False,
tag: Optional[str] = None,
purge: bool = False,
) -> None:
"""'stamp' the revision table with the given revision; don't
run any migrations.
:param config: a :class:`.Config` instance.
:param revision: target revisi... | 'stamp' the revision table with the given revision; don't
run any migrations.
:param config: a :class:`.Config` instance.
:param revision: target revision or list of revisions. May be a list
to indicate stamping of multiple branch heads; may be ``"base"``
to remove all revisions from the table... | stamp | python | sqlalchemy/alembic | alembic/command.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/command.py | MIT |
def edit(config: Config, rev: str) -> None:
"""Edit revision script(s) using $EDITOR.
:param config: a :class:`.Config` instance.
:param rev: target revision.
"""
script = ScriptDirectory.from_config(config)
if rev == "current":
def edit_current(rev, context):
if not re... | Edit revision script(s) using $EDITOR.
:param config: a :class:`.Config` instance.
:param rev: target revision.
| edit | python | sqlalchemy/alembic | alembic/command.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/command.py | MIT |
def ensure_version(config: Config, sql: bool = False) -> None:
"""Create the alembic version table if it doesn't exist already .
:param config: a :class:`.Config` instance.
:param sql: use ``--sql`` mode.
.. versionadded:: 1.7.6
"""
script = ScriptDirectory.from_config(config)
def do_... | Create the alembic version table if it doesn't exist already .
:param config: a :class:`.Config` instance.
:param sql: use ``--sql`` mode.
.. versionadded:: 1.7.6
| ensure_version | python | sqlalchemy/alembic | alembic/command.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/command.py | MIT |
def print_stdout(self, text: str, *arg: Any) -> None:
"""Render a message to standard out.
When :meth:`.Config.print_stdout` is called with additional args
those arguments will formatted against the provided text,
otherwise we simply output the provided text verbatim.
This is a... | Render a message to standard out.
When :meth:`.Config.print_stdout` is called with additional args
those arguments will formatted against the provided text,
otherwise we simply output the provided text verbatim.
This is a no-op when the``quiet`` messaging option is enabled.
e.... | print_stdout | python | sqlalchemy/alembic | alembic/config.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/config.py | MIT |
def file_config(self) -> ConfigParser:
"""Return the underlying ``ConfigParser`` object.
Dir*-ect access to the .ini file is available here,
though the :meth:`.Config.get_section` and
:meth:`.Config.get_main_option`
methods provide a possibly simpler interface.
"""
... | Return the underlying ``ConfigParser`` object.
Dir*-ect access to the .ini file is available here,
though the :meth:`.Config.get_section` and
:meth:`.Config.get_main_option`
methods provide a possibly simpler interface.
| file_config | python | sqlalchemy/alembic | alembic/config.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/config.py | MIT |
def toml_alembic_config(self) -> Mapping[str, Any]:
"""Return a dictionary of the [tool.alembic] section from
pyproject.toml"""
if self._toml_file_path and self._toml_file_path.exists():
here = self._toml_file_path.absolute().parent
self.toml_args["here"] = here.as_posi... | Return a dictionary of the [tool.alembic] section from
pyproject.toml | toml_alembic_config | python | sqlalchemy/alembic | alembic/config.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/config.py | MIT |
def get_template_directory(self) -> str:
"""Return the directory where Alembic setup templates are found.
This method is used by the alembic ``init`` and ``list_templates``
commands.
"""
import alembic
package_dir = Path(alembic.__file__).absolute().parent
retu... | Return the directory where Alembic setup templates are found.
This method is used by the alembic ``init`` and ``list_templates``
commands.
| get_template_directory | python | sqlalchemy/alembic | alembic/config.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/config.py | MIT |
def get_section(
self, name: str, default: Optional[Mapping[str, str]] = None
) -> Optional[Mapping[str, str]]:
"""Return all the configuration options from a given .ini file section
as a dictionary.
If the given section does not exist, the value of ``default``
is returned, ... | Return all the configuration options from a given .ini file section
as a dictionary.
If the given section does not exist, the value of ``default``
is returned, which is expected to be a dictionary or other mapping.
| get_section | python | sqlalchemy/alembic | alembic/config.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/config.py | MIT |
def set_section_option(self, section: str, name: str, value: str) -> None:
"""Set an option programmatically within the given section.
The section is created if it doesn't exist already.
The value here will override whatever was in the .ini
file.
Does **NOT** consume from the p... | Set an option programmatically within the given section.
The section is created if it doesn't exist already.
The value here will override whatever was in the .ini
file.
Does **NOT** consume from the pyproject.toml file.
.. seealso::
:meth:`.Config.get_alembic_opti... | set_section_option | python | sqlalchemy/alembic | alembic/config.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/config.py | MIT |
def get_section_option(
self, section: str, name: str, default: Optional[str] = None
) -> Optional[str]:
"""Return an option from the given section of the .ini file."""
if not self.file_config.has_section(section):
raise util.CommandError(
"No config file %r found... | Return an option from the given section of the .ini file. | get_section_option | python | sqlalchemy/alembic | alembic/config.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/config.py | MIT |
def get_main_option(
self, name: str, default: Optional[str] = None
) -> Optional[str]:
"""Return an option from the 'main' section of the .ini file.
This defaults to being a key from the ``[alembic]``
section, unless the ``-n/--name`` flag were used to
indicate a different ... | Return an option from the 'main' section of the .ini file.
This defaults to being a key from the ``[alembic]``
section, unless the ``-n/--name`` flag were used to
indicate a different section.
Does **NOT** consume from the pyproject.toml file.
.. seealso::
:meth:`... | get_main_option | python | sqlalchemy/alembic | alembic/config.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/config.py | MIT |
def get_alembic_option(
self, name: str, default: Optional[str] = None
) -> Union[None, str, list[str], dict[str, str], list[dict[str, str]]]:
"""Return an option from the "[alembic]" or "[tool.alembic]" section
of the configparser-parsed .ini file (e.g. ``alembic.ini``) or
toml-pars... | Return an option from the "[alembic]" or "[tool.alembic]" section
of the configparser-parsed .ini file (e.g. ``alembic.ini``) or
toml-parsed ``pyproject.toml`` file.
The value returned is expected to be None, string, list of strings,
or dictionary of strings. Within each type of strin... | get_alembic_option | python | sqlalchemy/alembic | alembic/config.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/config.py | MIT |
def register_command(self, fn: CommandFunction) -> None:
"""Registers a function as a CLI subcommand. The subcommand name
matches the function name, the arguments are extracted from the
signature and the help text is read from the docstring.
.. versionadded:: 1.15.3
.. seealso:... | Registers a function as a CLI subcommand. The subcommand name
matches the function name, the arguments are extracted from the
signature and the help text is read from the docstring.
.. versionadded:: 1.15.3
.. seealso::
:ref:`custom_commandline`
| register_command | python | sqlalchemy/alembic | alembic/config.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/config.py | MIT |
def main(self, argv: Optional[Sequence[str]] = None) -> None:
"""Executes the command line with the provided arguments."""
options = self.parser.parse_args(argv)
if not hasattr(options, "cmd"):
# see http://bugs.python.org/issue9253, argparse
# behavior changed incompatib... | Executes the command line with the provided arguments. | main | python | sqlalchemy/alembic | alembic/config.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/config.py | MIT |
def main(
argv: Optional[Sequence[str]] = None,
prog: Optional[str] = None,
**kwargs: Any,
) -> None:
"""The console runner function for Alembic."""
CommandLine(prog=prog).main(argv=argv) | The console runner function for Alembic. | main | python | sqlalchemy/alembic | alembic/config.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/config.py | MIT |
def compare_metadata(context: MigrationContext, metadata: MetaData) -> Any:
"""Compare a database schema to that given in a
:class:`~sqlalchemy.schema.MetaData` instance.
The database connection is presented in the context
of a :class:`.MigrationContext` object, which
provides database connectivity... | Compare a database schema to that given in a
:class:`~sqlalchemy.schema.MetaData` instance.
The database connection is presented in the context
of a :class:`.MigrationContext` object, which
provides database connectivity as well as optional
comparison functions to use for datatypes and
server d... | compare_metadata | python | sqlalchemy/alembic | alembic/autogenerate/api.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/autogenerate/api.py | MIT |
def produce_migrations(
context: MigrationContext, metadata: MetaData
) -> MigrationScript:
"""Produce a :class:`.MigrationScript` structure based on schema
comparison.
This function does essentially what :func:`.compare_metadata` does,
but then runs the resulting list of diffs to produce the full
... | Produce a :class:`.MigrationScript` structure based on schema
comparison.
This function does essentially what :func:`.compare_metadata` does,
but then runs the resulting list of diffs to produce the full
:class:`.MigrationScript` object. For an example of what this looks like,
see the example in ... | produce_migrations | python | sqlalchemy/alembic | alembic/autogenerate/api.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/autogenerate/api.py | MIT |
def render_python_code(
up_or_down_op: Union[UpgradeOps, DowngradeOps],
sqlalchemy_module_prefix: str = "sa.",
alembic_module_prefix: str = "op.",
render_as_batch: bool = False,
imports: Sequence[str] = (),
render_item: Optional[RenderItemFn] = None,
migration_context: Optional[MigrationCont... | Render Python code given an :class:`.UpgradeOps` or
:class:`.DowngradeOps` object.
This is a convenience function that can be used to test the
autogenerate output of a user-defined :class:`.MigrationScript` structure.
:param up_or_down_op: :class:`.UpgradeOps` or :class:`.DowngradeOps` object
:par... | render_python_code | python | sqlalchemy/alembic | alembic/autogenerate/api.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/autogenerate/api.py | MIT |
def _render_migration_diffs(
context: MigrationContext, template_args: Dict[Any, Any]
) -> None:
"""legacy, used by test_autogen_composition at the moment"""
autogen_context = AutogenContext(context)
upgrade_ops = ops.UpgradeOps([])
compare._produce_net_changes(autogen_context, upgrade_ops)
m... | legacy, used by test_autogen_composition at the moment | _render_migration_diffs | python | sqlalchemy/alembic | alembic/autogenerate/api.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/autogenerate/api.py | MIT |
def run_name_filters(
self,
name: Optional[str],
type_: NameFilterType,
parent_names: NameFilterParentNames,
) -> bool:
"""Run the context's name filters and return True if the targets
should be part of the autogenerate operation.
This method should be run fo... | Run the context's name filters and return True if the targets
should be part of the autogenerate operation.
This method should be run for every kind of name encountered within the
reflection side of an autogenerate operation, giving the environment
the chance to filter what names should... | run_name_filters | python | sqlalchemy/alembic | alembic/autogenerate/api.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/autogenerate/api.py | MIT |
def run_object_filters(
self,
object_: SchemaItem,
name: sqla_compat._ConstraintName,
type_: NameFilterType,
reflected: bool,
compare_to: Optional[SchemaItem],
) -> bool:
"""Run the context's object filters and return True if the targets
should be part... | Run the context's object filters and return True if the targets
should be part of the autogenerate operation.
This method should be run for every kind of object encountered within
an autogenerate operation, giving the environment the chance
to filter what objects should be included in t... | run_object_filters | python | sqlalchemy/alembic | alembic/autogenerate/api.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/autogenerate/api.py | MIT |
def sorted_tables(self) -> List[Table]:
"""Return an aggregate of the :attr:`.MetaData.sorted_tables`
collection(s).
For a sequence of :class:`.MetaData` objects, this
concatenates the :attr:`.MetaData.sorted_tables` collection
for each individual :class:`.MetaData` in the orde... | Return an aggregate of the :attr:`.MetaData.sorted_tables`
collection(s).
For a sequence of :class:`.MetaData` objects, this
concatenates the :attr:`.MetaData.sorted_tables` collection
for each individual :class:`.MetaData` in the order of the
sequence. It does **not** collate... | sorted_tables | python | sqlalchemy/alembic | alembic/autogenerate/api.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/autogenerate/api.py | MIT |
def table_key_to_table(self) -> Dict[str, Table]:
"""Return an aggregate of the :attr:`.MetaData.tables` dictionaries.
The :attr:`.MetaData.tables` collection is a dictionary of table key
to :class:`.Table`; this method aggregates the dictionary across
multiple :class:`.MetaData` objec... | Return an aggregate of the :attr:`.MetaData.tables` dictionaries.
The :attr:`.MetaData.tables` collection is a dictionary of table key
to :class:`.Table`; this method aggregates the dictionary across
multiple :class:`.MetaData` objects into one dictionary.
Duplicate table keys are **n... | table_key_to_table | python | sqlalchemy/alembic | alembic/autogenerate/api.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/autogenerate/api.py | MIT |
def _ident(name: Optional[Union[quoted_name, str]]) -> Optional[str]:
"""produce a __repr__() object for a string identifier that may
use quoted_name() in SQLAlchemy 0.9 and greater.
The issue worked around here is that quoted_name() doesn't have
very good repr() behavior by itself when unicode is invo... | produce a __repr__() object for a string identifier that may
use quoted_name() in SQLAlchemy 0.9 and greater.
The issue worked around here is that quoted_name() doesn't have
very good repr() behavior by itself when unicode is involved.
| _ident | python | sqlalchemy/alembic | alembic/autogenerate/render.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/autogenerate/render.py | MIT |
def _fk_colspec(
fk: ForeignKey,
metadata_schema: Optional[str],
namespace_metadata: MetaData,
) -> str:
"""Implement a 'safe' version of ForeignKey._get_colspec() that
won't fail if the remote table can't be resolved.
"""
colspec = fk._get_colspec()
tokens = colspec.split(".")
tnam... | Implement a 'safe' version of ForeignKey._get_colspec() that
won't fail if the remote table can't be resolved.
| _fk_colspec | python | sqlalchemy/alembic | alembic/autogenerate/render.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/autogenerate/render.py | MIT |
def chain(
self,
other: Union[
ProcessRevisionDirectiveFn,
Rewriter,
],
) -> Rewriter:
"""Produce a "chain" of this :class:`.Rewriter` to another.
This allows two or more rewriters to operate serially on a stream,
e.g.::
writer1 =... | Produce a "chain" of this :class:`.Rewriter` to another.
This allows two or more rewriters to operate serially on a stream,
e.g.::
writer1 = autogenerate.Rewriter()
writer2 = autogenerate.Rewriter()
@writer1.rewrites(ops.AddColumnOp)
def add_column_nul... | chain | python | sqlalchemy/alembic | alembic/autogenerate/rewriter.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/autogenerate/rewriter.py | MIT |
def rewrites(
self,
operator: Union[
Type[AddColumnOp],
Type[MigrateOperation],
Type[AlterColumnOp],
Type[CreateTableOp],
Type[ModifyTableOps],
],
) -> Callable[..., Any]:
"""Register a function as rewriter for a given type.... | Register a function as rewriter for a given type.
The function should receive three arguments, which are
the :class:`.MigrationContext`, a ``revision`` tuple, and
an op directive of the type indicated. E.g.::
@writer1.rewrites(ops.AddColumnOp)
def add_column_nullable(c... | rewrites | python | sqlalchemy/alembic | alembic/autogenerate/rewriter.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/autogenerate/rewriter.py | MIT |
def quote_dotted(
name: Union[quoted_name, str], quote: functools.partial
) -> Union[quoted_name, str]:
"""quote the elements of a dotted name"""
if isinstance(name, quoted_name):
return quote(name)
result = ".".join([quote(x) for x in name.split(".")])
return result | quote the elements of a dotted name | quote_dotted | python | sqlalchemy/alembic | alembic/ddl/base.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/ddl/base.py | MIT |
def version_table_impl(
self,
*,
version_table: str,
version_table_schema: Optional[str],
version_table_pk: bool,
**kw: Any,
) -> Table:
"""Generate a :class:`.Table` object which will be used as the
structure for the Alembic version table.
Th... | Generate a :class:`.Table` object which will be used as the
structure for the Alembic version table.
Third party dialects may override this hook to provide an alternate
structure for this :class:`.Table`; requirements are only that it
be named based on the ``version_table`` parameter an... | version_table_impl | python | sqlalchemy/alembic | alembic/ddl/impl.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/ddl/impl.py | MIT |
def requires_recreate_in_batch(
self, batch_op: BatchOperationsImpl
) -> bool:
"""Return True if the given :class:`.BatchOperationsImpl`
would need the table to be recreated and copied in order to
proceed.
Normally, only returns True on SQLite when operations other
t... | Return True if the given :class:`.BatchOperationsImpl`
would need the table to be recreated and copied in order to
proceed.
Normally, only returns True on SQLite when operations other
than add_column are present.
| requires_recreate_in_batch | python | sqlalchemy/alembic | alembic/ddl/impl.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/ddl/impl.py | MIT |
def prep_table_for_batch(
self, batch_impl: ApplyBatchImpl, table: Table
) -> None:
"""perform any operations needed on a table before a new
one is created to replace it in batch mode.
the PG dialect uses this to drop constraints on the table
before the new one uses those sa... | perform any operations needed on a table before a new
one is created to replace it in batch mode.
the PG dialect uses this to drop constraints on the table
before the new one uses those same names.
| prep_table_for_batch | python | sqlalchemy/alembic | alembic/ddl/impl.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/ddl/impl.py | MIT |
def _column_args_match(
self, inspected_params: Params, meta_params: Params
) -> bool:
"""We want to compare column parameters. However, we only want
to compare parameters that are set. If they both have `collation`,
we want to make sure they are the same. However, if only one
... | We want to compare column parameters. However, we only want
to compare parameters that are set. If they both have `collation`,
we want to make sure they are the same. However, if only one
specifies it, dont flag it for being less specific
| _column_args_match | python | sqlalchemy/alembic | alembic/ddl/impl.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/ddl/impl.py | MIT |
def compare_type(
self, inspector_column: Column[Any], metadata_column: Column
) -> bool:
"""Returns True if there ARE differences between the types of the two
columns. Takes impl.type_synonyms into account between retrospected
and metadata types
"""
inspector_params ... | Returns True if there ARE differences between the types of the two
columns. Takes impl.type_synonyms into account between retrospected
and metadata types
| compare_type | python | sqlalchemy/alembic | alembic/ddl/impl.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/ddl/impl.py | MIT |
def render_ddl_sql_expr(
self, expr: ClauseElement, is_server_default: bool = False, **kw: Any
) -> str:
"""Render a SQL expression that is typically a server default,
index expression, etc.
"""
compile_kw = {"literal_binds": True, "include_table": False}
return st... | Render a SQL expression that is typically a server default,
index expression, etc.
| render_ddl_sql_expr | python | sqlalchemy/alembic | alembic/ddl/impl.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/ddl/impl.py | MIT |
def autogen_column_reflect(self, inspector, table, column_info):
"""A hook that is attached to the 'column_reflect' event for when
a Table is reflected from the database during the autogenerate
process.
Dialects can elect to modify the information gathered here.
""" | A hook that is attached to the 'column_reflect' event for when
a Table is reflected from the database during the autogenerate
process.
Dialects can elect to modify the information gathered here.
| autogen_column_reflect | python | sqlalchemy/alembic | alembic/ddl/impl.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/ddl/impl.py | MIT |
def start_migrations(self) -> None:
"""A hook called when :meth:`.EnvironmentContext.run_migrations`
is called.
Implementations can set up per-migration-run state here.
""" | A hook called when :meth:`.EnvironmentContext.run_migrations`
is called.
Implementations can set up per-migration-run state here.
| start_migrations | python | sqlalchemy/alembic | alembic/ddl/impl.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/ddl/impl.py | MIT |
def compare_indexes(
self,
metadata_index: Index,
reflected_index: Index,
) -> ComparisonResult:
"""Compare two indexes by comparing the signature generated by
``create_index_sig``.
This method returns a ``ComparisonResult``.
"""
msg: List[str] = []
... | Compare two indexes by comparing the signature generated by
``create_index_sig``.
This method returns a ``ComparisonResult``.
| compare_indexes | python | sqlalchemy/alembic | alembic/ddl/impl.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/ddl/impl.py | MIT |
def compare_unique_constraint(
self,
metadata_constraint: UniqueConstraint,
reflected_constraint: UniqueConstraint,
) -> ComparisonResult:
"""Compare two unique constraints by comparing the two signatures.
The arguments are two tuples that contain the unique constraint and
... | Compare two unique constraints by comparing the two signatures.
The arguments are two tuples that contain the unique constraint and
the signatures generated by ``create_unique_constraint_sig``.
This method returns a ``ComparisonResult``.
| compare_unique_constraint | python | sqlalchemy/alembic | alembic/ddl/impl.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/ddl/impl.py | MIT |
def _mysql_drop_constraint(
element: DropConstraint, compiler: MySQLDDLCompiler, **kw
) -> str:
"""Redefine SQLAlchemy's drop constraint to
raise errors for invalid constraint type."""
constraint = element.element
if isinstance(
constraint,
(
schema.ForeignKeyConstraint,... | Redefine SQLAlchemy's drop constraint to
raise errors for invalid constraint type. | _mysql_drop_constraint | python | sqlalchemy/alembic | alembic/ddl/mysql.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/ddl/mysql.py | MIT |
def batch_create_exclude_constraint(
cls,
operations: BatchOperations,
constraint_name: str,
*elements: Any,
**kw: Any,
) -> Optional[Table]:
"""Issue a "create exclude constraint" instruction using the
current batch migration context.
.. note:: This... | Issue a "create exclude constraint" instruction using the
current batch migration context.
.. note:: This method is Postgresql specific, and additionally
requires at least SQLAlchemy 1.0.
.. seealso::
:meth:`.Operations.create_exclude_constraint`
| batch_create_exclude_constraint | python | sqlalchemy/alembic | alembic/ddl/postgresql.py | https://github.com/sqlalchemy/alembic/blob/master/alembic/ddl/postgresql.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.