Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def get_keypair_fn(): keypair_name = get_keypair_name() account = get_account_number() region = get_region() fn = f'{PRIVATE_KEY_LOCATION}/{keypair_name}-{account}-{region}.pem' return fn
[ "Location of .pem file for current keypair" ]
Please provide a description of the function:def lookup_image(wildcard): ec2 = get_ec2_resource() filter_ = {'Name': 'name', 'Values': [wildcard]} images = list(ec2.images.filter(Filters=[filter_])) # Note, can add filtering by Owners as follows # images = list(ec2.images.filter_(Filters = [filter_], O...
[ "Returns unique ec2.Image whose name matches wildcard\n lookup_ami('pytorch*').name => ami-29fa\n \n https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#image\n\n Assert fails if multiple images match or no images match.\n " ]
Please provide a description of the function:def lookup_instance(name: str, instance_type: str = '', image_name: str = '', states: tuple = ('running', 'stopped', 'initializing')): ec2 = get_ec2_resource() instances = ec2.instances.filter( Filters=[{'Name': 'instance-state-name', 'Values...
[ "Looks up AWS instance for given instance name, like\n simple.worker. If no instance found in current AWS environment, returns None. " ]
Please provide a description of the function:def ssh_to_task(task) -> paramiko.SSHClient: username = task.ssh_username hostname = task.public_ip ssh_key_fn = get_keypair_fn() print(f"ssh -i {ssh_key_fn} {username}@{hostname}") pkey = paramiko.RSAKey.from_private_key_file(ssh_key_fn) ssh_client = parami...
[ "Create ssh connection to task's machine\n\n returns Paramiko SSH client connected to host.\n\n " ]
Please provide a description of the function:def validate_aws_name(name): assert len(name) <= 127 # disallow unicode characters to avoid pain assert name == name.encode('ascii').decode('ascii') assert aws_name_regexp.match(name)
[ "Validate resource name using AWS name restrictions from # http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#tag-restrictions" ]
Please provide a description of the function:def delete_efs_by_id(efs_id): start_time = time.time() efs_client = get_efs_client() sys.stdout.write("deleting %s ... " % (efs_id,)) while True: try: response = efs_client.delete_file_system(FileSystemId=efs_id) if is_good_response(response): ...
[ "Deletion sometimes fails, try several times." ]
Please provide a description of the function:def extract_attr_for_match(items, **kwargs): # find the value of attribute to return query_arg = None for arg, value in kwargs.items(): if value == -1: assert query_arg is None, "Only single query arg (-1 valued) is allowed" query_arg = arg result...
[ "Helper method to get attribute value for an item matching some criterion.\n Specify target criteria value as dict, with target attribute having value -1\n\n Example:\n to extract state of vpc matching given vpc id\n\n response = [{'State': 'available', 'VpcId': 'vpc-2bb1584c'}]\n extract_attr_for_match(resp...
Please provide a description of the function:def get_instance_property(instance, property_name): name = get_name(instance) while True: try: value = getattr(instance, property_name) if value is not None: break print(f"retrieving {property_name} on {name} produced None, retrying") ...
[ "Retrieves property of an instance, keeps retrying until getting a non-None" ]
Please provide a description of the function:def get_name(tags_or_instance_or_id): ec2 = get_ec2_resource() if hasattr(tags_or_instance_or_id, 'tags'): tags = tags_or_instance_or_id.tags elif isinstance(tags_or_instance_or_id, str): tags = ec2.Instance(tags_or_instance_or_id).tags elif tags_or_insta...
[ "Helper utility to extract name out of tags dictionary or intancce.\n [{'Key': 'Name', 'Value': 'nexus'}] -> 'nexus'\n \n Assert fails if there's more than one name.\n Returns '' if there's less than one name.\n " ]
Please provide a description of the function:def wait_until_available(resource): while True: resource.load() if resource.state == 'available': break time.sleep(RETRY_INTERVAL_SEC)
[ "Waits until interval state becomes 'available'" ]
Please provide a description of the function:def maybe_create_placement_group(name='', max_retries=10): if not name: return client = get_ec2_client() while True: try: client.describe_placement_groups(GroupNames=[name]) print("Reusing placement_group group: " + name) break # no Exce...
[ "Creates placement_group group or reuses existing one. Crash if unable to create\n placement_group group. If name is empty, ignores request." ]
Please provide a description of the function:def lookup_instances(fragment, verbose=True, filter_by_key=True): def vprint(*args): if verbose: print(*args) region = get_region() client = get_ec2_client() ec2 = get_ec2_resource() response = client.describe_instances() assert is_good_response(re...
[ "Returns ec2.Instance object whose name contains fragment, in reverse order of launching (ie,\n most recent intance first). Optionally filters by key, only including instances launched with\n key_name matching current username.\n\n args:\n verbose: print information about all matching instances found\n\n f...
Please provide a description of the function:def create_spot_instances(launch_specs, spot_price=26, expiration_mins=15): ec2c = get_ec2_client() num_tasks = launch_specs['MinCount'] or 1 if 'MinCount' in launch_specs: del launch_specs['MinCount'] if 'MaxCount' in launch_specs: del launch_specs['Ma...
[ "\n args:\n spot_price: default is $26 which is right above p3.16xlarge on demand price\n expiration_mins: this request only valid for this many mins from now\n " ]
Please provide a description of the function:def is_chief(task: backend.Task, run_name: str): global run_task_dict if run_name not in run_task_dict: return True task_list = run_task_dict[run_name] assert task in task_list, f"Task {task.name} doesn't belong to run {run_name}" return task_list[0] == task
[ "Returns True if task is chief task in the corresponding run" ]
Please provide a description of the function:def ossystem(cmd): p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) (stdout, stderr) = p.communicate() return stdout.decode('ascii')
[ "Like os.system, but returns output of command as string." ]
Please provide a description of the function:def make_task( name: str = '', run_name: str = '', install_script: str = '', instance_type: str = '', image_name: str = '', disk_size: int = 0, preemptible=None, logging_task: backend.Task = None, create...
[ "\n Create task on AWS.\n\n Automatically places it in singleton Run/singleton Job objects, see Run/Job/Task hierarchy for details\n https://docs.google.com/document/d/1Gg4T243cYrDUW1YDCikmqp7fzSQDU3rZxOkJr9ohhs8/edit#heading=h.j4td4oixogib\n\n\n Args:\n disk_size: default size of root disk, in GBs\n crea...
Please provide a description of the function:def make_job( name: str = '', run_name: str = '', num_tasks: int = 1, install_script: str = '', instance_type: str = '', image_name: str = '', create_resources=True, **kwargs) -> Job: assert num_tasks > 0, ...
[ "\n Args:\n create_resources: if True, will create resources if necessary\n name: see backend.make_task\n run_name: see backend.make_task\n num_tasks: number of tasks to launch\n install_script: see make_task\n instance_type: see make_task\n image_name: see make_task\n\n Returns:\n\n " ]
Please provide a description of the function:def _maybe_start_instance(instance): if not instance: return if instance.state['Name'] == 'stopped': instance.start() while True: print(f"Waiting for {instance} to start.") instance.reload() if instance.state['Name'] == 'running': ...
[ "Starts instance if it's stopped, no-op otherwise." ]
Please provide a description of the function:def _maybe_wait_for_initializing_instance(instance): if not instance: return if instance.state['Name'] == 'initializing': while True: print(f"Waiting for {instance} to leave state 'initializing'.") instance.reload() if instance.state['Name...
[ "Starts instance if it's stopped, no-op otherwise." ]
Please provide a description of the function:def _maybe_create_resources(logging_task: Task = None): def log(*args): if logging_task: logging_task.log(*args) else: util.log(*args) def should_create_resources(): prefix = u.get_prefix() if u.get_keypair_name() not in u.get_keypai...
[ "Use heuristics to decide to possibly create resources", "Check if gateway, keypair, vpc exist." ]
Please provide a description of the function:def _set_aws_environment(task: Task = None): current_zone = os.environ.get('NCLUSTER_ZONE', '') current_region = os.environ.get('AWS_DEFAULT_REGION', '') def log(*args): if task: task.log(*args) else: util.log(*args) if current_region and cur...
[ "Sets up AWS environment from NCLUSTER environment variables" ]
Please provide a description of the function:def join(self, ignore_errors=False): assert self._status_fn, "Asked to join a task which hasn't had any commands executed on it" check_interval = 0.2 status_fn = self._status_fn if not self.wait_for_file(status_fn, max_wait_sec=30): self.log(f"Retr...
[ "Waits until last executed command completed." ]
Please provide a description of the function:def _run_with_output_on_failure(self, cmd, non_blocking=False, ignore_errors=False, max_wait_sec=365 * 24 * 3600, check_interval=0.2) -> str: if not self._can_run:...
[ "Experimental version of run propagates error messages to client. This command will be default \"run\" eventually" ]
Please provide a description of the function:def _run_raw(self, cmd: str, ignore_errors=False) -> Tuple[str, str]: # self._log("run_ssh: %s"%(cmd,)) stdin, stdout, stderr = u.call_with_retries(self.ssh_client.exec_command, command=cmd, get_pty=True) s...
[ "Runs given cmd in the task using current SSH session, returns\n stdout/stderr as strings. Because it blocks until cmd is done, use it for\n short cmds. Silently ignores failing commands.\n\n This is a barebones method to be used during initialization that have\n minimal dependencies (no tmux)\n " ]
Please provide a description of the function:def upload(self, local_fn: str, remote_fn: str = '', dont_overwrite: bool = False) -> None: # support wildcard through glob if '*' in local_fn: for local_subfn in glob.glob(local_fn): self.upload(local_subfn) return if '#' ...
[ "Uploads file to remote instance. If location not specified, dumps it\n into default directory. If remote location has files or directories with the\n same name, behavior is undefined.", "Makes remote file execute for locally executable files", " Uploads the contents of the source directory to the target...
Please provide a description of the function:def switch_window(self, window_id: int): # windows are numbered sequentially 0, 1, 2, ... # create any missing windows and make them point to the same directory if window_id not in self.tmux_available_window_ids: for i in range(max(self.tmux_available...
[ "\n Switches currently active tmux window for given task. 0 is the default window\n Args:\n window_id: integer id of tmux window to use\n " ]
Please provide a description of the function:def _replace_lines(fn, startswith, new_line): new_lines = [] for line in open(fn): if line.startswith(startswith): new_lines.append(new_line) else: new_lines.append(line) with open(fn, 'w') as f: f.write('\n'.join(new_lines))
[ "Replace lines starting with starts_with in fn with new_line." ]
Please provide a description of the function:def now_micros(absolute=False) -> int: micros = int(time.time() * 1e6) if absolute: return micros return micros - EPOCH_MICROS
[ "Return current micros since epoch as integer." ]
Please provide a description of the function:def now_millis(absolute=False) -> int: millis = int(time.time() * 1e3) if absolute: return millis return millis - EPOCH_MICROS // 1000
[ "Return current millis since epoch as integer." ]
Please provide a description of the function:def install_pdb_handler(): import signal import pdb def handler(_signum, _frame): pdb.set_trace() signal.signal(signal.SIGQUIT, handler)
[ "Make CTRL+\\ break into gdb." ]
Please provide a description of the function:def shell_add_echo(script): new_script = "" for cmd in script.split('\n'): cmd = cmd.strip() if not cmd: continue new_script += "echo \\* " + shlex.quote(cmd) + "\n" new_script += cmd + "\n" return new_script
[ "Goes over each line script, adds \"echo cmd\" in front of each cmd.\n\n ls a\n\n becomes\n\n echo * ls a\n ls a\n " ]
Please provide a description of the function:def random_id(k=5): # https://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python return ''.join(random.choices(string.ascii_lowercase + string.digits, k=k))
[ "Random id to use for AWS identifiers." ]
Please provide a description of the function:def alphanumeric_hash(s: str, size=5): import hashlib import base64 hash_object = hashlib.md5(s.encode('ascii')) s = base64.b32encode(hash_object.digest()) result = s[:size].decode('ascii').lower() return result
[ "Short alphanumeric string derived from hash of given string" ]
Please provide a description of the function:def reverse_taskname(name: str) -> str: components = name.split('.') assert len(components) <= 3 return '.'.join(components[::-1])
[ "\n Reverses components in the name of task. Reversed convention is used for filenames since\n it groups log/scratch files of related tasks together\n\n 0.somejob.somerun -> somerun.somejob.0\n 0.somejob -> somejob.0\n somename -> somename\n\n Args:\n name: name of task\n\n " ]
Please provide a description of the function:def is_bash_builtin(cmd): # from compgen -b bash_builtins = ['alias', 'bg', 'bind', 'alias', 'bg', 'bind', 'break', 'builtin', 'caller', 'cd', 'command', 'compgen', 'complete', 'compopt', 'continue', 'declare', 'dirs', 'disown', '...
[ "Return true if command is invoking bash built-in\n " ]
Please provide a description of the function:def is_set(name): val = os.environ.get(name, '0') assert val == '0' or val == '1', f"env var {name} has value {val}, expected 0 or 1" return val == '1'
[ "Helper method to check if given property is set" ]
Please provide a description of the function:def assert_script_in_current_directory(): script = sys.argv[0] assert os.path.abspath(os.path.dirname(script)) == os.path.abspath( '.'), f"Change into directory of script {script} and run again."
[ "Assert fail if current directory is different from location of the script" ]
Please provide a description of the function:def push_ctx(app=None): if app is not None: ctx = app.test_request_context() ctx.fixtures_request_context = True ctx.push() if _app_ctx_stack is not None: _app_ctx_stack.top.fixtures_app_context = True # Make sure tha...
[ "Creates new test context(s) for the given app\n\n If the app is not None, it overrides any existing app and/or request\n context. In other words, we will use the app that was passed in to create\n a new test request context on the top of the stack. If, however, nothing\n was passed in, we will assume t...
Please provide a description of the function:def pop_ctx(): if getattr(_request_ctx_stack.top, 'fixtures_request_context', False): _request_ctx_stack.pop() if _app_ctx_stack is not None and getattr(_app_ctx_stack.top, 'fixtures_app_context', False): _app_ctx_stack.pop()
[ "Removes the test context(s) from the current stack(s)\n " ]
Please provide a description of the function:def load_fixtures(db, fixtures): conn = db.engine.connect() metadata = db.metadata for fixture in fixtures: if 'model' in fixture: module_name, class_name = fixture['model'].rsplit('.', 1) module = importlib.import_module(mod...
[ "Loads the given fixtures into the database.\n " ]
Please provide a description of the function:def setup_handler(setup_fixtures_fn, setup_fn): def handler(obj): setup_fixtures_fn(obj) setup_fn(obj) return handler
[ "Returns a function that adds fixtures handling to the setup method.\n\n Makes sure that fixtures are setup before calling the given setup method.\n " ]
Please provide a description of the function:def teardown_handler(teardown_fixtures_fn, teardown_fn): def handler(obj): teardown_fn(obj) teardown_fixtures_fn(obj) return handler
[ "Returns a function that adds fixtures handling to the teardown method.\n\n Calls the given teardown method first before calling the fixtures teardown.\n " ]
Please provide a description of the function:def get_child_fn(attrs, names, bases): def call_method(obj, method): # The __get__ method takes an instance and an owner which changes # depending on the calling object. If the calling object is a class, # the...
[ "Returns a function from the child class that matches one of the names.\n\n Searches the child class's set of methods (i.e., the attrs dict) for all\n the functions matching the given list of names. If more than one is found,\n an exception is raised, if one is found, it is returned, and if non...
Please provide a description of the function:def print_msg(msg, header, file=sys.stdout): DEFAULT_MSG_BLOCK_WIDTH = 60 # Calculate the length of the boarder on each side of the header and the # total length of the bottom boarder side_boarder_length = (DEFAULT_MSG_BLOCK_WIDTH - (len(header) + 2)) /...
[ "Prints a boardered message to the screen", "Returns a string padded and centered by the given length" ]
Please provide a description of the function:def can_persist_fixtures(): # If we're running python 2.7 or greater, we're fine if sys.hexversion >= 0x02070000: return True # Otherwise, nose and py.test support the setUpClass and tearDownClass # methods, so if we're using either of those, go...
[ "Returns True if it's possible to persist fixtures across tests.\n\n Flask-Fixtures uses the setUpClass and tearDownClass methods to persist\n fixtures across tests. These methods were added to unittest.TestCase in\n python 2.7. So, we can only persist fixtures when using python 2.7.\n However, the nose...
Please provide a description of the function:def get(self, count=None, since_id=None, silent=False): if not silent: print('Retrieving photos from Twitter API...') self.auth_user = self.verify_credentials().screen_name self.since_ids = read_since_ids(self.users) for u...
[ "\n Get all photos from the user or members of the list\n :param count: Number of tweets to try and retrieve. If None, return\n all photos since `since_id`\n :param since_id: An integer specifying the oldest tweet id\n " ]
Please provide a description of the function:def read_since_ids(users): since_ids = {} for user in users: if config.has_option(SECTIONS['INCREMENTS'], user): since_ids[user] = config.getint(SECTIONS['INCREMENTS'], user) + 1 return since_ids
[ "\n Read max ids of the last downloads\n\n :param users: A list of users\n\n Return a dictionary mapping users to ids\n " ]
Please provide a description of the function:def set_max_ids(max_ids): config.read(CONFIG) for user, max_id in max_ids.items(): config.set(SECTIONS['INCREMENTS'], user, str(max_id)) with open(CONFIG, 'w') as f: config.write(f)
[ "\n Set max ids of the current downloads\n\n :param max_ids: A dictionary mapping users to ids\n " ]
Please provide a description of the function:def hash_bytes(buf): sha256 = hashlib.sha256() sha256.update(buf) return 'sha256:' + sha256.hexdigest()
[ "\n Hash bytes using the same method the registry uses (currently SHA-256).\n\n :param buf: Bytes to hash\n :type buf: binary str\n\n :rtype: str\n :returns: Hex-encoded hash of file's content (prefixed by ``sha256:``)\n " ]
Please provide a description of the function:def hash_file(filename): sha256 = hashlib.sha256() with open(filename, 'rb') as f: for chunk in iter(lambda: f.read(8192), b''): sha256.update(chunk) return 'sha256:' + sha256.hexdigest()
[ "\n Hash a file using the same method the registry uses (currently SHA-256).\n\n :param filename: Name of file to hash\n :type filename: str\n\n :rtype: str\n :returns: Hex-encoded hash of file's content (prefixed by ``sha256:``)\n " ]
Please provide a description of the function:def authenticate(self, username=None, password=None, actions=None, response=None, authorization=None): # pylint: disable=too-many-arguments,too-many-locals if response is None: ...
[ "\n Authenticate to the registry using a username and password,\n an authorization header or otherwise as the anonymous user.\n\n :param username: User name to authenticate as.\n :type username: str\n\n :param password: User's password.\n :type password: str\n\n :par...
Please provide a description of the function:def list_repos(self, batch_size=None, iterate=False): it = PaginatingResponse(self, '_base_request', '_catalog', 'repositories', params={'n': batch_size}) return it if iterate else list(...
[ "\n List all repositories in the registry.\n\n :param batch_size: Number of repository names to ask the server for at a time.\n :type batch_size: int\n\n :param iterate: Whether to return iterator over the names or a list of all the names.\n :type iterate: bool\n\n :rtype: ...
Please provide a description of the function:def push_blob(self, filename=None, progress=None, data=None, digest=None, check_exists=True): # pylint: disable=too-many-arguments if filename is None: dgst = digest ...
[ "\n Upload a file to the registry and return its (SHA-256) hash.\n\n The registry is content-addressable so the file's content (aka blob)\n can be retrieved later by passing the hash to :meth:`pull_blob`.\n\n :param filename: File to upload.\n :type filename: str\n\n :param...
Please provide a description of the function:def pull_blob(self, digest, size=False, chunk_size=None): if chunk_size is None: chunk_size = 8192 r = self._request('get', 'blobs/' + digest, stream=True) class Chunks(object): # pylint: disable=too-few-public-methods...
[ "\n Download a blob from the registry given the hash of its content.\n\n :param digest: Hash of the blob's content (prefixed by ``sha256:``).\n :type digest: str\n\n :param size: Whether to return the size of the blob too.\n :type size: bool\n\n :param chunk_size: Number of...
Please provide a description of the function:def blob_size(self, digest): r = self._request('head', 'blobs/' + digest) return long(r.headers['content-length'])
[ "\n Return the size of a blob in the registry given the hash of its content.\n\n :param digest: Hash of the blob's content (prefixed by ``sha256:``).\n :type digest: str\n\n :rtype: long\n :returns: Whether the blob exists.\n " ]
Please provide a description of the function:def set_manifest(self, alias, manifest_json): self._request('put', 'manifests/' + alias, data=manifest_json, headers={'Content-Type': _schema2_mimetype})
[ "\n Give a name (alias) to a manifest.\n\n :param alias: Alias name\n :type alias: str\n\n :param manifest_json: A V2 Schema 2 manifest JSON string\n :type digests: list\n " ]
Please provide a description of the function:def set_alias(self, alias, *digests): # pylint: disable=too-many-locals try: manifest_json = self.make_manifest(*digests) self.set_manifest(alias, manifest_json) return manifest_json except requests.excepti...
[ "\n Give a name (alias) to a set of blobs. Each blob is specified by\n the hash of its content.\n\n :param alias: Alias name\n :type alias: str\n\n :param digests: List of blob hashes (prefixed by ``sha256:``).\n :type digests: list of strings\n\n :rtype: str\n ...
Please provide a description of the function:def get_manifest_and_response(self, alias): r = self._request('get', 'manifests/' + alias, headers={'Accept': _schema2_mimetype + ', ' + _schema1_mimetype}) ...
[ "\n Request the manifest for an alias and return the manifest and the\n response.\n\n :param alias: Alias name.\n :type alias: str\n\n :rtype: tuple\n :returns: Tuple containing the manifest as a string (JSON) and the `requests.Response <http://docs.python-requests.org/en/m...
Please provide a description of the function:def get_alias(self, alias=None, manifest=None, verify=True, sizes=False, dcd=None): # pylint: disable=too-many-arguments return self._get_alias(alias, manifest,...
[ "\n Get the blob hashes assigned to an alias.\n\n :param alias: Alias name. You almost definitely will only need to pass this argument.\n :type alias: str\n\n :param manifest: If you previously obtained a manifest, specify it here instead of ``alias``. You almost definitely won't need to...
Please provide a description of the function:def get_digest(self, alias=None, manifest=None, verify=True, dcd=None): return self._get_alias(alias, manifest, verify, False, dcd, True)
[ "\n (v2 schema only) Get the hash of an alias's configuration blob.\n\n For an alias created using ``dxf``, this is the hash of the first blob\n assigned to the alias.\n\n For a Docker image tag, this is the same as\n ``docker inspect alias --format='{{.Id}}'``.\n\n :param ...
Please provide a description of the function:def _get_dcd(self, alias): # https://docs.docker.com/registry/spec/api/#deleting-an-image # Note When deleting a manifest from a registry version 2.3 or later, # the following header must be used when HEAD or GET-ing the manifest # to...
[ "\n Get the Docker-Content-Digest header for an alias.\n\n :param alias: Alias name.\n :type alias: str\n\n :rtype: str\n :returns: DCD header for the alias.\n " ]
Please provide a description of the function:def del_alias(self, alias): dcd = self._get_dcd(alias) dgsts = self.get_alias(alias) self._request('delete', 'manifests/{}'.format(dcd)) return dgsts
[ "\n Delete an alias from the registry. The blobs it points to won't be deleted. Use :meth:`del_blob` for that.\n\n .. Note::\n On private registry, garbage collection might need to be run manually; see:\n https://docs.docker.com/registry/garbage-collection/\n\n :param alias:...
Please provide a description of the function:def from_base(cls, base, repo): # pylint: disable=protected-access r = cls(base._host, repo, base._auth, base._insecure, base._auth_host, base._tlsverify) r._token = base._token r._headers = base._headers r._sessions = [base._...
[ "\n Create a :class:`DXF` object which uses the same host, settings and\n session as an existing :class:`DXFBase` object.\n\n :param base: Existing :class:`DXFBase` object.\n :type base: :class:`DXFBase`\n\n :param repo: Name of the repository to access on the registry. Typically ...
Please provide a description of the function:def get_name(self, name_case=DdlParseBase.NAME_CASE.original): if name_case == self.NAME_CASE.lower: return self._name.lower() elif name_case == self.NAME_CASE.upper: return self._name.upper() else: return ...
[ "\n Get Name converted case\n\n :param name_case: name case type\n * DdlParse.NAME_CASE.original : Return to no convert\n * DdlParse.NAME_CASE.lower : Return to lower\n * DdlParse.NAME_CASE.upper : Return to upper\n\n :return: name\n " ]
Please provide a description of the function:def constraint(self): constraint_arr = [] if self._not_null: constraint_arr.append("PRIMARY KEY" if self._pk else "NOT NULL") if self._unique: constraint_arr.append("UNIQUE") return " ".join(constraint_arr)
[ "Constraint string" ]
Please provide a description of the function:def bigquery_data_type(self): # BigQuery data type = {source_database: [data type, ...], ...} BQ_DATA_TYPE_DIC = OrderedDict() BQ_DATA_TYPE_DIC["STRING"] = {None: [re.compile(r"(CHAR|TEXT|CLOB|JSON|UUID)")]} BQ_DATA_TYPE_DIC["INTEGER...
[ "Get BigQuery Legacy SQL data type" ]
Please provide a description of the function:def to_bigquery_field(self, name_case=DdlParseBase.NAME_CASE.original): col_name = self.get_name(name_case) mode = self.bigquery_mode if self.array_dimensional <= 1: # no or one dimensional array data type type = sel...
[ "Generate BigQuery JSON field define" ]
Please provide a description of the function:def to_bigquery_fields(self, name_case=DdlParseBase.NAME_CASE.original): bq_fields = [] for col in self.values(): bq_fields.append(col.to_bigquery_field(name_case)) return "[{}]".format(",".join(bq_fields))
[ "\n Generate BigQuery JSON fields define\n\n :param name_case: name case type\n * DdlParse.NAME_CASE.original : Return to no convert\n * DdlParse.NAME_CASE.lower : Return to lower\n * DdlParse.NAME_CASE.upper : Return to upper\n\n :return: BigQuery JSON fields d...
Please provide a description of the function:def to_bigquery_fields(self, name_case=DdlParseBase.NAME_CASE.original): return self._columns.to_bigquery_fields(name_case)
[ "\n Generate BigQuery JSON fields define\n\n :param name_case: name case type\n * DdlParse.NAME_CASE.original : Return to no convert\n * DdlParse.NAME_CASE.lower : Return to lower\n * DdlParse.NAME_CASE.upper : Return to upper\n\n :return: BigQuery JSON fields d...
Please provide a description of the function:def to_bigquery_ddl(self, name_case=DdlParseBase.NAME_CASE.original): if self.schema is None: dataset = "dataset" elif name_case == self.NAME_CASE.lower: dataset = self.schema.lower() elif name_case == self.NAME_CASE....
[ "\n Generate BigQuery CREATE TABLE statements\n\n :param name_case: name case type\n * DdlParse.NAME_CASE.original : Return to no convert\n * DdlParse.NAME_CASE.lower : Return to lower\n * DdlParse.NAME_CASE.upper : Return to upper\n\n :return: BigQuery CREATE T...
Please provide a description of the function:def parse(self, ddl=None, source_database=None): if ddl is not None: self._ddl = ddl if source_database is not None: self.source_database = source_database if self._ddl is None: raise ValueError("DDL is ...
[ "\n Parse DDL script.\n\n :param ddl: DDL script\n :return: DdlParseTable, Parsed table define info.\n " ]
Please provide a description of the function:def launch(program, sock, stderr=True, cwd=None, env=None): if stderr is True: err = sock # redirect to socket elif stderr is False: err = open(os.devnull, 'wb') # hide elif stderr is None: err = None # red...
[ "\n A static method for launching a process that is connected to a given\n socket. Same rules from the Process constructor apply.\n " ]
Please provide a description of the function:def respond(self, packet, peer, flags=0): self.sock.sendto(packet, flags, peer)
[ "\n Send a message back to a peer.\n\n :param packet: The data to send\n :param peer: The address to send to, as a tuple (host, port)\n :param flags: Any sending flags you want to use for some reason\n " ]
Please provide a description of the function:def _parse_target(target, listen, udp, ipv6): if isinstance(target, str): if target.startswith('nc '): out_host = None out_port = None try: opts, pieces = getopt.getopt(target.s...
[ "\n Takes the basic version of the user args and extract as much data as\n possible from target. Returns a tuple that is its arguments but\n sanitized.\n " ]
Please provide a description of the function:def _connect(self, target, listen, udp, ipv6, retry): ty = socket.SOCK_DGRAM if udp else socket.SOCK_STREAM fam = socket.AF_INET6 if ipv6 else socket.AF_INET self.sock = socket.socket(fam, ty) if listen: self.sock.setsocko...
[ "\n Takes target/listen/udp/ipv6 and sets self.sock and self.peer\n " ]
Please provide a description of the function:def close(self): if self._sock_send is not None: self._sock_send.close() return self.sock.close()
[ "\n Close the socket.\n " ]
Please provide a description of the function:def shutdown(self, how=socket.SHUT_RDWR): if self._sock_send is not None: self._sock_send.shutdown(how) return self.sock.shutdown(how)
[ "\n Send a shutdown signal for both reading and writing, or whatever\n socket.SHUT_* constant you like.\n\n Shutdown differs from closing in that it explicitly changes the state of\n the socket resource to closed, whereas closing will only decrement the\n number of peers on this e...
Please provide a description of the function:def shutdown_rd(self): if self._sock_send is not None: self.sock.close() else: return self.shutdown(socket.SHUT_RD)
[ "\n Send a shutdown signal for reading - you may no longer read from this\n socket.\n " ]
Please provide a description of the function:def shutdown_wr(self): if self._sock_send is not None: self._sock_send.close() else: return self.shutdown(socket.SHUT_WR)
[ "\n Send a shutdown signal for writing - you may no longer write to this\n socket.\n " ]
Please provide a description of the function:def _recv_predicate(self, predicate, timeout='default', raise_eof=True): if timeout == 'default': timeout = self._timeout self.timed_out = False start = time.time() try: while True: cut_at = ...
[ "\n Receive until predicate returns a positive integer.\n The returned number is the size to return.\n " ]
Please provide a description of the function:def recv(self, n=4096, timeout='default'): self._print_recv_header( '======== Receiving {0}B{timeout_text} ========', timeout, n) return self._recv_predicate(lambda s: min(n, len(s)), timeout)
[ "\n Receive at most n bytes (default 4096) from the socket\n\n Aliases: read, get\n " ]
Please provide a description of the function:def recv_until(self, s, max_size=None, timeout='default'): self._print_recv_header( '======== Receiving until {0}{timeout_text} ========', timeout, repr(s)) if max_size is None: max_size = 2 ** 62 def _predicate(buf...
[ "\n Recieve data from the socket until the given substring is observed.\n Data in the same datagram as the substring, following the substring,\n will not be returned and will be cached for future receives.\n\n Aliases: read_until, readuntil, recvuntil\n " ]
Please provide a description of the function:def recv_all(self, timeout='default'): self._print_recv_header('======== Receiving until close{timeout_text} ========', timeout) return self._recv_predicate(lambda s: 0, timeout, raise_eof=False)
[ "\n Return all data recieved until connection closes.\n\n Aliases: read_all, readall, recvall\n " ]
Please provide a description of the function:def recv_exactly(self, n, timeout='default'): self._print_recv_header( '======== Receiving until exactly {0}B{timeout_text} ========', timeout, n) return self._recv_predicate(lambda s: n if len(s) >= n else 0, timeout)
[ "\n Recieve exactly n bytes\n\n Aliases: read_exactly, readexactly, recvexactly\n " ]
Please provide a description of the function:def send(self, s): self._print_header('======== Sending ({0}) ========'.format(len(s))) self._log_send(s) out = len(s) while s: s = s[self._send(s):] return out
[ "\n Sends all the given data to the socket.\n\n Aliases: write, put, sendall, send_all\n " ]
Please provide a description of the function:def interact(self, insock=sys.stdin, outsock=sys.stdout): self._print_header('======== Beginning interactive session ========') if hasattr(outsock, 'buffer'): outsock = outsock.buffer # pylint: disable=no-member self.timed_ou...
[ "\n Connects the socket to the terminal for user interaction.\n Alternate input and output files may be specified.\n\n This method cannot be used with a timeout.\n\n Aliases: interactive, interaction\n " ]
Please provide a description of the function:def recv_line(self, max_size=None, timeout='default', ending=None): if ending is None: ending = self.LINE_ENDING return self.recv_until(ending, max_size, timeout)
[ "\n Recieve until the next newline , default \"\\\\n\". The newline string can\n be changed by changing ``nc.LINE_ENDING``. The newline will be returned\n as part of the string.\n\n Aliases: recvline, readline, read_line, readln, recvln\n " ]
Please provide a description of the function:def send_line(self, line, ending=None): if ending is None: ending = self.LINE_ENDING return self.send(line + ending)
[ "\n Write the string to the wire, followed by a newline. The newline string\n can be changed by changing ``nc.LINE_ENDING``.\n\n Aliases: sendline, writeline, write_line, writeln, sendln\n " ]
Please provide a description of the function:def is_active(self, timperiods): now = int(time.time()) timperiod = timperiods[self.modulation_period] if not timperiod or timperiod.is_time_valid(now): return True return False
[ "\n Know if this result modulation is active now\n\n :return: True is we are in the period, otherwise False\n :rtype: bool\n " ]
Please provide a description of the function:def module_return(self, return_code, timeperiods): # Only if in modulation_period of modulation_period == None if self.is_active(timeperiods): # Try to change the exit code only if a new one is defined if self.exit_code_modula...
[ "Module the exit code if necessary ::\n\n * modulation_period is legit\n * exit_code_modulation\n * return_code in exit_codes_match\n\n :param return_code: actual code returned by the check\n :type return_code: int\n :return: return_code modulated if necessary (exit_code_mo...
Please provide a description of the function:def object(self, o_type, o_name=None): o_found = self._get_object(o_type=o_type, o_name=o_name) if not o_found: return {'_status': u'ERR', '_message': u'Required %s not found.' % o_type} return o_found
[ "Get an object from the scheduler.\n\n The result is a serialized object which is a Json structure containing:\n - content: the serialized object content\n - __sys_python_module__: the python class of the returned object\n\n The Alignak unserialize function of the alignak.misc.serializat...
Please provide a description of the function:def dump(self, o_name=None, details=False, raw=False): # pylint: disable=too-many-locals, too-many-branches def get_host_info(host, services, details=False, raw=False): # pylint: disable=too-many-branches __props...
[ "Dump an host (all hosts) from the scheduler.\n\n This gets the main host information from the scheduler. If details is set, then some\n more information are provided. This will not get all the host known attributes but only\n a reduced set that will inform about the host and its services statu...
Please provide a description of the function:def monitoring_problems(self): if self.app.type != 'scheduler': return {'_status': u'ERR', '_message': u"This service is only available for a scheduler daemon"} res = self.identity() res.update(self.app.get_mo...
[ "Get Alignak scheduler monitoring status\n\n Returns an object with the scheduler livesynthesis\n and the known problems\n\n :return: scheduler live synthesis\n :rtype: dict\n " ]
Please provide a description of the function:def _wait_new_conf(self): # Stop the scheduling loop self.app.sched.stop_scheduling() super(SchedulerInterface, self)._wait_new_conf()
[ "Ask the scheduler to drop its configuration and wait for a new one.\n\n This overrides the default method from GenericInterface\n\n :return: None\n " ]
Please provide a description of the function:def _initial_broks(self, broker_name): with self.app.conf_lock: logger.info("A new broker just connected : %s", broker_name) return self.app.sched.fill_initial_broks(broker_name)
[ "Get initial_broks from the scheduler\n\n This is used by the brokers to prepare the initial status broks\n\n This do not send broks, it only makes scheduler internal processing. Then the broker\n must use the *_broks* API to get all the stuff\n\n :param broker_name: broker name, used to...
Please provide a description of the function:def _broks(self, broker_name): logger.debug("Getting broks for %s from the scheduler", broker_name) for broker_link in list(self.app.brokers.values()): if broker_name == broker_link.name: break else: lo...
[ "Get the broks from a scheduler, used by brokers\n\n This is used by the brokers to get the broks list of a scheduler\n\n :param broker_name: broker name, used to filter broks\n :type broker_name: str\n :return: serialized brok list\n :rtype: dict\n " ]
Please provide a description of the function:def _checks(self, do_checks=False, do_actions=False, poller_tags=None, reactionner_tags=None, worker_name='none', module_types=None): if poller_tags is None: poller_tags = ['None'] if reactionner_tags is None: ...
[ "Get checks from scheduler, used by poller or reactionner when they are\n in active mode (passive = False)\n\n This function is not intended for external use. Let the poller and reactionner\n manage all this stuff by themselves ;)\n\n :param do_checks: used for poller to get checks\n ...
Please provide a description of the function:def put_results(self): res = cherrypy.request.json who_sent = res['from'] results = res['results'] results = unserialize(results, no_load=True) if results: logger.debug("Got some results: %d results from %s", len(...
[ "Put results to scheduler, used by poller or reactionner when they are\n in active mode (passive = False)\n\n This function is not intended for external use. Let the poller and reactionner\n manage all this stuff by themselves ;)\n\n :param from: poller/reactionner identification\n ...
Please provide a description of the function:def _run_external_commands(self): commands = cherrypy.request.json with self.app.lock: self.app.sched.run_external_commands(commands['cmds'])
[ "Post external_commands to scheduler (from arbiter)\n Wrapper to to app.sched.run_external_commands method\n\n :return: None\n " ]
Please provide a description of the function:def _get_objects(self, o_type): if o_type not in [t for t in self.app.sched.pushed_conf.types_creations]: return None try: _, _, strclss, _, _ = self.app.sched.pushed_conf.types_creations[o_type] o_list = getattr(...
[ "Get an object list from the scheduler\n\n Returns None if the required object type (`o_type`) is not known or an exception is raised.\n Else returns the objects list\n\n :param o_type: searched object type\n :type o_type: str\n :return: objects list\n :rtype: alignak.objec...