text
stringlengths
81
112k
train_new_deep_neural_network Train a new deep neural network and store the results as a new: ``MLJob`` and ``MLJobResult`` database records. def train_new_deep_neural_network(): """train_new_deep_neural_network Train a new deep neural network and store the results as a new: ``MLJob`` and ``MLJob...
prepare_new_dataset Prepare a new ``MLPrepare`` record and dataset files on disk. def prepare_new_dataset(): """prepare_new_dataset Prepare a new ``MLPrepare`` record and dataset files on disk. """ parser = argparse.ArgumentParser( description=( "Python client to Prepare a d...
Convert a 2D feature to a 3D feature by sampling a raster Parameters: raster (rasterio): raster to provide the z coordinate feature (dict): fiona feature record to convert Returns: result (Point or Linestring): shapely Point or LineString of xyz coordinate triples def drape(raster, fe...
Sample a raster at given coordinates Given a list of coordinates, return a list of x,y,z triples with z coordinates sampled from an input raster Parameters: raster (rasterio): raster dataset to sample coords: array of tuples containing coordinate pairs (x,y) or triples (x,y,z) Returns: ...
setup_logging Setup logging configuration :param default_level: level to log :param default_path: path to config (optional) :param env_key: path to config in this env var :param config_name: filename for config def setup_logging( default_level=logging.INFO, default_path="{}/loggin...
build_logger :param name: name that shows in the logger :param config: name of the config file :param log_level: level to log :param log_config_path: path to log config file def build_logger( name=os.getenv( "LOG_NAME", "client"), config="logging.json", log_level=logging.IN...
build_colorized_logger :param name: name that shows in the logger :param config: name of the config file :param log_level: level to log :param log_config_path: path to log config file def build_colorized_logger( name=os.getenv( "LOG_NAME", "client"), config="colors-logging.json...
Your AuhtService should override this method for request authentication, otherwise means no authentication. :param request: HttpRequest Django's HttpRequest object :param auth_route: str User's resqueted route :param actual_params: User's url parameters :return: bool def authenticate(se...
Converts 2D geometries to 3D using GEOS sample through fiona. \b Example: drape point.shp elevation.tif -o point_z.shp def cli(source_f, raster_f, output, verbose): """ Converts 2D geometries to 3D using GEOS sample through fiona. \b Example: drape point.shp elevation.tif -o point_z.s...
QuerySet for all comments for a particular model (either an instance or a class). def for_model(self, model): """ QuerySet for all comments for a particular model (either an instance or a class). """ ct = ContentType.objects.get_for_model(model) qs = self.get_que...
Blocking call, returns the value of the execution in JS def eval(self, command): 'Blocking call, returns the value of the execution in JS' event = threading.Event() # TODO: Add event to server #job_id = str(id(command)) import random job_id = str(random.random()) ...
Register a callback on server and on connected clients. def register(self, callback, name): 'Register a callback on server and on connected clients.' server.CALLBACKS[name] = callback self.run(''' window.skink.%s = function(args=[]) { window.skink.call("%s", args); ...
Launch a Python exception from an error that took place in the browser. messsage format: - name: str - description: str def launch_exception(message): """ Launch a Python exception from an error that took place in the browser. messsage format: - name: str -...
start_predictions Using environment variables, create an AntiNex AI Client. You can also use command line args if you want. This can train a new deep neural network if it does not exist or it can use an existing pre-trained deep neural network within the AntiNex Core to make new predictions. def ...
login def login( self): """login""" auth_url = self.api_urls["login"] if self.verbose: log.info(("log in user={} url={} ca_dir={} cert={}") .format( self.user, auth_url, self.c...
build_response :param status: status code :param error: error message :param data: dictionary to send back def build_response( self, status=NOT_SET, error="", data=None): """build_response :param status: status code :para...
retry_login def retry_login( self): """retry_login""" if not self.user or not self.password: return self.build_response( status=ERROR, error="please set the user and password") retry = 0 not_done = True while not_done: ...
get_prepare_by_id :param prepare_id: MLJob.id in the database def get_prepare_by_id( self, prepare_id=None): """get_prepare_by_id :param prepare_id: MLJob.id in the database """ if not prepare_id: log.error("missing prepare_id for get_prepa...
wait_for_job_to_finish :param job_id: MLJob.id to wait on :param sec_to_sleep: seconds to sleep during polling :param max_retries: max retires until stopping def wait_for_job_to_finish( self, job_id, sec_to_sleep=5.0, max_retries=100000): ...
wait_for_prepare_to_finish :param prepare_id: MLPrepare.id to wait on :param sec_to_sleep: seconds to sleep during polling :param max_retries: max retires until stopping def wait_for_prepare_to_finish( self, prepare_id, sec_to_sleep=5.0, max_retr...
NB: Overridden to remove dupe comment check for admins (necessary for canned responses) Return a new (unsaved) comment object based on the information in this form. Assumes that the form is already validated and will throw a ValueError if not. Does not set any of the fields tha...
Start Rinzler App :param app_name: str Application's identifier :return: dict def boot(app_name) -> Rinzler: """ Start Rinzler App :param app_name: str Application's identifier :return: dict """ app = Rinzler(app_name) app.log.info("App booted =)") return app
Maps a route namespace with the given params and point it's requests to the especified controller. :param route: str Namespace route to be mapped :param controller: callback Controller callable to map end-points :rtype: url def mount(self, route: str, controller: callable) -> url: """ ...
Sets the authentication service :param auth_service: BaseAuthService Authentication service :raises: TypeError If the auth_service object is not a subclass of rinzler.auth.BaseAuthService :rtype: Rinzler def set_auth_service(self, auth_service: BaseAuthService): """ Sets the aut...
Prepares for the CallBackResolver and handles the response and exceptions :param request HttpRequest :rtype: HttpResponse def handle(self, request: HttpRequest) -> HttpResponse: """ Prepares for the CallBackResolver and handles the response and exceptions :param request HttpRequ...
Executes the resolved end-point callback, or its fallback :rtype: Response or object def exec_route_callback(self) -> Response or object: """ Executes the resolved end-point callback, or its fallback :rtype: Response or object """ if self.__method.lower() in self.__end_p...
Determines whether a route matches the actual requested route or not :param actual_route str :param expected_route :rtype: Boolean def request_matches_route(self, actual_route: str, expected_route: str): """ Determines whether a route matches the actual requested route or not ...
Runs the pre-defined authenticaton service :param bound_route str route matched :param actual_params dict actual url parameters :rtype: bool def authenticate(self, bound_route, actual_params) -> bool: """ Runs the pre-defined authenticaton service :param bound_route str ...
Assembles a dictionary whith the parameters schema defined for this route :param expected_params dict parameters schema defined for this route :param actual_params dict actual url parameters :rtype: dict def get_callback_pattern(expected_params, actual_params): """ Assembles a d...
Gets route parameters as dictionary :param end_point str target route :rtype: list def get_url_params(end_point: str) -> list: """ Gets route parameters as dictionary :param end_point str target route :rtype: list """ var_params = end_point.split('/') ...
Extracts the route from the accessed URL and sets it to __end_point_uri :rtype: bool def set_end_point_uri(self) -> bool: """ Extracts the route from the accessed URL and sets it to __end_point_uri :rtype: bool """ expected_parts = self.__route.split("/") actual_...
Default callback for route not found :param request HttpRequest :rtype: Response def no_route_found(self, request): """ Default callback for route not found :param request HttpRequest :rtype: Response """ response_obj = OrderedDict() response_obj[...
Defaulf welcome page when the route / is note mapped yet :rtype: HttpResponse def welcome_page(self): """ Defaulf welcome page when the route / is note mapped yet :rtype: HttpResponse """ message = "HTTP/1.1 200 OK RINZLER FRAMEWORK" return HttpResponse( ...
Default callback for OPTIONS request :rtype: Response def default_route_options(): """ Default callback for OPTIONS request :rtype: Response """ response_obj = OrderedDict() response_obj["status"] = True response_obj["data"] = "Ok" return Respon...
Appends default headers to every response returned by the API :param response HttpResponse :rtype: HttpResponse def set_response_headers(self, response: HttpResponse) -> HttpResponse: """ Appends default headers to every response returned by the API :param response HttpResponse ...
Defines whether the JSON response will be indented or not :param request_headers: dict :return: self def get_json_ident(request_headers: dict) -> int: """ Defines whether the JSON response will be indented or not :param request_headers: dict :return: self """ ...
Implementation of prop (get_item) that also supports object attributes :param key: :param dct_or_obj: :return: def prop(key, dct_or_obj): """ Implementation of prop (get_item) that also supports object attributes :param key: :param dct_or_obj: :return: """ # Note that hasatt...
Returns true if all dct values pass f :param f: binary lambda predicate :param dct: :return: True or false def all_pass_dict(f, dct): """ Returns true if all dct values pass f :param f: binary lambda predicate :param dct: :return: True or false """ return all(map_with_obj_to...
Ramda propOr implementation. This also resolves object attributes, so key can be a dict prop or an attribute of dct_or_obj :param default: Value if dct_or_obj doesn't have key_or_prop or the resolved value is null :param key: :param dct_or_obj: :return: def prop_or(default, key, dct_or_obj): ...
Ramda propEq plus propOr implementation :param default: :param key: :param value: :param dct: :return: def prop_eq_or(default, key, value, dct): """ Ramda propEq plus propOr implementation :param default: :param key: :param value: :param dct: :return: """ ret...
Ramda propEq/propIn plus propOr :param default: :param key: :param value: :param dct: :return: def prop_eq_or_in_or(default, key, value, dct): """ Ramda propEq/propIn plus propOr :param default: :param key: :param value: :param dct: :return: """ return has(ke...
Optional version of item_path with a default value. keys can be dict keys or object attributes, or a combination :param default: :param keys: List of keys or dot-separated string :param dict_or_obj: A dict or obj :return: def item_path_or(default, keys, dict_or_obj): """ Optional version of ite...
Given a string of path segments separated by ., splits them into an array. Int strings are converted to numbers to serve as an array index :param keys: e.g. 'foo.bar.1.goo' :param dct: e.g. dict(foo=dict(bar=[dict(goo='a'), dict(goo='b')]) :return: The resolved value or an error. E.g. for above the ...
Given a string of path segments separated by ., splits them into an array. Int strings are converted to numbers to serve as an array index :param default: Value if any part yields None or undefined :param keys: e.g. 'foo.bar.1.goo' :param dct: e.g. dict(foo=dict(bar=[dict(goo='a'), dict(goo='b')]) ...
Implementation of ramda has :param prop: :param object_or_dct: :return: def has(prop, object_or_dct): """ Implementation of ramda has :param prop: :param object_or_dct: :return: """ return prop in object_or_dct if isinstance(dict, object_or_dct) else hasattr(object_or_dct, prop)
Implementation of omit that recurses. This tests the same keys at every level of dict and in lists :param omit_props: :param dct: :return: def omit_deep(omit_props, dct): """ Implementation of omit that recurses. This tests the same keys at every level of dict and in lists :param omit_props: ...
Implementation of pick that recurses. This tests the same keys at every level of dict and in lists :param pick_dct: Deep dict matching some portion of dct. :param dct: Dct to filter. Any key matching pick_dct pass through. It doesn't matter what the pick_dct value is as long as the key exists. Arrays also p...
Implementation of map that recurses. This tests the same keys at every level of dict and in lists :param f: 2-ary function expecting a key and value and returns a modified value :param dct: Dict for deep processing :return: Modified dct with matching props mapped def map_with_obj_deep(f, dct): """ ...
Implementation of map that recurses. This tests the same keys at every level of dict and in lists :param f: 2-ary function expecting a key and value and returns a modified key :param dct: Dict for deep processing :return: Modified dct with matching props mapped def map_keys_deep(f, dct): """ Implem...
Used by map_deep and map_keys_deep :param map_props: :param f: Expects a key and value and returns a pair :param dct: :return: def _map_deep(f, dct): """ Used by map_deep and map_keys_deep :param map_props: :param f: Expects a key and value and returns a pair :param dct: :return...
Filters deeply by comparing dct to filter_dct's value at each depth. Whenever a mismatch occurs the whole thing returns false :param params_dct: dict matching any portion of dct. E.g. filter_dct = {foo: {bar: 1}} would allow {foo: {bar: 1, car: 2}} to pass, {foo: {bar: 2}} would fail, {goo: ...} would fail ...
Ramda implementation of join :param strin: :param items: :return: def join(strin, items): """ Ramda implementation of join :param strin: :param items: :return: """ return strin.join(map(lambda item: str(item), items))
Implementation of Ramda's mapObjIndexed without the final argument. This returns the original key with the mapped value. Use map_key_values to modify the keys too :param f: Called with a key and value :param dct: :return {dict}: Keyed by the original key, valued by the mapped value def map_with_obj...
Calls f with each key of dct, possibly returning a modified key. Values are unchanged :param f: Called with each key and returns the same key or a modified key :param dct: :return: A dct with keys possibly modifed but values unchanged def map_keys(f, dct): """ Calls f with each key of dct, poss...
Calls f with each key and value of dct, possibly returning a modified key. Values are unchanged :param f: Called with each key and value and returns the same key or a modified key :param dct: :return: A dct with keys possibly modifed but values unchanged def map_keys_with_obj(f, dct): """ Calls...
Deep merge by this spec below :param dct1: :param dct2: :param merger Optional merger :return: def merge_deep(dct1, dct2, merger=None): """ Deep merge by this spec below :param dct1: :param dct2: :param merger Optional merger :return: """ my_merger = merger or Merger...
Shallow merge all the dcts :param dcts: :return: def merge_all(dcts): """ Shallow merge all the dcts :param dcts: :return: """ return reduce( lambda accum, dct: merge(accum, dct), dict(), dcts )
Like from pairs but combines duplicate key values into arrays :param pairs: :return: def from_pairs_to_array_values(pairs): """ Like from pairs but combines duplicate key values into arrays :param pairs: :return: """ result = {} for pair in pairs: result[pair[0]] = conca...
Returns the given prop of each item in the list :param prp: :param lst: :return: def map_prop_value_as_index(prp, lst): """ Returns the given prop of each item in the list :param prp: :param lst: :return: """ return from_pairs(map(lambda item: (prop(prp, item), item), lst))
Converts a key string like 'foo.bar.0.wopper' to ['foo', 'bar', 0, 'wopper'] :param {String} keyString The dot-separated key string :return {[String]} The lens array containing string or integers def key_string_to_lens_path(key_string): """ Converts a key string like 'foo.bar.0.wopper' to ['foo', 'bar', 0, ...
Simulates R.view with a lens_path since we don't have lens functions :param lens_path: Array of string paths :param obj: Object containing the given path :return: The value at the path or None def fake_lens_path_view(lens_path, obj): """ Simulates R.view with a lens_path since we don't have lens fu...
Simulates R.set with a lens_path since we don't have lens functions :param lens_path: Array of string paths :param value: The value to set at the lens path :param obj: Object containing the given path :return: The value at the path or None def fake_lens_path_set(lens_path, value, obj): """ Simu...
Undoes the work of flatten_dict @param {Object} obj 1-D object in the form returned by flattenObj @returns {Object} The original :param obj: :return: def unflatten_dct(obj): """ Undoes the work of flatten_dict @param {Object} obj 1-D object in the form returned by flattenObj @returns ...
ppj :param json_data: dictionary to print def ppj(json_data): """ppj :param json_data: dictionary to print """ return str(json.dumps( json_data, sort_keys=True, indent=4, separators=(',', ': ')))
Override change view to add extra context enabling moderate tool. def change_view(self, request, object_id, form_url='', extra_context=None): """ Override change view to add extra context enabling moderate tool. """ context = { 'has_moderate_tool': True } if ...
Add aditional moderate url. def get_urls(self): """ Add aditional moderate url. """ from django.conf.urls import url urls = super(AdminModeratorMixin, self).get_urls() info = self.model._meta.app_label, self.model._meta.model_name return [ url(r'^(.+)...
Renders a HttpResponse for the ongoing request :param indent int :rtype: HttpResponse def render(self, indent=0): """ Renders a HttpResponse for the ongoing request :param indent int :rtype: HttpResponse """ self.__indent = indent return HttpRespo...
Setup logging configuration def setup_logging(default_path='logging.yaml', env_key='LOG_CFG'): """ Setup logging configuration """ path = default_path value = os.getenv(env_key, None) if value: path = value if os.path.exists(path): with open(path, 'rt') as f: con...
Binds a GET route with the given callback :rtype: object def get(self, route: str(), callback: object()): """ Binds a GET route with the given callback :rtype: object """ self.__set_route('get', {route: callback}) return RouteMapping
Binds a POST route with the given callback :rtype: object def post(self, route: str(), callback: object()): """ Binds a POST route with the given callback :rtype: object """ self.__set_route('post', {route: callback}) return RouteMapping
Binds a PUT route with the given callback :rtype: object def put(self, route: str(), callback: object()): """ Binds a PUT route with the given callback :rtype: object """ self.__set_route('put', {route: callback}) return RouteMapping
Binds a PATCH route with the given callback :rtype: object def patch(self, route: str(), callback: object()): """ Binds a PATCH route with the given callback :rtype: object """ self.__set_route('patch', {route: callback}) return RouteMapping
Binds a PUT route with the given callback :rtype: object def delete(self, route: str(), callback: object()): """ Binds a PUT route with the given callback :rtype: object """ self.__set_route('delete', {route: callback}) return RouteMapping
Binds a HEAD route with the given callback :rtype: object def head(self, route: str(), callback: object()): """ Binds a HEAD route with the given callback :rtype: object """ self.__set_route('head', {route: callback}) return RouteMapping
Binds a OPTIONS route with the given callback :rtype: object def options(self, route: str(), callback: object()): """ Binds a OPTIONS route with the given callback :rtype: object """ self.__set_route('options', {route: callback}) return RouteMapping
Sets the given type_route and route to the route mapping :rtype: object def __set_route(self, type_route, route): """ Sets the given type_route and route to the route mapping :rtype: object """ if type_route in self.__routes: if not self.verify_route_already_...
Return a string identifying the operating system the application is running on. :rtype: str def operating_system(): """Return a string identifying the operating system the application is running on. :rtype: str """ if platform.system() == 'Darwin': return 'OS X Version %s' % plat...
Daemonize if the process is not already running. def start(self): """Daemonize if the process is not already running.""" if self._is_already_running(): LOGGER.error('Is already running') sys.exit(1) try: self._daemonize() self.controller.start() ...
Return the group id that the daemon will run with :rtype: int def gid(self): """Return the group id that the daemon will run with :rtype: int """ if not self._gid: if self.controller.config.daemon.group: self._gid = grp.getgrnam(self.config.daemon....
Return the user id that the process will run as :rtype: int def uid(self): """Return the user id that the process will run as :rtype: int """ if not self._uid: if self.config.daemon.user: self._uid = pwd.getpwnam(self.config.daemon.user).pw_uid ...
Fork into a background process and setup the process, copied in part from http://www.jejik.com/files/examples/daemon3x.py def _daemonize(self): """Fork into a background process and setup the process, copied in part from http://www.jejik.com/files/examples/daemon3x.py """ LOGGE...
Return the normalized path for the connection log, raising an exception if it can not written to. :return: str def _get_exception_log_path(): """Return the normalized path for the connection log, raising an exception if it can not written to. :return: str """ ...
Return the normalized path for the pidfile, raising an exception if it can not written to. :return: str :raises: ValueError :raises: OSError def _get_pidfile_path(self): """Return the normalized path for the pidfile, raising an exception if it can not written to. ...
Check to see if the process is running, first looking for a pidfile, then shelling out in either case, removing a pidfile if it exists but the process is not running. def _is_already_running(self): """Check to see if the process is running, first looking for a pidfile, then shelling out...
Remove the pid file from the filesystem def _remove_pidfile(self): """Remove the pid file from the filesystem""" LOGGER.debug('Removing pidfile: %s', self.pidfile_path) try: os.unlink(self.pidfile_path) except OSError: pass
Write the pid file out with the process number in the pid file def _write_pidfile(self): """Write the pid file out with the process number in the pid file""" LOGGER.debug('Writing pidfile: %s', self.pidfile_path) with open(self.pidfile_path, "w") as handle: handle.write(str(os.getpi...
Convert a string from snake case to camel case. For example, "some_var" would become "someVar". :param snake_case_string: Snake-cased string to convert to camel case. :returns: Camel-cased version of snake_case_string. def to_camel_case(snake_case_string): """ Convert a string from snake case to camel...
Convert a string from snake case to camel case with the first letter capitalized. For example, "some_var" would become "SomeVar". :param snake_case_string: Snake-cased string to convert to camel case. :returns: Camel-cased version of snake_case_string. def to_capitalized_camel_case(snake_case_string): ...
Convert a string from camel case to snake case. From example, "someVar" would become "some_var". :param camel_case_string: Camel-cased string to convert to snake case. :return: Snake-cased version of camel_case_string. def to_snake_case(camel_case_string): """ Convert a string from camel case to snake...
Make a copy of a dictionary with all keys converted to snake case. This is just calls to_snake_case on each of the keys in the dictionary and returns a new dictionary. :param camel_case_dict: Dictionary with the keys to convert. :type camel_case_dict: Dictionary. :return: Dictionary with the keys conv...
List the deployed lambda functions and print configuration. :return: exit_code def list_functions(awsclient): """List the deployed lambda functions and print configuration. :return: exit_code """ client_lambda = awsclient.get_client('lambda') response = client_lambda.list_functions() for ...
Create or update a lambda function. :param awsclient: :param function_name: :param role: :param handler_filename: :param handler_function: :param folders: :param description: :param timeout: :param memory: :param subnet_ids: :param security_groups: :param artifact_bucket...
Write zipfile contents to file. :param zipfile: :return: exit_code def bundle_lambda(zipfile): """Write zipfile contents to file. :param zipfile: :return: exit_code """ # TODO have 'bundle.zip' as default config if not zipfile: return 1 with open('bundle.zip', 'wb') as zfi...
Print out cloudformation metrics for a lambda function. :param awsclient :param name: name of the lambda function :return: exit_code def get_metrics(awsclient, name): """Print out cloudformation metrics for a lambda function. :param awsclient :param name: name of the lambda function :retu...
Rollback a lambda function to a given version. :param awsclient: :param function_name: :param alias_name: :param version: :return: exit_code def rollback(awsclient, function_name, alias_name=ALIAS_NAME, version=None): """Rollback a lambda function to a given version. :param awsclient: ...
Delete a lambda function. :param awsclient: :param function_name: :param events: list of events :param delete_logs: :return: exit_code def delete_lambda(awsclient, function_name, events=None, delete_logs=False): """Delete a lambda function. :param awsclient: :param function_name: ...
Deprecated: please use delete_lambda! :param awsclient: :param function_name: :param s3_event_sources: :param time_event_sources: :param delete_logs: :return: exit_code def delete_lambda_deprecated(awsclient, function_name, s3_event_sources=[], time_event_sources=[...
Deletes files used for creating bundle. * vendored/* * bundle.zip def cleanup_bundle(): """Deletes files used for creating bundle. * vendored/* * bundle.zip """ paths = ['./vendored', './bundle.zip'] for path in paths: if os.path.exists(path): log.deb...
Send a ping request to a lambda function. :param awsclient: :param function_name: :param alias_name: :param version: :return: ping response payload def ping(awsclient, function_name, alias_name=ALIAS_NAME, version=None): """Send a ping request to a lambda function. :param awsclient: :...
Send a ping request to a lambda function. :param awsclient: :param function_name: :param payload: :param invocation_type: :param alias_name: :param version: :param outfile: write response to file :return: ping response payload def invoke(awsclient, function_name, payload, invocation_ty...