Search is not available for this dataset
text
stringlengths
75
104k
def update(self, request, key): """Set an email address as primary address.""" request.UPDATE = http.QueryDict(request.body) email_addr = request.UPDATE.get('email') user_id = request.UPDATE.get('user') if not email_addr: return http.HttpResponseBadRequest() ...
def is_logged(self, user): """Check if a logged user is trying to access the register page. If so, redirect him/her to his/her profile""" response = None if user.is_authenticated(): if not user.needs_update: response = redirect('user_profile', username=use...
def get_env_setting(setting): """ Get the environment setting or return exception """ try: return os.environ[setting] except KeyError: error_msg = "Set the %s env variable" % setting raise ImproperlyConfigured(error_msg)
def parse_json(json_string, object_type, mappers): """ This function will use the custom JsonDecoder and the conventions.mappers to recreate your custom object in the parse json string state just call this method with the json_string your complete object_type and with your mappers dict. the mappers ...
def validate_social_account(account, url): """Verifies if a social account is valid. Examples: >>> validate_social_account('seocam', 'http://twitter.com') True >>> validate_social_account('seocam-fake-should-fail', 'http://twitter.com') False """ requ...
def fitting_rmsd(w_fit, C_fit, r_fit, Xs): '''Calculate the RMSD of fitting.''' return np.sqrt(sum((geometry.point_line_distance(p, C_fit, w_fit) - r_fit) ** 2 for p in Xs) / len(Xs))
def basic_parse(response, buf_size=ijson.backend.BUFSIZE): """ Iterator yielding unprefixed events. Parameters: - response: a stream response from requests """ lexer = iter(IncrementalJsonParser.lexer(response, buf_size)) for value in ijson.backend.parse_value(l...
def connect_to_kafka(self, bootstrap_servers='127.0.0.1:9092', auto_offset_reset='latest', client_id='Robot', **kwargs ): """Connect to kafka - ``bootstrap_servers``: default 127.0.0.1:9092 - ``cl...
def drop_connection(self, name, database=None): """ Force server to close current client subscription connection to the server @param str name: The name of the subscription @param str database: The name of the database """ request_executor = self._store.get_request_execut...
def execute_from_command_line(argv=None): """ A simple method that runs a ManagementUtility. """ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "colab.settings") from django.conf import settings if not hasattr(settings, 'SECRET_KEY') and 'initconfig' in sys.argv: command = initconfig.C...
def dashboard(request): """Dashboard page""" user = None if request.user.is_authenticated(): user = User.objects.get(username=request.user) latest_results, count_types = get_collaboration_data(user) latest_results.sort(key=lambda elem: elem.modified, reverse=True) context = { ...
def normalize(v): '''Normalize a vector based on its 2 norm.''' if 0 == np.linalg.norm(v): return v return v / np.linalg.norm(v)
def rotation_matrix_from_axis_and_angle(u, theta): '''Calculate a rotation matrix from an axis and an angle.''' x = u[0] y = u[1] z = u[2] s = np.sin(theta) c = np.cos(theta) return np.array([[c + x**2 * (1 - c), x * y * (1 - c) - z * s, x * z * (1 - c) + y * s], ...
def point_line_distance(p, l_p, l_v): '''Calculate the distance between a point and a line defined by a point and a direction vector. ''' l_v = normalize(l_v) u = p - l_p return np.linalg.norm(u - np.dot(u, l_v) * l_v)
def raw_query(self, query, query_parameters=None): """ To get all the document that equal to the query @param str query: The rql query @param dict query_parameters: Add query parameters to the query {key : value} """ self.assert_no_raw_query() if len(self._where...
def where_equals(self, field_name, value, exact=False): """ To get all the document that equal to the value in the given field_name @param str field_name: The field name in the index you want to query. @param value: The value will be the fields value you want to query @param boo...
def where(self, exact=False, **kwargs): """ To get all the document that equal to the value within kwargs with the specific key @param bool exact: If True getting exact match of the query @param kwargs: the keys of the kwargs will be the fields name in the index you want to query. ...
def search(self, field_name, search_terms, operator=QueryOperator.OR): """ For more complex text searching @param str field_name: The field name in the index you want to query. :type str @param str search_terms: The terms you want to query @param QueryOperator operator: ...
def where_ends_with(self, field_name, value): """ To get all the document that ends with the value in the giving field_name @param str field_name:The field name in the index you want to query. @param str value: The value will be the fields value you want to query """ if ...
def where_in(self, field_name, values, exact=False): """ Check that the field has one of the specified values @param str field_name: Name of the field @param str values: The values we wish to query @param bool exact: Getting the exact query (ex. case sensitive) """ ...
def to_facets(self, facets, start=0, page_size=None): """ Query the facets results for this query using the specified list of facets with the given start and pageSize @param List[Facet] facets: List of facets @param int start: Start index for paging @param page_size: Paging Pag...
def show_G_distribution(data): '''Show the distribution of the G function.''' Xs, t = fitting.preprocess_data(data) Theta, Phi = np.meshgrid(np.linspace(0, np.pi, 50), np.linspace(0, 2 * np.pi, 50)) G = [] for i in range(len(Theta)): G.append([]) for j in range(len(Theta[i])): ...
def show_fit(w_fit, C_fit, r_fit, Xs): '''Plot the fitting given the fitted axis direction, the fitted center, the fitted radius and the data points. ''' fig = plt.figure() ax = fig.gca(projection='3d') # Plot the data points ax.scatter([X[0] for X in Xs], [X[1] for X in Xs], [X[2...
def find_window(self, highlight_locations): """Getting the HIGHLIGHT_NUM_CHARS_BEFORE_MATCH setting to find how many characters before the first word found should be removed from the window """ if len(self.text_block) <= self.max_length: return (0, self.max_length) ...
def __set(self, key, real_value, coded_value): """Private method for setting a cookie's value""" morse_set = self.get(key, StringMorsel()) morse_set.set(key, real_value, coded_value) dict.__setitem__(self, key, morse_set)
def login(self): """ Try to login and set the internal session id. Please note: - Any failed login resets all existing session ids, even of other users. - SIDs expire after some time """ response = self.session.get(self.base_url + '/login_sid.lua', time...
def calculate_response(self, challenge, password): """Calculate response for the challenge-response authentication""" to_hash = (challenge + "-" + password).encode("UTF-16LE") hashed = hashlib.md5(to_hash).hexdigest() return "{0}-{1}".format(challenge, hashed)
def get_actors(self): """ Returns a list of Actor objects for querying SmartHome devices. This is currently the only working method for getting temperature data. """ devices = self.homeautoswitch("getdevicelistinfos") xml = ET.fromstring(devices) actors = [] ...
def get_actor_by_ain(self, ain): """ Return a actor identified by it's ain or return None """ for actor in self.get_actors(): if actor.actor_id == ain: return actor
def homeautoswitch(self, cmd, ain=None, param=None): """ Call a switch method. Should only be used by internal library functions. """ assert self.sid, "Not logged in" params = { 'switchcmd': cmd, 'sid': self.sid, } if param is not N...
def get_switch_actors(self): """ Get information about all actors This needs 1+(5n) requests where n = number of actors registered Deprecated, use get_actors instead. Returns a dict: [ain] = { 'name': Name of actor, 'state': Powerstate (boolean)...
def get_devices(self): """ Return a list of devices. Deprecated, use get_actors instead. """ url = self.base_url + '/net/home_auto_query.lua' response = self.session.get(url, params={ 'sid': self.sid, 'command': 'AllOutletStates', 'xhr'...
def get_consumption(self, deviceid, timerange="10"): """ Return all available energy consumption data for the device. You need to divice watt_values by 100 and volt_values by 1000 to get the "real" values. :return: dict """ tranges = ("10", "24h", "month", "year"...
def get_logs(self): """ Return the system logs since the last reboot. """ assert BeautifulSoup, "Please install bs4 to use this method" url = self.base_url + "/system/syslog.lua" response = self.session.get(url, params={ 'sid': self.sid, 'stylemod...
def seen_nonce(id, nonce, timestamp): """ Returns True if the Hawk nonce has been seen already. """ key = '{id}:{n}:{ts}'.format(id=id, n=nonce, ts=timestamp) if cache.get(key): log.warning('replay attack? already processed nonce {k}' .format(k=key)) return True ...
def cli(context, host, username, password): """ FritzBox SmartHome Tool \b Provides the following functions: - A easy to use library for querying SmartHome actors - This CLI tool for testing - A carbon client for pipeing data into graphite """ context.obj = FritzBox(host, username, ...
def actors(context): """Display a list of actors""" fritz = context.obj fritz.login() for actor in fritz.get_actors(): click.echo("{} ({} {}; AIN {} )".format( actor.name, actor.manufacturer, actor.productname, actor.actor_id, )) i...
def energy(context, features): """Display energy stats of all actors""" fritz = context.obj fritz.login() for actor in fritz.get_actors(): if actor.temperature is not None: click.echo("{} ({}): {:.2f} Watt current, {:.3f} wH total, {:.2f} °C".format( actor.name.encod...
def graphite(context, server, port, interval, prefix): """Display energy stats of all actors""" fritz = context.obj fritz.login() sid_ttl = time.time() + 600 # Find actors and create carbon keys click.echo(" * Requesting actors list") simple_chars = re.compile('[^A-Za-z0-9]+') actors = ...
def switch_on(context, ain): """Switch an actor's power to ON""" context.obj.login() actor = context.obj.get_actor_by_ain(ain) if actor: click.echo("Switching {} on".format(actor.name)) actor.switch_on() else: click.echo("Actor not found: {}".format(ain))
def switch_state(context, ain): """Get an actor's power state""" context.obj.login() actor = context.obj.get_actor_by_ain(ain) if actor: click.echo("State for {} is: {}".format(ain,'ON' if actor.get_state() else 'OFF')) else: click.echo("Actor not found: {}".format(ain))
def switch_toggle(context, ain): """Toggle an actor's power state""" context.obj.login() actor = context.obj.get_actor_by_ain(ain) if actor: if actor.get_state(): actor.switch_off() click.echo("State for {} is now OFF".format(ain)) else: actor.switch_o...
def logs(context, format): """Show system logs since last reboot""" fritz = context.obj fritz.login() messages = fritz.get_logs() if format == "plain": for msg in messages: merged = "{} {} {}".format(msg.date, msg.time, msg.message.encode("UTF-8")) click.echo(merged)...
def get_power(self): """ Returns the current power usage in milliWatts. Attention: Returns None if the value can't be queried or is unknown. """ value = self.box.homeautoswitch("getswitchpower", self.actor_id) return int(value) if value.isdigit() else None
def get_energy(self): """ Returns the consumed energy since the start of the statistics in Wh. Attention: Returns None if the value can't be queried or is unknown. """ value = self.box.homeautoswitch("getswitchenergy", self.actor_id) return int(value) if value.isdigit() e...
def get_temperature(self): """ Returns the current environment temperature. Attention: Returns None if the value can't be queried or is unknown. """ #raise NotImplementedError("This should work according to the AVM docs, but don't...") value = self.box.homeautoswitch("get...
def get_target_temperature(self): """ Returns the actual target temperature. Attention: Returns None if the value can't be queried or is unknown. """ value = self.box.homeautoswitch("gethkrtsoll", self.actor_id) self.target_temperature = self.__get_temp(value) ret...
def set_temperature(self, temp): """ Sets the temperature in celcius """ # Temperature is send to fritz.box a little weird param = 16 + ( ( temp - 8 ) * 2 ) if param < 16: param = 253 logger.info("Actor " + self.name + ": Temperature control set t...
def get_openshift_base_uri(self): """ https://<host>[:<port>]/ :return: str """ deprecated_key = "openshift_uri" key = "openshift_url" val = self._get_value(deprecated_key, self.conf_section, deprecated_key) if val is not None: warnings.warn("...
def get_builder_openshift_url(self): """ url of OpenShift where builder will connect """ key = "builder_openshift_url" url = self._get_deprecated(key, self.conf_section, key) if url is None: logger.warning("%r not found, falling back to get_openshift_base_uri()", key) ...
def generate_nodeselector_dict(self, nodeselector_str): """ helper method for generating nodeselector dict :param nodeselector_str: :return: dict """ nodeselector = {} if nodeselector_str and nodeselector_str != 'none': constraints = [x.strip() for x i...
def get_platform_node_selector(self, platform): """ search the configuration for entries of the form node_selector.platform :param platform: str, platform to search for, can be null :return dict """ nodeselector = {} if platform: nodeselector_str = sel...
def load(self): """ Extract tabular data as |TableData| instances from a CSV file. |load_source_desc_file| :return: Loaded table data. |load_table_name_desc| =================== ======================================== Format specifier ...
def load(self): """ Extract tabular data as |TableData| instances from a CSV text object. |load_source_desc_text| :return: Loaded table data. |load_table_name_desc| =================== ======================================== Format spec...
def set_params(self, **kwargs): """ set parameters according to specification these parameters are accepted: :param pulp_secret: str, resource name of pulp secret :param koji_target: str, koji tag with packages used to build the image :param kojiroot: str, URL from whic...
def has_ist_trigger(self): """Return True if this BuildConfig has ImageStreamTag trigger.""" triggers = self.template['spec'].get('triggers', []) if not triggers: return False for trigger in triggers: if trigger['type'] == 'ImageChange' and \ t...
def set_secret_for_plugin(self, secret, plugin=None, mount_path=None): """ Sets secret for plugin, if no plugin specified it will also set general secret :param secret: str, secret name :param plugin: tuple, (plugin type, plugin name, argument name) :param mount_path: st...
def set_secrets(self, secrets): """ :param secrets: dict, {(plugin type, plugin name, argument name): secret name} for example {('exit_plugins', 'koji_promote', 'koji_ssl_certs'): 'koji_ssl_certs', ...} """ secret_set = False for (plugin, secret) in secrets.items(): ...
def remove_tag_and_push_registries(tag_and_push_registries, version): """ Remove matching entries from tag_and_push_registries (in-place) :param tag_and_push_registries: dict, uri -> dict :param version: str, 'version' to match against """ registries = [uri ...
def adjust_for_registry_api_versions(self): """ Enable/disable plugins depending on supported registry API versions """ versions = self.spec.registry_api_versions.value if 'v2' not in versions: raise OsbsValidationException('v1-only docker registry API is not support...
def adjust_for_triggers(self): """Remove trigger-related plugins when needed If there are no triggers defined, it's assumed the feature is disabled and all trigger-related plugins are removed. If there are triggers defined, and this is a custom base image, some trigger-...
def adjust_for_scratch(self): """ Remove certain plugins in order to handle the "scratch build" scenario. Scratch builds must not affect subsequent builds, and should not be imported into Koji. """ if self.scratch: self.template['spec'].pop('triggers', None) ...
def adjust_for_custom_base_image(self): """ Disable plugins to handle builds depending on whether or not this is a build from a custom base image. """ plugins = [] if self.is_custom_base_image(): # Plugins irrelevant to building base images. plugin...
def render_koji(self): """ if there is yum repo specified, don't pick stuff from koji """ phase = 'prebuild_plugins' plugin = 'koji' if not self.dj.dock_json_has_plugin_conf(phase, plugin): return if self.spec.yum_repourls.value: logger.in...
def render_bump_release(self): """ If the bump_release plugin is present, configure it """ phase = 'prebuild_plugins' plugin = 'bump_release' if not self.dj.dock_json_has_plugin_conf(phase, plugin): return if self.spec.release.value: logge...
def render_sendmail(self): """ if we have smtp_host and smtp_from, configure sendmail plugin, else remove it """ phase = 'exit_plugins' plugin = 'sendmail' if not self.dj.dock_json_has_plugin_conf(phase, plugin): return if self.spec.smtp_host....
def render_fetch_maven_artifacts(self): """Configure fetch_maven_artifacts plugin""" phase = 'prebuild_plugins' plugin = 'fetch_maven_artifacts' if not self.dj.dock_json_has_plugin_conf(phase, plugin): return koji_hub = self.spec.kojihub.value koji_root = sel...
def render_tag_from_config(self): """Configure tag_from_config plugin""" phase = 'postbuild_plugins' plugin = 'tag_from_config' if not self.has_tag_suffixes_placeholder(): return unique_tag = self.spec.image_tag.value.split(':')[-1] tag_suffixes = {'unique': ...
def render_pulp_pull(self): """ If a pulp registry is specified, use pulp_pull plugin """ # pulp_pull is a multi-phase plugin phases = ('postbuild_plugins', 'exit_plugins') plugin = 'pulp_pull' for phase in phases: if not self.dj.dock_json_has_plugin_c...
def render_pulp_sync(self): """ If a pulp registry is specified, use the pulp plugin as well as the delete_from_registry to delete the image after sync """ if not self.dj.dock_json_has_plugin_conf('postbuild_plugins', 'pulp_sync'):...
def render_pulp_tag(self): """ Configure the pulp_tag plugin. """ if not self.dj.dock_json_has_plugin_conf('postbuild_plugins', 'pulp_tag'): return pulp_registry = self.spec.pulp_registry.value if pulp_registry...
def render_group_manifests(self): """ Configure the group_manifests plugin. Group is always set to false for now. """ if not self.dj.dock_json_has_plugin_conf('postbuild_plugins', 'group_manifests'): return push_conf = self.dj.dock_json_get_plugin_conf('postbuild_plu...
def render_import_image(self, use_auth=None): """ Configure the import_image plugin """ # import_image is a multi-phase plugin phases = ('postbuild_plugins', 'exit_plugins') plugin = 'import_image' for phase in phases: if self.spec.imagestream_name.va...
def render_customizations(self): """ Customize prod_inner for site specific customizations """ disable_plugins = self.customize_conf.get('disable_plugins', []) if not disable_plugins: logger.debug("No site-specific plugins to disable") else: for p...
def render_name(self, name, image_tag, platform): """Sets the Build/BuildConfig object name""" if self.scratch or self.isolated: name = image_tag # Platform name may contain characters not allowed by OpenShift. if platform: platform_suffix = '-{}'.for...
def setup_json_capture(osbs, os_conf, capture_dir): """ Only used for setting up the testing framework. """ try: os.mkdir(capture_dir) except OSError: pass finally: osbs.os._con.request = ResponseSaver(capture_dir, os_conf.get...
def get_terminal_size(): """ get size of console: rows x columns :return: tuple, (int, int) """ try: rows, columns = subprocess.check_output(['stty', 'size']).split() except subprocess.CalledProcessError: # not attached to terminal logger.info("not attached to terminal")...
def _longest_val_in_column(self, col): """ get size of longest value in specific column :param col: str, column name :return int """ try: # +2 is for implicit separator return max([len(x[col]) for x in self.table if x[col]]) + 2 except Key...
def _init(self): """ initialize all values based on provided input :return: None """ self.col_count = len(self.col_list) # list of lengths of longest entries in columns self.col_longest = self.get_all_longest_col_lengths() self.data_length = sum(self.col_...
def _count_sizes(self): """ count all values needed to display whole table <><---terminal-width-----------><> <> HEADER | HEADER2 | HEADER3 <> <>---------+----------+---------<> kudos to PostgreSQL developers :return: None """ format_list = [...
def get_all_longest_col_lengths(self): """ iterate over all columns and get their longest values :return: dict, {"column_name": 132} """ response = {} for col in self.col_list: response[col] = self._longest_val_in_column(col) return response
def _separate(self): """ get a width of separator for current column :return: int """ if self.total_free_space is None: return 0 else: sepa = self.default_column_space # we need to distribute remainders if self.default_colu...
def render(self): """ print provided table :return: None """ print(self.format_str.format(**self.header), file=sys.stderr) print(self.header_format_str.format(**self.header_data), file=sys.stderr) for row in self.data: print(self.format_str.format(**r...
def _validate_source_data(self): """ :raises ValidationError: """ try: jsonschema.validate(self._buffer, self._schema) except jsonschema.ValidationError as e: raise ValidationError(e)
def to_table_data(self): """ :raises ValueError: :raises pytablereader.error.ValidationError: """ self._validate_source_data() self._loader.inc_table_count() yield TableData( self._make_table_name(), ["key", "value"], [record ...
def to_table_data(self): """ :raises ValueError: :raises pytablereader.error.ValidationError: """ self._validate_source_data() for table_key, json_records in six.iteritems(self._buffer): attr_name_set = set() for json_record in json_records: ...
def to_table_data(self): """ :raises ValueError: :raises pytablereader.error.ValidationError: """ self._validate_source_data() for table_key, json_records in six.iteritems(self._buffer): headers = sorted(six.viewkeys(json_records)) self._loader....
def to_table_data(self): """ :raises ValueError: :raises pytablereader.error.ValidationError: """ self._validate_source_data() for table_key, json_records in six.iteritems(self._buffer): self._loader.inc_table_count() self._table_key = table_key ...
def set_params(self, **kwargs): """ set parameters in the user parameters these parameters are accepted: :param git_uri: str, uri of the git repository for the source :param git_ref: str, commit ID of the branch to be pulled :param git_branch: str, branch name of the bra...
def set_data_from_reactor_config(self): """ Sets data from reactor config """ reactor_config_override = self.user_params.reactor_config_override.value reactor_config_map = self.user_params.reactor_config_map.value data = None if reactor_config_override: ...
def _set_required_secrets(self, required_secrets, token_secrets): """ Sets required secrets """ if self.user_params.build_type.value == BUILD_TYPE_ORCHESTRATOR: required_secrets += token_secrets if not required_secrets: return secrets = self.temp...
def remove_plugin(self, phase, name, reason=None): """ if config contains plugin, remove it """ for p in self.template[phase]: if p.get('name') == name: self.template[phase].remove(p) if reason: logger.info('Removing {}:{}, ...
def add_plugin(self, phase, name, args, reason=None): """ if config has plugin, override it, else add it """ plugin_modified = False for plugin in self.template[phase]: if plugin['name'] == name: plugin['args'] = args plugin_modified =...
def get_plugin_conf(self, phase, name): """ Return the configuration for a plugin. Raises KeyError if there are no plugins of that type. Raises IndexError if the named plugin is not listed. """ match = [x for x in self.template[phase] if x.get('name') == name] re...
def has_plugin_conf(self, phase, name): """ Check whether a plugin is configured. """ try: self.get_plugin_conf(phase, name) return True except (KeyError, IndexError): return False
def adjust_for_scratch(self): """ Remove certain plugins in order to handle the "scratch build" scenario. Scratch builds must not affect subsequent builds, and should not be imported into Koji. """ if self.user_params.scratch.value: remove_plugins = [ ...
def adjust_for_isolated(self): """ Remove certain plugins in order to handle the "isolated build" scenario. """ if self.user_params.isolated.value: remove_plugins = [ ("prebuild_plugins", "check_and_set_rebuild"), ("prebuild_plugins", "...
def adjust_for_flatpak(self): """ Remove plugins that don't work when building Flatpaks """ if self.user_params.flatpak.value: remove_plugins = [ ("prebuild_plugins", "resolve_composes"), # We'll extract the filesystem anyways for a Flatpak ins...
def render_customizations(self): """ Customize template for site user specified customizations """ disable_plugins = self.pt.customize_conf.get('disable_plugins', []) if not disable_plugins: logger.debug('No site-user specified plugins to disable') else: ...
def render_koji(self): """ if there is yum repo in user params, don't pick stuff from koji """ phase = 'prebuild_plugins' plugin = 'koji' if not self.pt.has_plugin_conf(phase, plugin): return if self.user_params.yum_repourls.value: self.pt...