How to use stop_lambda method in localstack

Best Python code snippet using localstack_python

simulate_contention_interval.py

Source:simulate_contention_interval.py Github

copy

Full Screen

1import argparse2from math import log, ceil3from random import Random4from typing import Tuple, List5import matplotlib.pyplot as plt6import numpy as np7DEFAULT_STEP_LAMBDA = 0.018DEFAULT_STOP_LAMBDA = 4.09DEFAULT_START_LAMBDA = 1.010DEFAULT_ITERATIONS: int = int(1e6)11def simulate_first_successful_transmission_time(12 lambda_: float,13 seeded_random: Random,14) -> float:15 """16 Simulate attempting to transmit packets at random intervals sampled from an exponential distribution17 with parameter lambda_ until a packet transmission is deemed to be successful by not colliding with18 any other packet within a [t-1, t+1] time interval19 :param lambda_: The parameter for the exponential distribution from which to sample the transmission intervals20 :param seeded_random: An instance of random.Random used for running simulations21 :return: The amount of simulated time in arbitrary units it took until the first successful packet transmission22 """23 def sample_interval():24 return -lambda_ * log(seeded_random.uniform(0.0, 1.0))25 # Initial parameters discussed with Marcelo Ponce26 # t is initialized randomly via sample_interval27 # the first transmission has a greater likelihood if success since there is no prior transmission to contend with28 t_prev = float('-inf')29 t = sample_interval()30 t_next = t + sample_interval()31 while t - t_prev < 1 or t_next - t < 1:32 t_prev = t33 t = t_next34 t_next += sample_interval()35 return t36def simulate_average_contention_interval(37 lambda_: float,38 iterations: int,39 seeded_random: Random,40) -> float:41 """42 Run a simulation to determine the average contention interval for the given lambda value43 :param lambda_: The lambda value for which to run the contention interval simulation44 :param iterations: The number of trials to use to determine the average contention interval45 :param seeded_random: An instance of random.Random used for running the simulation46 :return: the average contention interval for the given lambda value47 """48 avg_contention_interval = np.average(49 [50 simulate_first_successful_transmission_time(lambda_, seeded_random)51 for _ in range(iterations)52 ]53 )54 print(f'λ={lambda_} --> {avg_contention_interval}')55 return avg_contention_interval56def find_optimal_lambda(57 iterations: int,58 seeded_random: Random,59 start_lambda: float,60 stop_lambda: float,61 step_lambda: float,62) -> Tuple[float, float]:63 """64 Run a contention interval simulation for each lambda value in the given range and return the minimum average65 contention interval and associated optimal lambda value. Plot the lambda values vs contention intervals.66 :param iterations: The number of times to simulate finding the contention interval for each lambda value67 :param seeded_random: An instance of random.Random used for running simulations68 :param start_lambda: The initial lambda value to simulate for69 :param stop_lambda: The final lambda value (inclusive) to simulate for70 :param step_lambda: The approximate step size between lambda values71 :return: A tuple of (optimal lambda value, minimum average contention interval)72 """73 # Run simulation for range of lambdas74 num_lambdas: int = ceil(((stop_lambda - start_lambda) / step_lambda))75 lambdas: List[float] = list(76 np.linspace(start=start_lambda, stop=stop_lambda, num=num_lambdas)77 )78 avg_contention_intervals: List[float] = [79 simulate_average_contention_interval(lambda_, iterations, seeded_random)80 for lambda_ in lambdas81 ]82 # identify optimal lambda and minimum interval83 i: int = np.argmin(avg_contention_intervals)84 optimal_lambda: float = lambdas[i]85 min_avg_contention_interval: float = avg_contention_intervals[i]86 # plot simulation and minimum interval87 fig = plt.figure()88 ax = fig.add_subplot(111)89 plt.plot(lambdas, avg_contention_intervals, 'r-')90 plt.plot(optimal_lambda, min_avg_contention_interval, 'bo')91 ax.annotate(92 f'Optimal λ: {optimal_lambda:.4f}\nMinimum Contention Interval: {min_avg_contention_interval:.4f}',93 xy=(optimal_lambda, min_avg_contention_interval),94 xytext=(10, -25),95 textcoords='offset points',96 )97 ax.set_ylim(bottom=min_avg_contention_interval - 0.4)98 plt.xlabel('λ')99 plt.ylabel('Contention interval (Arbitrary Units)')100 plt.show()101 return optimal_lambda, min_avg_contention_interval102def _get_args() -> argparse.Namespace:103 """104 Parse the arguments and perform basic validation105 :return: an argparse.Namespace containing the parsed arguments106 """107 parser: argparse.ArgumentParser = argparse.ArgumentParser()108 parser.add_argument(109 '-l',110 '--lambda',111 type=float,112 default=None,113 dest='lambda_',114 metavar='LAMBDA',115 help='λ parameter for to exponential distribution of intervals. Overrides all other lambda related options.',116 )117 parser.add_argument(118 '--start-lambda',119 type=float,120 default=DEFAULT_START_LAMBDA,121 help='The initial λ value to simulate for',122 )123 parser.add_argument(124 '--stop-lambda',125 type=float,126 default=DEFAULT_STOP_LAMBDA,127 help='The final λ value to simulate for',128 )129 parser.add_argument(130 '--step-lambda',131 type=float,132 default=DEFAULT_STEP_LAMBDA,133 help='The approximate step size between the λ values to simulate for',134 )135 parser.add_argument(136 '-i',137 '--iterations',138 type=int,139 default=DEFAULT_ITERATIONS,140 help='number of times to run the simulation for each λ value before averaging',141 )142 parser.add_argument(143 '-s',144 '--seed',145 type=int,146 default=None,147 help='seed for PRNG used to calculate random contention intervals',148 )149 args: argparse.Namespace = parser.parse_args()150 if args.lambda_ is not None:151 assert isinstance(args.lambda_, float)152 else:153 assert isinstance(args.start_lambda, float)154 assert isinstance(args.stop_lambda, float)155 assert isinstance(args.step_lambda, float)156 assert isinstance(args.iterations, int)157 assert args.seed is None or isinstance(args.seed, int)158 return args159def _create_random(seed: int) -> Random:160 """161 Create an instance of random.Random seeded with seed and advanced through 1248 iterations. Note that the Mersenne162 Twister pseudorandom number generator is used for all random operations163 :param seed: The seed to the Mersenne Twister pseudorandom number generator164 :return: An instance of random.Random seeded with seed and advanced through 1248 iterations165 """166 seeded_random: Random = Random()167 seeded_random.seed(seed)168 # throw away first 624*2 outputs of Mersenne Twister as recommended in https://stats.stackexchange.com/a/438057169 for _ in range(1248):170 seeded_random.random()171 return seeded_random172def main():173 """174 Parse the input arguments and initiate the simulation175 """176 args: argparse.Namespace = _get_args()177 seeded_random = _create_random(args.seed)178 if args.lambda_ is not None:179 # Simulate given value of lambda180 avg_contention_interval = simulate_average_contention_interval(181 lambda_=args.lambda_,182 iterations=args.iterations,183 seeded_random=seeded_random,184 )185 print(186 f'The average contention interval for λ={args.lambda_:.4f} is {avg_contention_interval:.4f}'187 )188 else:189 # Find optimal lambda in range [start_lambda, stop_lambda] with granularity of step_lambda190 opt_lambda, avg_contention_interval = find_optimal_lambda(191 iterations=args.iterations,192 seeded_random=seeded_random,193 start_lambda=args.start_lambda,194 stop_lambda=args.stop_lambda,195 step_lambda=args.step_lambda,196 )197 print(198 f'The optimal lambda value is λ={opt_lambda:.4f} with an average contention interval of {avg_contention_interval:.4f}'199 )200if __name__ == '__main__':...

Full Screen

Full Screen

app.py

Source:app.py Github

copy

Full Screen

...20 send_notification_to_ms_teams("Start cluster response {}".format(response))21# -----------------------STOP SERVICE-------------------------------#22# Run at 1:30pm (UTC) (i.e 07:00pm [IST]) every Monday through Friday.23@app.schedule(Cron(30, 13, '?', '*', 'MON-FRI', '*'))24def stop_lambda(event):25 print("Stopping cluster")26 try:27 response = rds.stop_db_cluster(DBClusterIdentifier=os.environ.get("DBClusterIdentifier"))28 except Exception as ex:29 err = "Exception occurred on stopping neptune due to {}".format(ex)30 print(err)31 send_notification_to_ms_teams(err)32 print('Stopped your cluster: ' + str(response))33 # Sending notification to Microsoft Team34 send_notification_to_ms_teams("Stop cluster response {}".format(response))35@app.schedule(Cron(30, 17, '?', '*', 'MON-FRI', '*'))36def stop_neptune_at_11_pm(event):37 stop_lambda(event)38# Sending notification to Microsoft Team39def send_notification_to_ms_teams(message):40 message += "<----->\n Posted using repo -----> https://github.com/m-thirumal/aws-service-start-stop-scheduler"41 print("Sending message {} to MS Teams".format(message))42 ms_teams_message = pymsteams.connectorcard(os.environ.get('msTeamChannelIncomingWebhook'))43 ms_teams_message.text(message)...

Full Screen

Full Screen

cav_internal.py

Source:cav_internal.py Github

copy

Full Screen

1import numpy as np2import matplotlib.pyplot as plt3class FabryPerotCavity(object):4 def __init__(self):5 #FP settings6 self.R1 = 0.997 self.R2 = 0.998 self.d = 1E6 #m9 self.c = 3E8 #m/s10 # create frequency arrays: optical regime first11 self.start_lambda = 300E-9 #m12 self.stop_lambda = 800E-9 #m13 self.step_lambda = 0.0001E-9 #m Make sure this is small enough ! otherwise resonances don't show correctly14 self.lambdas = np.arange( self.start_lambda, self.stop_lambda + self.step_lambda , self.step_lambda )15 self.omegas = ( 2 * np.pi ) / self.lambdas16 def CalculateInternalCavityField(self):17 '''Calculate P_cav / P_in '''18 phi_array = ( self.omegas * self.d ) / self.c19 power_ratios = ( 1 - self.R1 ) / ( np.absolute( 1 + ( np.exp( 1j * phi_array ) ) * np.sqrt( self.R1 * self.R2 ) )**2 )20 return phi_array, power_ratios21if __name__ == '__main__':22 FPcav = FabryPerotCavity()23 phi_array, power_ratios = FPcav.CalculateInternalCavityField()24 plt.plot( phi_array , power_ratios, color = 'b' )...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run localstack automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful