def __init__(self): self.team_name = config.get('team_config', 'team_name') self.instances = config.get('instance_config', 'instances').replace(' ', '').split(',') self.num_dict = { s.split(':')[0]: int(s.split(':')[1]) for s in config.get('instance_config', 'number_of_solutions'). replace(' ', '').split(',') }
def mutate(parent: Chromosome) -> Chromosome: """ Takes a child and mutates it according to mutation method in .ini file """ mutation_rate = float(config.get('run_config', 'mutation_rate')) getattr(Mutation, config.get('algorithm_config', 'mutation').lower().strip())(Mutation(), parent, mutation_rate) return parent
def mutation(parents: [Chromosome]) -> [Chromosome]: parent_a, parent_b = parents getattr(Mutation, config.get('algorithm_config', 'mutation').lower().strip())( Mutation(), parent_a, float(config.get('run_config', 'mutation_rate'))) getattr(Mutation, config.get('algorithm_config', 'mutation').lower().strip())( Mutation(), parent_b, float(config.get('run_config', 'mutation_rate'))) return parents
def __init__(self): level = "INFO" if config.get("CB_LOGLEVEL"): level = config.get("CB_LOGLEVEL") logging.basicConfig( handlers=[ logging.FileHandler("combahton.log"), logging.StreamHandler() ], level=level, format="%(asctime)s [%(levelname)s] %(message)s" ) coloredlogs.install(level=level)
def crossover(parents: [Chromosome]) -> (Chromosome, Chromosome): """ This function calls the required crossover method based on .ini file """ parent_a, parent_b = parents if random.random() > float(config.get('run_config', 'crossover_rate')): return parents child_a, child_b = getattr( Crossover, config.get('algorithm_config', 'crossover').lower().strip())(Crossover(), parent_a, parent_b) return [child_a, child_b]
def solve(self): """ This method solves the problem using NTGA algorithm """ generation_limit = int(config.get('run_config', 'generation_limit')) self.generate_initial_population() new_population = [] print("Generation limit:", str(generation_limit)) for i in range(generation_limit): print("generation: ", i) self.population = self.evaluate(self.population) self.non_dominated_set.adds(self.population) while len(new_population) < self.population_size: parents = self.selection() children = mutation(crossover(parents)) for child in children: count = 0 while (child in new_population) or children[0] == children[1]: count += 1 mutate(child) if count > 100: break new_population += children self.population = new_population new_population = [] return self.non_dominated_set
def mutation(parents: [Chromosome]) -> [Chromosome]: """ Gets a list of parents and mutates the children according to mutation method in .ini file """ parent_a, parent_b = parents mutation_rate = float(config.get('run_config', 'mutation_rate')) getattr(Mutation, config.get('algorithm_config', 'mutation').lower().strip())(Mutation(), parent_a, mutation_rate) getattr(Mutation, config.get('algorithm_config', 'mutation').lower().strip())(Mutation(), parent_b, mutation_rate) return parents
def crossover(parents: [Chromosome]) -> (Chromosome, Chromosome): parent_a, parent_b = parents child_a, child_b = getattr( Crossover, config.get('algorithm_config', 'crossover').lower().strip())(Crossover(), parent_a, parent_b) return [child_a, child_b]
def request(self, **kwargs): """Send a request to api.combahton.net/v2 using kwargs""" post_data = { "email": self.auth_user, "secret": self.auth_secret } for key, value in kwargs.items(): post_data[key] = value l7_cookie = config.get("LAYER7_VALIDATE") if config.get("LAYER7_VALIDATE") else "" logger.debug("Sending request to {scope:s} (cookie: {cookie:s}) with params: {param:s}".format(scope = self.scope, cookie = l7_cookie, param = json.dumps(post_data))) response = requests.post(self.scope, json=post_data, headers=self.headers, cookies={ 'layer7-validate': l7_cookie }) if "Authentication required" in response.text: cookie = r_l7_cookie.search(response.text) with open(".env", "a+") as file: file.write("\nLAYER7_VALIDATE={cookie:s}".format(cookie=cookie[1])) return { "status": "layer7_challenge" } if response.headers["Content-Type"] == "application/pdf": return response logger.debug(response.text) try: logger.debug("Parsing response as JSON") return json.loads(response.text) except (json.JSONDecodeError, ValueError): try: logger.debug("Trying to fix malformed json") json_fix = self.try_fix_json(response.text) if json_fix: logger.debug("JSON has been fixed.") return json_fix else: logger.debug("JSON could not be parsed. Falling back to plain text") return response.text except ValueError: logger.debug("JSON could not be parsed. Falling back to plain text") return response.text
def solve(self): generation_limit = int(config.get('run_config', 'generation_limit')) self.generate_initial_population() new_population = [] for i in range(generation_limit): self.population = self.evaluate(self.population) self.non_dominated_set.adds(self.population) while len(new_population) < self.population_size: parents = self.selection() children = mutation(crossover(parents)) for child in children: while (child in new_population) or children[0] == children[1]: child.mutate() new_population += children self.population = new_population return self.non_dominated_set
from ftplib import FTP from pathlib import Path from tqdm import tqdm import click from helpers.config import config # pylint: disable=import-error,no-name-in-module from helpers.logger import Logger # pylint: disable=import-error,no-name-in-module log = Logger().get_logger() @click.command(name="iso-upload") @click.argument("contract", type=click.INT) @click.argument("image", type=click.Path(exists=True)) @click.argument("password", type=click.STRING, default=config.get("CB_ISOFTP_PWD")) def iso(contract, password, image): """Cloud: Manage / Upload Private ISO Images Either provide the password, or set it inside an environment variable: CB_ISOFTP_PWD""" image = Path(image) host = "isoshare-ffm2.combahton.net" user = "******".format(contract) with FTP(host = host, user = user, passwd = password) as ftp, \ open(image, 'rb') as file, \ tqdm(unit = 'B', unit_scale = True, leave = False, miniters = 1, desc = 'Uploading {}...'.format(image.name), total = image.stat().st_size) as tqdm_instance: ftp.storbinary(f'STOR {image.name}', file, callback=lambda sent: tqdm_instance.update(len(sent)))
def __init__(self, problem: Problem) -> None: self.xyz = 1 self.problem = problem self.population_size = int(config.get('run_config', 'population_size')) self.non_dominated_set = NonDominatedSet() self.population = []
from helpers.config import config # pylint: disable=import-error,no-name-in-module api = APIv2() log = Logger().get_logger() @click.group() def layer7(): """Methods to access and modify the layer 7 filter settings""" @click.command(name="set-routing") @click.argument("routing_type", type=click.Choice( ['only_on', 'only_off', 'activate', 'deactivate'])) @click.argument("ipv4", default=config.get("CB_DEFAULT_IP")) def l7_routing(routing_type, ipv4): """Set the Layer 7 routing mode of the specified IPv4 Valid routing types are only_on, only_off, activate, deactivate""" try: ipaddr = str(ipaddress.ip_address(ipv4)) response = api.request(component="antiddos", method="layer7", action="routing", routing=routing_type, ipaddr=ipaddr) if "status" in response: res_status = api.parse_status(response["status"]) log.log(res_status["level"], res_status["message"]) else: log.fatal("An unknown error occured.")
import sys import click from commands.v2.antiddos.__main__ import antiddos as antiddos_v2 from commands.v2.cloud.__main__ import cloud as cloud_v2 from commands.v2.customer.__main__ import customer as customer_v2 from commands.v2.ipaddr.__main__ import ipaddr as ipaddr_v2 from commands.misc.__main__ import misc from helpers.config import config from helpers.logger import Logger from helpers.version import check_version, __version__ if not config.get("CB_DEBUG"): sys.tracebacklimit = 0 log = Logger().get_logger() @click.group( help= "combahton-cli Version: {version:s} \n\nSimple CLI Interface to interact with combahton Services" .format(version=__version__)) def cli(): pass cli.add_command(misc) def populate_commands_v2():
import click from tabulate import tabulate # pylint: disable=import-error from helpers.config import config # pylint: disable=import-error,no-name-in-module from helpers.api import APIv2 # pylint: disable=import-error,no-name-in-module from helpers.logger import Logger # pylint: disable=import-error,no-name-in-module api = APIv2() log = Logger().get_logger() @click.group() def ipaddr(): """Provides access to ip address details from combahton.net""" @click.command(name="get-rdns") @click.argument("address", default=config.get("CB_DEFAULT_IP")) @click.option("-f", "--format", "output_format", type=click.Choice(['table','json'], case_sensitive=False), default='table') def ipaddr_get_rdns(address,output_format): """View details about the specified ip address. If you do not specify an IP address, CB_DEFAULT_IP will be used.""" action = "none" try: address = ipaddress.ip_address(address) if isinstance(address, ipaddress.IPv4Address): action = "ipv4" elif isinstance(address, ipaddress.IPv6Address): action = "ipv6" response = api.request(component = "ipaddr", method="view", action=action, ipaddr = str(address)) if "status" in response: res_status = api.parse_status(response["status"]) if res_status:
def __init__(self): self.scope = "https://api.combahton.net/v2" self.auth_user = config.get("CB_AUTH_USER") self.auth_secret = config.get("CB_AUTH_SECRET")