repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
ansible/ansible-kubernetes-modules-
library/openshift_v1_build_request.py
#!/usr/bin/python # -*- coding: utf-8 -*- from ansible.module_utils.openshift_common import OpenShiftAnsibleModule, OpenShiftAnsibleException DOCUMENTATION = ''' module: openshift_v1_build_request short_description: OpenShift BuildRequest description: - Manage the lifecycle of a build_request object. Supports check m...
ansible/ansible-kubernetes-modules-
library/k8s_v1_component_status_list.py
<gh_stars>10-100 #!/usr/bin/python # -*- coding: utf-8 -*- from ansible.module_utils.k8s_common import KubernetesAnsibleModule, KubernetesAnsibleException DOCUMENTATION = ''' module: k8s_v1_component_status_list short_description: Kubernetes ComponentStatusList description: - Retrieve a list of component_status. List...
ansible/ansible-kubernetes-modules-
library/openshift_v1_image_stream_tag.py
#!/usr/bin/python # -*- coding: utf-8 -*- from ansible.module_utils.openshift_common import OpenShiftAnsibleModule, OpenShiftAnsibleException DOCUMENTATION = ''' module: openshift_v1_image_stream_tag short_description: OpenShift ImageStreamTag description: - Manage the lifecycle of a image_stream_tag object. Supports...
ansible/ansible-kubernetes-modules-
library/k8s_v1beta1_pod_security_policy.py
<filename>library/k8s_v1beta1_pod_security_policy.py #!/usr/bin/python # -*- coding: utf-8 -*- from ansible.module_utils.k8s_common import KubernetesAnsibleModule, KubernetesAnsibleException DOCUMENTATION = ''' module: k8s_v1beta1_pod_security_policy short_description: Kubernetes PodSecurityPolicy description: - Mana...
rameshxghimire/vocable
players.py
""" players.py contains required classes. """ class Players(object): """Define player character and associated functions. """ def __init__(self, name, next_start_let=None, word_input="", pass_taken=0): self.name = name self.next_start_let = next_start_let self.pass_taken = pass_t...
rameshxghimire/vocable
classes.py
<reponame>rameshxghimire/vocable """classes.py contains Player and Game class definitions. """ class Player(): """blueprint for player objects to be instantiated dynamically. """ def __init__(self, name="", word_list=[], pass_taken=0): self.name = name self.word_list = word_list ...
rameshxghimire/vocable
game.py
<filename>game.py """ game.py contains game related classes. """ class Game(object): def __init__(self, num_players=[], player_names=[], spelled_words=[], start_letter="", condition=True, winner=False): self.num_players = num_players self.player_names = player_names self.spelled_words...
rameshxghimire/vocable
vocable.py
"""vocable.py contains the game logic, ui and other elements. """ import sys import datetime from classes import Player from classes import Game # record start time playtime = datetime.datetime.now() # function to initiate the welcome screen def welcome_screen(): # welcome statement print(f""" -----*...
DmitriyValetov/TopicNet
topicnet/cooking_machine/pretty_output.py
import numpy as np from datetime import datetime from .routine import get_fix_string, get_fix_list from .routine import get_equal_strings, get_equal_lists from .models.base_model import MODEL_NAME_LENGTH UP_END = "┌" DOWN_END = "└" MIDDLE = "├" LAST = "┤" EMPTY = "│" START_END = "┐" SPACE = " " USELESS_SUBKEYS = { ...
DmitriyValetov/TopicNet
topicnet/tests/test_top_documents_viewer.py
import artm import numpy as np import shutil import pytest import warnings from ..cooking_machine.models.topic_model import TopicModel from ..cooking_machine.dataset import Dataset, W_DIFF_BATCHES_1 from ..viewers import top_documents_viewer NUM_TOPICS = 5 NUM_DOCUMENT_PASSES = 1 NUM_ITERATIONS = 10 class TestTop...
DmitriyValetov/TopicNet
topicnet/dataset_manager/__init__.py
from .api import get_info, load_dataset
DmitriyValetov/TopicNet
topicnet/tests/test_topic_mapping.py
import numpy as np import pandas as pd import numpy.testing as npt from ..viewers import topic_mapping from ..cooking_machine.models.base_model import BaseModel class dummy_model(BaseModel): def __init__(self, matrix): self.values = matrix def get_phi(self, class_ids): """ """ index =...
DmitriyValetov/TopicNet
topicnet/viewers/top_similar_documents_viewer.py
import numpy as np import warnings from collections import defaultdict from scipy.spatial.distance import cdist as sp_cdist from typing import Callable from .base_viewer import BaseViewer from ..cooking_machine import BaseDataset # If change, also modify docstring for view() METRICS_NAMES = [ 'jensenshannon', '...
DmitriyValetov/TopicNet
topicnet/cooking_machine/models/topic_model.py
import artm import dill import glob import inspect import json import os import pandas as pd import pickle import shutil import warnings from artm.wrapper.exceptions import ArtmException from copy import deepcopy from inspect import signature from numbers import Number from six import iteritems from typing import ( ...
DmitriyValetov/TopicNet
topicnet/cooking_machine/recipes/exploratory_search_pipeline.py
<filename>topicnet/cooking_machine/recipes/exploratory_search_pipeline.py from .recipe_wrapper import BaseRecipe from .. import Dataset modality_selection_template = ( 'PerplexityScore{modality}' ' < 1.01 * MINIMUM(PerplexityScore{modality}) and SparsityPhiScore{modality} -> max' ) general_selection_template =...
DmitriyValetov/TopicNet
topicnet/cooking_machine/routine.py
import numpy as np import hashlib import json import re import warnings from datetime import datetime from statistics import mean, median import numexpr as ne W_TOO_STRICT = 'No models match criteria ' W_TOO_STRICT_DETAILS = '(The requirements on {} have eliminated all {} models)' W_NOT_ENOUGH_MODELS_FOR_CHOICE = 'No...
DmitriyValetov/TopicNet
topicnet/cooking_machine/models/base_score.py
import dill from . import scores as tn_scores class BaseScore: """ Base Class to construct custom score functions. """ def __init__(self, name: str = None): # TODO: name should not be optional """ Parameters ---------- name: Name of the score """...
DmitriyValetov/TopicNet
topicnet/cooking_machine/models/topic_prior_regularizer.py
import numpy as np import warnings from .base_regularizer import BaseRegularizer class TopicPriorRegularizer(BaseRegularizer): """ TopicPriorRegularizer adds prior beta_t to every column in Phi matrix of ARTM model. Thus every phi_wt has preassigned prior probability of being attached to topic t. ...
DmitriyValetov/TopicNet
topicnet/cooking_machine/cubes/__init__.py
from .base_cube import BaseCube, retrieve_score_for_strategy from .regularizer_cube import RegularizersModifierCube from .controller_cube import RegularizationControllerCube from .cube_creator import CubeCreator from .perplexity_strategy import PerplexityStrategy from .greedy_strategy import GreedyStrategy from .strate...
DmitriyValetov/TopicNet
topicnet/viewers/topic_flow_viewer.py
import numpy as np import plotly.graph_objects as go import artm from .base_viewer import BaseViewer from .top_tokens_viewer import TopTokensViewer class TopicFlowViewer(BaseViewer): """ Viewer to show trending topics over time. """ def __init__(self, model, time_labels, dataset, ...
DmitriyValetov/TopicNet
topicnet/cooking_machine/cubes/regularizer_cube.py
<filename>topicnet/cooking_machine/cubes/regularizer_cube.py from .base_cube import BaseCube from ..routine import transform_complex_entity_to_dict from ..rel_toolbox_lite import count_vocab_size, handle_regularizer from copy import deepcopy class RegularizersModifierCube(BaseCube): """ Allows to create cubes...
DmitriyValetov/TopicNet
setup.py
<reponame>DmitriyValetov/TopicNet<filename>setup.py from distutils.core import setup setup( name = 'topicnet', packages = [ 'topicnet', 'topicnet.cooking_machine', 'topicnet.cooking_machine.cubes', 'topicnet.cooking_machine.models', 'topicnet.cooking_machine.recipes', ...
DmitriyValetov/TopicNet
topicnet/viewers/base_viewer.py
from ..cooking_machine.models import BaseModel class BaseViewer: """ """ def __init__(self, model): if not isinstance(model, BaseModel): raise TypeError('Parameter "model" should derive from BaseModel') self._model = model @property def model(self): """ """ ...
DmitriyValetov/TopicNet
topicnet/viewers/topic_mapping.py
import numpy as np from scipy import optimize from scipy.spatial import distance from .top_tokens_viewer import TopTokensViewer from .base_viewer import BaseViewer def compute_topic_mapping(matrix_left, matrix_right, metric='euclidean'): """ This function provides mapping of topics from one model to the ...
DmitriyValetov/TopicNet
topicnet/tests/test_cubes.py
import pytest import warnings import os import shutil import artm import numpy as np from ..cooking_machine.cubes.greedy_strategy import GreedyStrategy from ..cooking_machine.cubes.perplexity_strategy import PerplexityStrategy from ..cooking_machine.cubes import RegularizersModifierCube, CubeCreator from ..cooking_...
DmitriyValetov/TopicNet
topicnet/dataset_manager/api.py
import urllib from urllib.request import Request, urlopen import ssl import os from glob import glob from tqdm import tqdm import gzip from ..cooking_machine.dataset import Dataset URL = 'https://172.16.58.3:8085' def get_info() -> str: """ Gets info about all datasets. Returns ------- str wi...
DmitriyValetov/TopicNet
topicnet/cooking_machine/models/example_score.py
import numpy as np from .base_score import BaseScore class ScoreExample(BaseScore): """ Example score that calculates average size of topic kernel across all topics. We inherit from BaseScore in order to have self.value property and self.update() method (the internal logic of TopicNet relies on th...
DmitriyValetov/TopicNet
topicnet/cooking_machine/models/base_regularizer.py
<filename>topicnet/cooking_machine/models/base_regularizer.py class BaseRegularizer: """ Base regularizer class to construct custom regularizers. """ def __init__(self, name, tau, gamma=None): self.name = name self.tau = tau self.gamma = gamma def attach(self, model): ...
DmitriyValetov/TopicNet
topicnet/cooking_machine/cubes/strategy.py
from itertools import product from functools import reduce from operator import mul class BaseStrategy(): """ Allows to visit nodes of parameters' grid in a particular order. """ def __init__(self): """ Initialize stage. Checks params and update internal attributes. """ ...
DmitriyValetov/TopicNet
topicnet/cooking_machine/models/scores.py
<filename>topicnet/cooking_machine/models/scores.py from .example_score import ScoreExample from .intratext_coherence_score import IntratextCoherenceScore from .blei_lafferty_score import BleiLaffertyScore from .semantic_radius_score import SemanticRadiusScore __all__ = ["ScoreExample", "IntratextCoherenceScore", "Ble...
DmitriyValetov/TopicNet
topicnet/cooking_machine/models/intratext_coherence_score.py
import dill import numpy as np import pandas as pd import sys import tqdm import warnings from collections import defaultdict from enum import Enum, IntEnum, auto from typing import ( Dict, List, Optional, Tuple, Union, ) from .base_score import BaseScore from .base_model import BaseModel from ..d...
DmitriyValetov/TopicNet
topicnet/cooking_machine/model_tracking.py
import numpy as np from copy import deepcopy from .models.base_model import padd_model_name START = padd_model_name('root') UP_END = "┌" DOWN_END = "└" MIDDLE = "├" LAST = "┤" EMPTY = "│" START_END = "┐" SPACE = " " class Tree(object): """ Contains tree of an experiment and methods to work with it. "...
DmitriyValetov/TopicNet
topicnet/cooking_machine/models/frozen_score.py
<reponame>DmitriyValetov/TopicNet import warnings from enum import Enum from numbers import Number from typing import ( List, Optional ) from .base_score import BaseScore class FrozenScore(BaseScore): """ Custom scores can have anything inside. So there is a probability that pickle will not be a...
DmitriyValetov/TopicNet
topicnet/cooking_machine/models/scores_wrapper.py
<reponame>DmitriyValetov/TopicNet import artm import copy from collections.abc import Mapping from typing import ( Dict, List, Optional, Union, ) from .base_score import BaseScore from .frozen_score import FrozenScore class ScoresWrapper(Mapping): def __init__(self, topicnet_sco...
DmitriyValetov/TopicNet
topicnet/cooking_machine/recipes/multimodal_exploratory_search_pipeline.py
from typing import List, Union from .recipe_wrapper import BaseRecipe from .. import Dataset multimodal_search_template = ''' # This config modifies a strategy described in the article # Multi-objective Topic Modeling for Exploratory Search in Tech News # by <NAME>, <NAME> and <NAME>, Jan 2018 # Use .format_recipe(m...
DmitriyValetov/TopicNet
topicnet/cooking_machine/recipes/artm_baseline_pipeline.py
from typing import List from .recipe_wrapper import BaseRecipe from .. import Dataset ARTM_baseline_template = ''' # This config follows a strategy described by <NAME> # one of the core programmers of BigARTM library in personal correspondence. # According to his letter 'decent' topic model can be obtained by # Decorr...
DmitriyValetov/TopicNet
topicnet/cooking_machine/cubes/cube_creator.py
<reponame>DmitriyValetov/TopicNet from .base_cube import BaseCube from inspect import signature from copy import deepcopy import warnings class CubeCreator(BaseCube): """ Class for creating models with different initial parameters. """ DEFAULT_SEED_VALUE = 4 def __init__(self, num_iter: int, par...
DmitriyValetov/TopicNet
topicnet/cooking_machine/recipes/recipe_wrapper.py
from ..config_parser import build_experiment_environment_from_yaml_config recipe_template_example = """ This string should be formatted as a confing in YAML format. If you struggle making yours, look in other recipes for guidance. Also cooking_machine/config_parser.py docstring provides some insight on the matter. {fi...
DmitriyValetov/TopicNet
topicnet/tests/test_experiment_logging.py
import artm import shutil import pytest import warnings from ..cooking_machine.models.topic_model import TopicModel from ..cooking_machine.experiment import Experiment from ..cooking_machine.dataset import Dataset, W_DIFF_BATCHES_1 from ..cooking_machine.model_constructor import init_simple_default_model from ..cookin...
DmitriyValetov/TopicNet
topicnet/viewers/initial_doc_to_topic_viewer.py
from .base_viewer import BaseViewer class TopTopicsFeatures(BaseViewer): """ """ def __init__(self, dataset_id, model): super(TopTopicsFeatures, self).__init__(model=model) self._dataset = model.experiment.datasets[dataset_id] def view(self, document_id, topic_name=None, batch_vectorizer=...
DmitriyValetov/TopicNet
topicnet/__init__.py
import artm # change log style lc = artm.messages.ConfigureLoggingArgs() lc.minloglevel = 3 lib = artm.wrapper.LibArtm(logging_config=lc) __pdoc__ = {"tests": False}
DmitriyValetov/TopicNet
topicnet/cooking_machine/models/__init__.py
from .base_model import BaseModel from .topic_model import TopicModel from .dummy_topic_model import DummyTopicModel from .base_score import BaseScore from .example_score import ScoreExample from .intratext_coherence_score import IntratextCoherenceScore SUPPORTED_MODEL_CLASSES = ( TopicModel, )
DmitriyValetov/TopicNet
topicnet/cooking_machine/recipes/__init__.py
<gh_stars>0 from .multimodal_exploratory_search_pipeline import MultimodalSearchRecipe from .artm_baseline_pipeline import BaselineRecipe from .exploratory_search_pipeline import SearchRecipe from .artm_baseline_pipeline import ARTM_baseline_template as ARTM_baseline from .exploratory_search_pipeline import exploratory...
DmitriyValetov/TopicNet
topicnet/cooking_machine/dataset.py
<gh_stars>0 import os import sys import csv import artm import shutil import tempfile import warnings import pandas as pd from glob import glob from typing import Optional from .routine import blake2bchecksum VW_TEXT_COL = 'vw_text' RAW_TEXT_COL = 'raw_text' W_DIFF_BATCHES_1 = "Attempted to use batches for different...
DmitriyValetov/TopicNet
topicnet/cooking_machine/rel_toolbox_lite.py
<gh_stars>100-1000 import os def count_vocab_size(dictionary, modalities): # TODO: check tokens filtered by dict.filter() fname = 'tmp.txt' try: dictionary.save_text(fname) modality_count = {name: 0 for name in modalities} modality_vocab_size = {name: 0 for name in modalities} ...
DmitriyValetov/TopicNet
topicnet/cooking_machine/__init__.py
from .dataset import Dataset from .dataset import BaseDataset from .experiment import Experiment from .model_constructor import *
DmitriyValetov/TopicNet
topicnet/cooking_machine/cubes/greedy_strategy.py
import numpy as np from .strategy import BaseStrategy class GreedyStrategy(BaseStrategy): """ Allows to visit nodes of parameters' grid in a particular order. The rough idea: We are given grid of (values1 x values2 x values3). This strategy will find best value among points of form [v...
bashrootshell/simple-guess-numbers
guess-1.py
#!/usr/bin/env python3 import random """ Jogo de adivinhação com números de 1 a 16. Executa até encontrar o número certo. PEP8 compliant “Readability counts." “Beautiful is better than ugly.” — The Zen of Python """ numero = random.randrange(1, 16) print('Chute um número entre 1 e 16.') wh...
bashrootshell/simple-guess-numbers
guess-2-improved.py
<filename>guess-2-improved.py #!/usr/bin/env python3 from random import randrange # from numpy.random import randint """ Jogo de adivinhação com números de 1 a 30. Máximo de 8 tentativas. Executa validação de entrada. PEP8 compliant “Readability counts." “Beautiful is better than ugly.” —...
bashrootshell/simple-guess-numbers
guess-3-improved.py
<reponame>bashrootshell/simple-guess-numbers #!/usr/bin/env python3 from random import randint """ v3 - código mais limpo Jogo de adivinhação com números de 1 a 30. Máximo de 8 tentativas. Executa validação de entrada. PEP8 compliant “Readability counts." “Beautiful is better than ugly.” ...
ibrahimsh/final-project-software-programming
SymbolTable.py
<filename>SymbolTable.py __author__ = 'MatrixRev' class SymbolTable(): dict={ '$a':'Personal name (NR)','$b':'Numeration (NR)', '$c':'Titles and other words associated with a name (R)', '$d':'Dates associated with a name (NR)','$e':'Relator term (R)', '$f':'Date of a work (NR)','$g':'...
ibrahimsh/final-project-software-programming
OWL.py
<reponame>ibrahimsh/final-project-software-programming<filename>OWL.py<gh_stars>0 __author__ = 'MatrixRev' class OWL(): def __init__(self, namespace, outfile, propurl): self.namespace = str(namespace) self.outfile = outfile #self.outfile = 'output.owl' #self.propurl = 'http://staff.washing...
ibrahimsh/final-project-software-programming
MarcParser.py
<reponame>ibrahimsh/final-project-software-programming __author__ = 'MatrixRev' import os import re import json import codecs from collections import defaultdict import string library_path="C://Users//MatrixRev//Desktop//library_12//" # output file path data_path="C://Users//MatrixRev//Dropbox//data" # input Marc fil...
ibrahimsh/final-project-software-programming
rdfontology.py
__author__ = 'MatrixRev' import codecs import json import re from collections import Mapping from collections import defaultdict from collections import Counter import Levenshtein import nltk from nltk.corpus import stopwords import fileinput import string import os import collections import rdflib from rdflib.namespa...
ibrahimsh/final-project-software-programming
HashTable.py
__author__ = 'MatrixRev' import codecs import json import re from collections import Mapping from collections import defaultdict from collections import Counter import Levenshtein import nltk from nltk.corpus import stopwords import fileinput import string import os import collections import rdflib from rdflib.namespa...
ibrahimsh/final-project-software-programming
jasonParser.py
<filename>jasonParser.py<gh_stars>0 __author__ = 'MatrixRev' import json import codecs import glob import os import sys #path = u"C://Users//MatrixRev//Desktop//library_5//" path="C://Users//MatrixRev//Desktop//mainLib//" # input file outFile='C:/Users/MatrixRev/Desktop/books/output/mainsubjects.txt' #output file pat...
mnanchev/terraform-aws-cost-explorer-monthly-billing-report
cost_utilization.py
import calendar import datetime import os from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import boto3 from botocore.exceptions import ClientError if os.environ['CLIENT']: CLIENT = os.environ['CLIENT'] else: CLIENT = '' S...
CyberSolutionsTech/cst-micro-chassis
tests/cst_micro_chassis/test_resources.py
<reponame>CyberSolutionsTech/cst-micro-chassis<filename>tests/cst_micro_chassis/test_resources.py from uuid import UUID, uuid4 import datetime from flask import Flask from flask import Blueprint from flask_restful import Api from flask_sqlalchemy import SQLAlchemy from cst_micro_chassis import CstMicroChassis from cs...
CyberSolutionsTech/cst-micro-chassis
tests/cst_micro_chassis/test_utils.py
import pytest from cst_micro_chassis.utils import retry from unittest import mock class SomeTestClass: def __init__(self): self.wrapped_test_function_called_count = 0 @retry(delay=1) def wrapped_test_function(self, argument): self.wrapped_test_function_called_count += 1 if argume...
CyberSolutionsTech/cst-micro-chassis
tests/cst_micro_chassis/test_chassis.py
<filename>tests/cst_micro_chassis/test_chassis.py from flask import Flask from cst_micro_chassis.chassis import CstMicroChassis def test_flask_extension_generates_healthcheck(): app = Flask('test-cst-micro-chassis') CstMicroChassis().init_app(app) with app.test_client() as c: app.config['CST_PRO...
CyberSolutionsTech/cst-micro-chassis
src/cst_micro_chassis/utils.py
<reponame>CyberSolutionsTech/cst-micro-chassis import time import logging from functools import wraps logger = logging.getLogger(__name__) def retry(tries=3, delay=2, back_off=2, custom_logger=None): """ Retry calling the decorated function until getting non-falsy results. :param tries: Number of times...
CyberSolutionsTech/cst-micro-chassis
src/cst_micro_chassis/chassis.py
import os from logging.config import dictConfig from flask import Blueprint, jsonify from .logging import get_log_config_dict class CstMicroChassis: def __init__(self, app=None): if app is not None: self.init_app(app) self._app = None self._db = None def init_app(self, ...
CyberSolutionsTech/cst-micro-chassis
src/cst_micro_chassis/resources.py
<gh_stars>0 import os from uuid import uuid4 from flask import g, request from flask_restful import Resource try: API_DEFAULT_PAGE_SIZE = int(os.environ.get('CST_API_DEFAULT_PAGE_SIZE')) except (TypeError, ValueError): API_DEFAULT_PAGE_SIZE = 25 class ApiResource(Resource): def __init__(self, *args, **kw...
CyberSolutionsTech/cst-micro-chassis
src/cst_micro_chassis/logging.py
<filename>src/cst_micro_chassis/logging.py from logging import Formatter, config import os try: # the logger might be used outside of flasks application context, don't always rely on flask.g from flask import g except (ImportError, RuntimeError): g = None FORMAT = '%(asctime)s [%(levelname)s][%(operation...
CyberSolutionsTech/cst-micro-chassis
src/cst_micro_chassis/__init__.py
from .chassis import CstMicroChassis
CyberSolutionsTech/cst-micro-chassis
setup.py
from setuptools import setup, find_packages __version__ = '0.1.0' def read(filename): with open(filename, "r", encoding="utf-8") as fh: return fh.read() setup( name='cst-micro-chassis', version=__version__, author='CyberSolutionsTech', license='MIT', author_email='<EMAIL>', desc...
CyberSolutionsTech/cst-micro-chassis
tests/cst_micro_chassis/test_logging.py
from cst_micro_chassis.logging import get_log_config_dict def test_logging_simple(): app_name = 'new_restful_api' conf_dict = get_log_config_dict(app_name) assert app_name in conf_dict['loggers'].keys() assert conf_dict['loggers'][app_name]['level'] == 'INFO'
anisotropi4/wren
Travel-Time/04-Model/travel-time-01.py
<filename>Travel-Time/04-Model/travel-time-01.py<gh_stars>1-10 #!/usr/bin/env python3 import csv import re from os import listdir from collections import OrderedDict with open('stations') as file_data: tsv_in = csv.reader(file_data, delimiter='\t') stations = dict([i for i in tsv_in]) images_list = listdir('...
anisotropi4/wren
Travel-Time/04-Model/link.py
#!/usr/bin/env python3 import os, sys header = True with open('stationorder') as file_data: for file_line in file_data: if header: header = False continue (n, crs, _, _) = file_line.rstrip().split('\t') for i in range(1,5): from_file = 'images/topo-{0}-P...
anisotropi4/wren
Travel-Time/04-Model/travel-time-02.py
<reponame>anisotropi4/wren<filename>Travel-Time/04-Model/travel-time-02.py #!/usr/bin/env python3 import sys import csv import re from os import listdir from collections import OrderedDict with open('stations') as file_data: tsv_in = csv.reader(file_data, delimiter='\t') stations = dict([i for i in tsv_in]) i...
rchl/core
homeassistant/components/tcp/sensor.py
"""Support for TCP socket based sensors.""" import logging import select import socket import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( CONF_HOST, CONF_NAME, CONF_PAYLOAD, CONF_PORT, CONF_TIMEOUT, CONF_UNIT_OF_MEASUREMENT, ...
rchl/core
homeassistant/components/shelly/entity.py
"""Shelly entity helper.""" from dataclasses import dataclass from typing import Any, Callable, Optional, Union import aioshelly from homeassistant.core import callback from homeassistant.helpers import device_registry, entity, update_coordinator from . import ShellyDeviceRestWrapper, ShellyDeviceWrapper from .const...
rchl/core
tests/components/recollect_waste/test_config_flow.py
<gh_stars>1-10 """Define tests for the Recollect Waste config flow.""" from aiorecollect.errors import RecollectError from homeassistant import data_entry_flow from homeassistant.components.recollect_waste import ( CONF_PLACE_ID, CONF_SERVICE_ID, DOMAIN, ) from homeassistant.config_entries import SOURCE_IM...
rchl/core
tests/components/zerproc/test_light.py
"""Test the zerproc lights.""" import pytest import pyzerproc from homeassistant import setup from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_HS_COLOR, ATTR_RGB_COLOR, ATTR_XY_COLOR, SCAN_INTERVAL, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, ) from homeassistant.components.zerproc...
rchl/core
homeassistant/components/roomba/config_flow.py
<gh_stars>1-10 """Config flow to configure roomba component.""" from roombapy import Roomba import voluptuous as vol from homeassistant import config_entries, core from homeassistant.const import CONF_HOST, CONF_PASSWORD from homeassistant.core import callback from . import CannotConnect, async_connect_or_timeout, as...
rchl/core
homeassistant/components/deconz/gateway.py
"""Representation of a deCONZ gateway.""" import asyncio import async_timeout from pydeconz import DeconzSession, errors from homeassistant.const import CONF_API_KEY, CONF_HOST, CONF_PORT from homeassistant.core import callback from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers import...
rchl/core
tests/helpers/test_config_entry_oauth2_flow.py
"""Tests for the Somfy config flow.""" import asyncio import logging import time import pytest from homeassistant import config_entries, data_entry_flow, setup from homeassistant.config import async_process_ha_core_config from homeassistant.helpers import config_entry_oauth2_flow from homeassistant.helpers.network im...
rchl/core
tests/components/flume/test_config_flow.py
<filename>tests/components/flume/test_config_flow.py """Test the flume config flow.""" import requests.exceptions from homeassistant import config_entries, setup from homeassistant.components.flume.const import DOMAIN from homeassistant.const import ( CONF_CLIENT_ID, CONF_CLIENT_SECRET, CONF_PASSWORD, ...
rchl/core
homeassistant/components/shelly/utils.py
"""Shelly helpers functions.""" from datetime import datetime, timedelta import logging from typing import Optional import aioshelly from homeassistant.components.sensor import DEVICE_CLASS_TIMESTAMP from homeassistant.const import TEMP_CELSIUS, TEMP_FAHRENHEIT from .const import DOMAIN _LOGGER = logging.getLogger...
rchl/core
homeassistant/components/fireservicerota/binary_sensor.py
"""Binary Sensor platform for FireServiceRota integration.""" import logging from homeassistant.components.binary_sensor import BinarySensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.helpers.typing import HomeAssistantType from homeassistant.helpers.update_coordinator import ( C...
rchl/core
homeassistant/components/dsmr/config_flow.py
<filename>homeassistant/components/dsmr/config_flow.py """Config flow for DSMR integration.""" import asyncio from functools import partial import logging from typing import Any, Dict, Optional from async_timeout import timeout from dsmr_parser import obis_references as obis_ref from dsmr_parser.clients.protocol impor...
rchl/core
homeassistant/components/motion_blinds/config_flow.py
<filename>homeassistant/components/motion_blinds/config_flow.py<gh_stars>1-10 """Config flow to configure Motion Blinds using their WLAN API.""" import logging import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_API_KEY, CONF_HOST # pylint: disable=unused-import fro...
rchl/core
tests/helpers/test_check_config.py
"""Test check_config helper.""" import logging from homeassistant.config import YAML_CONFIG_FILE from homeassistant.helpers.check_config import ( CheckConfigError, async_check_ha_config_file, ) from tests.async_mock import Mock, patch from tests.common import mock_platform, patch_yaml_files _LOGGER = logging...
rchl/core
tests/components/yeelight/test_init.py
<filename>tests/components/yeelight/test_init.py """Test Yeelight.""" from yeelight import BulbType from homeassistant.components.yeelight import ( CONF_NIGHTLIGHT_SWITCH, CONF_NIGHTLIGHT_SWITCH_TYPE, DOMAIN, NIGHTLIGHT_SWITCH_TYPE_LIGHT, ) from homeassistant.const import CONF_DEVICES, CONF_NAME from h...
rchl/core
tests/components/ipma/test_config_flow.py
<reponame>rchl/core """Tests for IPMA config flow.""" from homeassistant.components.ipma import DOMAIN, config_flow from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_MODE from homeassistant.helpers import entity_registry from homeassistant.setup import async_setup_component from .test_weather import...
rchl/core
homeassistant/components/blueprint/importer.py
<gh_stars>1-10 """Import logic for blueprint.""" from dataclasses import dataclass import re from typing import Optional import voluptuous as vol import yarl from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import aiohttp_client, config_va...
rchl/core
homeassistant/components/hyperion/light.py
"""Support for Hyperion-NG remotes.""" import logging from hyperion import client, const import voluptuous as vol from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_EFFECT, ATTR_HS_COLOR, PLATFORM_SCHEMA, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_EFFECT, LightEntity, )...
rchl/core
tests/components/cert_expiry/test_init.py
"""Tests for Cert Expiry setup.""" from datetime import timedelta from homeassistant.components.cert_expiry.const import DOMAIN from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN from homeassistant.config_entries import ENTRY_STATE_LOADED, ENTRY_STATE_NOT_LOADED from homeassistant.const import CONF_HO...
rchl/core
homeassistant/components/recollect_waste/sensor.py
<reponame>rchl/core """Support for Recollect Waste sensors.""" from typing import Callable import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import ATTR_ATTRIBUTION from homeassistant.core i...
rchl/core
tests/components/webhook/test_trigger.py
"""The tests for the webhook automation trigger.""" import pytest from homeassistant.core import callback from homeassistant.setup import async_setup_component from tests.async_mock import patch from tests.components.blueprint.conftest import stub_blueprint_populate # noqa @pytest.fixture(autouse=True) async def s...
rchl/core
tests/helpers/test_placeholder.py
"""Test placeholders.""" import pytest from homeassistant.helpers import placeholder from homeassistant.util.yaml import Placeholder def test_extract_placeholders(): """Test extracting placeholders from data.""" assert placeholder.extract_placeholders(Placeholder("hello")) == {"hello"} assert placeholder...
rchl/core
homeassistant/components/nest/config_flow.py
<reponame>rchl/core """Config flow to configure Nest. This configuration flow supports two APIs: - The new Device Access program and the Smart Device Management API - The legacy nest API NestFlowHandler is an implementation of AbstractOAuth2FlowHandler with some overrides to support the old APIs auth flow. That ...
rchl/core
homeassistant/components/hassio/system_health.py
<reponame>rchl/core """Provide info to system health.""" import os from homeassistant.components import system_health from homeassistant.core import HomeAssistant, callback SUPERVISOR_PING = f"http://{os.environ['HASSIO']}/supervisor/ping" OBSERVER_URL = f"http://{os.environ['HASSIO']}:4357" @callback def async_reg...
rchl/core
homeassistant/components/blueprint/__init__.py
"""The blueprint integration.""" from . import websocket_api from .const import DOMAIN # noqa from .errors import ( # noqa BlueprintException, BlueprintWithNameException, FailedToLoad, InvalidBlueprint, InvalidBlueprintInputs, MissingPlaceholder, ) from .models import Blueprint, BlueprintInput...
rchl/core
homeassistant/components/nest/api.py
"""API for Google Nest Device Access bound to Home Assistant OAuth.""" from aiohttp import ClientSession from google.oauth2.credentials import Credentials from google_nest_sdm.auth import AbstractAuth from homeassistant.helpers import config_entry_oauth2_flow # See https://developers.google.com/nest/device-access/re...
rchl/core
homeassistant/components/automation/config.py
<gh_stars>1-10 """Config validation helper for the automation integration.""" import asyncio import voluptuous as vol from homeassistant.components import blueprint from homeassistant.components.device_automation.exceptions import ( InvalidDeviceAutomationConfig, ) from homeassistant.config import async_log_excep...
rchl/core
homeassistant/components/nest/const.py
"""Constants used by the Nest component.""" DOMAIN = "nest" DATA_SDM = "sdm" SIGNAL_NEST_UPDATE = "nest_update" # For the Google Nest Device Access API OAUTH2_AUTHORIZE = ( "https://nestservices.google.com/partnerconnections/{project_id}/auth" ) OAUTH2_TOKEN = "https://www.googleapis.com/oauth2/v4/token" SDM_SCO...
rchl/core
tests/components/cloudflare/conftest.py
<gh_stars>1-10 """Define fixtures available for all tests.""" from pytest import fixture from . import _get_mock_cfupdate from tests.async_mock import patch @fixture def cfupdate(hass): """Mock the CloudflareUpdater for easier testing.""" mock_cfupdate = _get_mock_cfupdate() with patch( "homeass...
rchl/core
homeassistant/components/tasmota/fan.py
<filename>homeassistant/components/tasmota/fan.py<gh_stars>1-10 """Support for Tasmota fans.""" from hatasmota import const as tasmota_const from homeassistant.components import fan from homeassistant.components.fan import FanEntity from homeassistant.core import callback from homeassistant.helpers.dispatcher import ...
rchl/core
tests/components/cert_expiry/test_sensors.py
<gh_stars>1-10 """Tests for the Cert Expiry sensors.""" from datetime import timedelta import socket import ssl from homeassistant.components.cert_expiry.const import DOMAIN from homeassistant.config_entries import ENTRY_STATE_SETUP_RETRY from homeassistant.const import CONF_HOST, CONF_PORT, STATE_UNAVAILABLE, STATE_U...