code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
for (host, port) in self.hosts: requestId = self._next_id() log.debug('Request %s: %s', requestId, payloads) try: conn = self._get_conn(host, port) request = encoder_fn(client_id=self.client_id, cor...
def _send_broker_unaware_request(self, payloads, encoder_fn, decoder_fn)
Attempt to send a broker-agnostic request to one of the available brokers. Keep trying until you succeed.
3.00294
2.895183
1.03722
# encoders / decoders do not maintain ordering currently # so we need to keep this so we can rebuild order before returning original_ordering = [(p.topic, p.partition) for p in payloads] broker = self._get_coordinator_for_group(group) # Send the list of request payload...
def _send_consumer_aware_request(self, group, payloads, encoder_fn, decoder_fn)
Send a list of requests to the consumer coordinator for the group specified using the supplied encode/decode functions. As the payloads that use consumer-aware requests do not contain the group (e.g. OffsetFetchRequest), all payloads must be for a single group. Arguments: group...
3.297688
3.250567
1.014496
c = copy.deepcopy(self) for key in c.conns: c.conns[key] = self.conns[key].copy() return c
def copy(self)
Create an inactive copy of the client object, suitable for passing to a separate thread. Note that the copied connections are not initialized, so reinit() must be called on the returned copy.
3.490806
4.109509
0.849446
topics = [kafka_bytestring(t) for t in topics] if topics: for topic in topics: self.reset_topic_metadata(topic) else: self.reset_all_metadata() resp = self.send_metadata_request(topics) log.debug('Updating broker metadata: %s', ...
def load_metadata_for_topics(self, *topics)
Fetch broker and topic-partition metadata from the server, and update internal data: broker list, topic/partition list, and topic/parition -> broker map This method should be called after receiving any error Arguments: *topics (optional): If a list of topics is provided, ...
3.770262
3.580459
1.053011
# KazooClient and SetPartitioner objects need to be instantiated after # the consumer process has forked. Instantiating prior to forking # gives the appearance that things are working but after forking the # connection to zookeeper is lost and no state changes are visible ...
def _partition(self)
Consume messages from kafka Consume messages from kafka using the Kazoo SetPartitioner to allow multiple consumer processes to negotiate access to the kafka partitions
4.297736
4.019778
1.069148
# if the robot is disabled, don't do anything if not self.robot_enabled: return distance = speed * tm_diff angle = rotation_speed * tm_diff x = distance * math.cos(angle) y = distance * math.sin(angle) self.distance_drive(x, y, angle)
def drive(self, speed, rotation_speed, tm_diff)
Call this from your :func:`PhysicsEngine.update_sim` function. Will update the robot's position on the simulation field. You can either calculate the speed & rotation manually, or you can use the predefined functions in :mod:`pyfrc.physics.drivetrains`. The outpu...
3.197351
3.514366
0.909795
# if the robot is disabled, don't do anything if not self.robot_enabled: return angle = vw * tm_diff vx = vx * tm_diff vy = vy * tm_diff x = vx * math.sin(angle) + vy * math.cos(angle) y = vx * math.cos(angle) + vy * math.sin(angle) ...
def vector_drive(self, vx, vy, vw, tm_diff)
Call this from your :func:`PhysicsEngine.update_sim` function. Will update the robot's position on the simulation field. This moves the robot using a velocity vector relative to the robot instead of by speed/rotation speed. :param vx: Speed in x direct...
2.836
3.04959
0.929961
with self._lock: self.vx += x self.vy += y self.angle += angle c = math.cos(self.angle) s = math.sin(self.angle) self.x += x * c - y * s self.y += x * s + y * c self._update_gyros(angle)
def distance_drive(self, x, y, angle)
Call this from your :func:`PhysicsEngine.update_sim` function. Will update the robot's position on the simulation field. This moves the robot some relative distance and angle from its current position. :param x: Feet to move the robot in the x dire...
2.886889
3.392035
0.851079
with self._lock: return self.x, self.y, self.angle
def get_position(self)
:returns: Robot's current position on the field as `(x,y,angle)`. `x` and `y` are specified in feet, `angle` is in radians
6.818837
6.160206
1.106917
with self._lock: dx = self.x - x dy = self.y - y distance = math.hypot(dx, dy) angle = math.atan2(dy, dx) return distance, math.degrees(angle)
def get_offset(self, x, y)
Computes how far away and at what angle a coordinate is located. Distance is returned in feet, angle is returned in degrees :returns: distance,angle offset of the given x,y coordinate .. versionadded:: 2018.1.7
2.866271
3.317144
0.864078
# TODO: There are some cases where it would be ok to do this... if not self.fake_time.slept[idx]: errstr = ( "%s() function is not calling wpilib.Timer.delay() in its loop!" % self.mode_map[self.mode] ) raise RuntimeError(errs...
def _check_sleep(self, idx)
This ensures that the robot code called Wait() at some point
7.982542
7.688096
1.038299
assert 0.0 < deadzone < 1.0 scale_param = 1.0 - deadzone def _linear_deadzone(motor_input): abs_motor_input = abs(motor_input) if abs_motor_input < deadzone: return 0.0 else: return math.copysign( (abs_motor_input - deadzone) / scale_para...
def linear_deadzone(deadzone: float) -> DeadzoneCallable
Real motors won't actually move unless you give them some minimum amount of input. This computes an output speed for a motor and causes it to 'not move' if the input isn't high enough. Additionally, the output is adjusted linearly to compensate. Example: For a deadzone of 0.2: ...
2.435285
2.726868
0.89307
return TwoMotorDrivetrain(x_wheelbase, speed, deadzone).get_vector(l_motor, r_motor)
def two_motor_drivetrain(l_motor, r_motor, x_wheelbase=2, speed=5, deadzone=None)
.. deprecated:: 2018.2.0 Use :class:`TwoMotorDrivetrain` instead
4.049776
4.973716
0.814235
return FourMotorDrivetrain(x_wheelbase, speed, deadzone).get_vector( lr_motor, rr_motor, lf_motor, rf_motor )
def four_motor_drivetrain( lr_motor, rr_motor, lf_motor, rf_motor, x_wheelbase=2, speed=5, deadzone=None )
.. deprecated:: 2018.2.0 Use :class:`FourMotorDrivetrain` instead
3.52676
3.066348
1.15015
return MecanumDrivetrain(x_wheelbase, y_wheelbase, speed, deadzone).get_vector( lr_motor, rr_motor, lf_motor, rf_motor )
def mecanum_drivetrain( lr_motor, rr_motor, lf_motor, rf_motor, x_wheelbase=2, y_wheelbase=3, speed=5, deadzone=None, )
.. deprecated:: 2018.2.0 Use :class:`MecanumDrivetrain` instead
2.746296
2.546097
1.07863
if deadzone: lf_motor = deadzone(lf_motor) lr_motor = deadzone(lr_motor) rf_motor = deadzone(rf_motor) rr_motor = deadzone(rr_motor) # Calculate speed of each wheel lr = lr_motor * speed rr = rr_motor * speed lf = lf_motor * speed rf = rf_motor * speed ...
def four_motor_swerve_drivetrain( lr_motor, rr_motor, lf_motor, rf_motor, lr_angle, rr_angle, lf_angle, rf_angle, x_wheelbase=2, y_wheelbase=2, speed=5, deadzone=None, )
Four motors that can be rotated in any direction If any motors are inverted, then you will need to multiply that motor's value by -1. :param lr_motor: Left rear motor value (-1 to 1); 1 is forward :param rr_motor: Right rear motor value (-1 to 1); 1 is forward ...
1.952722
1.977611
0.987415
if self.deadzone: l_motor = self.deadzone(l_motor) r_motor = self.deadzone(r_motor) l = -l_motor * self.speed r = r_motor * self.speed # Motion equations fwd = (l + r) * 0.5 rcw = (l - r) / float(self.x_wheelbase) self.l_speed =...
def get_vector(self, l_motor: float, r_motor: float) -> typing.Tuple[float, float]
Given motor values, retrieves the vector of (distance, speed) for your robot :param l_motor: Left motor value (-1 to 1); -1 is forward :param r_motor: Right motor value (-1 to 1); 1 is forward :returns: speed of robot (ft/s), clockwise rotation of robot (radians/s)
3.62531
3.530597
1.026826
if self.deadzone: lf_motor = self.deadzone(lf_motor) lr_motor = self.deadzone(lr_motor) rf_motor = self.deadzone(rf_motor) rr_motor = self.deadzone(rr_motor) l = -(lf_motor + lr_motor) * 0.5 * self.speed r = (rf_motor + rr_motor) * 0.5 *...
def get_vector( self, lr_motor: float, rr_motor: float, lf_motor: float, rf_motor: float ) -> typing.Tuple[float, float]
:param lr_motor: Left rear motor value (-1 to 1); -1 is forward :param rr_motor: Right rear motor value (-1 to 1); 1 is forward :param lf_motor: Left front motor value (-1 to 1); -1 is forward :param rf_motor: Right front motor value (-1 to 1); 1 is forward ...
2.763225
2.677422
1.032047
# # From http://www.chiefdelphi.com/media/papers/download/2722 pp7-9 # [F] [omega](r) = [V] # # F is # .25 .25 .25 .25 # -.25 .25 -.25 .25 # -.25k -.25k .25k .25k # # omega is # [lf lr rr rf] if self.deadzone: ...
def get_vector( self, lr_motor: float, rr_motor: float, lf_motor: float, rf_motor: float ) -> typing.Tuple[float, float, float]
Given motor values, retrieves the vector of (distance, speed) for your robot :param lr_motor: Left rear motor value (-1 to 1); 1 is forward :param rr_motor: Right rear motor value (-1 to 1); 1 is forward :param lf_motor: Left front motor value (-1 to 1); 1 is forward ...
3.333166
3.310256
1.006921
return pymysql.connect( host=host, port=port, user=user, passwd=password, db=database )
def connect_mysql(host, port, user, password, database)
Connect to MySQL with retries.
2.565949
2.6742
0.95952
logger.info('Waiting for database: `%s`', MYSQL_DB) connect_mysql( host=MYSQL_HOST, port=MYSQL_PORT, user=MYSQL_USER, password=MYSQL_PASSWORD, database=MYSQL_DB ) logger.info('Database `%s` found', MYSQL_DB)
def main()
Start main part of the wait script.
4.054515
3.735475
1.085408
return numpy.array([data[indices_of_increasing.index(i)] for i in range(len(data))])
def unsort_vector(data, indices_of_increasing)
Upermutate 1-D data that is sorted by indices_of_increasing.
3.025753
2.878546
1.051139
if not plt: raise ImportError('Cannot plot without the matplotlib package') plt.rcParams.update({'font.size': 8}) plt.figure() num_cols = len(ace_model.x) / 2 + 1 for i in range(len(ace_model.x)): plt.subplot(num_cols, 2, i + 1) plt.plot(ace_model.x[i], ace_model.x_trans...
def plot_transforms(ace_model, fname='ace_transforms.png')
Plot the transforms.
2.38909
2.329056
1.025776
if not plt: raise ImportError('Cannot plot without the matplotlib package') plt.rcParams.update({'font.size': 8}) plt.figure() num_cols = len(ace_model.x) / 2 + 1 for i in range(len(ace_model.x)): plt.subplot(num_cols, 2, i + 1) plt.plot(ace_model.x[i], ace_model.y, '.')...
def plot_input(ace_model, fname='ace_input.png')
Plot the transforms.
2.426768
2.400263
1.011042
self.x = x_input self.y = y_input
def specify_data_set(self, x_input, y_input)
Define input to ACE. Parameters ---------- x_input : list list of iterables, one for each independent variable y_input : array the dependent observations
2.824749
3.978783
0.709953
self._initialize() while self._outer_error_is_decreasing() and self._outer_iters < MAX_OUTERS: print('* Starting outer iteration {0:03d}. Current err = {1:12.5E}' ''.format(self._outer_iters, self._last_outer_error)) self._iterate_to_update_x_transforms...
def solve(self)
Run the ACE calculational loop.
6.135402
5.611114
1.093438
self.y_transform = self.y - numpy.mean(self.y) self.y_transform /= numpy.std(self.y_transform) self.x_transforms = [numpy.zeros(len(self.y)) for _xi in self.x] self._compute_sorted_indices()
def _initialize(self)
Set up and normalize initial data once input data is specified.
4.446265
4.001266
1.111214
sorted_indices = [] for to_sort in [self.y] + self.x: data_w_indices = [(val, i) for (i, val) in enumerate(to_sort)] data_w_indices.sort() sorted_indices.append([i for val, i in data_w_indices]) # save in meaningful variable names self._yi_sor...
def _compute_sorted_indices(self)
The smoothers need sorted data. This sorts it from the perspective of each column. if self._x[0][3] is the 9th-smallest value in self._x[0], then _xi_sorted[3] = 8 We only have to sort the data once.
4.23562
3.60191
1.175937
is_decreasing, self._last_outer_error = self._error_is_decreasing(self._last_outer_error) return is_decreasing
def _outer_error_is_decreasing(self)
True if outer iteration error is decreasing.
3.97193
3.148581
1.261499
current_error = self._compute_error() is_decreasing = current_error < last_error return is_decreasing, current_error
def _error_is_decreasing(self, last_error)
True if current error is less than last_error.
3.796587
3.356946
1.130964
sum_x = sum(self.x_transforms) err = sum((self.y_transform - sum_x) ** 2) / len(sum_x) return err
def _compute_error(self)
Compute unexplained error.
5.561031
4.80627
1.157037
self._inner_iters = 0 self._last_inner_error = float('inf') while self._inner_error_is_decreasing(): print(' Starting inner iteration {0:03d}. Current err = {1:12.5E}' ''.format(self._inner_iters, self._last_inner_error)) self._update_x_transfo...
def _iterate_to_update_x_transforms(self)
Perform the inner iteration.
3.888999
3.410635
1.140257
# start by subtracting all transforms theta_minus_phis = self.y_transform - numpy.sum(self.x_transforms, axis=0) # add one transform at a time so as to exclude it from the subtracted sum for xtransform_index in range(len(self.x_transforms)): xtransform = self.x_tran...
def _update_x_transforms(self)
Compute a new set of x-transform functions phik. phik(xk) = theta(y) - sum of phii(xi) over i!=k This is the first of the eponymous conditional expectations. The conditional expectations are computed using the SuperSmoother.
4.745529
4.307479
1.101695
# sort all phis wrt increasing y. sorted_data_indices = self._yi_sorted sorted_xtransforms = [] for xt in self.x_transforms: sorted_xt = sort_vector(xt, sorted_data_indices) sorted_xtransforms.append(sorted_xt) sum_of_x_transformations_choppy = n...
def _update_y_transform(self)
Update the y-transform (theta). y-transform theta is forced to have mean = 0 and stddev = 1. This is the second conditional expectation
3.989678
3.862775
1.032853
self._write_columns(fname, self.x, self.y)
def write_input_to_file(self, fname='ace_input.txt')
Write y and x values used in this run to a space-delimited txt file.
11.97967
7.854191
1.525258
self._write_columns(fname, self.x_transforms, self.y_transform)
def write_transforms_to_file(self, fname='ace_transforms.txt')
Write y and x transforms used in this run to a space-delimited txt file.
10.102797
7.462373
1.353832
x = numpy.random.uniform(size=N) err = numpy.random.standard_normal(N) y = numpy.sin(2 * math.pi * (1 - x) ** 2) + x * err return x, y
def build_sample_smoother_problem_friedman82(N=200)
Sample problem from supersmoother publication.
3.757331
3.468169
1.083376
x, y = build_sample_smoother_problem_friedman82() plt.figure() # plt.plot(x, y, '.', label='Data') for span in smoother.DEFAULT_SPANS: smooth = smoother.BasicFixedSpanSmoother() smooth.specify_data_set(x, y, sort_data=True) smooth.set_span(span) smooth.compute() ...
def run_friedman82_basic()
Run Friedman's test of fixed-span smoothers from Figure 2b.
3.823649
3.385456
1.129434
element.initialize(self.canvas) self.elements.append(element)
def add_moving_element(self, element)
Add elements to the board
8.469501
7.013496
1.2076
return # TODO if event.keysym == "Up": self.manager.set_joystick(0.0, -1.0, 0) elif event.keysym == "Down": self.manager.set_joystick(0.0, 1.0, 0) elif event.keysym == "Left": self.manager.set_joystick(-1.0, 0.0, 0) elif eve...
def on_key_pressed(self, event)
likely to take in a set of parameters to treat as up, down, left, right, likely to actually be based on a joystick event... not sure yet
1.936103
1.886914
1.026069
if smoother_cls is None: smoother_cls = DEFAULT_BASIC_SMOOTHER smoother = smoother_cls() smoother.specify_data_set(x_values, y_values) smoother.set_span(span) smoother.compute() return smoother
def perform_smooth(x_values, y_values, span=None, smoother_cls=None)
Convenience function to run the basic smoother. Parameters ---------- x_values : iterable List of x value observations y_ values : iterable list of y value observations span : float, optional Fraction of data to use as the window smoother_cls : Class The class of...
2.605899
2.918067
0.893022
self.x.append(x) self.y.append(y)
def add_data_point_xy(self, x, y)
Add a new data point to the data set to be smoothed.
2.758154
2.396875
1.150729
if sort_data: xy = sorted(zip(x_input, y_input)) x, y = zip(*xy) x_input_list = list(x_input) self._original_index_of_xvalue = [x_input_list.index(xi) for xi in x] if len(set(self._original_index_of_xvalue)) != len(x): raise Ru...
def specify_data_set(self, x_input, y_input, sort_data=False)
Fully define data by lists of x values and y values. This will sort them by increasing x but remember how to unsort them for providing results. Parameters ---------- x_input : iterable list of floats that represent x y_input : iterable list of floats tha...
2.72137
2.975799
0.914501
plt.figure() xy = sorted(zip(self.x, self.smooth_result)) x, y = zip(*xy) plt.plot(x, y, '-') plt.plot(self.x, self.y, '.') if fname: plt.savefig(fname) else: plt.show() plt.close()
def plot(self, fname=None)
Plot the input data and resulting smooth. Parameters ---------- fname : str, optional name of file to produce. If none, will show interactively.
2.938459
2.920028
1.006312
if self._original_index_of_xvalue: # data was sorted. Unsort it here. self.smooth_result = numpy.zeros(len(self.y)) self.cross_validated_residual = numpy.zeros(len(residual)) original_x = numpy.zeros(len(self.y)) for i, (xval, smooth_val, resi...
def _store_unsorted_results(self, smooth, residual)
Convert sorted smooth/residual back to as-input order.
2.880376
2.765502
1.041538
self._compute_window_size() smooth = [] residual = [] x, y = self.x, self.y # step through x and y data with a window window_size wide. self._update_values_in_window() self._update_mean_in_window() self._update_variance_in_window() for i...
def compute(self)
Perform the smoothing operations.
4.395542
4.160742
1.056432
self._neighbors_on_each_side = int(len(self.x) * self._span) // 2 self.window_size = self._neighbors_on_each_side * 2 + 1 if self.window_size <= 1: # cannot do averaging with 1 point in window. Force >=2 self.window_size = 2
def _compute_window_size(self)
Determine characteristics of symmetric neighborhood with J/2 values on each side.
5.878856
4.993386
1.177329
window_bound_upper = self._window_bound_lower + self.window_size self._x_in_window = self.x[self._window_bound_lower:window_bound_upper] self._y_in_window = self.y[self._window_bound_lower:window_bound_upper]
def _update_values_in_window(self)
Update which values are in the current window.
2.602154
2.385519
1.090812
self._mean_x_in_window = numpy.mean(self._x_in_window) self._mean_y_in_window = numpy.mean(self._y_in_window)
def _update_mean_in_window(self)
Compute mean in window the slow way. useful for first step. Considers all values in window See Also -------- _add_observation_to_means : fast update of mean for single observation addition _remove_observation_from_means : fast update of mean for single observation removal
2.102105
2.278539
0.922567
self._covariance_in_window = sum([(xj - self._mean_x_in_window) * (yj - self._mean_y_in_window) for xj, yj in zip(self._x_in_window, self._y_in_window)]) self._variance_in_window = sum([(xj - self._mean_x_in_wi...
def _update_variance_in_window(self)
Compute variance and covariance in window using all values in window (slow). See Also -------- _add_observation_to_variances : fast update for single observation addition _remove_observation_from_variances : fast update for single observation removal
2.274719
2.205126
1.03156
x_to_remove, y_to_remove = self._x_in_window[0], self._y_in_window[0] self._window_bound_lower += 1 self._update_values_in_window() x_to_add, y_to_add = self._x_in_window[-1], self._y_in_window[-1] self._remove_observation(x_to_remove, y_to_remove) self._add_ob...
def _advance_window(self)
Update values in current window and the current window means and variances.
2.758985
2.425836
1.137333
self._remove_observation_from_variances(x_to_remove, y_to_remove) self._remove_observation_from_means(x_to_remove, y_to_remove) self.window_size -= 1
def _remove_observation(self, x_to_remove, y_to_remove)
Remove observation from window, updating means/variance efficiently.
2.547413
1.997689
1.27518
self._add_observation_to_means(x_to_add, y_to_add) self._add_observation_to_variances(x_to_add, y_to_add) self.window_size += 1
def _add_observation(self, x_to_add, y_to_add)
Add observation to window, updating means/variance efficiently.
2.434884
1.831243
1.329634
self._mean_x_in_window = ((self.window_size * self._mean_x_in_window + xj) / (self.window_size + 1.0)) self._mean_y_in_window = ((self.window_size * self._mean_y_in_window + yj) / (self.window_size + 1.0))
def _add_observation_to_means(self, xj, yj)
Update the means without recalculating for the addition of one observation.
2.035766
1.945104
1.04661
self._mean_x_in_window = ((self.window_size * self._mean_x_in_window - xj) / (self.window_size - 1.0)) self._mean_y_in_window = ((self.window_size * self._mean_y_in_window - yj) / (self.window_size - 1.0))
def _remove_observation_from_means(self, xj, yj)
Update the means without recalculating for the deletion of one observation.
2.183047
2.044811
1.067604
term1 = (self.window_size + 1.0) / self.window_size * (xj - self._mean_x_in_window) self._covariance_in_window += term1 * (yj - self._mean_y_in_window) self._variance_in_window += term1 * (xj - self._mean_x_in_window)
def _add_observation_to_variances(self, xj, yj)
Quickly update the variance and co-variance for the addition of one observation. See Also -------- _update_variance_in_window : compute variance considering full window
2.935169
2.786749
1.053259
if self._variance_in_window: beta = self._covariance_in_window / self._variance_in_window alpha = self._mean_y_in_window - beta * self._mean_x_in_window value_of_smooth_here = beta * (xi) + alpha else: value_of_smooth_here = 0.0 return val...
def _compute_smooth_during_construction(self, xi)
Evaluate value of smooth at x-value xi. Parameters ---------- xi : float Value of x where smooth value is desired Returns ------- smooth_here : float Value of smooth s(xi)
4.095574
3.5772
1.144911
denom = (1.0 - 1.0 / self.window_size - (xi - self._mean_x_in_window) ** 2 / self._variance_in_window) if denom == 0.0: # can happen with small data sets return 1.0 return abs((yi - smooth_here) / denom)
def _compute_cross_validated_residual_here(self, xi, yi, smooth_here)
Compute cross validated residual. This is the absolute residual from Eq. 9. in [1]
5.321773
5.194592
1.024483
x_cubed = numpy.random.standard_normal(N) x = scipy.special.cbrt(x_cubed) noise = numpy.random.standard_normal(N) y = numpy.exp((x ** 3.0) + noise) return [x], y
def build_sample_ace_problem_breiman85(N=200)
Sample problem from Breiman 1985.
4.30839
4.05208
1.063254
x = numpy.linspace(0, 1, N) # x = numpy.random.uniform(0, 1, size=N) noise = numpy.random.standard_normal(N) y = numpy.exp(numpy.sin(2 * numpy.pi * x)) + 0.0 * noise return [x], y
def build_sample_ace_problem_breiman2(N=500)
Build sample problem y(x) = exp(sin(x)).
3.225938
2.819053
1.144334
x, y = build_sample_ace_problem_breiman85(200) ace_solver = ace.ACESolver() ace_solver.specify_data_set(x, y) ace_solver.solve() try: ace.plot_transforms(ace_solver, 'sample_ace_breiman85.png') except ImportError: pass return ace_solver
def run_breiman85()
Run Breiman 85 sample.
5.895498
5.749723
1.025353
x, y = build_sample_ace_problem_breiman2(500) ace_solver = ace.ACESolver() ace_solver.specify_data_set(x, y) ace_solver.solve() try: plt = ace.plot_transforms(ace_solver, None) except ImportError: pass plt.subplot(1, 2, 1) phi = numpy.sin(2.0 * numpy.pi * x[0]) ...
def run_breiman2()
Run Breiman's other sample problem.
4.403255
4.250964
1.035825
if not isinstance(messages, list): messages = [messages] first = True success = False if key is None: key = int(time.time() * 1000) messages = [encodeutils.to_utf8(m) for m in messages] key = bytes(str(key), 'utf-8') if PY3 else str(ke...
def publish(self, topic, messages, key=None)
Takes messages and puts them on the supplied kafka topic
5.50603
5.32359
1.03427
message_set = KafkaProtocol._encode_message_set( [create_message(payload, pl_key) for payload, pl_key in payloads]) gzipped = gzip_encode(message_set, compresslevel=compresslevel) codec = ATTRIBUTE_CODEC_MASK & CODEC_GZIP return Message(0, 0x00 | codec, key, gzipped)
def create_gzip_message(payloads, key=None, compresslevel=None)
Construct a Gzipped Message containing multiple Messages The given payloads will be encoded, compressed, and sent as a single atomic message to Kafka. Arguments: payloads: list(bytes), a list of payload to send be sent to Kafka key: bytes, a key used for partition routing (optional)
8.062656
9.612606
0.838759
if message.magic == 0: msg = b''.join([ struct.pack('>BB', message.magic, message.attributes), write_int_string(message.key), write_int_string(message.value) ]) crc = crc32(msg) msg = struct.pack('>I%ds' % l...
def _encode_message(cls, message)
Encode a single message. The magic number of a message is a format version number. The only supported magic number right now is zero Format ====== Message => Crc MagicByte Attributes Key Value Crc => int32 MagicByte => int8 Attributes => int8 ...
3.504694
2.900224
1.208422
cur = 0 read_message = False while cur < len(data): try: ((offset, ), cur) = relative_unpack('>q', data, cur) (msg, cur) = read_int_string(data, cur) for (offset, message) in KafkaProtocol._decode_message(msg, offset): ...
def _decode_message_set_iter(cls, data)
Iteratively decode a MessageSet Reads repeated elements of (offset, message), calling decode_message to decode a single message. Since compressed messages contain futher MessageSets, these two methods have been decoupled so that they may recurse easily.
8.765322
8.796581
0.996446
((crc, magic, att), cur) = relative_unpack('>IBB', data, 0) if crc != crc32(data[4:]): raise ChecksumError("Message checksum failed") (key, cur) = read_int_string(data, cur) (value, cur) = read_int_string(data, cur) codec = att & ATTRIBUTE_CODEC_MASK ...
def _decode_message(cls, data, offset)
Decode a single Message The only caller of this method is decode_message_set_iter. They are decoupled to support nested messages (compressed MessageSets). The offset is actually read from decode_message_set_iter (it is part of the MessageSet payload).
3.775118
3.707943
1.018116
payloads = [] if payloads is None else payloads grouped_payloads = group_by_topic_and_partition(payloads) message = [] message.append(cls._encode_message_header(client_id, correlation_id, KafkaProtocol.PRODUCE_KEY)) mes...
def encode_produce_request(cls, client_id, correlation_id, payloads=None, acks=1, timeout=1000)
Encode some ProduceRequest structs Arguments: client_id: string correlation_id: int payloads: list of ProduceRequest acks: How "acky" you want the request to be 0: immediate response 1: written to disk by the leader ...
2.211283
2.40952
0.917728
((correlation_id, num_topics), cur) = relative_unpack('>ii', data, 0) for _ in range(num_topics): ((strlen,), cur) = relative_unpack('>h', data, cur) topic = data[cur:cur + strlen] cur += strlen ((num_partitions,), cur) = relative_unpack('>i', da...
def decode_produce_response(cls, data)
Decode bytes to a ProduceResponse Arguments: data: bytes to decode
3.747089
4.430687
0.845713
payloads = [] if payloads is None else payloads grouped_payloads = group_by_topic_and_partition(payloads) message = [] message.append(cls._encode_message_header(client_id, correlation_id, KafkaProtocol.FETCH_KEY)) # -1...
def encode_fetch_request(cls, client_id, correlation_id, payloads=None, max_wait_time=100, min_bytes=4096)
Encodes some FetchRequest structs Arguments: client_id: string correlation_id: int payloads: list of FetchRequest max_wait_time: int, how long to block waiting on min_bytes of data min_bytes: int, the minimum number of bytes to accumulate before ...
2.416694
2.563232
0.942831
((correlation_id, num_topics), cur) = relative_unpack('>ii', data, 0) for _ in range(num_topics): (topic, cur) = read_short_string(data, cur) ((num_partitions,), cur) = relative_unpack('>i', data, cur) for j in range(num_partitions): ((parti...
def decode_fetch_response(cls, data)
Decode bytes to a FetchResponse Arguments: data: bytes to decode
4.084139
4.666863
0.875136
((correlation_id, num_topics), cur) = relative_unpack('>ii', data, 0) for _ in range(num_topics): (topic, cur) = read_short_string(data, cur) ((num_partitions,), cur) = relative_unpack('>i', data, cur) for _ in range(num_partitions): ((parti...
def decode_offset_response(cls, data)
Decode bytes to an OffsetResponse Arguments: data: bytes to decode
3.322385
3.772889
0.880595
if payloads is None: topics = [] if topics is None else topics else: topics = payloads message = [] message.append(cls._encode_message_header(client_id, correlation_id, KafkaProtocol.METADATA_KEY)) ...
def encode_metadata_request(cls, client_id, correlation_id, topics=None, payloads=None)
Encode a MetadataRequest Arguments: client_id: string correlation_id: int topics: list of strings
2.953664
3.059267
0.965481
((correlation_id, numbrokers), cur) = relative_unpack('>ii', data, 0) # Broker info brokers = [] for _ in range(numbrokers): ((nodeId, ), cur) = relative_unpack('>i', data, cur) (host, cur) = read_short_string(data, cur) ((port,), cur) = rela...
def decode_metadata_response(cls, data)
Decode bytes to a MetadataResponse Arguments: data: bytes to decode
2.324275
2.420434
0.960272
grouped_payloads = group_by_topic_and_partition(payloads) message = [] message.append(cls._encode_message_header(client_id, correlation_id, KafkaProtocol.OFFSET_COMMIT_KEY)) message.append(write_short_string(group)) mess...
def encode_offset_commit_request(cls, client_id, correlation_id, group, payloads)
Encode some OffsetCommitRequest structs Arguments: client_id: string correlation_id: int group: string, the consumer group you are committing offsets for payloads: list of OffsetCommitRequest
1.987089
2.094296
0.94881
((correlation_id,), cur) = relative_unpack('>i', data, 0) ((num_topics,), cur) = relative_unpack('>i', data, cur) for _ in xrange(num_topics): (topic, cur) = read_short_string(data, cur) ((num_partitions,), cur) = relative_unpack('>i', data, cur) fo...
def decode_offset_commit_response(cls, data)
Decode bytes to an OffsetCommitResponse Arguments: data: bytes to decode
3.413193
3.588243
0.951216
grouped_payloads = group_by_topic_and_partition(payloads) message = [] reqver = 1 if from_kafka else 0 message.append(cls._encode_message_header(client_id, correlation_id, KafkaProtocol.OFFSET_FETCH_KEY, ...
def encode_offset_fetch_request(cls, client_id, correlation_id, group, payloads, from_kafka=False)
Encode some OffsetFetchRequest structs. The request is encoded using version 0 if from_kafka is false, indicating a request for Zookeeper offsets. It is encoded using version 1 otherwise, indicating a request for Kafka offsets. Arguments: client_id: string correl...
2.330651
2.397117
0.972272
((correlation_id,), cur) = relative_unpack('>i', data, 0) ((num_topics,), cur) = relative_unpack('>i', data, cur) for _ in range(num_topics): (topic, cur) = read_short_string(data, cur) ((num_partitions,), cur) = relative_unpack('>i', data, cur) fo...
def decode_offset_fetch_response(cls, data)
Decode bytes to an OffsetFetchResponse Arguments: data: bytes to decode
2.717455
2.830565
0.96004
filepath, sep, namespace = target.rpartition('|') if sep and not filepath: raise BadDirectory("Path to file not supplied.") module, sep, class_or_function = namespace.rpartition(':') if (sep and not module) or (filepath and not module): raise MissingModule("Need a module path for ...
def _get_module(target)
Import a named class, module, method or function. Accepts these formats: ".../file/path|module_name:Class.method" ".../file/path|module_name:Class" ".../file/path|module_name:function" "module_name:Class" "module_name:function" "module_name:Class.function" If a ...
3.584217
3.32083
1.079314
module, klass, function = _get_module(target) if not module and source_module: module = source_module if not module: raise MissingModule( "No module name supplied or source_module provided.") actual_module = sys.modules[module] if not klass: return getattr(ac...
def load(target, source_module=None)
Get the actual implementation of the target.
3.389632
3.224662
1.051159
# Edit descriptions to be nicer if isinstance(node, sphinx.addnodes.desc_addname): if len(node.children) == 1: child = node.children[0] text = child.astext() if text.startswith("wpilib.") and text.endswith("."): # remove the last element ...
def process_child(node)
This function changes class references to not have the intermediate module name by hacking at the doctree
2.908507
2.901473
1.002424
# short circuit if nothing happened. This check is kept outside # to prevent un-necessarily acquiring a lock for checking the state if self.count_since_commit == 0: return with self.commit_lock: # Do this check again, just in case the state has changed ...
def commit(self, partitions=None)
Commit stored offsets to Kafka via OffsetCommitRequest (v0) Keyword Arguments: partitions (list): list of partitions to commit, default is to commit all of them Returns: True on success, False on failure
3.820125
3.67631
1.039119
datafile = open(fname) datarows = [] for line in datafile: datarows.append([float(li) for li in line.split()]) datacols = list(zip(*datarows)) x_values = datacols[1:] y_values = datacols[0] return x_values, y_values
def read_column_data_from_txt(fname)
Read data from a simple text file. Format should be just numbers. First column is the dependent variable. others are independent. Whitespace delimited. Returns ------- x_values : list List of x columns y_values : list list of y values
2.956696
3.002141
0.984862
x_values, y_values = read_column_data_from_txt(fname) self.build_model_from_xy(x_values, y_values)
def build_model_from_txt(self, fname)
Construct the model and perform regressions based on data in a txt file. Parameters ---------- fname : str The name of the file to load.
3.680787
4.327387
0.85058
self.init_ace(x_values, y_values) self.run_ace() self.build_interpolators()
def build_model_from_xy(self, x_values, y_values)
Construct the model and perform regressions based on x, y data.
8.039958
7.410105
1.084999
self.phi_continuous = [] for xi, phii in zip(self.ace.x, self.ace.x_transforms): self.phi_continuous.append(interp1d(xi, phii)) self.inverse_theta_continuous = interp1d(self.ace.y_transform, self.ace.y)
def build_interpolators(self)
Compute 1-D interpolation functions for all the transforms so they're continuous..
5.452988
4.719068
1.155522
if len(x_values) != len(self.phi_continuous): raise ValueError('x_values must have length equal to the number of independent variables ' '({0}) rather than {1}.'.format(len(self.phi_continuous), len(x_...
def eval(self, x_values)
Evaluate the ACE regression at any combination of independent variable values. Parameters ---------- x_values : iterable a float x-value for each independent variable, e.g. (1.5, 2.5)
3.357953
3.536787
0.949436
prompt += " [y/n]" a = "" while a not in ["y", "n"]: a = input(prompt).lower() return a == "y"
def yesno(prompt)
Returns True if user answers 'y'
2.792289
3.117124
0.89579
def decorator(func): def f_retry(*args, **kwargs): for i in range(1, retries + 1): try: return func(*args, **kwargs) # pylint: disable=W0703 # We want to catch all exceptions here to retry. ...
def retry(retries=KAFKA_WAIT_RETRIES, delay=KAFKA_WAIT_INTERVAL, check_exceptions=())
Retry decorator.
2.806146
2.798448
1.002751
client.update_cluster() logger.debug('Found topics: %r', client.topics.keys()) for req_topic in req_topics: if req_topic not in client.topics.keys(): err_topic_not_found = 'Topic not found: {}'.format(req_topic) logger.warning(err_topic_not_found) raise Topi...
def check_topics(client, req_topics)
Check for existence of provided topics in Kafka.
2.083197
2.033284
1.024548
logger.info('Checking for available topics: %r', repr(REQUIRED_TOPICS)) client = connect_kafka(hosts=KAFKA_HOSTS) check_topics(client, REQUIRED_TOPICS)
def main()
Start main part of the wait script.
8.133097
7.822547
1.039699
if isinstance(hosts, six.string_types): hosts = hosts.strip().split(',') result = [] for host_port in hosts: res = host_port.split(':') host = res[0] port = int(res[1]) if len(res) > 1 else DEFAULT_KAFKA_PORT result.append((host.strip(), port)) if randomi...
def collect_hosts(hosts, randomize=True)
Collects a comma-separated set of hosts (host:port) and optionally randomize the returned list.
2.512135
2.445395
1.027292
log.debug("About to send %d bytes to Kafka, request %d" % (len(payload), request_id)) # Make sure we have a connection if not self._sock: self.reinit() try: self._sock.sendall(payload) except socket.error: log.exception('Unable to s...
def send(self, request_id, payload)
Send a request to Kafka Arguments:: request_id (int): can be any int (used only for debug logging...) payload: an encoded kafka packet (see KafkaProtocol)
4.1738
3.867897
1.079088
log.debug("Reading response %d from Kafka" % request_id) # Make sure we have a connection if not self._sock: self.reinit() # Read the size off of the header resp = self._read_bytes(4) (size,) = struct.unpack('>i', resp) # Read the remainder...
def recv(self, request_id)
Get a response packet from Kafka Arguments: request_id: can be any int (only used for debug logging...) Returns: str: Encoded kafka packet response from server
4.510598
4.709248
0.957817
c = copy.deepcopy(self) # Python 3 doesn't copy custom attributes of the threadlocal subclass c.host = copy.copy(self.host) c.port = copy.copy(self.port) c.timeout = copy.copy(self.timeout) c._sock = None return c
def copy(self)
Create an inactive copy of the connection object, suitable for passing to a background thread. The returned copy is not connected; you must call reinit() before using.
4.829342
5.613355
0.860331
log.debug("Closing socket connection for %s:%d" % (self.host, self.port)) if self._sock: # Call shutdown to be a good TCP client # But expect an error if the socket has already been # closed by the server try: self._sock.shutdown(s...
def close(self)
Shutdown and close the connection socket
4.416125
4.228295
1.044422
log.debug("Reinitializing socket connection for %s:%d" % (self.host, self.port)) if self._sock: self.close() try: self._sock = socket.create_connection((self.host, self.port), self.timeout) except socket.error: log.exception('Unable to conne...
def reinit(self)
Re-initialize the socket connection close current socket (if open) and start a fresh connection raise ConnectionError on error
2.766748
2.572071
1.075689
configs = self._deprecate_configs(**configs) self._config = {} for key in self.DEFAULT_CONFIG: self._config[key] = configs.pop(key, self.DEFAULT_CONFIG[key]) if configs: raise KafkaConfigurationError('Unknown configuration key(s): ' + ...
def configure(self, **configs)
Configure the consumer instance Configuration settings can be passed to constructor, otherwise defaults will be used: Keyword Arguments: bootstrap_servers (list): List of initial broker nodes the consumer should contact to bootstrap initial cluster metadata. This d...
2.896555
2.79368
1.036824
self._topics = [] self._client.load_metadata_for_topics() # Setup offsets self._offsets = OffsetsStruct(fetch=dict(), commit=dict(), highwater=dict(), task_done=dic...
def set_topic_partitions(self, *topics)
Set the topic/partitions to consume Optionally specify offsets to start from Accepts types: * str (utf-8): topic name (will consume all available partitions) * tuple: (topic, partition) * dict: - { topic: partition } - { topic: [partition list] } ...
3.109965
3.024163
1.028372
self._set_consumer_timeout_start() while True: try: return six.next(self._get_message_iterator()) # Handle batch completion except StopIteration: self._reset_message_iterator() self._check_consumer_timeout()
def next(self)
Return the next available message Blocks indefinitely unless consumer_timeout_ms > 0 Returns: a single KafkaMessage from the message iterator Raises: ConsumerTimeout after consumer_timeout_ms and no message Note: This is also the method called inte...
8.766684
6.863231
1.277341