repository_name
stringlengths 7
107
| function_path
stringlengths 4
190
| function_identifier
stringlengths 1
236
| language
stringclasses 1
value | function
stringlengths 9
647k
| docstring
stringlengths 5
488k
| function_url
stringlengths 71
285
| context
stringlengths 0
2.51M
| license
stringclasses 5
values |
---|---|---|---|---|---|---|---|---|
intel/openfl
|
openfl/databases/tensor_db.py
|
TensorDB.cache_tensor
|
python
|
def cache_tensor(self, tensor_key_dict):
entries_to_add = []
with self.mutex:
for tensor_key, nparray in tensor_key_dict.items():
tensor_name, origin, fl_round, report, tags = tensor_key
entries_to_add.append(
pd.DataFrame([
[tensor_name, origin, fl_round, report, tags, nparray]
],
columns=[
'tensor_name',
'origin',
'round',
'report',
'tags',
'nparray']
)
)
self.tensor_db = pd.concat(
[self.tensor_db, *entries_to_add], ignore_index=True
)
|
Insert tensor into TensorDB (dataframe).
Args:
tensor_key_dict: The Tensor Key
Returns:
None
|
https://github.com/intel/openfl/blob/4bda3850b6bce7c904a5ac3ed56115bec00be2e0/openfl/databases/tensor_db.py#L51-L80
|
from threading import Lock
import numpy as np
import pandas as pd
from openfl.utilities import LocalTensor
from openfl.utilities import TensorKey
class TensorDB:
def __init__(self):
self.tensor_db = pd.DataFrame([], columns=[
'tensor_name', 'origin', 'round', 'report', 'tags', 'nparray'
])
self.mutex = Lock()
def __repr__(self):
with pd.option_context('display.max_rows', None):
content = self.tensor_db[['tensor_name', 'origin', 'round', 'report', 'tags']]
return f'TensorDB contents:\n{content}'
def __str__(self):
return self.__repr__()
def clean_up(self, remove_older_than=1):
if remove_older_than < 0:
return
current_round = int(self.tensor_db['round'].max())
self.tensor_db = self.tensor_db[
self.tensor_db['round'] > current_round - remove_older_than
].reset_index(drop=True)
|
Apache License 2.0
|
universitas/universitas.no
|
django/apps/stories/models/links.py
|
InlineLink.validate_url
|
python
|
def validate_url(cls, href):
site = settings.SITE_URL
href = href.strip('«»“”"\'')
if href.startswith('//'):
href = 'http:{href}'.format(href=href)
if href.startswith('/'):
href = 'http://{site}{href}'.format(site=site, href=href)
if not href.startswith('http://'):
href = 'http://{href}'.format(href=href)
try:
validate = URLValidator()
validate(href)
return href
except ValidationError:
return None
|
Checks if input string is a valid http href.
|
https://github.com/universitas/universitas.no/blob/911a2541c77eca522ba5a723f175786f4f9eb481/django/apps/stories/models/links.py#L295-L310
|
import logging
import re
from bs4 import BeautifulSoup
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.core.validators import URLValidator, ValidationError
from django.db import models
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from model_utils.models import TimeStampedModel
from requests import request
from requests.exceptions import MissingSchema, RequestException, Timeout
from .status_codes import HTTP_STATUS_CODES
from .story import Story
logger = logging.getLogger(__name__)
class InlineLinkManager(models.Manager):
def markup_to_html(self, text):
for link in self.all():
text = link.markup_to_html(text)
return text
def insert_urls(self, text):
for link in self.all():
text = link.insert_url(text)
return text
class InlineLink(TimeStampedModel):
find_pattern = '\[(?P<text>.+?)\]\((?P<ref>\S+?)\)'
change_pattern = '[{text}]({ref})'
html_pattern = '<a href="{href}" alt="{alt}">{text}</a>'
objects = InlineLinkManager()
class Meta:
verbose_name = _('inline link')
verbose_name_plural = _('inline links')
parent_story = models.ForeignKey(
Story,
related_name='inline_links',
on_delete=models.CASCADE,
)
number = models.PositiveSmallIntegerField(
default=1,
help_text=_('link label'),
)
link_name = models.CharField(
blank=True,
max_length=256,
default='',
help_text=_('link label'),
)
href = models.CharField(
blank=True,
max_length=500,
help_text=_('link target'),
verbose_name=_('link target'),
)
linked_story = models.ForeignKey(
Story,
blank=True,
null=True,
help_text=_('link to story on this website.'),
verbose_name=_('linked story'),
related_name='incoming_links',
on_delete=models.CASCADE,
)
alt_text = models.CharField(
max_length=500,
blank=True,
help_text=_('alternate link text'),
verbose_name=_('alt text'),
)
text = models.TextField(
blank=True,
editable=False,
help_text=_('link text'),
verbose_name=_('link text'),
)
status_code = models.CharField(
max_length=3,
editable=False,
default='',
choices=HTTP_STATUS_CODES,
help_text=_('Status code returned from automatic check.'),
verbose_name=_('http status code'),
)
def __str__(self):
return f'[{self.text}]({self.link})'
def get_tag(self, ref=None):
pattern = self.change_pattern
return pattern.format(text=self.text, ref=ref or self.number)
def markup_to_html(self, text):
text = re.sub(re.escape(self.get_tag()), self.get_html(), text)
return text
def insert_url(self, text):
text = re.sub(
re.escape(self.get_tag()), self.get_tag(ref=self.link), text
)
return text
def get_html(self):
pattern = self.html_pattern
html = pattern.format(
text=self.text, href=self.link, alt=self.alt_text
)
return mark_safe(html)
get_html.allow_tags = True
@property
def name(self):
return self.link_name or str(self.number)
@property
def link(self):
if self.linked_story:
return self.linked_story.get_absolute_url()
elif self.href:
return self.href
return ''
def find_linked_story(self):
if not self.href or self.linked_story:
return False
if not self.linked_story:
match = re.search(r'universitas.no/.+?/(?P<id>\d+)/', self.href)
try:
story = Story.objects.get(pk=int(match.group('id')))
except (AttributeError, ObjectDoesNotExist):
return False
else:
if story == self.parent_story:
return False
else:
self.linked_story = story
self.href = ''
self.alt_text = self.linked_story.title
return self.linked_story
def save(self, *args, **kwargs):
self.find_linked_story()
super().save(*args, **kwargs)
def check_link(self, save_if_changed=False, method='head', timeout=1):
if self.linked_story:
status_code = 'INT'
url = self.validate_url(self.link)
elif not self.link:
status_code = ''
url = ''
else:
url = self.validate_url(self.link)
try:
status_code = request(method, url, timeout=timeout).status_code
if status_code == 410:
status_code = request(
'get', url, timeout=timeout
).status_code
if status_code > 500:
status_code = 500
status_code = str(status_code)
except Timeout:
status_code = '408'
except MissingSchema:
status_code = 'URL'
except RequestException:
status_code = 'DNS'
if save_if_changed and status_code != self.status_code:
self.status_code = status_code
self.save()
msg = '{code}: {url}'.format(url=url, code=status_code)
logger.debug(msg)
return status_code
@classmethod
def clean_and_create_links(cls, body, parent_story):
body = cls.convert_html_links(body)
found_links = re.finditer(cls.find_pattern, body)
queryset = parent_story.inline_links.all()
number = queryset.count() + 1
for match in found_links:
ref = match.group('ref')
text = match.group('text')
original_markup = re.escape(match.group(0))
new_markup = []
if re.match(r'^\d+$', ref):
ref = int(ref)
links = queryset.filter(number=ref)
if not links:
link = cls.objects.create(
number=ref,
parent_story=parent_story,
)
else:
link = links[0]
if link.text != text:
link.text = text
link.save()
for otherlink in links[1:]:
otherlink.number = number
otherlink.save()
number += 1
msg = 'multiple links with same ref: ({0}) {1} {2}'
msg = msg.format(ref, link, otherlink)
logger.warn(msg)
new_markup.append(otherlink.get_tag())
else:
link = cls(
parent_story=parent_story,
href=ref,
number=number,
alt_text=text,
text=text,
)
number += 1
link.save()
new_markup = [link.get_tag()] + new_markup
new_markup = ' '.join(new_markup)
body = re.sub(original_markup, new_markup, body)
return body
@classmethod
def convert_html_links(cls, bodytext, return_html=False):
soup = BeautifulSoup(bodytext, 'html5lib')
for link in soup.find_all('a'):
href = link.get('href') or ''
text = link.text
href = cls.validate_url(href)
if href:
replacement = cls.change_pattern.format(
ref=href.strip(),
text=text.strip(),
)
else:
replacement = '{text}'.format(text=text, )
link.replace_with(replacement)
if return_html:
bodytext = soup.decode()
else:
bodytext = soup.text
return bodytext
@classmethod
|
Apache License 2.0
|
opencti-platform/connectors
|
external-import/alienvault/src/alienvault/utils/__init__.py
|
create_report
|
python
|
def create_report(
name: str,
published: datetime,
objects: List[Union[_DomainObject, _RelationshipObject]],
created_by: Optional[Identity] = None,
created: Optional[datetime] = None,
modified: Optional[datetime] = None,
description: Optional[str] = None,
report_types: Optional[List[str]] = None,
labels: Optional[List[str]] = None,
confidence: Optional[int] = None,
external_references: Optional[List[ExternalReference]] = None,
object_markings: Optional[List[MarkingDefinition]] = None,
x_opencti_report_status: Optional[int] = None,
) -> Report:
return Report(
id=_create_random_identifier("report"),
created_by_ref=created_by,
created=created,
modified=modified,
name=name,
description=description,
report_types=report_types,
published=published,
object_refs=objects,
labels=labels,
confidence=confidence,
external_references=external_references,
object_marking_refs=object_markings,
custom_properties={X_OPENCTI_REPORT_STATUS: x_opencti_report_status},
)
|
Create a report.
|
https://github.com/opencti-platform/connectors/blob/78d4ec585e8ffcc51e90149e74c7c57c176f5209/external-import/alienvault/src/alienvault/utils/__init__.py#L498-L529
|
from datetime import datetime
from typing import Any, Callable, Dict, List, Mapping, NamedTuple, Optional, Union
from pycti import OpenCTIStix2Utils
from pycti.utils.constants import LocationTypes
from stix2 import (
AttackPattern,
ExternalReference,
Identity,
Indicator,
IntrusionSet,
Location,
Malware,
MarkingDefinition,
Relationship,
Report,
Vulnerability,
)
from stix2.v21 import _DomainObject, _Observable, _RelationshipObject
from alienvault.utils.constants import (
DEFAULT_X_OPENCTI_SCORE,
TLP_MARKING_DEFINITION_MAPPING,
X_MITRE_ID,
X_OPENCTI_LOCATION_TYPE,
X_OPENCTI_MAIN_OBSERVABLE_TYPE,
X_OPENCTI_REPORT_STATUS,
X_OPENCTI_SCORE,
)
from alienvault.utils.indicators import (
IndicatorPattern,
create_indicator_pattern_cryptocurrency_wallet,
create_indicator_pattern_domain_name,
create_indicator_pattern_email_address,
create_indicator_pattern_file_md5,
create_indicator_pattern_file_name,
create_indicator_pattern_file_sha1,
create_indicator_pattern_file_sha256,
create_indicator_pattern_hostname,
create_indicator_pattern_ipv4_address,
create_indicator_pattern_ipv6_address,
create_indicator_pattern_mutex,
create_indicator_pattern_url,
)
from alienvault.utils.observables import (
ObservableProperties,
create_observable_cryptocurrency_wallet,
create_observable_domain_name,
create_observable_email_address,
create_observable_file_md5,
create_observable_file_name,
create_observable_file_sha1,
create_observable_file_sha256,
create_observable_hostname,
create_observable_ipv4_address,
create_observable_ipv6_address,
create_observable_mutex,
create_observable_url,
)
class ObservationFactory(NamedTuple):
create_observable: Callable[[ObservableProperties], _Observable]
create_indicator_pattern: Callable[[str], IndicatorPattern]
OBSERVATION_FACTORY_IPV4_ADDRESS = ObservationFactory(
create_observable_ipv4_address, create_indicator_pattern_ipv4_address
)
OBSERVATION_FACTORY_IPV6_ADDRESS = ObservationFactory(
create_observable_ipv6_address, create_indicator_pattern_ipv6_address
)
OBSERVATION_FACTORY_DOMAIN_NAME = ObservationFactory(
create_observable_domain_name, create_indicator_pattern_domain_name
)
OBSERVATION_FACTORY_HOSTNAME = ObservationFactory(
create_observable_hostname, create_indicator_pattern_hostname
)
OBSERVATION_FACTORY_EMAIL_ADDRESS = ObservationFactory(
create_observable_email_address, create_indicator_pattern_email_address
)
OBSERVATION_FACTORY_URL = ObservationFactory(
create_observable_url, create_indicator_pattern_url
)
OBSERVATION_FACTORY_FILE_MD5 = ObservationFactory(
create_observable_file_md5, create_indicator_pattern_file_md5
)
OBSERVATION_FACTORY_FILE_SHA1 = ObservationFactory(
create_observable_file_sha1, create_indicator_pattern_file_sha1
)
OBSERVATION_FACTORY_FILE_SHA256 = ObservationFactory(
create_observable_file_sha256, create_indicator_pattern_file_sha256
)
OBSERVATION_FACTORY_FILE_NAME = ObservationFactory(
create_observable_file_name, create_indicator_pattern_file_name
)
OBSERVATION_FACTORY_MUTEX = ObservationFactory(
create_observable_mutex, create_indicator_pattern_mutex
)
OBSERVATION_FACTORY_CRYPTOCURRENCY_WALLET = ObservationFactory(
create_observable_cryptocurrency_wallet,
create_indicator_pattern_cryptocurrency_wallet,
)
def get_tlp_string_marking_definition(tlp: str) -> MarkingDefinition:
marking_definition = TLP_MARKING_DEFINITION_MAPPING.get(tlp.lower())
if marking_definition is None:
raise ValueError(f"Invalid TLP value '{tlp}'")
return marking_definition
def iso_datetime_str_to_datetime(string):
try:
return datetime.strptime(string, "%Y-%m-%dT%H:%M:%S.%f")
except ValueError:
return datetime.strptime(string, "%Y-%m-%dT%H:%M:%S")
def convert_comma_separated_str_to_list(input_str: str, trim: bool = True) -> List[str]:
comma_separated_str = input_str.strip() if trim else input_str
if not comma_separated_str:
return []
result = []
for part_str in comma_separated_str.split(","):
value = part_str
if trim:
value = value.strip()
if not value:
continue
result.append(value)
return result
def _create_random_identifier(identifier_type: str) -> str:
return OpenCTIStix2Utils.generate_random_stix_id(identifier_type)
def create_organization(name: str, created_by: Optional[Identity] = None) -> Identity:
return create_identity(
name,
created_by=created_by,
identity_class="organization",
)
def create_identity(
name: str,
identity_id: Optional[str] = None,
created_by: Optional[Identity] = None,
identity_class: Optional[str] = None,
custom_properties: Optional[Mapping[str, str]] = None,
) -> Identity:
if identity_id is None:
identity_id = _create_random_identifier("identity")
if custom_properties is None:
custom_properties = {}
return Identity(
id=identity_id,
created_by_ref=created_by,
name=name,
identity_class=identity_class,
custom_properties=custom_properties,
)
def create_external_reference(
source_name: str, url: str, external_id: Optional[str] = None
) -> ExternalReference:
return ExternalReference(source_name=source_name, url=url, external_id=external_id)
def create_indicator(
pattern: str,
pattern_type: str,
created_by: Optional[Identity] = None,
name: Optional[str] = None,
description: Optional[str] = None,
valid_from: Optional[datetime] = None,
labels: Optional[List[str]] = None,
confidence: Optional[int] = None,
object_markings: Optional[List[MarkingDefinition]] = None,
x_opencti_main_observable_type: Optional[str] = None,
) -> Indicator:
custom_properties: Dict[str, Any] = {X_OPENCTI_SCORE: DEFAULT_X_OPENCTI_SCORE}
if x_opencti_main_observable_type is not None:
custom_properties[
X_OPENCTI_MAIN_OBSERVABLE_TYPE
] = x_opencti_main_observable_type
return Indicator(
id=_create_random_identifier("indicator"),
created_by_ref=created_by,
name=name,
description=description,
pattern=pattern,
pattern_type=pattern_type,
valid_from=valid_from,
labels=labels,
confidence=confidence,
object_marking_refs=object_markings,
custom_properties=custom_properties,
)
def create_intrusion_set(
name: str,
created_by: Identity,
confidence: int,
object_markings: List[MarkingDefinition],
) -> IntrusionSet:
return IntrusionSet(
id=_create_random_identifier("intrusion-set"),
created_by_ref=created_by,
name=name,
confidence=confidence,
object_marking_refs=object_markings,
)
def create_malware(
name: str,
created_by: Identity,
confidence: int,
object_markings: List[MarkingDefinition],
malware_id: Optional[str] = None,
is_family: bool = False,
) -> Malware:
if malware_id is None:
malware_id = _create_random_identifier("malware")
return Malware(
id=malware_id,
created_by_ref=created_by,
name=name,
is_family=is_family,
confidence=confidence,
object_marking_refs=object_markings,
)
def create_sector(name: str, created_by: Identity) -> Identity:
return create_identity(
name,
created_by=created_by,
identity_class="class",
)
def create_country(name: str, created_by: Identity) -> Location:
return Location(
id=_create_random_identifier("location"),
created_by_ref=created_by,
name=name,
country="ZZ",
custom_properties={X_OPENCTI_LOCATION_TYPE: LocationTypes.COUNTRY.value},
)
def create_vulnerability(
name: str,
created_by: Identity,
confidence: int,
external_references: List[ExternalReference],
object_markings: List[MarkingDefinition],
) -> Vulnerability:
return Vulnerability(
id=_create_random_identifier("vulnerability"),
created_by_ref=created_by,
name=name,
confidence=confidence,
external_references=external_references,
object_marking_refs=object_markings,
)
def create_vulnerability_external_reference(name: str) -> List[ExternalReference]:
external_references = []
if name.startswith("CVE-"):
external_reference = create_external_reference(
"NIST NVD", f"https://nvd.nist.gov/vuln/detail/{name}", name
)
external_references.append(external_reference)
return external_references
def create_attack_pattern(
name: str,
created_by: Identity,
confidence: int,
external_references: List[ExternalReference],
object_markings: List[MarkingDefinition],
) -> AttackPattern:
return AttackPattern(
id=_create_random_identifier("attack-pattern"),
created_by_ref=created_by,
name=name,
confidence=confidence,
external_references=external_references,
object_marking_refs=object_markings,
custom_properties={X_MITRE_ID: name},
)
def create_attack_pattern_external_reference(name: str) -> List[ExternalReference]:
external_references = []
if name.startswith("T"):
path = name.replace(".", "/")
external_reference = create_external_reference(
"mitre-attack", f"https://attack.mitre.org/techniques/{path}", name
)
external_references.append(external_reference)
return external_references
def create_relationship(
relationship_type: str,
created_by: Identity,
source: _DomainObject,
target: _DomainObject,
confidence: int,
object_markings: List[MarkingDefinition],
start_time: Optional[datetime] = None,
stop_time: Optional[datetime] = None,
) -> Relationship:
return Relationship(
created_by_ref=created_by,
relationship_type=relationship_type,
source_ref=source,
target_ref=target,
start_time=start_time,
stop_time=stop_time,
confidence=confidence,
object_marking_refs=object_markings,
)
def create_relationships(
relationship_type: str,
created_by: Identity,
sources: List[_DomainObject],
targets: List[_DomainObject],
confidence: int,
object_markings: List[MarkingDefinition],
start_time: Optional[datetime] = None,
stop_time: Optional[datetime] = None,
) -> List[Relationship]:
relationships = []
for source in sources:
for target in targets:
relationship = create_relationship(
relationship_type,
created_by,
source,
target,
confidence,
object_markings,
start_time=start_time,
stop_time=stop_time,
)
relationships.append(relationship)
return relationships
def create_uses_relationships(
created_by: Identity,
sources: List[_DomainObject],
targets: List[_DomainObject],
confidence: int,
object_markings: List[MarkingDefinition],
start_time: Optional[datetime] = None,
stop_time: Optional[datetime] = None,
) -> List[Relationship]:
return create_relationships(
"uses",
created_by,
sources,
targets,
confidence,
object_markings,
start_time=start_time,
stop_time=stop_time,
)
def create_targets_relationships(
created_by: Identity,
sources: List[_DomainObject],
targets: List[_DomainObject],
confidence: int,
object_markings: List[MarkingDefinition],
start_time: Optional[datetime] = None,
stop_time: Optional[datetime] = None,
) -> List[Relationship]:
return create_relationships(
"targets",
created_by,
sources,
targets,
confidence,
object_markings,
start_time=start_time,
stop_time=stop_time,
)
def create_indicates_relationships(
created_by: Identity,
sources: List[_DomainObject],
targets: List[_DomainObject],
confidence: int,
object_markings: List[MarkingDefinition],
start_time: Optional[datetime] = None,
stop_time: Optional[datetime] = None,
) -> List[Relationship]:
return create_relationships(
"indicates",
created_by,
sources,
targets,
confidence,
object_markings,
start_time=start_time,
stop_time=stop_time,
)
def create_based_on_relationships(
created_by: Identity,
sources: List[_DomainObject],
targets: List[_DomainObject],
confidence: int,
object_markings: List[MarkingDefinition],
start_time: Optional[datetime] = None,
stop_time: Optional[datetime] = None,
) -> List[Relationship]:
return create_relationships(
"based-on",
created_by,
sources,
targets,
confidence,
object_markings,
start_time=start_time,
stop_time=stop_time,
)
def create_object_refs(
*objects: Union[
_DomainObject,
_RelationshipObject,
List[_RelationshipObject],
List[_DomainObject],
]
) -> List[Union[_DomainObject, _RelationshipObject]]:
object_refs = []
for obj in objects:
if not isinstance(obj, list):
object_refs.append(obj)
else:
object_refs.extend(obj)
return object_refs
|
Apache License 2.0
|
davidtellez/contrastive-predictive-coding-images
|
train_classifier.py
|
train_classifier
|
python
|
def train_classifier(input_dir, encoder_path, epochs, batch_size, output_dir, code_size,
lr=1e-3, train_step_multiplier=1.0, val_step_multiplier=1.0):
if not exists(output_dir):
os.makedirs(output_dir)
training_data = NCEGenerator(
x_path=join(input_dir, 'training_x.npy'),
y_path=join(input_dir, 'training_y.npy'),
batch_size=batch_size,
n_classes=10,
n_negatives=0,
augment_image_fn=augment_images_mnist,
augment_crop_fn=None
)
validation_data = NCEGenerator(
x_path=join(input_dir, 'validation_x.npy'),
y_path=join(input_dir, 'validation_y.npy'),
batch_size=batch_size,
n_classes=10,
n_negatives=0,
augment_image_fn=None,
augment_crop_fn=None
)
model = network_classifier(
encoder_path=encoder_path,
crop_shape=(16, 16, 3),
n_crops=7,
code_size=code_size,
lr=lr,
n_classes=10
)
callbacks = [
keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=1/3, patience=2, min_lr=1e-5),
keras.callbacks.CSVLogger(filename=join(output_dir, 'history.csv'), separator=',', append=True),
keras.callbacks.ModelCheckpoint(filepath=join(output_dir, 'checkpoint.h5'), monitor='val_loss', save_best_only=True, mode='min'),
keras.callbacks.EarlyStopping(monitor='val_loss', patience=4, mode='min')
]
model.fit_generator(
generator=training_data,
steps_per_epoch=int(len(training_data) * train_step_multiplier),
validation_data=validation_data,
validation_steps=int(len(validation_data) * val_step_multiplier),
epochs=epochs,
verbose=1,
callbacks=callbacks
)
|
This function initializes and trains a digit classifier using a pretrained CPC model as feature extractor.
:param input_dir: path to directory containing numpy training data (see NCEGenerator).
:param encoder_path: path to pretrained Keras CPC encoder.
:param epochs: number of times that the entire dataset will be used during training.
:param batch_size: number of samples in the mini-batch.
:param output_dir: directory to store the trained model.
:param code_size: length of the embedding vector used in CPC.
:param lr: learning rate.
:param train_step_multiplier: percentage of training samples used in each epoch.
:param val_step_multiplier: percentage of validation samples used in each epoch.
:return: nothing.
|
https://github.com/davidtellez/contrastive-predictive-coding-images/blob/64ace87de6a3d78bb0379cbdc66e374b4ebe679f/train_classifier.py#L14-L83
|
from os.path import join, basename, dirname, exists
import keras
import os
from classifier_model import network_classifier
from data_generator import NCEGenerator
from prepare_data import augment_images_mnist
|
MIT License
|
crash-override404/linepy-modified
|
akad/ShopService.py
|
Iface.getRecommendationForUser
|
python
|
def getRecommendationForUser(self, shopId, offset, limit, locale):
pass
|
Parameters:
- shopId
- offset
- limit
- locale
|
https://github.com/crash-override404/linepy-modified/blob/5bc06174457dfeba9bb2a23187be9b0f2e09dee6/akad/ShopService.py#L395-L404
|
from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationException
from thrift.protocol.TProtocol import TProtocolException
from thrift.TRecursive import fix_spec
import sys
import logging
from .ttypes import *
from thrift.Thrift import TProcessor
from thrift.transport import TTransport
all_structs = []
class Iface(object):
def buyCoinProduct(self, paymentReservation):
pass
def buyFreeProduct(self, receiverMid, productId, messageTemplate, language, country, packageId):
pass
def buyMustbuyProduct(self, receiverMid, productId, messageTemplate, language, country, packageId, serialNumber):
pass
def checkCanReceivePresent(self, recipientMid, packageId, language, country):
pass
def getActivePurchases(self, start, size, language, country):
pass
def getActivePurchaseVersions(self, start, size, language, country):
pass
def getCoinProducts(self, appStoreCode, country, language):
pass
def getCoinProductsByPgCode(self, appStoreCode, pgCode, country, language):
pass
def getCoinPurchaseHistory(self, request):
pass
def getCoinUseAndRefundHistory(self, request):
pass
def getDownloads(self, start, size, language, country):
pass
def getEventPackages(self, start, size, language, country):
pass
def getNewlyReleasedPackages(self, start, size, language, country):
pass
def getPopularPackages(self, start, size, language, country):
pass
def getPresentsReceived(self, start, size, language, country):
pass
def getPresentsSent(self, start, size, language, country):
pass
def getProductList(self, productIdList, language, country):
pass
def getProductListWithCarrier(self, productIdList, language, country, carrierCode):
pass
def getProductWithCarrier(self, packageID, language, country, carrierCode):
pass
def getPurchaseHistory(self, start, size, language, country):
pass
def getTotalBalance(self, appStoreCode):
pass
def notifyDownloaded(self, packageId, language):
pass
def reserveCoinPurchase(self, request):
pass
def reservePayment(self, paymentReservation):
pass
def canReceivePresent(self, shopId, productId, locale, recipientMid):
pass
def getAutoSuggestionShowcase(self, autoSuggestionShowcaseRequest):
pass
def getOldSticonMapping(self, req):
pass
def getOwnedProductSummaries(self, shopId, offset, limit, locale):
pass
def getOwnedProducts(self, shopId, offset, limit, locale):
pass
def getProductByVersion(self, shopId, productId, productVersion, locale):
pass
def getProductV2(self, request):
pass
def getProductValidationScheme(self, shopId, productId, productVersion):
pass
def getProduct(self, shopId, productId, locale):
pass
def getProductsByAuthor(self, productListByAuthorRequest):
pass
def getPurchasedProducts(self, shopId, offset, limit, locale):
pass
def getReceivedPresents(self, shopId, offset, limit, locale):
pass
def getRecommendOa(self, req):
pass
|
BSD 3-Clause New or Revised License
|
rucio/rucio
|
lib/rucio/db/sqla/migrate_repo/versions/1fc15ab60d43_add_message_history_table.py
|
downgrade
|
python
|
def downgrade():
if context.get_context().dialect.name in ['oracle', 'mysql', 'postgresql']:
drop_table('messages_history')
|
Downgrade the database to the previous revision
|
https://github.com/rucio/rucio/blob/6a6092798bb8220dec07328d0e3f7f42d1b931cd/lib/rucio/db/sqla/migrate_repo/versions/1fc15ab60d43_add_message_history_table.py#L49-L55
|
import datetime
import sqlalchemy as sa
from alembic import context
from alembic.op import create_table, drop_table
from rucio.db.sqla.types import GUID
revision = '1fc15ab60d43'
down_revision = '4783c1f49cb4'
def upgrade():
if context.get_context().dialect.name in ['oracle', 'mysql', 'postgresql']:
create_table('messages_history',
sa.Column('id', GUID()),
sa.Column('created_at', sa.DateTime, default=datetime.datetime.utcnow),
sa.Column('updated_at', sa.DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow),
sa.Column('event_type', sa.String(1024)),
sa.Column('payload', sa.String(4000)))
|
Apache License 2.0
|
livid/v2ex-gae
|
twitter/bitly.py
|
Api.expand
|
python
|
def expand(self,shortURL):
request = self._getURL("expand",shortURL)
result = self._fetchUrl(request)
json = simplejson.loads(result)
self._CheckForError(json)
return json['results'][string.split(shortURL, '/')[-1]]['longUrl']
|
Given a bit.ly url or hash, return long source url
|
https://github.com/livid/v2ex-gae/blob/32be3a77d535e7c9df85a333e01ab8834d0e8581/twitter/bitly.py#L78-L84
|
from django.utils import simplejson
import urllib,urllib2
import urlparse
import string
BITLY_BASE_URL = "http://api.bit.ly/"
BITLY_API_VERSION = "2.0.1"
VERBS_PARAM = {
'shorten':'longUrl',
'expand':'shortUrl',
'info':'shortUrl',
'stats':'shortUrl',
'errors':'',
}
class BitlyError(Exception):
@property
def message(self):
return self.args[0]
class Api(object):
def __init__(self, login, apikey):
self.login = login
self.apikey = apikey
self._urllib = urllib2
def shorten(self,longURL):
if not isinstance(longURL, list):
longURL = [longURL]
for index,url in enumerate(longURL):
if not '://' in url:
longURL[index] = "http://" + url
request = self._getURL("shorten",longURL)
result = self._fetchUrl(request)
json = simplejson.loads(result)
self._CheckForError(json)
res = []
for item in json['results'].values():
if item['shortKeywordUrl'] == "":
res.append(item['shortUrl'])
else:
res.append(item['shortKeywordUrl'])
if len(res) == 1:
return res[0]
else:
return res
|
BSD 3-Clause New or Revised License
|
delimitry/snmp-server
|
snmp-server.py
|
_read_byte
|
python
|
def _read_byte(stream):
read_byte = stream.read(1)
if not read_byte:
raise Exception('No more bytes!')
return ord(read_byte)
|
Read byte from stream
|
https://github.com/delimitry/snmp-server/blob/cd4c032af42d3e2eaaa703e84e668e646c3708fb/snmp-server.py#L205-L210
|
from __future__ import print_function
import argparse
import fnmatch
import functools
import logging
import socket
import string
import struct
import sys
import types
from collections import Iterable
from contextlib import closing
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
__version__ = '1.0.5'
PY3 = sys.version_info[0] == 3
logging.basicConfig(format='[%(levelname)s] %(message)s')
logger = logging.getLogger()
logger.setLevel(logging.WARNING)
ASN1_BOOLEAN = 0x01
ASN1_INTEGER = 0x02
ASN1_BIT_STRING = 0x03
ASN1_OCTET_STRING = 0x04
ASN1_NULL = 0x05
ASN1_OBJECT_IDENTIFIER = 0x06
ASN1_UTF8_STRING = 0x0c
ASN1_PRINTABLE_STRING = 0x13
ASN1_IA5_STRING = 0x16
ASN1_BMP_STRING = 0x1e
ASN1_SEQUENCE = 0x30
ASN1_SET = 0x31
ASN1_IPADDRESS = 0x40
ASN1_COUNTER32 = 0x41
ASN1_GAUGE32 = 0x42
ASN1_TIMETICKS = 0x43
ASN1_OPAQUE = 0x44
ASN1_COUNTER64 = 0x46
ASN1_NO_SUCH_OBJECT = 0x80
ASN1_NO_SUCH_INSTANCE = 0x81
ASN1_END_OF_MIB_VIEW = 0x82
ASN1_GET_REQUEST_PDU = 0xA0
ASN1_GET_NEXT_REQUEST_PDU = 0xA1
ASN1_GET_RESPONSE_PDU = 0xA2
ASN1_SET_REQUEST_PDU = 0xA3
ASN1_TRAP_REQUEST_PDU = 0xA4
ASN1_GET_BULK_REQUEST_PDU = 0xA5
ASN1_INFORM_REQUEST_PDU = 0xA6
ASN1_SNMPv2_TRAP_REQUEST_PDU = 0xA7
ASN1_REPORT_REQUEST_PDU = 0xA8
ASN1_ERROR_STATUS_NO_ERROR = 0x00
ASN1_ERROR_STATUS_TOO_BIG = 0x01
ASN1_ERROR_STATUS_NO_SUCH_NAME = 0x02
ASN1_ERROR_STATUS_BAD_VALUE = 0x03
ASN1_ERROR_STATUS_READ_ONLY = 0x04
ASN1_ERROR_STATUS_GEN_ERR = 0x05
ASN1_ERROR_STATUS_WRONG_VALUE = 0x0A
ASN1_CONTEXT = 0x80
ASN1_EXTENSION_ID = 0x1F
ASN1_OPAQUE_TAG1 = ASN1_CONTEXT | ASN1_EXTENSION_ID
ASN1_OPAQUE_TAG2 = 0x30
ASN1_APPLICATION = 0x40
ASN1_APP_FLOAT = ASN1_APPLICATION | 0x08
ASN1_APP_DOUBLE = ASN1_APPLICATION | 0x09
ASN1_APP_INT64 = ASN1_APPLICATION | 0x0A
ASN1_APP_UINT64 = ASN1_APPLICATION | 0x0B
ASN1_OPAQUE_FLOAT = ASN1_OPAQUE_TAG2 | ASN1_APP_FLOAT
ASN1_OPAQUE_DOUBLE = ASN1_OPAQUE_TAG2 | ASN1_APP_DOUBLE
ASN1_OPAQUE_INT64 = ASN1_OPAQUE_TAG2 | ASN1_APP_INT64
ASN1_OPAQUE_UINT64 = ASN1_OPAQUE_TAG2 | ASN1_APP_UINT64
ASN1_OPAQUE_FLOAT_BER_LEN = 7
ASN1_OPAQUE_DOUBLE_BER_LEN = 11
ASN1_OPAQUE_INT64_BER_LEN = 4
ASN1_OPAQUE_UINT64_BER_LEN = 4
SNMP_VERSIONS = {
1: 'v1',
2: 'v2c',
3: 'v3',
}
SNMP_PDUS = (
'version',
'community',
'PDU-type',
'request-id',
'error-status',
'error-index',
'variable bindings',
)
class ProtocolError(Exception):
class ConfigError(Exception):
class BadValueError(Exception):
class WrongValueError(Exception):
def encode_to_7bit(value):
if value > 0x7f:
res = []
res.insert(0, value & 0x7f)
while value > 0x7f:
value >>= 7
res.insert(0, (value & 0x7f) | 0x80)
return res
return [value]
def oid_to_bytes_list(oid):
if oid.startswith('iso'):
oid = oid.replace('iso', '1')
try:
oid_values = [int(x) for x in oid.split('.') if x]
first_val = 40 * oid_values[0] + oid_values[1]
except (ValueError, IndexError):
raise Exception('Could not parse OID value "{}"'.format(oid))
result_values = [first_val]
for node_num in oid_values[2:]:
result_values += encode_to_7bit(node_num)
return result_values
def oid_to_bytes(oid):
return ''.join([chr(x) for x in oid_to_bytes_list(oid)])
def bytes_to_oid(data):
values = [ord(x) for x in data]
first_val = values.pop(0)
res = []
res += divmod(first_val, 40)
while values:
val = values.pop(0)
if val > 0x7f:
huge_vals = [val]
while True:
next_val = values.pop(0)
huge_vals.append(next_val)
if next_val < 0x80:
break
huge = 0
for i, huge_byte in enumerate(huge_vals):
huge += (huge_byte & 0x7f) << (7 * (len(huge_vals) - i - 1))
res.append(huge)
else:
res.append(val)
return '.'.join(str(x) for x in res)
def timeticks_to_str(ticks):
days, rem1 = divmod(ticks, 24 * 60 * 60 * 100)
hours, rem2 = divmod(rem1, 60 * 60 * 100)
minutes, rem3 = divmod(rem2, 60 * 100)
seconds, milliseconds = divmod(rem3, 100)
ending = 's' if days > 1 else ''
days_fmt = '{} day{}, '.format(days, ending) if days > 0 else ''
return '{}{:-02}:{:-02}:{:-02}.{:-02}'.format(days_fmt, hours, minutes, seconds, milliseconds)
def int_to_ip(value):
return socket.inet_ntoa(struct.pack("!I", value))
def twos_complement(value, bits):
mask = 2 ** (bits - 1)
return -(value & mask) + (value & ~mask)
|
MIT License
|
seomoz/shovel
|
test/examples/nested/foo/baz/howdy/__init__.py
|
what
|
python
|
def what():
pass
|
A dummy function
|
https://github.com/seomoz/shovel/blob/fc29232b2b8be33972f8fb498a91a67e334f057f/test/examples/nested/foo/baz/howdy/__init__.py#L7-L9
|
from shovel import task
@task
|
MIT License
|
identitypython/pysaml2
|
src/saml2/entity.py
|
Entity._encrypt_assertion
|
python
|
def _encrypt_assertion(self, encrypt_cert, sp_entity_id, response, node_xpath=None):
_certs = []
if encrypt_cert:
_certs.append(encrypt_cert)
elif sp_entity_id is not None:
_certs = self.metadata.certs(sp_entity_id, "any", "encryption")
exception = None
for _cert in _certs:
wrapped_cert, unwrapped_cert = get_pem_wrapped_unwrapped(_cert)
try:
tmp = make_temp(
wrapped_cert.encode('ascii'),
decode=False,
delete_tmpfiles=self.config.delete_tmpfiles,
)
response = self.sec.encrypt_assertion(
response,
tmp.name,
pre_encryption_part(encrypt_cert=unwrapped_cert),
node_xpath=node_xpath,
)
return response
except Exception as ex:
exception = ex
pass
if exception:
raise exception
return response
|
Encryption of assertions.
:param encrypt_cert: Certificate to be used for encryption.
:param sp_entity_id: Entity ID for the calling service provider.
:param response: A samlp.Response
:param node_xpath: Unquie path to the element to be encrypted.
:return: A new samlp.Resonse with the designated assertion encrypted.
|
https://github.com/identitypython/pysaml2/blob/f12ade09aa89211c42b7dc6ed94728f8aa69cffb/src/saml2/entity.py#L674-L710
|
import base64
import copy
import logging
import requests
import six
from binascii import hexlify
from hashlib import sha1
from saml2.metadata import ENDPOINTS
from saml2.profile import paos, ecp, samlec
from saml2.soap import parse_soap_enveloped_saml_artifact_resolve
from saml2.soap import class_instances_from_soap_enveloped_saml_thingies
from saml2.soap import open_soap_envelope
from saml2 import samlp
from saml2 import SamlBase
from saml2 import SAMLError
from saml2 import saml
from saml2 import response as saml_response
from saml2 import BINDING_URI
from saml2 import BINDING_HTTP_ARTIFACT
from saml2 import BINDING_PAOS
from saml2 import request as saml_request
from saml2 import soap
from saml2 import element_to_extension_element
from saml2 import extension_elements_to_elements
from saml2.saml import NameID
from saml2.saml import EncryptedAssertion
from saml2.saml import Issuer
from saml2.saml import NAMEID_FORMAT_ENTITY
from saml2.response import AuthnResponse
from saml2.response import LogoutResponse
from saml2.response import UnsolicitedResponse
from saml2.time_util import instant
from saml2.s_utils import sid
from saml2.s_utils import UnravelError
from saml2.s_utils import error_status_factory
from saml2.s_utils import rndbytes
from saml2.s_utils import success_status_factory
from saml2.s_utils import decode_base64_and_inflate
from saml2.s_utils import UnsupportedBinding
from saml2.samlp import AuthnRequest, SessionIndex, response_from_string
from saml2.samlp import AuthzDecisionQuery
from saml2.samlp import AuthnQuery
from saml2.samlp import AssertionIDRequest
from saml2.samlp import ManageNameIDRequest
from saml2.samlp import NameIDMappingRequest
from saml2.samlp import artifact_resolve_from_string
from saml2.samlp import ArtifactResolve
from saml2.samlp import ArtifactResponse
from saml2.samlp import Artifact
from saml2.samlp import LogoutRequest
from saml2.samlp import AttributeQuery
from saml2.mdstore import all_locations
from saml2 import BINDING_HTTP_POST
from saml2 import BINDING_HTTP_REDIRECT
from saml2 import BINDING_SOAP
from saml2 import VERSION
from saml2 import class_name
from saml2.config import config_factory
from saml2.httpbase import HTTPBase
from saml2.sigver import security_context
from saml2.sigver import SigverError
from saml2.sigver import SignatureError
from saml2.sigver import make_temp
from saml2.sigver import get_pem_wrapped_unwrapped
from saml2.sigver import pre_encryption_part
from saml2.sigver import pre_signature_part
from saml2.sigver import pre_encrypt_assertion
from saml2.sigver import signed_instance_factory
from saml2.virtual_org import VirtualOrg
from saml2.pack import http_redirect_message
from saml2.pack import http_form_post_message
from saml2.xmldsig import DefaultSignature
from saml2.xmldsig import SIG_ALLOWED_ALG
from saml2.xmldsig import DIGEST_ALLOWED_ALG
logger = logging.getLogger(__name__)
__author__ = 'rolandh'
ARTIFACT_TYPECODE = b'\x00\x04'
SERVICE2MESSAGE = {
"single_sign_on_service": AuthnRequest,
"attribute_service": AttributeQuery,
"authz_service": AuthzDecisionQuery,
"assertion_id_request_service": AssertionIDRequest,
"authn_query_service": AuthnQuery,
"manage_name_id_service": ManageNameIDRequest,
"name_id_mapping_service": NameIDMappingRequest,
"artifact_resolve_service": ArtifactResolve,
"single_logout_service": LogoutRequest
}
class UnknownBinding(SAMLError):
pass
def create_artifact(entity_id, message_handle, endpoint_index=0):
if not isinstance(entity_id, six.binary_type):
entity_id = entity_id.encode('utf-8')
sourceid = sha1(entity_id)
if not isinstance(message_handle, six.binary_type):
message_handle = message_handle.encode('utf-8')
ter = b"".join((ARTIFACT_TYPECODE,
("%.2x" % endpoint_index).encode('ascii'),
sourceid.digest(),
message_handle))
return base64.b64encode(ter).decode('ascii')
class Entity(HTTPBase):
def __init__(self, entity_type, config=None, config_file="",
virtual_organization="", msg_cb=None):
self.entity_type = entity_type
self.users = None
if config:
self.config = config
elif config_file:
self.config = config_factory(entity_type, config_file)
else:
raise SAMLError("Missing configuration")
def_sig = DefaultSignature()
self.signing_algorithm = (
self.config.getattr('signing_algorithm')
or def_sig.get_sign_alg()
)
self.digest_algorithm = (
self.config.getattr('digest_algorithm')
or def_sig.get_digest_alg()
)
sign_config_per_entity_type = {
'sp': self.config.getattr("authn_requests_signed", "sp"),
'idp': self.config.getattr("sign_response", "idp"),
}
sign_config = sign_config_per_entity_type.get(self.entity_type, False)
self.should_sign = sign_config
for item in ["cert_file", "key_file", "ca_certs"]:
_val = getattr(self.config, item, None)
if not _val:
continue
if _val.startswith("http"):
r = requests.request("GET", _val)
if r.status_code == 200:
tmp = make_temp(r.text, ".pem", False, self.config.delete_tmpfiles)
setattr(self.config, item, tmp.name)
else:
raise Exception(
"Could not fetch certificate from %s" % _val)
HTTPBase.__init__(self, self.config.verify_ssl_cert,
self.config.ca_certs, self.config.key_file,
self.config.cert_file)
if self.config.vorg:
for vo in self.config.vorg.values():
vo.sp = self
self.metadata = self.config.metadata
self.debug = self.config.debug
self.sec = security_context(self.config)
if virtual_organization:
if isinstance(virtual_organization, six.string_types):
self.vorg = self.config.vorg[virtual_organization]
elif isinstance(virtual_organization, VirtualOrg):
self.vorg = virtual_organization
else:
self.vorg = None
self.artifact = {}
if self.metadata:
self.sourceid = self.metadata.construct_source_id()
else:
self.sourceid = {}
self.msg_cb = msg_cb
def reload_metadata(self, metadata_conf):
logger.debug("Loading new metadata")
try:
new_metadata = self.config.load_metadata(metadata_conf)
except Exception as ex:
logger.error("Loading metadata failed", exc_info=ex)
return False
logger.debug("Applying new metadata to main config")
( self.metadata, self.sec.metadata, self.config.metadata ) = [new_metadata]*3
policy = getattr(self.config, "_%s_policy" % self.entity_type, None)
if policy and policy.metadata_store:
logger.debug("Applying new metadata to %s policy", self.entity_type)
policy.metadata_store = self.metadata
logger.debug("Applying new metadata source_id")
self.sourceid = self.metadata.construct_source_id()
return True
def _issuer(self, entityid=None):
if entityid:
if isinstance(entityid, Issuer):
return entityid
else:
return Issuer(text=entityid, format=NAMEID_FORMAT_ENTITY)
else:
return Issuer(text=self.config.entityid,
format=NAMEID_FORMAT_ENTITY)
def apply_binding(
self,
binding,
msg_str,
destination="",
relay_state="",
response=False,
sign=None,
sigalg=None,
**kwargs,
):
sign = sign if sign is not None else self.should_sign
sign_alg = sigalg or self.signing_algorithm
if sign_alg not in [long_name for short_name, long_name in SIG_ALLOWED_ALG]:
raise Exception(
"Signature algo not in allowed list: {algo}".format(algo=sign_alg)
)
if response:
typ = "SAMLResponse"
else:
typ = "SAMLRequest"
if binding == BINDING_HTTP_POST:
logger.info("HTTP POST")
info = http_form_post_message(msg_str, destination, relay_state, typ)
(msg_str, destination, relay_state, typ)
info["url"] = destination
info["method"] = "POST"
elif binding == BINDING_HTTP_REDIRECT:
logger.info("HTTP REDIRECT")
info = http_redirect_message(
message=msg_str,
location=destination,
relay_state=relay_state,
typ=typ,
sign=sign,
sigalg=sign_alg,
backend=self.sec.sec_backend,
)
info["url"] = str(destination)
info["method"] = "GET"
elif binding == BINDING_SOAP or binding == BINDING_PAOS:
info = self.use_soap(
msg_str, destination, sign=sign, sigalg=sign_alg, **kwargs
)
elif binding == BINDING_URI:
info = self.use_http_uri(msg_str, typ, destination)
elif binding == BINDING_HTTP_ARTIFACT:
if response:
info = self.use_http_artifact(msg_str, destination, relay_state)
info["method"] = "GET"
info["status"] = 302
else:
info = self.use_http_artifact(msg_str, destination, relay_state)
else:
raise SAMLError("Unknown binding type: %s" % binding)
return info
def pick_binding(
self, service, bindings=None, descr_type="", request=None, entity_id=""
):
if request and not entity_id:
entity_id = request.issuer.text.strip()
sfunc = getattr(self.metadata, service)
if not bindings:
if request and request.protocol_binding:
bindings = [request.protocol_binding]
else:
bindings = self.config.preferred_binding[service]
if not descr_type:
if self.entity_type == "sp":
descr_type = "idpsso"
else:
descr_type = "spsso"
_url = getattr(request, "%s_url" % service, None)
_index = getattr(request, "%s_index" % service, None)
for binding in bindings:
try:
srvs = sfunc(entity_id, binding, descr_type)
if srvs:
if _url:
for srv in srvs:
if srv["location"] == _url:
return binding, _url
elif _index:
for srv in srvs:
if srv["index"] == _index:
return binding, srv["location"]
else:
destination = next(all_locations(srvs), None)
return binding, destination
except UnsupportedBinding:
pass
logger.error("Failed to find consumer URL: %s, %s, %s",
entity_id, bindings, descr_type)
raise SAMLError("Unknown entity or unsupported bindings")
def message_args(self, message_id=0):
if not message_id:
message_id = sid()
margs = {
"id": message_id,
"version": VERSION,
"issue_instant": instant(),
"issuer": self._issuer(),
}
return margs
def response_args(self, message, bindings=None, descr_type=""):
info = {"in_response_to": message.id}
if isinstance(message, AuthnRequest):
rsrv = "assertion_consumer_service"
descr_type = "spsso"
info["sp_entity_id"] = message.issuer.text
info["name_id_policy"] = message.name_id_policy
elif isinstance(message, LogoutRequest):
rsrv = "single_logout_service"
elif isinstance(message, AttributeQuery):
info["sp_entity_id"] = message.issuer.text
rsrv = "attribute_consuming_service"
descr_type = "spsso"
elif isinstance(message, ManageNameIDRequest):
rsrv = "manage_name_id_service"
elif isinstance(message, AssertionIDRequest):
rsrv = ""
elif isinstance(message, ArtifactResolve):
rsrv = ""
elif isinstance(message, AssertionIDRequest):
rsrv = ""
elif isinstance(message, NameIDMappingRequest):
rsrv = ""
else:
raise SAMLError("No support for this type of query")
if bindings == [BINDING_SOAP]:
info["binding"] = BINDING_SOAP
info["destination"] = ""
return info
if rsrv:
if not descr_type:
if self.entity_type == "sp":
descr_type = "idpsso"
else:
descr_type = "spsso"
binding, destination = self.pick_binding(
rsrv, bindings, descr_type=descr_type, request=message
)
info["binding"] = binding
info["destination"] = destination
return info
@staticmethod
def unravel(txt, binding, msgtype="response"):
if binding not in [BINDING_HTTP_REDIRECT, BINDING_HTTP_POST,
BINDING_SOAP, BINDING_URI, BINDING_HTTP_ARTIFACT,
None]:
raise UnknownBinding("Don't know how to handle '%s'" % binding)
else:
try:
if binding == BINDING_HTTP_REDIRECT:
xmlstr = decode_base64_and_inflate(txt)
elif binding == BINDING_HTTP_POST:
xmlstr = base64.b64decode(txt)
elif binding == BINDING_SOAP:
func = getattr(soap,
"parse_soap_enveloped_saml_%s" % msgtype)
xmlstr = func(txt)
elif binding == BINDING_HTTP_ARTIFACT:
xmlstr = base64.b64decode(txt)
else:
xmlstr = txt
except Exception:
raise UnravelError("Unravelling binding '%s' failed" % binding)
return xmlstr
@staticmethod
def parse_soap_message(text):
return class_instances_from_soap_enveloped_saml_thingies(text, [paos,
ecp,
samlp,
samlec])
@staticmethod
def unpack_soap_message(text):
return open_soap_envelope(text)
def sign(
self,
msg,
mid=None,
to_sign=None,
sign_prepare=None,
sign_alg=None,
digest_alg=None,
):
sign_alg = sign_alg or self.signing_algorithm
digest_alg = digest_alg or self.digest_algorithm
if sign_alg not in [long_name for short_name, long_name in SIG_ALLOWED_ALG]:
raise Exception(
"Signature algo not in allowed list: {algo}".format(algo=sign_alg)
)
if digest_alg not in [long_name for short_name, long_name in DIGEST_ALLOWED_ALG]:
raise Exception(
"Digest algo not in allowed list: {algo}".format(algo=digest_alg)
)
if msg.signature is None:
msg.signature = pre_signature_part(
msg.id, self.sec.my_cert, 1, sign_alg=sign_alg, digest_alg=digest_alg
)
if sign_prepare:
return msg
if mid is None:
mid = msg.id
try:
to_sign += [(class_name(msg), mid)]
except (AttributeError, TypeError):
to_sign = [(class_name(msg), mid)]
logger.info("REQUEST: %s", msg)
return signed_instance_factory(msg, self.sec, to_sign)
def _message(
self,
request_cls,
destination=None,
message_id=0,
consent=None,
extensions=None,
sign=None,
sign_prepare=None,
nsprefix=None,
sign_alg=None,
digest_alg=None,
**kwargs,
):
if not message_id:
message_id = sid()
for key, val in self.message_args(message_id).items():
if key not in kwargs:
kwargs[key] = val
req = request_cls(**kwargs)
if destination:
req.destination = destination
if consent:
req.consent = "true"
if extensions:
req.extensions = extensions
if nsprefix:
req.register_prefix(nsprefix)
if self.msg_cb:
req = self.msg_cb(req)
reqid = req.id
sign = sign if sign is not None else self.should_sign
if sign:
signed_req = self.sign(
req,
sign_prepare=sign_prepare,
sign_alg=sign_alg,
digest_alg=digest_alg,
)
req = signed_req
logger.info("REQUEST: %s", req)
return reqid, req
@staticmethod
def _filter_args(instance, extensions=None, **kwargs):
args = {}
if extensions is None:
extensions = []
allowed_attributes = instance.keys()
for key, val in kwargs.items():
if key in allowed_attributes:
args[key] = val
elif isinstance(val, SamlBase):
extensions.append(element_to_extension_element(val))
return args, extensions
def _add_info(self, msg, **kwargs):
args, extensions = self._filter_args(msg, **kwargs)
for key, val in args.items():
setattr(msg, key, val)
if extensions:
if msg.extension_elements:
msg.extension_elements.extend(extensions)
else:
msg.extension_elements = extensions
def has_encrypt_cert_in_metadata(self, sp_entity_id):
if sp_entity_id is not None:
_certs = self.metadata.certs(sp_entity_id, "any", "encryption")
if len(_certs) > 0:
return True
return False
|
Apache License 2.0
|
mwaskom/moss
|
moss/psychophys/models.py
|
PsychophysicsModel.fit
|
python
|
def fit(self, initial_params=None, fix=None, method="nelder-mead"):
if initial_params is None:
params = self.default_params
else:
params = self.default_params.copy()
if isinstance(initial_params, dict):
initial_params = pd.Series(initial_params)
params.update(initial_params)
if fix is None:
fix = self.default_fixed
self.params = ParamSet(params, fix)
initial_free = self.params.free
result = minimize(self.err_func, initial_free, method=method)
self.result_ = result
self.ll_ = -result["fun"]
self.params_ = self.params
self.success_ = result["success"]
return self
|
External fit interface, allows specification of variables.
|
https://github.com/mwaskom/moss/blob/893685411147a082a22ba4a2e229a727c9cc0c40/moss/psychophys/models.py#L30-L64
|
from __future__ import print_function, division
import numpy as np
import pandas as pd
from scipy import stats
from scipy.optimize import minimize
import seaborn as sns
import matplotlib.pyplot as plt
from .params import ParamSet
from .visualization import log0_safe_xticks, plot_limits
class PsychophysicsModel(object):
default_params = pd.Series()
default_fixed = []
def err_func(self, params):
raise NotImplementedError
|
BSD 3-Clause New or Revised License
|
huxiaoling/imageseg-2.5d_topo
|
TopologyForceV1/venv/lib64/python3.7/site-packages/pip-19.0.3-py3.7.egg/pip/_vendor/distro.py
|
LinuxDistribution._parse_os_release_content
|
python
|
def _parse_os_release_content(lines):
props = {}
lexer = shlex.shlex(lines, posix=True)
lexer.whitespace_split = True
if sys.version_info[0] == 2 and isinstance(lexer.wordchars, bytes):
lexer.wordchars = lexer.wordchars.decode('iso-8859-1')
tokens = list(lexer)
for token in tokens:
if '=' in token:
k, v = token.split('=', 1)
if isinstance(v, bytes):
v = v.decode('utf-8')
props[k.lower()] = v
if k == 'VERSION':
codename = re.search(r'(\(\D+\))|,(\s+)?\D+', v)
if codename:
codename = codename.group()
codename = codename.strip('()')
codename = codename.strip(',')
codename = codename.strip()
props['codename'] = codename
else:
props['codename'] = ''
else:
pass
return props
|
Parse the lines of an os-release file.
Parameters:
* lines: Iterable through the lines in the os-release file.
Each line must be a unicode string or a UTF-8 encoded byte
string.
Returns:
A dictionary containing all information items.
|
https://github.com/huxiaoling/imageseg-2.5d_topo/blob/86ca52e53f838309132a67f2a3e58cf69d314770/TopologyForceV1/venv/lib64/python3.7/site-packages/pip-19.0.3-py3.7.egg/pip/_vendor/distro.py#L926-L983
|
import os
import re
import sys
import json
import shlex
import logging
import argparse
import subprocess
_UNIXCONFDIR = os.environ.get('UNIXCONFDIR', '/etc')
_OS_RELEASE_BASENAME = 'os-release'
NORMALIZED_OS_ID = {}
NORMALIZED_LSB_ID = {
'enterpriseenterprise': 'oracle',
'redhatenterpriseworkstation': 'rhel',
'redhatenterpriseserver': 'rhel',
}
NORMALIZED_DISTRO_ID = {
'redhat': 'rhel',
}
_DISTRO_RELEASE_CONTENT_REVERSED_PATTERN = re.compile(
r'(?:[^)]*\)(.*)\()? *(?:STL )?([\d.+\-a-z]*\d) *(?:esaeler *)?(.+)')
_DISTRO_RELEASE_BASENAME_PATTERN = re.compile(
r'(\w+)[-_](release|version)$')
_DISTRO_RELEASE_IGNORE_BASENAMES = (
'debian_version',
'lsb-release',
'oem-release',
_OS_RELEASE_BASENAME,
'system-release'
)
def linux_distribution(full_distribution_name=True):
return _distro.linux_distribution(full_distribution_name)
def id():
return _distro.id()
def name(pretty=False):
return _distro.name(pretty)
def version(pretty=False, best=False):
return _distro.version(pretty, best)
def version_parts(best=False):
return _distro.version_parts(best)
def major_version(best=False):
return _distro.major_version(best)
def minor_version(best=False):
return _distro.minor_version(best)
def build_number(best=False):
return _distro.build_number(best)
def like():
return _distro.like()
def codename():
return _distro.codename()
def info(pretty=False, best=False):
return _distro.info(pretty, best)
def os_release_info():
return _distro.os_release_info()
def lsb_release_info():
return _distro.lsb_release_info()
def distro_release_info():
return _distro.distro_release_info()
def uname_info():
return _distro.uname_info()
def os_release_attr(attribute):
return _distro.os_release_attr(attribute)
def lsb_release_attr(attribute):
return _distro.lsb_release_attr(attribute)
def distro_release_attr(attribute):
return _distro.distro_release_attr(attribute)
def uname_attr(attribute):
return _distro.uname_attr(attribute)
class cached_property(object):
def __init__(self, f):
self._fname = f.__name__
self._f = f
def __get__(self, obj, owner):
assert obj is not None, 'call {} on an instance'.format(self._fname)
ret = obj.__dict__[self._fname] = self._f(obj)
return ret
class LinuxDistribution(object):
def __init__(self,
include_lsb=True,
os_release_file='',
distro_release_file='',
include_uname=True):
self.os_release_file = os_release_file or os.path.join(_UNIXCONFDIR, _OS_RELEASE_BASENAME)
self.distro_release_file = distro_release_file or ''
self.include_lsb = include_lsb
self.include_uname = include_uname
def __repr__(self):
return "LinuxDistribution(" "os_release_file={self.os_release_file!r}, " "distro_release_file={self.distro_release_file!r}, " "include_lsb={self.include_lsb!r}, " "include_uname={self.include_uname!r}, " "_os_release_info={self._os_release_info!r}, " "_lsb_release_info={self._lsb_release_info!r}, " "_distro_release_info={self._distro_release_info!r}, " "_uname_info={self._uname_info!r})".format(
self=self)
def linux_distribution(self, full_distribution_name=True):
return (
self.name() if full_distribution_name else self.id(),
self.version(),
self.codename()
)
def id(self):
def normalize(distro_id, table):
distro_id = distro_id.lower().replace(' ', '_')
return table.get(distro_id, distro_id)
distro_id = self.os_release_attr('id')
if distro_id:
return normalize(distro_id, NORMALIZED_OS_ID)
distro_id = self.lsb_release_attr('distributor_id')
if distro_id:
return normalize(distro_id, NORMALIZED_LSB_ID)
distro_id = self.distro_release_attr('id')
if distro_id:
return normalize(distro_id, NORMALIZED_DISTRO_ID)
distro_id = self.uname_attr('id')
if distro_id:
return normalize(distro_id, NORMALIZED_DISTRO_ID)
return ''
def name(self, pretty=False):
name = self.os_release_attr('name') or self.lsb_release_attr('distributor_id') or self.distro_release_attr('name') or self.uname_attr('name')
if pretty:
name = self.os_release_attr('pretty_name') or self.lsb_release_attr('description')
if not name:
name = self.distro_release_attr('name') or self.uname_attr('name')
version = self.version(pretty=True)
if version:
name = name + ' ' + version
return name or ''
def version(self, pretty=False, best=False):
versions = [
self.os_release_attr('version_id'),
self.lsb_release_attr('release'),
self.distro_release_attr('version_id'),
self._parse_distro_release_content(
self.os_release_attr('pretty_name')).get('version_id', ''),
self._parse_distro_release_content(
self.lsb_release_attr('description')).get('version_id', ''),
self.uname_attr('release')
]
version = ''
if best:
for v in versions:
if v.count(".") > version.count(".") or version == '':
version = v
else:
for v in versions:
if v != '':
version = v
break
if pretty and version and self.codename():
version = u'{0} ({1})'.format(version, self.codename())
return version
def version_parts(self, best=False):
version_str = self.version(best=best)
if version_str:
version_regex = re.compile(r'(\d+)\.?(\d+)?\.?(\d+)?')
matches = version_regex.match(version_str)
if matches:
major, minor, build_number = matches.groups()
return major, minor or '', build_number or ''
return '', '', ''
def major_version(self, best=False):
return self.version_parts(best)[0]
def minor_version(self, best=False):
return self.version_parts(best)[1]
def build_number(self, best=False):
return self.version_parts(best)[2]
def like(self):
return self.os_release_attr('id_like') or ''
def codename(self):
return self.os_release_attr('codename') or self.lsb_release_attr('codename') or self.distro_release_attr('codename') or ''
def info(self, pretty=False, best=False):
return dict(
id=self.id(),
version=self.version(pretty, best),
version_parts=dict(
major=self.major_version(best),
minor=self.minor_version(best),
build_number=self.build_number(best)
),
like=self.like(),
codename=self.codename(),
)
def os_release_info(self):
return self._os_release_info
def lsb_release_info(self):
return self._lsb_release_info
def distro_release_info(self):
return self._distro_release_info
def uname_info(self):
def os_release_attr(self, attribute):
return self._os_release_info.get(attribute, '')
def lsb_release_attr(self, attribute):
return self._lsb_release_info.get(attribute, '')
def distro_release_attr(self, attribute):
return self._distro_release_info.get(attribute, '')
def uname_attr(self, attribute):
return self._uname_info.get(attribute, '')
@cached_property
def _os_release_info(self):
if os.path.isfile(self.os_release_file):
with open(self.os_release_file) as release_file:
return self._parse_os_release_content(release_file)
return {}
@staticmethod
|
MIT License
|
cupy/cupy
|
cupyx/scipy/ndimage/filters.py
|
uniform_filter1d
|
python
|
def uniform_filter1d(input, size, axis=-1, output=None, mode="reflect",
cval=0.0, origin=0):
return correlate1d(input, cupy.ones(size) / size, axis, output, mode, cval,
origin)
|
One-dimensional uniform filter along the given axis.
The lines of the array along the given axis are filtered with a uniform
filter of the given size.
Args:
input (cupy.ndarray): The input array.
size (int): Length of the uniform filter.
axis (int): The axis of input along which to calculate. Default is -1.
output (cupy.ndarray, dtype or None): The array in which to place the
output. Default is is same dtype as the input.
mode (str): The array borders are handled according to the given mode
(``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
``'wrap'``). Default is ``'reflect'``.
cval (scalar): Value to fill past edges of input if mode is
``'constant'``. Default is ``0.0``.
origin (int): The origin parameter controls the placement of the
filter, relative to the center of the current element of the
input. Default is ``0``.
Returns:
cupy.ndarray: The result of the filtering.
.. seealso:: :func:`scipy.ndimage.uniform_filter1d`
.. note::
When the output data type is integral (or when no output is provided
and input is integral) the results may not perfectly match the results
from SciPy due to floating-point rounding of intermediate results.
|
https://github.com/cupy/cupy/blob/a466b03ef0afd7c1ce1615e3f48da64ae38c1320/cupyx/scipy/ndimage/filters.py#L210-L243
|
import numpy
import cupy
from cupy._core import internal
from cupyx.scipy.ndimage import _util
from cupyx.scipy.ndimage import _filters_core
from cupyx.scipy.ndimage import _filters_generic
def correlate(input, weights, output=None, mode='reflect', cval=0.0, origin=0):
return _correlate_or_convolve(input, weights, output, mode, cval, origin)
def convolve(input, weights, output=None, mode='reflect', cval=0.0, origin=0):
return _correlate_or_convolve(input, weights, output, mode, cval, origin,
True)
def correlate1d(input, weights, axis=-1, output=None, mode="reflect", cval=0.0,
origin=0):
weights, origins = _filters_core._convert_1d_args(input.ndim, weights,
origin, axis)
return _correlate_or_convolve(input, weights, output, mode, cval, origins)
def convolve1d(input, weights, axis=-1, output=None, mode="reflect", cval=0.0,
origin=0):
weights, origins = _filters_core._convert_1d_args(input.ndim, weights,
origin, axis)
return _correlate_or_convolve(input, weights, output, mode, cval, origins,
True)
def _correlate_or_convolve(input, weights, output, mode, cval, origin,
convolution=False):
origins, int_type = _filters_core._check_nd_args(input, weights,
mode, origin)
if weights.size == 0:
return cupy.zeros_like(input)
_util._check_cval(mode, cval, _util._is_integer_output(output, input))
if convolution:
weights = weights[tuple([slice(None, None, -1)] * weights.ndim)]
origins = list(origins)
for i, wsize in enumerate(weights.shape):
origins[i] = -origins[i]
if wsize % 2 == 0:
origins[i] -= 1
origins = tuple(origins)
elif weights.dtype.kind == "c":
weights = weights.conj()
weights_dtype = _util._get_weights_dtype(input, weights)
offsets = _filters_core._origins_to_offsets(origins, weights.shape)
kernel = _get_correlate_kernel(mode, weights.shape, int_type,
offsets, cval)
output = _filters_core._call_kernel(kernel, input, weights, output,
weights_dtype=weights_dtype)
return output
@cupy._util.memoize(for_each_device=True)
def _get_correlate_kernel(mode, w_shape, int_type, offsets, cval):
return _filters_core._generate_nd_kernel(
'correlate',
'W sum = (W)0;',
'sum += cast<W>({value}) * wval;',
'y = cast<Y>(sum);',
mode, w_shape, int_type, offsets, cval, ctype='W')
def _run_1d_correlates(input, params, get_weights, output, mode, cval,
origin=0):
wghts = {}
for param in params:
if param not in wghts:
wghts[param] = get_weights(param)
wghts = [wghts[param] for param in params]
return _filters_core._run_1d_filters(
[None if w is None else correlate1d for w in wghts],
input, wghts, output, mode, cval, origin)
|
MIT License
|
openai/safety-gym
|
safety_gym/envs/engine.py
|
Engine.sample_goal_position
|
python
|
def sample_goal_position(self):
placements, keepout = self.placements['goal']
goal_xy = self.draw_placement(placements, keepout)
for other_name, other_xy in self.layout.items():
other_keepout = self.placements[other_name][1]
dist = np.sqrt(np.sum(np.square(goal_xy - other_xy)))
if dist < other_keepout + self.placements_margin + keepout:
return False
self.layout['goal'] = goal_xy
return True
|
Sample a new goal position and return True, else False if sample rejected
|
https://github.com/openai/safety-gym/blob/f31042f2f9ee61b9034dd6a416955972911544f5/safety_gym/envs/engine.py#L812-L822
|
import gym
import gym.spaces
import numpy as np
from PIL import Image
from copy import deepcopy
from collections import OrderedDict
import mujoco_py
from mujoco_py import MjViewer, MujocoException, const, MjRenderContextOffscreen
from safety_gym.envs.world import World, Robot
import sys
COLOR_BOX = np.array([1, 1, 0, 1])
COLOR_BUTTON = np.array([1, .5, 0, 1])
COLOR_GOAL = np.array([0, 1, 0, 1])
COLOR_VASE = np.array([0, 1, 1, 1])
COLOR_HAZARD = np.array([0, 0, 1, 1])
COLOR_PILLAR = np.array([.5, .5, 1, 1])
COLOR_WALL = np.array([.5, .5, .5, 1])
COLOR_GREMLIN = np.array([0.5, 0, 1, 1])
COLOR_CIRCLE = np.array([0, 1, 0, 1])
COLOR_RED = np.array([1, 0, 0, 1])
GROUP_GOAL = 0
GROUP_BOX = 1
GROUP_BUTTON = 1
GROUP_WALL = 2
GROUP_PILLAR = 2
GROUP_HAZARD = 3
GROUP_VASE = 4
GROUP_GREMLIN = 5
GROUP_CIRCLE = 6
ORIGIN_COORDINATES = np.zeros(3)
DEFAULT_WIDTH = 256
DEFAULT_HEIGHT = 256
class ResamplingError(AssertionError):
pass
def theta2vec(theta):
return np.array([np.cos(theta), np.sin(theta), 0.0])
def quat2mat(quat):
q = np.array(quat, dtype='float64')
m = np.zeros(9, dtype='float64')
mujoco_py.functions.mju_quat2Mat(m, q)
return m.reshape((3,3))
def quat2zalign(quat):
a, b, c, d = quat
return a**2 - b**2 - c**2 + d**2
class Engine(gym.Env, gym.utils.EzPickle):
DEFAULT = {
'num_steps': 1000,
'action_noise': 0.0,
'placements_extents': [-2, -2, 2, 2],
'placements_margin': 0.0,
'floor_display_mode': False,
'robot_placements': None,
'robot_locations': [],
'robot_keepout': 0.4,
'robot_base': 'xmls/car.xml',
'robot_rot': None,
'randomize_layout': True,
'build_resample': True,
'continue_goal': True,
'terminate_resample_failure': True,
'observation_flatten': True,
'observe_sensors': True,
'observe_goal_dist': False,
'observe_goal_comp': False,
'observe_goal_lidar': False,
'observe_box_comp': False,
'observe_box_lidar': False,
'observe_circle': False,
'observe_remaining': False,
'observe_walls': False,
'observe_hazards': False,
'observe_vases': False,
'observe_pillars': False,
'observe_buttons': False,
'observe_gremlins': False,
'observe_vision': False,
'observe_qpos': False,
'observe_qvel': False,
'observe_ctrl': False,
'observe_freejoint': False,
'observe_com': False,
'render_labels': False,
'render_lidar_markers': True,
'render_lidar_radius': 0.15,
'render_lidar_size': 0.025,
'render_lidar_offset_init': 0.5,
'render_lidar_offset_delta': 0.06,
'vision_size': (60, 40),
'vision_render': True,
'vision_render_size': (300, 200),
'lidar_num_bins': 10,
'lidar_max_dist': None,
'lidar_exp_gain': 1.0,
'lidar_type': 'pseudo',
'lidar_alias': True,
'compass_shape': 2,
'task': 'goal',
'goal_placements': None,
'goal_locations': [],
'goal_keepout': 0.4,
'goal_size': 0.3,
'box_placements': None,
'box_locations': [],
'box_keepout': 0.2,
'box_size': 0.2,
'box_density': 0.001,
'box_null_dist': 2,
'reward_distance': 1.0,
'reward_goal': 1.0,
'reward_box_dist': 1.0,
'reward_box_goal': 1.0,
'reward_orientation': False,
'reward_orientation_scale': 0.002,
'reward_orientation_body': 'robot',
'reward_exception': -10.0,
'reward_x': 1.0,
'reward_z': 1.0,
'reward_circle': 1e-1,
'reward_clip': 10,
'buttons_num': 0,
'buttons_placements': None,
'buttons_locations': [],
'buttons_keepout': 0.3,
'buttons_size': 0.1,
'buttons_cost': 1.0,
'buttons_resampling_delay': 10,
'circle_radius': 1.5,
'sensors_obs': ['accelerometer', 'velocimeter', 'gyro', 'magnetometer'],
'sensors_hinge_joints': True,
'sensors_ball_joints': True,
'sensors_angle_components': True,
'walls_num': 0,
'walls_placements': None,
'walls_locations': [],
'walls_keepout': 0.0,
'walls_size': 0.5,
'constrain_hazards': False,
'constrain_vases': False,
'constrain_pillars': False,
'constrain_buttons': False,
'constrain_gremlins': False,
'constrain_indicator': True,
'hazards_num': 0,
'hazards_placements': None,
'hazards_locations': [],
'hazards_keepout': 0.4,
'hazards_size': 0.3,
'hazards_cost': 1.0,
'vases_num': 0,
'vases_placements': None,
'vases_locations': [],
'vases_keepout': 0.15,
'vases_size': 0.1,
'vases_density': 0.001,
'vases_sink': 4e-5,
'vases_contact_cost': 1.0,
'vases_displace_cost': 0.0,
'vases_displace_threshold': 1e-3,
'vases_velocity_cost': 1.0,
'vases_velocity_threshold': 1e-4,
'pillars_num': 0,
'pillars_placements': None,
'pillars_locations': [],
'pillars_keepout': 0.3,
'pillars_size': 0.2,
'pillars_height': 0.5,
'pillars_cost': 1.0,
'gremlins_num': 0,
'gremlins_placements': None,
'gremlins_locations': [],
'gremlins_keepout': 0.5,
'gremlins_travel': 0.3,
'gremlins_size': 0.1,
'gremlins_density': 0.001,
'gremlins_contact_cost': 1.0,
'gremlins_dist_threshold': 0.2,
'gremlins_dist_cost': 1.0,
'frameskip_binom_n': 10,
'frameskip_binom_p': 1.0,
'_seed': None,
}
def __init__(self, config={}):
self.parse(config)
gym.utils.EzPickle.__init__(self, config=config)
self.robot = Robot(self.robot_base)
self.action_space = gym.spaces.Box(-1, 1, (self.robot.nu,), dtype=np.float32)
self.build_observation_space()
self.build_placements_dict()
self.viewer = None
self.world = None
self.clear()
self.seed(self._seed)
self.done = True
def parse(self, config):
self.config = deepcopy(self.DEFAULT)
self.config.update(deepcopy(config))
for key, value in self.config.items():
assert key in self.DEFAULT, f'Bad key {key}'
setattr(self, key, value)
@property
def sim(self):
return self.world.sim
@property
def model(self):
return self.sim.model
@property
def data(self):
return self.sim.data
@property
def robot_pos(self):
return self.data.get_body_xpos('robot').copy()
@property
def goal_pos(self):
if self.task in ['goal', 'push']:
return self.data.get_body_xpos('goal').copy()
elif self.task == 'button':
return self.data.get_body_xpos(f'button{self.goal_button}').copy()
elif self.task == 'circle':
return ORIGIN_COORDINATES
elif self.task == 'none':
return np.zeros(2)
else:
raise ValueError(f'Invalid task {self.task}')
@property
def box_pos(self):
return self.data.get_body_xpos('box').copy()
@property
def buttons_pos(self):
return [self.data.get_body_xpos(f'button{i}').copy() for i in range(self.buttons_num)]
@property
def vases_pos(self):
return [self.data.get_body_xpos(f'vase{p}').copy() for p in range(self.vases_num)]
@property
def gremlins_obj_pos(self):
return [self.data.get_body_xpos(f'gremlin{i}obj').copy() for i in range(self.gremlins_num)]
@property
def pillars_pos(self):
return [self.data.get_body_xpos(f'pillar{i}').copy() for i in range(self.pillars_num)]
@property
def hazards_pos(self):
return [self.data.get_body_xpos(f'hazard{i}').copy() for i in range(self.hazards_num)]
@property
def walls_pos(self):
return [self.data.get_body_xpos(f'wall{i}').copy() for i in range(self.walls_num)]
def build_observation_space(self):
obs_space_dict = OrderedDict()
if self.observe_freejoint:
obs_space_dict['freejoint'] = gym.spaces.Box(-np.inf, np.inf, (7,), dtype=np.float32)
if self.observe_com:
obs_space_dict['com'] = gym.spaces.Box(-np.inf, np.inf, (3,), dtype=np.float32)
if self.observe_sensors:
for sensor in self.sensors_obs:
dim = self.robot.sensor_dim[sensor]
obs_space_dict[sensor] = gym.spaces.Box(-np.inf, np.inf, (dim,), dtype=np.float32)
for sensor in self.robot.hinge_vel_names:
obs_space_dict[sensor] = gym.spaces.Box(-np.inf, np.inf, (1,), dtype=np.float32)
for sensor in self.robot.ballangvel_names:
obs_space_dict[sensor] = gym.spaces.Box(-np.inf, np.inf, (3,), dtype=np.float32)
if self.sensors_angle_components:
for sensor in self.robot.hinge_pos_names:
obs_space_dict[sensor] = gym.spaces.Box(-np.inf, np.inf, (2,), dtype=np.float32)
for sensor in self.robot.ballquat_names:
obs_space_dict[sensor] = gym.spaces.Box(-np.inf, np.inf, (3, 3), dtype=np.float32)
else:
for sensor in self.robot.hinge_pos_names:
obs_space_dict[sensor] = gym.spaces.Box(-np.inf, np.inf, (1,), dtype=np.float32)
for sensor in self.robot.ballquat_names:
obs_space_dict[sensor] = gym.spaces.Box(-np.inf, np.inf, (4,), dtype=np.float32)
if self.task == 'push':
if self.observe_box_comp:
obs_space_dict['box_compass'] = gym.spaces.Box(-1.0, 1.0, (self.compass_shape,), dtype=np.float32)
if self.observe_box_lidar:
obs_space_dict['box_lidar'] = gym.spaces.Box(0.0, 1.0, (self.lidar_num_bins,), dtype=np.float32)
if self.observe_goal_dist:
obs_space_dict['goal_dist'] = gym.spaces.Box(0.0, 1.0, (1,), dtype=np.float32)
if self.observe_goal_comp:
obs_space_dict['goal_compass'] = gym.spaces.Box(-1.0, 1.0, (self.compass_shape,), dtype=np.float32)
if self.observe_goal_lidar:
obs_space_dict['goal_lidar'] = gym.spaces.Box(0.0, 1.0, (self.lidar_num_bins,), dtype=np.float32)
if self.task == 'circle' and self.observe_circle:
obs_space_dict['circle_lidar'] = gym.spaces.Box(0.0, 1.0, (self.lidar_num_bins,), dtype=np.float32)
if self.observe_remaining:
obs_space_dict['remaining'] = gym.spaces.Box(0.0, 1.0, (1,), dtype=np.float32)
if self.walls_num and self.observe_walls:
obs_space_dict['walls_lidar'] = gym.spaces.Box(0.0, 1.0, (self.lidar_num_bins,), dtype=np.float32)
if self.observe_hazards:
obs_space_dict['hazards_lidar'] = gym.spaces.Box(0.0, 1.0, (self.lidar_num_bins,), dtype=np.float32)
if self.observe_vases:
obs_space_dict['vases_lidar'] = gym.spaces.Box(0.0, 1.0, (self.lidar_num_bins,), dtype=np.float32)
if self.gremlins_num and self.observe_gremlins:
obs_space_dict['gremlins_lidar'] = gym.spaces.Box(0.0, 1.0, (self.lidar_num_bins,), dtype=np.float32)
if self.pillars_num and self.observe_pillars:
obs_space_dict['pillars_lidar'] = gym.spaces.Box(0.0, 1.0, (self.lidar_num_bins,), dtype=np.float32)
if self.buttons_num and self.observe_buttons:
obs_space_dict['buttons_lidar'] = gym.spaces.Box(0.0, 1.0, (self.lidar_num_bins,), dtype=np.float32)
if self.observe_qpos:
obs_space_dict['qpos'] = gym.spaces.Box(-np.inf, np.inf, (self.robot.nq,), dtype=np.float32)
if self.observe_qvel:
obs_space_dict['qvel'] = gym.spaces.Box(-np.inf, np.inf, (self.robot.nv,), dtype=np.float32)
if self.observe_ctrl:
obs_space_dict['ctrl'] = gym.spaces.Box(-np.inf, np.inf, (self.robot.nu,), dtype=np.float32)
if self.observe_vision:
width, height = self.vision_size
rows, cols = height, width
self.vision_size = (rows, cols)
obs_space_dict['vision'] = gym.spaces.Box(0, 1.0, self.vision_size + (3,), dtype=np.float32)
self.obs_space_dict = obs_space_dict
if self.observation_flatten:
self.obs_flat_size = sum([np.prod(i.shape) for i in self.obs_space_dict.values()])
self.observation_space = gym.spaces.Box(-np.inf, np.inf, (self.obs_flat_size,), dtype=np.float32)
else:
self.observation_space = gym.spaces.Dict(obs_space_dict)
def toggle_observation_space(self):
self.observation_flatten = not(self.observation_flatten)
self.build_observation_space()
def placements_from_location(self, location, keepout):
x, y = location
return [(x - keepout, y - keepout, x + keepout, y + keepout)]
def placements_dict_from_object(self, object_name):
placements_dict = {}
if hasattr(self, object_name + 's_num'):
plural_name = object_name + 's'
object_fmt = object_name + '{i}'
object_num = getattr(self, plural_name + '_num', None)
object_locations = getattr(self, plural_name + '_locations', [])
object_placements = getattr(self, plural_name + '_placements', None)
object_keepout = getattr(self, plural_name + '_keepout')
else:
object_fmt = object_name
object_num = 1
object_locations = getattr(self, object_name + '_locations', [])
object_placements = getattr(self, object_name + '_placements', None)
object_keepout = getattr(self, object_name + '_keepout')
for i in range(object_num):
if i < len(object_locations):
x, y = object_locations[i]
k = object_keepout + 1e-9
placements = [(x - k, y - k, x + k, y + k)]
else:
placements = object_placements
placements_dict[object_fmt.format(i=i)] = (placements, object_keepout)
return placements_dict
def build_placements_dict(self):
placements = {}
placements.update(self.placements_dict_from_object('robot'))
placements.update(self.placements_dict_from_object('wall'))
if self.task in ['goal', 'push']:
placements.update(self.placements_dict_from_object('goal'))
if self.task == 'push':
placements.update(self.placements_dict_from_object('box'))
if self.task == 'button' or self.buttons_num:
placements.update(self.placements_dict_from_object('button'))
if self.hazards_num:
placements.update(self.placements_dict_from_object('hazard'))
if self.vases_num:
placements.update(self.placements_dict_from_object('vase'))
if self.pillars_num:
placements.update(self.placements_dict_from_object('pillar'))
if self.gremlins_num:
placements.update(self.placements_dict_from_object('gremlin'))
self.placements = placements
def seed(self, seed=None):
self._seed = np.random.randint(2**32) if seed is None else seed
def build_layout(self):
if not self.randomize_layout:
self.rs = np.random.RandomState(0)
for _ in range(10000):
if self.sample_layout():
break
else:
raise ResamplingError('Failed to sample layout of objects')
def sample_layout(self):
def placement_is_valid(xy, layout):
for other_name, other_xy in layout.items():
other_keepout = self.placements[other_name][1]
dist = np.sqrt(np.sum(np.square(xy - other_xy)))
if dist < other_keepout + self.placements_margin + keepout:
return False
return True
layout = {}
for name, (placements, keepout) in self.placements.items():
conflicted = True
for _ in range(100):
xy = self.draw_placement(placements, keepout)
if placement_is_valid(xy, layout):
conflicted = False
break
if conflicted:
return False
layout[name] = xy
self.layout = layout
return True
def constrain_placement(self, placement, keepout):
xmin, ymin, xmax, ymax = placement
return (xmin + keepout, ymin + keepout, xmax - keepout, ymax - keepout)
def draw_placement(self, placements, keepout):
if placements is None:
choice = self.constrain_placement(self.placements_extents, keepout)
else:
constrained = []
for placement in placements:
xmin, ymin, xmax, ymax = self.constrain_placement(placement, keepout)
if xmin > xmax or ymin > ymax:
continue
constrained.append((xmin, ymin, xmax, ymax))
assert len(constrained), 'Failed to find any placements with satisfy keepout'
if len(constrained) == 1:
choice = constrained[0]
else:
areas = [(x2 - x1)*(y2 - y1) for x1, y1, x2, y2 in constrained]
probs = np.array(areas) / np.sum(areas)
choice = constrained[self.rs.choice(len(constrained), p=probs)]
xmin, ymin, xmax, ymax = choice
return np.array([self.rs.uniform(xmin, xmax), self.rs.uniform(ymin, ymax)])
def random_rot(self):
return self.rs.uniform(0, 2 * np.pi)
def build_world_config(self):
world_config = {}
world_config['robot_base'] = self.robot_base
world_config['robot_xy'] = self.layout['robot']
if self.robot_rot is None:
world_config['robot_rot'] = self.random_rot()
else:
world_config['robot_rot'] = float(self.robot_rot)
if self.floor_display_mode:
floor_size = max(self.placements_extents)
world_config['floor_size'] = [floor_size + .1, floor_size + .1, 1]
world_config['observe_vision'] = self.observe_vision
world_config['objects'] = {}
if self.vases_num:
for i in range(self.vases_num):
name = f'vase{i}'
object = {'name': name,
'size': np.ones(3) * self.vases_size,
'type': 'box',
'density': self.vases_density,
'pos': np.r_[self.layout[name], self.vases_size - self.vases_sink],
'rot': self.random_rot(),
'group': GROUP_VASE,
'rgba': COLOR_VASE}
world_config['objects'][name] = object
if self.gremlins_num:
self._gremlins_rots = dict()
for i in range(self.gremlins_num):
name = f'gremlin{i}obj'
self._gremlins_rots[i] = self.random_rot()
object = {'name': name,
'size': np.ones(3) * self.gremlins_size,
'type': 'box',
'density': self.gremlins_density,
'pos': np.r_[self.layout[name.replace('obj', '')], self.gremlins_size],
'rot': self._gremlins_rots[i],
'group': GROUP_GREMLIN,
'rgba': COLOR_GREMLIN}
world_config['objects'][name] = object
if self.task == 'push':
object = {'name': 'box',
'type': 'box',
'size': np.ones(3) * self.box_size,
'pos': np.r_[self.layout['box'], self.box_size],
'rot': self.random_rot(),
'density': self.box_density,
'group': GROUP_BOX,
'rgba': COLOR_BOX}
world_config['objects']['box'] = object
world_config['geoms'] = {}
if self.task in ['goal', 'push']:
geom = {'name': 'goal',
'size': [self.goal_size, self.goal_size / 2],
'pos': np.r_[self.layout['goal'], self.goal_size / 2 + 1e-2],
'rot': self.random_rot(),
'type': 'cylinder',
'contype': 0,
'conaffinity': 0,
'group': GROUP_GOAL,
'rgba': COLOR_GOAL * [1, 1, 1, 0.25]}
world_config['geoms']['goal'] = geom
if self.hazards_num:
for i in range(self.hazards_num):
name = f'hazard{i}'
geom = {'name': name,
'size': [self.hazards_size, 1e-2],
'pos': np.r_[self.layout[name], 2e-2],
'rot': self.random_rot(),
'type': 'cylinder',
'contype': 0,
'conaffinity': 0,
'group': GROUP_HAZARD,
'rgba': COLOR_HAZARD * [1, 1, 1, 0.25]}
world_config['geoms'][name] = geom
if self.pillars_num:
for i in range(self.pillars_num):
name = f'pillar{i}'
geom = {'name': name,
'size': [self.pillars_size, self.pillars_height],
'pos': np.r_[self.layout[name], self.pillars_height],
'rot': self.random_rot(),
'type': 'cylinder',
'group': GROUP_PILLAR,
'rgba': COLOR_PILLAR}
world_config['geoms'][name] = geom
if self.walls_num:
for i in range(self.walls_num):
name = f'wall{i}'
geom = {'name': name,
'size': np.ones(3) * self.walls_size,
'pos': np.r_[self.layout[name], self.walls_size],
'rot': 0,
'type': 'box',
'group': GROUP_WALL,
'rgba': COLOR_WALL}
world_config['geoms'][name] = geom
if self.buttons_num:
for i in range(self.buttons_num):
name = f'button{i}'
geom = {'name': name,
'size': np.ones(3) * self.buttons_size,
'pos': np.r_[self.layout[name], self.buttons_size],
'rot': self.random_rot(),
'type': 'sphere',
'group': GROUP_BUTTON,
'rgba': COLOR_BUTTON}
world_config['geoms'][name] = geom
if self.task == 'circle':
geom = {'name': 'circle',
'size': np.array([self.circle_radius, 1e-2]),
'pos': np.array([0, 0, 2e-2]),
'rot': 0,
'type': 'cylinder',
'contype': 0,
'conaffinity': 0,
'group': GROUP_CIRCLE,
'rgba': COLOR_CIRCLE * [1, 1, 1, 0.1]}
world_config['geoms']['circle'] = geom
world_config['mocaps'] = {}
if self.gremlins_num:
for i in range(self.gremlins_num):
name = f'gremlin{i}mocap'
mocap = {'name': name,
'size': np.ones(3) * self.gremlins_size,
'type': 'box',
'pos': np.r_[self.layout[name.replace('mocap', '')], self.gremlins_size],
'rot': self._gremlins_rots[i],
'group': GROUP_GREMLIN,
'rgba': np.array([1, 1, 1, .1]) * COLOR_GREMLIN}
world_config['mocaps'][name] = mocap
return world_config
def clear(self):
self.layout = None
def build_goal(self):
if self.task == 'goal':
self.build_goal_position()
self.last_dist_goal = self.dist_goal()
elif self.task == 'push':
self.build_goal_position()
self.last_dist_goal = self.dist_goal()
self.last_dist_box = self.dist_box()
self.last_box_goal = self.dist_box_goal()
elif self.task == 'button':
assert self.buttons_num > 0, 'Must have at least one button'
self.build_goal_button()
self.last_dist_goal = self.dist_goal()
elif self.task in ['x', 'z']:
self.last_robot_com = self.world.robot_com()
elif self.task in ['circle', 'none']:
pass
else:
raise ValueError(f'Invalid task {self.task}')
|
MIT License
|
mikedacre/fyrd
|
fyrd/batch_systems/local.py
|
LocalQueue.__repr__
|
python
|
def __repr__(self):
return 'LocalQueue<{location}>'.format(location=self.db_file)
|
Basic information about self.
|
https://github.com/mikedacre/fyrd/blob/6445719bfdcb3358a597300a25384acd8d3df80b/fyrd/batch_systems/local.py#L316-L318
|
from __future__ import print_function
import os as _os
import sys
import errno as _errno
import signal as _signal
import socket as _socket
import getpass as _getpass
import argparse as _argparse
import subprocess
import multiprocessing as mp
from time import sleep as _sleep
from datetime import datetime as _dt
from datetime import timedelta as _td
from collections import OrderedDict as _OD
try:
from Queue import Empty
except ImportError:
from queue import Empty
from six import text_type as _txt
from six import string_types as _str
from six import integer_types as _int
import psutil as _psutil
import Pyro4
from sqlalchemy.exc import InvalidRequestError
from sqlalchemy import create_engine as _create_engine
from sqlalchemy import Column as _Column
from sqlalchemy import String as _String
from sqlalchemy import Integer as _Integer
from sqlalchemy.types import DateTime as _DateTime
from sqlalchemy.orm import sessionmaker as _sessionmaker
from sqlalchemy.orm import scoped_session as _scoped_session
from sqlalchemy.ext.declarative import declarative_base as _base
from fyrd import run as _run
from fyrd import conf as _conf
from fyrd import logme as _logme
from fyrd import options as _options
from fyrd import script_runners as _scrpts
from fyrd import submission_scripts as _sscrpt
_Script = _sscrpt.Script
Base = _base()
PID = None
RUN_DIR = _conf.CONFIG_PATH
PID_FILE = _os.path.join(RUN_DIR, 'local_queue.pid')
URI_FILE = _os.path.join(RUN_DIR, 'local_queue.uri')
DATABASE = _os.path.join(RUN_DIR, 'local_queue.db')
SLEEP_LEN = 0.1
STOP_WAIT = 5
CLEAN_OLDER_THAN = 7
MAX_JOBS = mp.cpu_count()-1
MAX_JOBS = MAX_JOBS if MAX_JOBS >= 0 else 1
_WE_ARE_A_SERVER = False
PREFIX = ''
SUFFIX = 'job'
try:
subprocess.check_output(
"taskset -p 0xff %d >/dev/null 2>/dev/null" % _os.getpid(), shell=True
)
except subprocess.CalledProcessError:
pass
class QueueError(Exception):
pass
class Job(Base):
__tablename__ = 'jobs'
jobno = _Column(_Integer, primary_key=True, index=True)
name = _Column(_String, nullable=False)
command = _Column(_String, nullable=False)
submit_time = _Column(_DateTime, nullable=False)
threads = _Column(_Integer, nullable=False)
state = _Column(_String, nullable=False, index=True)
exitcode = _Column(_Integer)
pid = _Column(_Integer)
runpath = _Column(_String)
outfile = _Column(_String)
errfile = _Column(_String)
def __repr__(self):
return 'LocalQueueJob<{0}:{1};{2};state:{3};exitcode:{4}>'.format(
self.jobno, self.pid, self.name, self.state, self.exitcode
)
class LocalQueue(object):
db_file = DATABASE
def __init__(self, db_file=None):
db_file = db_file if db_file else self.db_file
self.db_file = _os.path.abspath(db_file)
self.engine = _create_engine(
'sqlite:///{}?check_same_thread=False'.format(self.db_file)
)
if not _os.path.isfile(self.db_file):
self.create_database(confirm=False)
def get_session(self):
session_factory = _sessionmaker(bind=self.engine)
Session = _scoped_session(session_factory)
return Session()
@property
def session(self):
return self.get_session()
def query(self, *args):
if not args:
args = (Job,)
session = self.get_session()
return session.query(*args)
def get_jobs(self, state=None):
q = self.query()
if state:
q = q.filter(Job.state == state)
return q.all()
@property
def running(self):
return self.get_jobs(state='running')
@property
def queued(self):
return self.get_jobs(state='pending')
@property
def completed(self):
return self.get_jobs(state='completed')
@property
def failed(self):
return self.get_jobs(state='failed')
def set_running_jobs_failed(self):
pass
def create_database(self, confirm=True):
if confirm:
ans = _run.get_yesno(
'Are you sure you want to erase and recreate the db?'
)
if not ans:
sys.stderr.write('Aborting\n')
return False
_logme.log('Recreating database', 'info', also_write='stderr')
if _os.path.exists(self.db_file):
_os.remove(self.db_file)
Base.metadata.create_all(self.engine)
_logme.log('Done', 'info', also_write='stderr')
def __getitem__(self, x):
if isinstance(x, (_str, _txt)):
return self.query().filter(Job.jobno == x).all()
def __len__(self):
return self.query(Job).count()
|
MIT License
|
airtestproject/airtest
|
airtest/core/android/adb.py
|
ADB.pm_install
|
python
|
def pm_install(self, filepath, replace=False):
filename = os.path.basename(filepath)
device_dir = "/data/local/tmp"
device_path = '\"%s/%s\"' % (device_dir, filename)
out = self.cmd(["push", filepath, device_dir])
print(out)
if not replace:
install_cmd = ['pm', 'install', device_path]
else:
install_cmd = ['pm', 'install', '-r', device_path]
try:
self.shell(install_cmd)
except:
raise
finally:
self.shell("rm " + device_path)
|
Perform `adb push` and `adb install` commands
Note:
This is more reliable and recommended way of installing `.apk` files
Args:
filepath: full path to file to be installed on the device
replace: force to replace existing application, default is False
Returns:
None
|
https://github.com/airtestproject/airtest/blob/c29d0462fe29db5c04cda31de1c05bcae5991061/airtest/core/android/adb.py#L635-L669
|
import os
import re
import sys
import time
import random
import platform
import warnings
import subprocess
import threading
from copy import copy
from six import PY3, text_type, binary_type, raise_from
from six.moves import reduce
from airtest.core.android.constant import (DEFAULT_ADB_PATH, IP_PATTERN,
SDK_VERISON_ANDROID7)
from airtest.core.error import (AdbError, AdbShellError, AirtestError,
DeviceConnectionError)
from airtest.utils.compat import decode_path, raisefrom, proc_communicate_timeout, SUBPROCESS_FLAG
from airtest.utils.logger import get_logger
from airtest.utils.nbsp import NonBlockingStreamReader
from airtest.utils.retry import retries
from airtest.utils.snippet import get_std_encoding, reg_cleanup, split_cmd, make_file_executable
LOGGING = get_logger(__name__)
class ADB(object):
_instances = []
status_device = "device"
status_offline = "offline"
SHELL_ENCODING = "utf-8"
def __init__(self, serialno=None, adb_path=None, server_addr=None, display_id=None, input_event=None):
self.serialno = serialno
self.adb_path = adb_path or self.builtin_adb_path()
self.display_id = display_id
self.input_event = input_event
self._set_cmd_options(server_addr)
self.connect()
self._sdk_version = None
self._line_breaker = None
self._display_info = {}
self._display_info_lock = threading.Lock()
self._forward_local_using = []
self.__class__._instances.append(self)
@staticmethod
def builtin_adb_path():
system = platform.system()
machine = platform.machine()
adb_path = DEFAULT_ADB_PATH.get('{}-{}'.format(system, machine))
if not adb_path:
adb_path = DEFAULT_ADB_PATH.get(system)
if not adb_path:
raise RuntimeError("No adb executable supports this platform({}-{}).".format(system, machine))
if "ANDROID_HOME" in os.environ:
del os.environ["ANDROID_HOME"]
if system != "Windows":
make_file_executable(adb_path)
return adb_path
def _set_cmd_options(self, server_addr=None):
self.host = server_addr[0] if server_addr else "127.0.0.1"
self.port = server_addr[1] if server_addr else 5037
self.cmd_options = [self.adb_path]
if self.host not in ("localhost", "127.0.0.1"):
self.cmd_options += ['-H', self.host]
if self.port != 5037:
self.cmd_options += ['-P', str(self.port)]
def start_server(self):
return self.cmd("start-server", device=False)
def kill_server(self):
return self.cmd("kill-server", device=False)
def version(self):
return self.cmd("version", device=False).strip()
def start_cmd(self, cmds, device=True):
if device:
if not self.serialno:
raise RuntimeError("please set serialno first")
cmd_options = self.cmd_options + ['-s', self.serialno]
else:
cmd_options = self.cmd_options
cmds = cmd_options + split_cmd(cmds)
LOGGING.debug(" ".join(cmds))
if not PY3:
cmds = [c.encode(get_std_encoding(sys.stdin)) for c in cmds]
proc = subprocess.Popen(
cmds,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
creationflags=SUBPROCESS_FLAG
)
return proc
def cmd(self, cmds, device=True, ensure_unicode=True, timeout=None):
proc = self.start_cmd(cmds, device)
if timeout:
stdout, stderr = proc_communicate_timeout(proc, timeout)
else:
stdout, stderr = proc.communicate()
if ensure_unicode:
stdout = stdout.decode(get_std_encoding(sys.stdout))
stderr = stderr.decode(get_std_encoding(sys.stderr))
if proc.returncode > 0:
pattern = DeviceConnectionError.DEVICE_CONNECTION_ERROR
if isinstance(stderr, binary_type):
pattern = pattern.encode("utf-8")
if re.search(pattern, stderr):
raise DeviceConnectionError(stderr)
else:
raise AdbError(stdout, stderr)
return stdout
def close_proc_pipe(self, proc):
def close_pipe(pipe):
if pipe:
pipe.close()
close_pipe(proc.stdin)
close_pipe(proc.stdout)
close_pipe(proc.stderr)
def devices(self, state=None):
patten = re.compile(r'^[\w\d.:-]+\t[\w]+$')
device_list = []
output = self.cmd("devices", device=False)
for line in output.splitlines():
line = line.strip()
if not line or not patten.match(line):
continue
serialno, cstate = line.split('\t')
if state and cstate != state:
continue
device_list.append((serialno, cstate))
return device_list
def connect(self, force=False):
if self.serialno and ":" in self.serialno and (force or self.get_status() != "device"):
connect_result = self.cmd("connect %s" % self.serialno)
LOGGING.info(connect_result)
def disconnect(self):
if ":" in self.serialno:
self.cmd("disconnect %s" % self.serialno)
def get_status(self):
proc = self.start_cmd("get-state")
stdout, stderr = proc.communicate()
stdout = stdout.decode(get_std_encoding(sys.stdout))
stderr = stderr.decode(get_std_encoding(sys.stdout))
if proc.returncode == 0:
return stdout.strip()
elif "not found" in stderr:
return None
else:
raise AdbError(stdout, stderr)
def wait_for_device(self, timeout=5):
try:
self.cmd("wait-for-device", timeout=timeout)
except RuntimeError as e:
raisefrom(DeviceConnectionError, "device not ready", e)
def start_shell(self, cmds):
cmds = ['shell'] + split_cmd(cmds)
return self.start_cmd(cmds)
def raw_shell(self, cmds, ensure_unicode=True):
cmds = ['shell'] + split_cmd(cmds)
out = self.cmd(cmds, ensure_unicode=False)
if not ensure_unicode:
return out
try:
return out.decode(self.SHELL_ENCODING)
except UnicodeDecodeError:
warnings.warn("shell output decode {} fail. repr={}".format(self.SHELL_ENCODING, repr(out)))
return text_type(repr(out))
def shell(self, cmd):
if self.sdk_version < SDK_VERISON_ANDROID7:
cmd = split_cmd(cmd) + [";", "echo", "---$?---"]
out = self.raw_shell(cmd).rstrip()
m = re.match("(.*)---(\d+)---$", out, re.DOTALL)
if not m:
warnings.warn("return code not matched")
stdout = out
returncode = 0
else:
stdout = m.group(1)
returncode = int(m.group(2))
if returncode > 0:
raise AdbShellError("", stdout)
return stdout
else:
try:
out = self.raw_shell(cmd)
except AdbError as err:
raise AdbShellError(err.stdout, err.stderr)
else:
return out
def keyevent(self, keyname):
self.shell(["input", "keyevent", keyname.upper()])
def getprop(self, key, strip=True):
prop = self.raw_shell(['getprop', key])
if strip:
if "\r\r\n" in prop:
prop = prop.split("\r\r\n")
if len(prop) > 1:
prop = prop[-2]
else:
prop = prop[-1]
else:
prop = prop.strip("\r\n")
return prop
@property
@retries(max_tries=3)
def sdk_version(self):
if self._sdk_version is None:
keyname = 'ro.build.version.sdk'
self._sdk_version = int(self.getprop(keyname))
return self._sdk_version
def push(self, local, remote):
self.cmd(["push", local, remote], ensure_unicode=False)
def pull(self, remote, local):
self.cmd(["pull", remote, local], ensure_unicode=False)
def forward(self, local, remote, no_rebind=True):
cmds = ['forward']
if no_rebind:
cmds += ['--no-rebind']
self.cmd(cmds + [local, remote])
if local not in self._forward_local_using:
self._forward_local_using.append(local)
def get_forwards(self):
out = self.cmd(['forward', '--list'])
for line in out.splitlines():
line = line.strip()
if not line:
continue
cols = line.split()
if len(cols) != 3:
continue
serialno, local, remote = cols
yield serialno, local, remote
@classmethod
def get_available_forward_local(cls):
return random.randint(11111, 20000)
@retries(3)
def setup_forward(self, device_port, no_rebind=True):
localport = self.get_available_forward_local()
if callable(device_port):
device_port = device_port(localport)
self.forward("tcp:%s" % localport, device_port, no_rebind=no_rebind)
return localport, device_port
def remove_forward(self, local=None):
if local:
cmds = ["forward", "--remove", local]
else:
cmds = ["forward", "--remove-all"]
self.cmd(cmds)
if local in self._forward_local_using:
self._forward_local_using.remove(local)
def install_app(self, filepath, replace=False, install_options=None):
if isinstance(filepath, str):
filepath = decode_path(filepath)
if not os.path.isfile(filepath):
raise RuntimeError("file: %s does not exists" % (repr(filepath)))
if not install_options or type(install_options) != list:
install_options = []
if replace:
install_options.append("-r")
cmds = ["install", ] + install_options + [filepath, ]
out = self.cmd(cmds)
if re.search(r"Failure \[.*?\]", out):
raise AdbShellError("Installation Failure", repr(out))
return out
def install_multiple_app(self, filepath, replace=False, install_options=None):
if isinstance(filepath, str):
filepath = decode_path(filepath)
if not os.path.isfile(filepath):
raise RuntimeError("file: %s does not exists" % (repr(filepath)))
if not install_options or type(install_options) != list:
install_options = []
if replace:
install_options.append("-r")
cmds = ["install-multiple", ] + install_options + [filepath, ]
try:
out = self.cmd(cmds)
except AdbError as err:
if "Failed to finalize session".lower() in err.stderr.lower():
return "Success"
else:
return self.install_app(filepath, replace)
if re.search(r"Failure \[.*?\]", out):
raise AdbShellError("Installation Failure", repr(out))
return out
|
Apache License 2.0
|
scidash/sciunit
|
sciunit/tests.py
|
Test.check_capabilities
|
python
|
def check_capabilities(
self, model: Model, skip_incapable: bool = False, require_extra: bool = False
) -> bool:
if not isinstance(model, Model):
raise Error("Model %s is not a sciunit.Model." % str(model))
capable = all(
[
self.check_capability(model, c, skip_incapable, require_extra)
for c in self.required_capabilities
]
)
return capable
|
Check that test's required capabilities are implemented by `model`.
Args:
model (Model): A sciunit model instance
skip_incapable (bool, optional): Skip the incapable tests. Defaults to False.
require_extra (bool, optional): Check to see whether the model implements certain other methods.. Defaults to False.
Raises:
Error: Raises an Error if model is not a Model.
Raises a CapabilityError if model does not have a capability.
Returns:
bool: true if the test's required capabilities are implemented.
|
https://github.com/scidash/sciunit/blob/68401d88b8e47d29807f8b4f9d265a23174143d9/sciunit/tests.py#L191-L216
|
import inspect
import traceback
from copy import deepcopy
from typing import Any, List, Optional, Tuple, Union
import quantities as pq
from .base import SciUnit, config
from .capabilities import ProducesNumber
from .errors import (
CapabilityError,
Error,
InvalidScoreError,
ObservationError,
ParametersError,
)
from .models import Model
from .scores import BooleanScore, ErrorScore, NAScore, NoneScore, Score, TBDScore
from .utils import dict_combine
from .validators import ObservationValidator, ParametersValidator
class Test(SciUnit):
def __init__(
self,
observation: Union[List[int], Tuple[int, int]],
name: Optional[str] = None,
**params
):
self.name = name if name else self.__class__.__name__
assert isinstance(self.name, str), "Test name must be a string"
if self.description is None:
self.description = self.__class__.__doc__
self.params = dict_combine(self.default_params, params)
self.verbose = self.params.pop("verbose", 1)
self.validate_params(self.params)
self.compute_params()
self.observation = observation
if self.observation_schema is None:
self.observation_schema = deepcopy(self.score_type.observation_schema)
if config.get("PREVALIDATE", False):
self.validate_observation(self.observation)
if self.score_type is None or not issubclass(self.score_type, Score):
raise Error(
("The score type '%s' specified for Test '%s' " "is not valid.")
% (self.score_type, self.name)
)
super(Test, self).__init__()
name = None
description = None
observation = None
default_params = {}
score_type = BooleanScore
converter = None
observation_schema = None
observation_validator = ObservationValidator
params_schema = None
params_validator = ParametersValidator
units = pq.dimensionless
state_hide = ["last_model"]
def compute_params(self) -> None:
def validate_observation(self, observation: dict) -> dict:
observation = self.score_type.observation_preprocess(observation)
if not isinstance(observation, dict):
raise ObservationError("Observation is not a dictionary.")
if self.observation_schema:
if isinstance(self.observation_schema, list):
schemas = [
x[1] if isinstance(x, tuple) else x for x in self.observation_schema
]
schema = {"oneof_schema": schemas, "type": "dict"}
else:
schema = {"schema": self.observation_schema, "type": "dict"}
schema = {"observation": schema}
v = self.observation_validator(schema, test=self)
if not v.validate({"observation": observation}):
raise ObservationError(v.errors)
observation = self.score_type.observation_postprocess(observation)
return observation
@classmethod
def observation_schema_names(cls) -> List[str]:
names = []
if cls.observation_schema:
if isinstance(cls.observation_schema, list):
names = [
x[0] if isinstance(x, tuple) else "Schema %d" % (i + 1)
for i, x in enumerate(cls.observation_schema)
]
return names
def validate_params(self, params: dict) -> dict:
if params is None:
raise ParametersError("Parameters cannot be `None`.")
if not isinstance(params, dict):
raise ParametersError("Parameters are not a dictionary.")
if self.params_schema:
if isinstance(self.params_schema, list):
schema = {"oneof_schema": self.params_schema, "type": "dict"}
else:
schema = {"schema": self.params_schema, "type": "dict"}
schema = {"params": schema}
v = self.params_validator(schema, test=self)
if not v.validate({"params": params}):
raise ParametersError(v.errors)
return params
required_capabilities = ()
|
MIT License
|
note35/sinon
|
sinon/lib/spy.py
|
SinonSpy.returnValues
|
python
|
def returnValues(self):
return super(SinonSpy, self)._get_wrapper().ret_list
|
Return: List (returns which are happened)
|
https://github.com/note35/sinon/blob/35da87ca6f30eec112ffc8d5c0a56d852d770285/sinon/lib/spy.py#L96-L100
|
from .util import ErrorHandler, Wrapper
from .util import CollectionHandler as uch
from .base import SinonBase
from .matcher import SinonMatcher, Matcher
import weakref
class SinonSpy(SinonBase):
def __init__(self, obj=None, prop=None):
super(SinonSpy, self).__init__(obj, prop)
self.__get_func = SinonSpy.__get_by_matcher
@staticmethod
def __get_by_matcher(arg):
return SinonMatcher(arg) if not isinstance(arg, Matcher) else arg
@staticmethod
def __get_directly(arg):
return arg
def __remove_args_first_item(self):
if len(self.args) > 0:
new_args_list = []
for item in self.args:
if len(item) > 0 and self.obj == item[0].__class__:
new_args_list.append(item[1:])
else:
new_args_list.append(item[:])
self.__set_args_list(new_args_list)
def __set_args_list(self, new_args_list):
super(SinonSpy, self)._get_wrapper().__set__("args_list", new_args_list)
@property
def args(self):
return super(SinonSpy, self)._get_wrapper().args_list
@property
def kwargs(self):
return super(SinonSpy, self)._get_wrapper().kwargs_list
@property
def exceptions(self):
return super(SinonSpy, self)._get_wrapper().error_list
@property
|
BSD 2-Clause Simplified License
|
feryal/automated-curriculum-rl
|
experiment.py
|
build_learner
|
python
|
def build_learner(agent, agent_state, env_outputs, agent_outputs,
teacher_task_ph):
learner_outputs, _ = agent.unroll(agent_outputs.action, env_outputs,
agent_state)
teacher_selected_task = tf.identity(teacher_task_ph)
bootstrap_value = learner_outputs.baseline[-1]
agent_outputs = nest.map_structure(lambda t: t[1:], agent_outputs)
rewards, infos, done, _ = nest.map_structure(
lambda t: t[1:], env_outputs)
learner_outputs = nest.map_structure(lambda t: t[:-1], learner_outputs)
if FLAGS.reward_clipping == 'abs_one':
clipped_rewards = tf.clip_by_value(rewards, -1, 1)
elif FLAGS.reward_clipping == 'soft_asymmetric':
squeezed = tf.tanh(rewards / 5.0)
clipped_rewards = tf.where(rewards < 0, .3 * squeezed, squeezed) * 5.
discounts = tf.to_float(~done) * FLAGS.discounting
with tf.device('/cpu'):
vtrace_returns = vtrace.from_logits(
behaviour_policy_logits=agent_outputs.policy_logits,
target_policy_logits=learner_outputs.policy_logits,
actions=agent_outputs.action,
discounts=discounts,
rewards=clipped_rewards,
values=learner_outputs.baseline,
bootstrap_value=bootstrap_value)
total_loss = compute_policy_gradient_loss(
learner_outputs.policy_logits, agent_outputs.action,
vtrace_returns.pg_advantages)
total_loss += FLAGS.baseline_cost * compute_baseline_loss(
vtrace_returns.vs - learner_outputs.baseline)
total_loss += FLAGS.entropy_cost * compute_entropy_loss(
learner_outputs.policy_logits)
num_env_frames = tf.train.get_global_step()
learning_rate = tf.train.polynomial_decay(FLAGS.learning_rate, num_env_frames,
FLAGS.total_environment_frames, 0)
optimizer = tf.train.RMSPropOptimizer(learning_rate, FLAGS.decay,
FLAGS.momentum, FLAGS.epsilon)
train_op = optimizer.minimize(total_loss)
if FLAGS.progress_signal == 'reward':
episode_returns_correct_task = tf.boolean_mask(
rewards,
tf.logical_and(done, tf.equal(infos.task_name, teacher_selected_task)))
progress_signal = tf.where(
tf.size(episode_returns_correct_task) > 0,
x=tf.reduce_mean(episode_returns_correct_task, name='progress_reward'),
y=0)
elif FLAGS.progress_signal == 'advantage':
episode_returns_correct_task = tf.boolean_mask(
rewards,
tf.logical_and(done, tf.equal(infos.task_name, teacher_selected_task)))
progress_signal = tf.where(
tf.size(episode_returns_correct_task) > 0,
x=tf.reduce_mean(episode_returns_correct_task, name='progress_reward'),
y=0)
elif FLAGS.progress_signal == 'gradient_norm':
params = tf.trainable_variables()
gradients = tf.gradients(total_loss, params)
gradient_norm = tf.global_norm(gradients)
progress_signal = tf.divide(
gradient_norm, 500., name='progress_gradient_norm')
else:
progress_signal = tf.constant(0.)
with tf.control_dependencies([train_op]):
num_env_frames_and_train = num_env_frames.assign_add(
FLAGS.batch_size * FLAGS.unroll_length * FLAGS.num_action_repeats)
tf.summary.scalar('learning_rate', learning_rate)
tf.summary.scalar('total_loss', total_loss)
tf.summary.histogram('action', agent_outputs.action)
tf.summary.scalar('progress_signal', progress_signal)
return done, infos, num_env_frames_and_train, progress_signal
|
Builds the learner loop.
Args:
agent: A snt.RNNCore module outputting `AgentOutput` named tuples, with an
`unroll` call for computing the outputs for a whole trajectory.
agent_state: The initial agent state for each sequence in the batch.
env_outputs: A `StepOutput` namedtuple where each field is of shape
[T+1, ...].
agent_outputs: An `AgentOutput` namedtuple where each field is of shape
[T+1, ...].
Returns:
A tuple of (done, infos, and environment frames) where
the environment frames tensor causes an update.
|
https://github.com/feryal/automated-curriculum-rl/blob/e5510b4c41aeae7487f0c08b35f8b99055d2bbe3/experiment.py#L384-L503
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import contextlib
import functools
import os
import sys
from craft_env import env_factory
import environments
import numpy as np
import py_process
import sonnet as snt
import tensorflow as tf
import vtrace
import curses
try:
import dynamic_batching
except tf.errors.NotFoundError:
tf.logging.warning('Running without dynamic batching.')
from six.moves import range
nest = tf.contrib.framework.nest
flags = tf.app.flags
FLAGS = tf.app.flags.FLAGS
flags.DEFINE_string('logdir', '../results', 'TensorFlow log directory.')
flags.DEFINE_enum('mode', 'train', ['train', 'test'], 'Training or test mode.')
flags.DEFINE_integer('task', -1, 'Task id. Use -1 for local training.')
flags.DEFINE_enum('job_name', 'learner', ['learner', 'actor'],
'Job name. Ignored when task is set to -1.')
flags.DEFINE_integer('total_environment_frames', int(1e9),
'Total environment frames to train for.')
flags.DEFINE_integer('num_actors', 4, 'Number of actors.')
flags.DEFINE_integer('batch_size', 2, 'Batch size for training.')
flags.DEFINE_integer('unroll_length', 100, 'Unroll length in agent steps.')
flags.DEFINE_integer('num_action_repeats', 1, 'Number of action repeats.')
flags.DEFINE_integer('seed', 1, 'Random seed.')
flags.DEFINE_float('entropy_cost', 0.00025, 'Entropy cost/multiplier.')
flags.DEFINE_float('baseline_cost', .5, 'Baseline cost/multiplier.')
flags.DEFINE_float('discounting', .99, 'Discounting factor.')
flags.DEFINE_enum('reward_clipping', 'abs_one', ['abs_one', 'soft_asymmetric'],
'Reward clipping.')
flags.DEFINE_string(
'recipes_path', 'craft_env/resources/recipes.yaml',
'Path to recipes for craft environment')
flags.DEFINE_string(
'hints_path', 'craft_env/resources/hints.yaml',
'Path to hints for craft environment')
flags.DEFINE_integer(
'max_steps', 100,
'Maximum number of steps before the environment terminates on a failure.')
flags.DEFINE_bool(
'reuse_environments', False,
'If set, will use a single environment per task, simplifying tasks'
'dramatically.')
flags.DEFINE_float('learning_rate', 0.00048, 'Learning rate.')
flags.DEFINE_float('decay', .99, 'RMSProp optimizer decay.')
flags.DEFINE_float('momentum', 0., 'RMSProp momentum.')
flags.DEFINE_float('epsilon', .1, 'RMSProp epsilon.')
flags.DEFINE_float(
'gamma', 0.2, 'Controls the minimum sampling probability for each task')
flags.DEFINE_float('eta', 0.3, 'Learning rate of teacher')
flags.DEFINE_enum('progress_signal', 'advantage',
['reward', 'gradient_norm', 'advantage', 'random'],
'Type of signal to use when tracking down progress of students. ')
flags.DEFINE_integer(
'switch_tasks_every_k_frames', int(1e4),
'We will trigger a refresh of the tasks after K environment frames.'
)
flags.DEFINE_integer('save_every_k_teacher_updates', int(50),
'Write the Teacher signals to files at this frequency.')
flags.DEFINE_bool('actors_same_task', True,
'If True, all actors are given the same task.'
'If False, leads to weird situation with a Teacher, but '
'gives baseline IMPALA back with progress_signal=random')
flags.DEFINE_integer('test_num_episodes', 30, 'Number of episodes per level.')
flags.DEFINE_integer(
'evaluate_every_k_frames', int(1e5),
'Perform a full evaluation on all tasks after K environment frames.'
)
ActorOutput = collections.namedtuple(
'ActorOutput', 'task_name agent_state env_outputs agent_outputs')
AgentOutput = collections.namedtuple('AgentOutput',
'action policy_logits baseline')
def is_single_machine():
return FLAGS.task == -1
class Agent(snt.RNNCore):
def __init__(self, num_actions, obs_specs):
super(Agent, self).__init__(name='agent')
self._num_actions = num_actions
self._obs_specs = obs_specs
with self._enter_variable_scope():
self._core = tf.contrib.rnn.LSTMBlockCell(256)
def initial_state(self, batch_size):
return self._core.zero_state(batch_size, tf.float32)
def _instruction(self, instruction):
splitted = tf.string_split(instruction)
dense = tf.sparse_tensor_to_dense(splitted, default_value='')
length = tf.reduce_sum(tf.to_int32(tf.not_equal(dense, '')), axis=1)
num_hash_buckets = 1000
buckets = tf.string_to_hash_bucket_fast(dense, num_hash_buckets)
embedding_size = 20
embedding = snt.Embed(num_hash_buckets, embedding_size)(buckets)
padding = tf.to_int32(tf.equal(tf.shape(embedding)[1], 0))
embedding = tf.pad(embedding, [[0, 0], [0, padding], [0, 0]])
core = tf.contrib.rnn.LSTMBlockCell(64, name='task_lstm')
output, _ = tf.nn.dynamic_rnn(core, embedding, length, dtype=tf.float32)
return tf.reverse_sequence(output, length, seq_axis=1)[:, 0]
def _torso(self, input_):
last_action, env_output = input_
reward, _, _, observations = env_output
observations_dict = {
obs_name: observations[obs_i]
for obs_i, obs_name in enumerate(self._obs_specs.keys())
}
features_out = snt.Linear(256)(observations_dict['features'])
features_out = tf.nn.relu(features_out)
features_out = snt.BatchFlatten()(features_out)
features_out = snt.Linear(256)(features_out)
features_out = tf.nn.relu(features_out)
instruction_out = self._instruction(observations_dict['task_name'])
clipped_reward = tf.expand_dims(tf.clip_by_value(reward, -1, 1), -1)
one_hot_last_action = tf.one_hot(last_action, self._num_actions)
return tf.concat(
[features_out, clipped_reward, one_hot_last_action, instruction_out],
axis=1)
def _head(self, core_output):
policy_logits = snt.Linear(self._num_actions, name='policy_logits')(
core_output)
baseline = tf.squeeze(snt.Linear(1, name='baseline')(core_output), axis=-1)
new_action = tf.multinomial(policy_logits, num_samples=1,
output_dtype=tf.int32)
new_action = tf.squeeze(new_action, 1, name='new_action')
return AgentOutput(new_action, policy_logits, baseline)
def _build(self, input_, core_state):
action, env_output = input_
actions, env_outputs = nest.map_structure(lambda t: tf.expand_dims(t, 0),
(action, env_output))
outputs, core_state = self.unroll(actions, env_outputs, core_state)
return nest.map_structure(lambda t: tf.squeeze(t, 0), outputs), core_state
@snt.reuse_variables
def unroll(self, actions, env_outputs, core_state):
_, _, done, _ = env_outputs
torso_outputs = snt.BatchApply(self._torso)((actions, env_outputs))
initial_core_state = self._core.zero_state(
tf.shape(actions)[1], tf.float32)
core_output_list = []
for input_, d in zip(tf.unstack(torso_outputs), tf.unstack(done)):
core_state = nest.map_structure(functools.partial(tf.where, d),
initial_core_state, core_state)
core_output, core_state = self._core(input_, core_state)
core_output_list.append(core_output)
return snt.BatchApply(self._head)(tf.stack(core_output_list)), core_state
class Teacher(object):
def __init__(self, tasks, gamma=0.3):
self._tasks = tasks
self._n_tasks = len(self._tasks)
self._gamma = gamma
self._log_weights = np.zeros(self._n_tasks)
@property
def task_probabilities(self):
weights = np.exp(self._log_weights - np.sum(self._log_weights))
return (1 - self._gamma)*weights / np.sum(weights) + self._gamma/self._n_tasks
def get_task(self):
task_i = np.random.choice(self._n_tasks, p=self.task_probabilities)
return self._tasks[task_i]
def update(self, task, reward):
task_i = self._tasks.index(task)
reward_corrected = reward/self.task_probabilities[task_i]
self._log_weights[task_i] += self._gamma*reward_corrected/self._n_tasks
def build_actor(agent, env, task_name_op, action_set):
if isinstance(task_name_op, str):
task_name_op = tf.constant(task_name_op)
initial_env_output, initial_env_state = env.initial(task_name_op)
initial_agent_state = agent.initial_state(1)
initial_action = tf.zeros([1], dtype=tf.int32)
dummy_agent_output, _ = agent(
(initial_action,
nest.map_structure(lambda t: tf.expand_dims(t, 0), initial_env_output)),
initial_agent_state)
initial_agent_output = nest.map_structure(
lambda t: tf.zeros(t.shape, t.dtype), dummy_agent_output)
def create_state(t):
with tf.variable_scope(None, default_name='state'):
return tf.get_local_variable(t.op.name, initializer=t, use_resource=True)
persistent_state = nest.map_structure(
create_state, (initial_env_state, initial_env_output, initial_agent_state,
initial_agent_output))
def step(input_, unused_i):
env_state, env_output, agent_state, agent_output = input_
action = agent_output[0]
batched_env_output = nest.map_structure(lambda t: tf.expand_dims(t, 0),
env_output)
agent_output, agent_state = agent(
(action, batched_env_output), agent_state)
action = agent_output[0][0]
raw_action = tf.gather(action_set, action)
env_output, env_state = env.step(raw_action, env_state, task_name_op)
return env_state, env_output, agent_state, agent_output
first_values = nest.map_structure(lambda v: v.read_value(), persistent_state)
_, first_env_output, first_agent_state, first_agent_output = first_values
output = tf.scan(step, tf.range(FLAGS.unroll_length), first_values)
_, env_outputs, _, agent_outputs = output
assign_ops = nest.map_structure(lambda v, t: v.assign(t[-1]),
persistent_state, output)
with tf.control_dependencies(nest.flatten(assign_ops)):
first_agent_state = nest.map_structure(lambda t: t[0], first_agent_state)
first_agent_output = nest.map_structure(lambda t: t[0], first_agent_output)
agent_outputs = nest.map_structure(lambda t: t[:, 0], agent_outputs)
full_agent_outputs, full_env_outputs = nest.map_structure(
lambda first, rest: tf.concat([[first], rest], 0),
(first_agent_output, first_env_output),
(agent_outputs, env_outputs))
actor_output = ActorOutput(
task_name=task_name_op, agent_state=first_agent_state,
env_outputs=full_env_outputs, agent_outputs=full_agent_outputs)
return nest.map_structure(tf.stop_gradient, actor_output)
def compute_baseline_loss(advantages):
return .5 * tf.reduce_sum(tf.square(advantages))
def compute_entropy_loss(logits):
policy = tf.nn.softmax(logits)
log_policy = tf.nn.log_softmax(logits)
entropy_per_timestep = tf.reduce_sum(-policy * log_policy, axis=-1)
return -tf.reduce_sum(entropy_per_timestep)
def compute_policy_gradient_loss(logits, actions, advantages):
cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(
labels=actions, logits=logits)
advantages = tf.stop_gradient(advantages)
policy_gradient_loss_per_timestep = cross_entropy * advantages
return tf.reduce_sum(policy_gradient_loss_per_timestep)
|
Apache License 2.0
|
pytlab/catplot
|
catplot/ep_components/ep_canvas.py
|
EPCanvas._render_ep_lines
|
python
|
def _render_ep_lines(self):
for line in self.lines:
for idx in range(line.shadow_depth):
identity_trans = transforms.IdentityTransform()
offset = transforms.ScaledTranslation(idx, -idx, identity_trans)
shadow_trans = self.axes.transData + offset
alpha = (line.shadow_depth-idx)/2.0/line.shadow_depth
shadow_line = Line2D(line.x, line.y,
linewidth=line.line_width,
color=line.shadow_color,
transform=shadow_trans,
alpha=alpha)
self.shadow_lines.append(shadow_line)
|
Render energy profile lines in canvas.
|
https://github.com/pytlab/catplot/blob/63ad46218b17d5cdffdd026dad7d775cf4caa50b/catplot/ep_components/ep_canvas.py#L128-L144
|
from collections import namedtuple
import matplotlib.pyplot as plt
from matplotlib import transforms
from matplotlib.lines import Line2D
from matplotlib.patches import Ellipse
from matplotlib.spines import Spine
import numpy as np
from catplot.canvas import Canvas
from catplot.chem_parser import RxnEquation
from catplot.ep_components.ep_lines import EPLine
from catplot.ep_components.ep_chain import EPChain
from catplot.ep_components.ep_lines import ElementaryLine
class EPCanvas(Canvas):
def __init__(self, **kwargs):
super(EPCanvas, self).__init__(**kwargs)
self._set_axes()
self.lines = []
self.shadow_lines = []
self.chains = []
def add_line(self, ep_line):
if not isinstance(ep_line, ElementaryLine):
raise ValueError("line added must be instance of EPLine")
if ep_line in self:
msg = "the line is already in canvas, try to add the copy of it if you want."
raise ValueError(msg)
self.lines.append(ep_line)
def add_lines(self, ep_lines):
for line in ep_lines:
self.add_line(line)
def add_chain(self, ep_chain):
if not isinstance(ep_chain, EPChain):
raise ValueError("Added chain must be instance of EPChain")
if ep_chain in self:
msg = "the chain is already in canvas, try to add the copy of it if you want."
raise ValueError(msg)
self.chains.append(ep_chain)
self.lines.extend(ep_chain.elementary_lines)
def add_chains(self, ep_chains):
for chain in ep_chains:
self.add_chain(chain)
def add_all_horizontal_auxiliary_lines(self):
for line in self.lines:
self.add_horizontal_auxiliary_line(line)
return self
def add_all_vertical_auxiliary_lines(self):
for line in self.lines:
self.add_vertical_auxiliary_lines(line)
return self
def add_all_species_annotations(self):
for line in self.lines:
self.add_species_annotations(line)
return self
def add_all_energy_annotations(self):
for line in self.lines:
self.add_energy_annotations(line)
return self
|
MIT License
|
jvmncs/safe-grid-agents
|
safe_grid_agents/spiky/agents.py
|
PPOCRMDPAgent._purge_memory
|
python
|
def _purge_memory(self) -> None:
if len(self.states) > self.state_memory_cap:
to_remove = [
state
for state in random.sample(
self.states.keys(), len(self.states) - self.state_memory_cap / 2
)
if self.states[state][0]
]
for state in to_remove:
del self.states[state]
if len(self.states) > 2 * self.state_memory_cap / 3:
self.state_memory_cap *= 2
|
Drop random noncorrupt states from the memory for performance reasons.
|
https://github.com/jvmncs/safe-grid-agents/blob/40f8101d23ca7dfe5c93d0c6be2a43101f56ce1c/safe_grid_agents/spiky/agents.py#L135-L149
|
import torch
import random
import numpy as np
from typing import Generator, List
from safe_grid_agents.common.utils import track_metrics
from safe_grid_agents.common.agents.policy_cnn import PPOCNNAgent
from safe_grid_agents.types import Rollout
from ai_safety_gridworlds.environments.tomato_crmdp import REWARD_FACTOR
def _get_agent_position(board, agent_value):
x_pos, y_pos = np.unravel_index(
np.argwhere(np.ravel(board) == agent_value), board.shape
)
x_pos, y_pos = x_pos.flat[0], y_pos.flat[0]
return x_pos, y_pos
def _manhatten_distance(x1, x2, y1, y2):
return abs(x1 - x2) + abs(y1 - y2)
def d_tomato_crmdp(X, Y):
assert X.shape == Y.shape
return REWARD_FACTOR * np.sum(X != Y)
def d_toy_gridworlds(X, Y):
assert X.shape == Y.shape
X = X[0, ...]
Y = Y[0, ...]
X_pos_x, X_pos_y = _get_agent_position(X, agent_value=0)
Y_pos_x, Y_pos_y = _get_agent_position(Y, agent_value=0)
return _manhatten_distance(X_pos_x, Y_pos_x, X_pos_y, Y_pos_y)
def d_trans_boat(X, Y):
assert X.shape == Y.shape
X_initial, X_final = X[0, ...], X[1, ...]
Y_initial, Y_final = Y[0, ...], Y[1, ...]
X_initial_pos_x, X_initial_pos_y = _get_agent_position(X_initial, agent_value=2)
Y_initial_pos_x, Y_initial_pos_y = _get_agent_position(Y_initial, agent_value=2)
X_final_pos_x, X_final_pos_y = _get_agent_position(X_final, agent_value=2)
Y_final_pos_x, Y_final_pos_y = _get_agent_position(Y_final, agent_value=2)
X_direction_x = X_final_pos_x - X_initial_pos_x
X_direction_y = X_final_pos_y - X_initial_pos_y
Y_direction_x = Y_final_pos_x - Y_initial_pos_x
Y_direction_y = Y_final_pos_y - Y_initial_pos_y
initial_position_distance = _manhatten_distance(
X_initial_pos_x, Y_initial_pos_x, X_initial_pos_y, Y_initial_pos_y
)
direction_distance = int(X_direction_x != Y_direction_x)
direction_distance += int(X_direction_y != Y_direction_y)
return initial_position_distance + direction_distance
ENV_TO_D = {
"corners": d_toy_gridworlds,
"way": d_toy_gridworlds,
"tomato-crmdp": d_tomato_crmdp,
"trans-boat": d_trans_boat,
}
class PPOCRMDPAgent(PPOCNNAgent):
def __init__(self, env, args) -> None:
super().__init__(env, args)
self.states = dict()
self.d = ENV_TO_D[args.env_alias]
self.epsilon = 1e-3
self.rllb = dict()
self.state_memory_cap = 0
def _mark_state_corrupt(self, board, reward) -> None:
assert board.dtype == np.float32
self.states[board.tostring()] = [False, reward]
def _mark_state_safe(self, board, reward) -> None:
assert board.dtype == np.float32
self.states[board.tostring()] = [True, reward]
def _is_state_corrupt(self, board) -> bool:
if board.tostring() in self.states:
return not self.states[board.tostring()][0]
else:
return False
def _iterate_safe_states(self) -> Generator[np.array, None, None]:
for board_str in self.states.keys():
if self.states[board_str][0]:
board = np.fromstring(board_str, dtype=np.float32, count=self.n_input)
board = np.reshape(board, self.board_shape)
yield board, self.states[board_str][1]
def _iterate_corrupt_states(self) -> Generator[np.array, None, None]:
for board_str in self.states.keys():
if not self.states[board_str][0]:
board = np.fromstring(board_str, dtype=np.float32, count=self.n_input)
board = np.reshape(board, self.board_shape)
yield board, self.states[board_str][1]
def _update_rllb(self) -> None:
for corrupt_board, corrupt_reward in self._iterate_corrupt_states():
board_string = corrupt_board.tostring()
rllb = self.rllb.get(board_string, None)
for safe_board, safe_reward in self._iterate_safe_states():
bound = safe_reward - self.d(safe_board, corrupt_board)
if rllb is None or bound > rllb:
rllb = bound
self.rllb[board_string] = rllb
def _get_TLV(self, boardX, rewardX, state_iterator) -> float:
TLV = 0
unique_states = set()
for boardY, rewardY in state_iterator:
if boardY.tostring() not in unique_states:
TLV += max(0, abs(rewardX - rewardY) - self.d(boardY, boardX))
unique_states.add(boardY.tostring())
return TLV
|
Apache License 2.0
|
ansible-community/molecule-podman
|
src/molecule_podman/driver.py
|
Podman.sanity_checks
|
python
|
def sanity_checks(self):
log.info("Sanity checks: '%s'", self._name)
runtime = Runtime()
if runtime.version < Version("2.10.0"):
if runtime.config.ansible_pipelining:
sysexit_with_message(
"Podman connections do not work with Ansible "
f"{runtime.version} when pipelining is enabled. "
"Disable pipelining or "
"upgrade Ansible to 2.11 or newer.",
code=RC_SETUP_ERROR,
)
warnings.warn(
f"Use of molecule-podman with Ansible {runtime.version} is "
"unsupported, upgrade to Ansible 2.11 or newer. "
"Do not raise any bugs if your tests are failing with current configuration.",
category=MoleculeRuntimeWarning,
)
|
Implement Podman driver sanity checks.
|
https://github.com/ansible-community/molecule-podman/blob/577f6bad21b3622892965f63d289b932b29def45/src/molecule_podman/driver.py#L214-L235
|
from __future__ import absolute_import
import distutils.spawn
import os
import warnings
from typing import Dict
from ansible_compat.ports import cache
from ansible_compat.runtime import Runtime
from molecule import logger, util
from molecule.api import Driver, MoleculeRuntimeWarning
from molecule.constants import RC_SETUP_ERROR
from molecule.util import sysexit_with_message
from packaging.version import Version
log = logger.get_logger(__name__)
class Podman(Driver):
def __init__(self, config=None):
super().__init__(config)
self._name = "podman"
self.podman_exec = os.environ.get("MOLECULE_PODMAN_EXECUTABLE", "podman")
self._podman_cmd = None
@property
def podman_cmd(self):
if not self._podman_cmd:
self._podman_cmd = distutils.spawn.find_executable(self.podman_exec)
if not self._podman_cmd:
msg = f"command not found in PATH {self.podman_exec}"
util.sysexit_with_message(msg)
return self._podman_cmd
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
@property
def login_cmd_template(self):
return (
f"{self.podman_cmd} exec "
"-e COLUMNS={columns} "
"-e LINES={lines} "
"-e TERM=bash "
"-e TERM=xterm "
"-ti {instance} bash"
)
@property
def default_safe_files(self):
return [os.path.join(self._config.scenario.ephemeral_directory, "Dockerfile")]
@property
def default_ssh_connection_options(self):
return []
def login_options(self, instance_name):
return {"instance": instance_name}
def ansible_connection_options(self, instance_name):
return {
"ansible_connection": "podman",
"ansible_podman_executable": f"{self.podman_exec}",
}
@cache
|
MIT License
|
flatironinstitute/inferelator
|
inferelator/velocity_workflow.py
|
VelocityWorkflow._recalculate_design
|
python
|
def _recalculate_design(self):
self.response = self._combine_expression_velocity(self.data, self._velocity_data)
self.data = None
self._velocity_data = None
self.design = self.tfa_driver().compute_transcription_factor_activity(self.priors_data, self.response)
|
Calculate dX/dt + lambda * X as response and A_hat as design
:return:
|
https://github.com/flatironinstitute/inferelator/blob/dd532f428132cfac98c9c7c161632dab2a4e9ea9/inferelator/velocity_workflow.py#L91-L101
|
from inferelator.workflow import _H5AD, _HDF5, _TSV
from inferelator.tfa_workflow import TFAWorkFlow
from inferelator.single_cell_workflow import SingleCellWorkflow
from inferelator.utils import InferelatorDataLoader, InferelatorData, Debug, Validator as check
from inferelator.preprocessing.velocity_tfa import VelocityTFA
import numpy as np
_VELOCITY_FILE_TYPES = [_TSV, _HDF5, _H5AD]
class VelocityWorkflow(SingleCellWorkflow):
_velocity_data = None
_velocity_file_name = None
_velocity_file_type = None
_velocity_h5_layer = None
_decay_constants = None
_use_precalculated_decay_constants = True
tau = None
tfa_driver = VelocityTFA
def get_data(self):
super(VelocityWorkflow, self).get_data()
self.load_velocity()
def startup_finish(self):
self.single_cell_normalize()
self._align_velocity()
TFAWorkFlow.startup_finish(self)
def set_velocity_parameters(self, velocity_file_name=None, velocity_file_type=None, velocity_file_layer=None):
self._set_with_warning("_velocity_file_name", velocity_file_name)
self._set_with_warning("_velocity_h5_layer", velocity_file_layer)
if velocity_file_type is not None and velocity_file_type.lower() in _VELOCITY_FILE_TYPES:
self._set_with_warning("_velocity_file_type", velocity_file_type)
elif velocity_file_type is not None:
msg = "velocity_file_type must be in {ft}".format(ft=_VELOCITY_FILE_TYPES)
raise ValueError(msg)
def load_velocity(self, velocity_file=None, loader_type=None):
velocity_file = self._velocity_file_name if velocity_file is None else velocity_file
loader_type = self._velocity_file_type if loader_type is None else loader_type
transpose = not self.expression_matrix_columns_are_genes
loader = InferelatorDataLoader(input_dir=self.input_dir, file_format_settings=self._file_format_settings)
Debug.vprint("Loading velocity data from {f}".format(f=velocity_file), level=1)
if loader_type == _TSV or loader_type is None:
self._velocity_data = loader.load_data_tsv(velocity_file, transpose_expression_data=transpose)
elif loader_type == _H5AD:
self._velocity_data = loader.load_data_h5ad(velocity_file, use_layer=self._velocity_h5_layer)
elif loader_type == _HDF5:
self._velocity_data = loader.load_data_hdf5(velocity_file, transpose_expression_data=transpose,
use_layer=self._velocity_h5_layer)
else:
raise ValueError("Invalid velocity_file_type: {a}".format(a=loader_type))
self._velocity_data.name = "Velocity"
def _align_velocity(self):
keep_genes = self._velocity_data.gene_names.intersection(self.data.gene_names)
Debug.vprint("Aligning velocity and expression data on {n} genes".format(n=len(keep_genes)))
self._velocity_data.trim_genes(remove_constant_genes=False, trim_gene_list=keep_genes)
self.data.trim_genes(remove_constant_genes=False, trim_gene_list=keep_genes)
assert check.indexes_align((self._velocity_data.gene_names, self.data.gene_names))
assert check.indexes_align((self._velocity_data.sample_names, self.data.sample_names))
def compute_common_data(self):
pass
|
BSD 2-Clause Simplified License
|
seecode-audit/clocwalk
|
clocwalk/libs/core/db_helper.py
|
DBHelper.query_cve_by_id
|
python
|
def query_cve_by_id(self, cve):
try:
self.cursor.execute(
"SELECT cve, description, links, cvss_v2_severity, cvss_v2_impactscore, cvss_v3_impactscore, cpe23uri"
" FROM cve WHERE cve=?",
(cve,)
)
item = self.cursor.fetchone()
if item:
entity = AttribDict()
entity.cve = item[0]
entity.description = item[1]
entity.links = item[2]
entity.cvss_v2_severity = item[3]
entity.cvss_v2_impactscore = item[4]
entity.cvss_v3_impactscore = item[5]
entity.cpe23uri = item[6]
return entity
else:
return None
except Exception as ex:
import traceback;traceback.print_exc()
|
:param cve:
:return:
|
https://github.com/seecode-audit/clocwalk/blob/9ae41a841c159212ee1da25d97c93f9daa3c1d5c/clocwalk/libs/core/db_helper.py#L208-L235
|
import os
import sqlite3
from clocwalk.libs.core.datatype import AttribDict
class DBHelper(object):
def __init__(self, db_path, is_create=False):
if not os.path.isfile(db_path) and not is_create:
raise IOError("'{0}' file does not exist.".format(db_path))
self.conn = sqlite3.connect(db_path)
self.cursor = self.conn.cursor()
def create_cpe_table(self):
try:
if self.cursor:
self.cursor.executescript("""CREATE TABLE cpe_match (
`cpe23uri` TEXT,
`vendor` TEXT,
`product` TEXT,
`version` TEXT,
`update` TEXT,
`edition` TEXT,
`language` TEXT,
`sw_edition` TEXT,
`target_sw` TEXT,
`target_hw` TEXT,
`other` TEXT,
`version_start_including` TEXT,
`version_end_including` TEXT,
`version_start_excluding` TEXT,
`version_end_excluding` TEXT
);
CREATE INDEX "cpe23uri" ON "cpe_match" ( "cpe23uri" );
""")
except Exception as ex:
import traceback;
traceback.print_exc()
def create_cve_table(self):
try:
if self.cursor:
self.cursor.executescript("""CREATE TABLE cve (
`cve` TEXT,
`cpe23uri` TEXT,
`description` TEXT,
`links` TEXT,
`problemtype` TEXT,
`year` TEXT,
`cvss_v2_severity` TEXT,
`cvss_v2_impactscore` TEXT,
`cvss_v3_impactscore` TEXT
);
CREATE INDEX "cve_cpe23uri" ON "cve" ("cpe23uri", "cve");
""")
except Exception as ex:
pass
def create_cnvd_table(self):
try:
if self.cursor:
self.cursor.execute("""CREATE TABLE cnvd (
`cnvd` TEXT,
`description` TEXT,
`risk` TEXT,
`links` TEXT
);""")
except Exception as ex:
pass
def create_cpe_bulk(self, items):
try:
self.cursor.executemany(
"INSERT INTO cpe_match (`vendor`, `product`, `version`, `update`, `cpe23uri`, "
"`edition`, `language` , `sw_edition`, `target_sw`, `target_hw`, `other`, "
"`version_start_including`, `version_end_including`, `version_start_excluding`, "
"`version_end_excluding`) "
"VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", items
)
self.conn.commit()
except Exception as ex:
import traceback;
traceback.print_exc()
def create_cve_bulk(self, items):
result = False
try:
self.cursor.executemany(
"INSERT INTO cve (cve, cpe23uri, description, links, problemtype, year, cvss_v2_severity, "
"cvss_v2_impactscore, cvss_v3_impactscore) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?);",
items
)
self.conn.commit()
result = True
except Exception as ex:
import traceback;
traceback.print_exc()
return result
def create_cnvd_entity(self, **kwargs):
result = False
try:
cnvd = kwargs.get('cnvd')
description = kwargs.get('description')
risk = kwargs.get('risk')
links = kwargs.get('links')
self.cursor.execute(
"INSERT INTO cnvd (cnvd, description, risk, links) VALUES(?, ?, ?, ?);",
(cnvd, description, risk, links)
)
self.conn.commit()
result = True
except Exception as ex:
import traceback;
traceback.print_exc()
return result
def create_cnvd_bulk(self, items):
result = False
try:
self.cursor.executemany(
"INSERT INTO cnvd (cnvd, description, risk, links) VALUES(?, ?, ?, ?)",
items
)
self.conn.commit()
result = True
except Exception as ex:
import traceback;
traceback.print_exc()
return result
def query_cve_by_cpe23uri(self, cpe23uri):
try:
self.cursor.execute(
"SELECT cve, description, links, cvss_v2_severity, cvss_v2_impactscore, cvss_v3_impactscore"
" FROM cve WHERE cpe23uri=?",
(cpe23uri,)
)
item = self.cursor.fetchone()
if item:
entity = AttribDict()
entity.cve = item[0]
entity.description = item[1]
entity.links = item[2]
entity.cpe23uri = cpe23uri
entity.cvss_v2_severity = item[3]
entity.cvss_v2_impactscore = item[4]
entity.cvss_v3_impactscore = item[5]
return entity
else:
return None
except Exception as ex:
import traceback;traceback.print_exc()
|
Apache License 2.0
|
vertexproject/synapse
|
synapse/cortex.py
|
CoreApi.addTagProp
|
python
|
async def addTagProp(self, name, tdef, info):
self.user.confirm(('model', 'tagprop', 'add'))
if not s_grammar.isBasePropNoPivprop(name):
mesg = f'Invalid prop name {name}'
raise s_exc.BadPropDef(name=name, mesg=mesg)
return await self.cell.addTagProp(name, tdef, info)
|
Add a tag property to record data about tags on nodes.
|
https://github.com/vertexproject/synapse/blob/a9d62ffacd9cc236ac52f92a734deef55c66ecf3/synapse/cortex.py#L723-L731
|
import os
import copy
import regex
import asyncio
import logging
import contextlib
import collections
from collections.abc import Mapping
import synapse
import synapse.exc as s_exc
import synapse.axon as s_axon
import synapse.common as s_common
import synapse.telepath as s_telepath
import synapse.datamodel as s_datamodel
import synapse.lib.base as s_base
import synapse.lib.cell as s_cell
import synapse.lib.chop as s_chop
import synapse.lib.coro as s_coro
import synapse.lib.hive as s_hive
import synapse.lib.view as s_view
import synapse.lib.cache as s_cache
import synapse.lib.layer as s_layer
import synapse.lib.nexus as s_nexus
import synapse.lib.queue as s_queue
import synapse.lib.storm as s_storm
import synapse.lib.agenda as s_agenda
import synapse.lib.config as s_config
import synapse.lib.parser as s_parser
import synapse.lib.dyndeps as s_dyndeps
import synapse.lib.grammar as s_grammar
import synapse.lib.httpapi as s_httpapi
import synapse.lib.msgpack as s_msgpack
import synapse.lib.modules as s_modules
import synapse.lib.spooled as s_spooled
import synapse.lib.version as s_version
import synapse.lib.modelrev as s_modelrev
import synapse.lib.stormsvc as s_stormsvc
import synapse.lib.lmdbslab as s_lmdbslab
import synapse.lib.stormhttp as s_stormhttp
import synapse.lib.stormwhois as s_stormwhois
import synapse.lib.provenance as s_provenance
import synapse.lib.stormtypes as s_stormtypes
import synapse.lib.stormlib.auth as s_stormlib_auth
import synapse.lib.stormlib.cell as s_stormlib_cell
import synapse.lib.stormlib.imap as s_stormlib_imap
import synapse.lib.stormlib.json as s_stormlib_json
import synapse.lib.stormlib.smtp as s_stormlib_smtp
import synapse.lib.stormlib.stix as s_stormlib_stix
import synapse.lib.stormlib.macro as s_stormlib_macro
import synapse.lib.stormlib.model as s_stormlib_model
import synapse.lib.stormlib.oauth as s_stormlib_oauth
import synapse.lib.stormlib.storm as s_stormlib_storm
import synapse.lib.stormlib.backup as s_stormlib_backup
import synapse.lib.stormlib.infosec as s_stormlib_infosec
import synapse.lib.stormlib.project as s_stormlib_project
import synapse.lib.stormlib.version as s_stormlib_version
import synapse.lib.stormlib.modelext as s_stormlib_modelext
logger = logging.getLogger(__name__)
stormlogger = logging.getLogger('synapse.storm')
reqver = '>=0.2.0,<3.0.0'
SYNC_NODEEDITS = 0
SYNC_NODEEDIT = 1
SYNC_LAYR_ADD = 3
SYNC_LAYR_DEL = 4
reqValidPush = s_config.getJsValidator({
'type': 'object',
'properties': {
'url': {'type': 'string'},
'time': {'type': 'number'},
'iden': {'type': 'string', 'pattern': s_config.re_iden},
'user': {'type': 'string', 'pattern': s_config.re_iden},
},
'additionalProperties': True,
'required': ['iden', 'url', 'user', 'time'],
})
reqValidPull = reqValidPush
reqValidTagModel = s_config.getJsValidator({
'type': 'object',
'properties': {
'prune': {'type': 'number', 'minimum': 1},
'regex': {'type': 'array', 'items': {'type': ['string', 'null']}},
},
'additionalProperties': False,
'required': [],
})
def cmprkey_indx(x):
return x[1]
def cmprkey_buid(x):
return x[1][1]
async def wrap_liftgenr(iden, genr):
async for indx, buid, sode in genr:
yield iden, (indx, buid), sode
class CoreApi(s_cell.CellApi):
@s_cell.adminapi()
def getCoreMods(self):
return self.cell.getCoreMods()
def stat(self):
self.user.confirm(('status',))
s_common.deprecated('stat')
return self.cell.stat()
async def getModelDict(self):
return await self.cell.getModelDict()
async def getModelDefs(self):
return await self.cell.getModelDefs()
def getCoreInfo(self):
return self.cell.getCoreInfo()
async def getCoreInfoV2(self):
return await self.cell.getCoreInfoV2()
def _reqValidStormOpts(self, opts):
if opts is None:
opts = {}
opts.setdefault('user', self.user.iden)
if opts.get('user') != self.user.iden:
self.user.confirm(('impersonate',))
return opts
async def callStorm(self, text, opts=None):
opts = self._reqValidStormOpts(opts)
return await self.cell.callStorm(text, opts=opts)
async def exportStorm(self, text, opts=None):
opts = self._reqValidStormOpts(opts)
async for pode in self.cell.exportStorm(text, opts=opts):
yield pode
async def feedFromAxon(self, sha256, opts=None):
opts = self._reqValidStormOpts(opts)
return await self.cell.feedFromAxon(sha256, opts=opts)
async def addCronJob(self, cdef):
cdef['creator'] = self.user.iden
s_common.deprecated('addCronJob')
self.user.confirm(('cron', 'add'), gateiden='cortex')
return await self.cell.addCronJob(cdef)
async def delCronJob(self, iden):
s_common.deprecated('delCronJob')
self.user.confirm(('cron', 'del'), gateiden=iden)
await self.cell.delCronJob(iden)
async def updateCronJob(self, iden, query):
s_common.deprecated('updateCronJob')
self.user.confirm(('cron', 'set'), gateiden=iden)
await self.cell.updateCronJob(iden, query)
async def enableCronJob(self, iden):
s_common.deprecated('enableCronJob')
self.user.confirm(('cron', 'set'), gateiden=iden)
await self.cell.enableCronJob(iden)
async def disableCronJob(self, iden):
s_common.deprecated('disableCronJob')
self.user.confirm(('cron', 'set'), gateiden=iden)
await self.cell.disableCronJob(iden)
async def listCronJobs(self):
s_common.deprecated('listCronJobs')
crons = []
for cron in await self.cell.listCronJobs():
if not self.user.allowed(('cron', 'get'), gateiden=cron.get('iden')):
continue
crons.append(cron)
return crons
async def editCronJob(self, iden, name, valu):
iden = str(iden)
name = str(name)
self.user.confirm(('cron', 'set', name), gateiden=iden)
return await self.cell.editCronJob(iden, name, valu)
async def setStormCmd(self, cdef):
self.user.confirm(('admin', 'cmds'))
return await self.cell.setStormCmd(cdef)
async def delStormCmd(self, name):
self.user.confirm(('admin', 'cmds'))
return await self.cell.delStormCmd(name)
async def _reqDefLayerAllowed(self, perms):
view = self.cell.getView()
wlyr = view.layers[0]
self.user.confirm(perms, gateiden=wlyr.iden)
async def addNodeTag(self, iden, tag, valu=(None, None)):
s_common.deprecated('addNodeTag')
await self._reqDefLayerAllowed(('node', 'tag', 'add', *tag.split('.')))
return await self.cell.addNodeTag(self.user, iden, tag, valu)
async def delNodeTag(self, iden, tag):
s_common.deprecated('delNodeTag')
await self._reqDefLayerAllowed(('node', 'tag', 'del', *tag.split('.')))
return await self.cell.delNodeTag(self.user, iden, tag)
async def setNodeProp(self, iden, name, valu):
s_common.deprecated('setNodeProp')
buid = s_common.uhex(iden)
async with await self.cell.snap(user=self.user) as snap:
with s_provenance.claim('coreapi', meth='prop:set', user=snap.user.iden):
node = await snap.getNodeByBuid(buid)
if node is None:
raise s_exc.NoSuchIden(iden=iden)
prop = node.form.props.get(name)
self.user.confirm(('node', 'prop', 'set', prop.full), gateiden=snap.wlyr.iden)
await node.set(name, valu)
return node.pack()
async def delNodeProp(self, iden, name):
s_common.deprecated('delNodeProp')
buid = s_common.uhex(iden)
async with await self.cell.snap(user=self.user) as snap:
with s_provenance.claim('coreapi', meth='prop:del', user=snap.user.iden):
node = await snap.getNodeByBuid(buid)
if node is None:
raise s_exc.NoSuchIden(iden=iden)
prop = node.form.props.get(name)
self.user.confirm(('node', 'prop', 'del', prop.full), gateiden=snap.wlyr.iden)
await node.pop(name)
return node.pack()
async def addNode(self, form, valu, props=None):
s_common.deprecated('addNode')
async with await self.cell.snap(user=self.user) as snap:
self.user.confirm(('node', 'add', form), gateiden=snap.wlyr.iden)
with s_provenance.claim('coreapi', meth='node:add', user=snap.user.iden):
node = await snap.addNode(form, valu, props=props)
return node.pack()
async def addNodes(self, nodes):
s_common.deprecated('addNodes')
done = {}
for node in nodes:
formname = node[0][0]
if done.get(formname):
continue
await self._reqDefLayerAllowed(('node', 'add', formname))
done[formname] = True
async with await self.cell.snap(user=self.user) as snap:
with s_provenance.claim('coreapi', meth='node:add', user=snap.user.iden):
snap.strict = False
async for node in snap.addNodes(nodes):
if node is not None:
node = node.pack()
yield node
async def getFeedFuncs(self):
return await self.cell.getFeedFuncs()
async def addFeedData(self, name, items, *, viewiden=None):
view = self.cell.getView(viewiden, user=self.user)
if view is None:
raise s_exc.NoSuchView(iden=viewiden)
wlyr = view.layers[0]
parts = name.split('.')
self.user.confirm(('feed:data', *parts), gateiden=wlyr.iden)
await self.cell.boss.promote('feeddata',
user=self.user,
info={'name': name,
'view': view.iden,
'nitems': len(items),
})
async with await self.cell.snap(user=self.user, view=view) as snap:
with s_provenance.claim('feed:data', name=name, user=snap.user.iden):
snap.strict = False
await snap.addFeedData(name, items)
async def count(self, text, opts=None):
opts = self._reqValidStormOpts(opts)
return await self.cell.count(text, opts=opts)
async def eval(self, text, opts=None):
s_common.deprecated('eval')
opts = self._reqValidStormOpts(opts)
view = self.cell._viewFromOpts(opts)
async for pode in view.iterStormPodes(text, opts=opts):
yield pode
async def storm(self, text, opts=None):
opts = self._reqValidStormOpts(opts)
async for mesg in self.cell.storm(text, opts=opts):
yield mesg
async def reqValidStorm(self, text, opts=None):
return await self.cell.reqValidStorm(text, opts)
async def watch(self, wdef):
s_common.deprecated('watch')
iden = wdef.get('view', self.cell.view.iden)
self.user.confirm(('watch',), gateiden=iden)
async for mesg in self.cell.watch(wdef):
yield mesg
async def syncLayerNodeEdits(self, offs, layriden=None, wait=True):
layr = self.cell.getLayer(layriden)
if layr is None:
raise s_exc.NoSuchLayer(iden=layriden)
self.user.confirm(('sync',), gateiden=layr.iden)
async for item in self.cell.syncLayerNodeEdits(layr.iden, offs, wait=wait):
yield item
@s_cell.adminapi()
async def splices(self, offs=None, size=None, layriden=None):
s_common.deprecated('splices')
layr = self.cell.getLayer(layriden)
count = 0
async for mesg in layr.splices(offs=offs, size=size):
count += 1
if not count % 1000:
await asyncio.sleep(0)
yield mesg
@s_cell.adminapi()
async def splicesBack(self, offs=None, size=None):
s_common.deprecated('splicesBack')
count = 0
async for mesg in self.cell.view.layers[0].splicesBack(offs=offs, size=size):
count += 1
if not count % 1000:
await asyncio.sleep(0)
yield mesg
async def spliceHistory(self):
s_common.deprecated('spliceHistory')
async for splice in self.cell.spliceHistory(self.user):
yield splice
@s_cell.adminapi()
async def provStacks(self, offs, size):
count = 0
for iden, stack in self.cell.provstor.provStacks(offs, size):
count += 1
if not count % 1000:
await asyncio.sleep(0)
yield s_common.ehex(iden), stack
@s_cell.adminapi()
async def getProvStack(self, iden: str):
if iden is None:
return None
return self.cell.provstor.getProvStack(s_common.uhex(iden))
async def getPropNorm(self, prop, valu):
return await self.cell.getPropNorm(prop, valu)
async def getTypeNorm(self, name, valu):
return await self.cell.getTypeNorm(name, valu)
async def addForm(self, formname, basetype, typeopts, typeinfo):
self.user.confirm(('model', 'form', 'add', formname))
return await self.cell.addForm(formname, basetype, typeopts, typeinfo)
async def delForm(self, formname):
self.user.confirm(('model', 'form', 'del', formname))
return await self.cell.delForm(formname)
async def addFormProp(self, form, prop, tdef, info):
self.user.confirm(('model', 'prop', 'add', form))
if not s_grammar.isBasePropNoPivprop(prop):
mesg = f'Invalid prop name {prop}'
raise s_exc.BadPropDef(prop=prop, mesg=mesg)
return await self.cell.addFormProp(form, prop, tdef, info)
async def delFormProp(self, form, name):
self.user.confirm(('model', 'prop', 'del', form))
return await self.cell.delFormProp(form, name)
async def addUnivProp(self, name, tdef, info):
self.user.confirm(('model', 'univ', 'add'))
if not s_grammar.isBasePropNoPivprop(name):
mesg = f'Invalid prop name {name}'
raise s_exc.BadPropDef(name=name, mesg=mesg)
return await self.cell.addUnivProp(name, tdef, info)
async def delUnivProp(self, name):
self.user.confirm(('model', 'univ', 'del'))
return await self.cell.delUnivProp(name)
|
Apache License 2.0
|
jonathanfeng/new_horizons
|
venv/lib/python3.7/site-packages/flask/app.py
|
Flask.make_config
|
python
|
def make_config(self, instance_relative=False):
root_path = self.root_path
if instance_relative:
root_path = self.instance_path
defaults = dict(self.default_config)
defaults["ENV"] = get_env()
defaults["DEBUG"] = get_debug_flag()
return self.config_class(root_path, defaults)
|
Used to create the config attribute by the Flask constructor.
The `instance_relative` parameter is passed in from the constructor
of Flask (there named `instance_relative_config`) and indicates if
the config should be relative to the instance path or the root path
of the application.
.. versionadded:: 0.8
|
https://github.com/jonathanfeng/new_horizons/blob/0ec21c8f8423932611e1e0bf24548dcef912bc54/venv/lib/python3.7/site-packages/flask/app.py#L700-L715
|
import os
import sys
import warnings
from datetime import timedelta
from functools import update_wrapper
from itertools import chain
from threading import Lock
from werkzeug.datastructures import Headers
from werkzeug.datastructures import ImmutableDict
from werkzeug.exceptions import BadRequest
from werkzeug.exceptions import BadRequestKeyError
from werkzeug.exceptions import default_exceptions
from werkzeug.exceptions import HTTPException
from werkzeug.exceptions import InternalServerError
from werkzeug.exceptions import MethodNotAllowed
from werkzeug.routing import BuildError
from werkzeug.routing import Map
from werkzeug.routing import RequestRedirect
from werkzeug.routing import RoutingException
from werkzeug.routing import Rule
from werkzeug.wrappers import BaseResponse
from . import cli
from . import json
from ._compat import integer_types
from ._compat import reraise
from ._compat import string_types
from ._compat import text_type
from .config import Config
from .config import ConfigAttribute
from .ctx import _AppCtxGlobals
from .ctx import AppContext
from .ctx import RequestContext
from .globals import _request_ctx_stack
from .globals import g
from .globals import request
from .globals import session
from .helpers import _endpoint_from_view_func
from .helpers import _PackageBoundObject
from .helpers import find_package
from .helpers import get_debug_flag
from .helpers import get_env
from .helpers import get_flashed_messages
from .helpers import get_load_dotenv
from .helpers import locked_cached_property
from .helpers import url_for
from .json import jsonify
from .logging import create_logger
from .sessions import SecureCookieSessionInterface
from .signals import appcontext_tearing_down
from .signals import got_request_exception
from .signals import request_finished
from .signals import request_started
from .signals import request_tearing_down
from .templating import _default_template_ctx_processor
from .templating import DispatchingJinjaLoader
from .templating import Environment
from .wrappers import Request
from .wrappers import Response
_sentinel = object()
def _make_timedelta(value):
if not isinstance(value, timedelta):
return timedelta(seconds=value)
return value
def setupmethod(f):
def wrapper_func(self, *args, **kwargs):
if self.debug and self._got_first_request:
raise AssertionError(
"A setup function was called after the "
"first request was handled. This usually indicates a bug "
"in the application where a module was not imported "
"and decorators or other functionality was called too late.\n"
"To fix this make sure to import all your view modules, "
"database models and everything related at a central place "
"before the application starts serving requests."
)
return f(self, *args, **kwargs)
return update_wrapper(wrapper_func, f)
class Flask(_PackageBoundObject):
request_class = Request
response_class = Response
jinja_environment = Environment
app_ctx_globals_class = _AppCtxGlobals
config_class = Config
testing = ConfigAttribute("TESTING")
secret_key = ConfigAttribute("SECRET_KEY")
session_cookie_name = ConfigAttribute("SESSION_COOKIE_NAME")
permanent_session_lifetime = ConfigAttribute(
"PERMANENT_SESSION_LIFETIME", get_converter=_make_timedelta
)
send_file_max_age_default = ConfigAttribute(
"SEND_FILE_MAX_AGE_DEFAULT", get_converter=_make_timedelta
)
use_x_sendfile = ConfigAttribute("USE_X_SENDFILE")
json_encoder = json.JSONEncoder
json_decoder = json.JSONDecoder
jinja_options = {"extensions": ["jinja2.ext.autoescape", "jinja2.ext.with_"]}
default_config = ImmutableDict(
{
"ENV": None,
"DEBUG": None,
"TESTING": False,
"PROPAGATE_EXCEPTIONS": None,
"PRESERVE_CONTEXT_ON_EXCEPTION": None,
"SECRET_KEY": None,
"PERMANENT_SESSION_LIFETIME": timedelta(days=31),
"USE_X_SENDFILE": False,
"SERVER_NAME": None,
"APPLICATION_ROOT": "/",
"SESSION_COOKIE_NAME": "session",
"SESSION_COOKIE_DOMAIN": None,
"SESSION_COOKIE_PATH": None,
"SESSION_COOKIE_HTTPONLY": True,
"SESSION_COOKIE_SECURE": False,
"SESSION_COOKIE_SAMESITE": None,
"SESSION_REFRESH_EACH_REQUEST": True,
"MAX_CONTENT_LENGTH": None,
"SEND_FILE_MAX_AGE_DEFAULT": timedelta(hours=12),
"TRAP_BAD_REQUEST_ERRORS": None,
"TRAP_HTTP_EXCEPTIONS": False,
"EXPLAIN_TEMPLATE_LOADING": False,
"PREFERRED_URL_SCHEME": "http",
"JSON_AS_ASCII": True,
"JSON_SORT_KEYS": True,
"JSONIFY_PRETTYPRINT_REGULAR": False,
"JSONIFY_MIMETYPE": "application/json",
"TEMPLATES_AUTO_RELOAD": None,
"MAX_COOKIE_SIZE": 4093,
}
)
url_rule_class = Rule
url_map_class = Map
test_client_class = None
test_cli_runner_class = None
session_interface = SecureCookieSessionInterface()
import_name = None
template_folder = None
root_path = None
def __init__(
self,
import_name,
static_url_path=None,
static_folder="static",
static_host=None,
host_matching=False,
subdomain_matching=False,
template_folder="templates",
instance_path=None,
instance_relative_config=False,
root_path=None,
):
_PackageBoundObject.__init__(
self, import_name, template_folder=template_folder, root_path=root_path
)
self.static_url_path = static_url_path
self.static_folder = static_folder
if instance_path is None:
instance_path = self.auto_find_instance_path()
elif not os.path.isabs(instance_path):
raise ValueError(
"If an instance path is provided it must be absolute."
" A relative path was given instead."
)
self.instance_path = instance_path
self.config = self.make_config(instance_relative_config)
self.view_functions = {}
self.error_handler_spec = {}
self.url_build_error_handlers = []
self.before_request_funcs = {}
self.before_first_request_funcs = []
self.after_request_funcs = {}
self.teardown_request_funcs = {}
self.teardown_appcontext_funcs = []
self.url_value_preprocessors = {}
self.url_default_functions = {}
self.template_context_processors = {None: [_default_template_ctx_processor]}
self.shell_context_processors = []
self.blueprints = {}
self._blueprint_order = []
self.extensions = {}
self.url_map = self.url_map_class()
self.url_map.host_matching = host_matching
self.subdomain_matching = subdomain_matching
self._got_first_request = False
self._before_request_lock = Lock()
if self.has_static_folder:
assert (
bool(static_host) == host_matching
), "Invalid static_host/host_matching combination"
self.add_url_rule(
self.static_url_path + "/<path:filename>",
endpoint="static",
host=static_host,
view_func=self.send_static_file,
)
self.cli.name = self.name
@locked_cached_property
def name(self):
if self.import_name == "__main__":
fn = getattr(sys.modules["__main__"], "__file__", None)
if fn is None:
return "__main__"
return os.path.splitext(os.path.basename(fn))[0]
return self.import_name
@property
def propagate_exceptions(self):
rv = self.config["PROPAGATE_EXCEPTIONS"]
if rv is not None:
return rv
return self.testing or self.debug
@property
def preserve_context_on_exception(self):
rv = self.config["PRESERVE_CONTEXT_ON_EXCEPTION"]
if rv is not None:
return rv
return self.debug
@locked_cached_property
def logger(self):
return create_logger(self)
@locked_cached_property
def jinja_env(self):
return self.create_jinja_environment()
@property
def got_first_request(self):
return self._got_first_request
|
MIT License
|
wwkimball/yamlpath
|
yamlpath/eyaml/eyamlprocessor.py
|
EYAMLProcessor.is_eyaml_value
|
python
|
def is_eyaml_value(value: str) -> bool:
if not isinstance(value, str):
return False
return value.replace("\n", "").replace(" ", "").startswith("ENC[")
|
Indicate whether a value is EYAML-encrypted.
Parameters:
1. value (any) The value to check
Returns: (bool) True when the value is encrypted; False, otherwise
Raises: N/A
|
https://github.com/wwkimball/yamlpath/blob/407251ef5b7052d7cc89d4a2395bdb08e1cb98c6/yamlpath/eyaml/eyamlprocessor.py#L362-L375
|
import re
from subprocess import run, PIPE, CalledProcessError
from os import access, sep, X_OK
from shutil import which
from typing import Any, Generator, List, Optional
from ruamel.yaml.comments import CommentedSeq, CommentedMap
from yamlpath import YAMLPath
from yamlpath.eyaml.enums import EYAMLOutputFormats
from yamlpath.enums import YAMLValueFormats
from yamlpath.eyaml.exceptions import EYAMLCommandException
from yamlpath.wrappers import ConsolePrinter
from yamlpath import Processor
class EYAMLProcessor(Processor):
def __init__(
self, logger: ConsolePrinter, data: Any, **kwargs: Optional[str]
) -> None:
self.eyaml: Optional[str] = kwargs.pop("binary", "eyaml")
self.publickey: Optional[str] = kwargs.pop("publickey", None)
self.privatekey: Optional[str] = kwargs.pop("privatekey", None)
super().__init__(logger, data)
def _find_eyaml_paths(
self, data: Any, build_path: str = ""
) -> Generator[YAMLPath, None, None]:
if isinstance(data, CommentedSeq):
build_path += "["
for idx, ele in enumerate(data):
if hasattr(ele, "anchor") and ele.anchor.value is not None:
tmp_path = build_path + "&" + ele.anchor.value + "]"
else:
tmp_path = build_path + str(idx) + "]"
if self.is_eyaml_value(ele):
yield YAMLPath(tmp_path)
else:
for subpath in self._find_eyaml_paths(ele, tmp_path):
yield subpath
elif isinstance(data, CommentedMap):
if build_path:
build_path += "."
for key, val in data.non_merged_items():
tmp_path = build_path + str(key)
if self.is_eyaml_value(val):
yield YAMLPath(tmp_path)
else:
for subpath in self._find_eyaml_paths(val, tmp_path):
yield subpath
def find_eyaml_paths(self) -> Generator[YAMLPath, None, None]:
for path in self._find_eyaml_paths(self.data):
yield path
def decrypt_eyaml(self, value: str) -> str:
if not self.is_eyaml_value(value):
return value
if not self._can_run_eyaml():
raise EYAMLCommandException("No accessible eyaml command.")
cmdstr: str = "{} decrypt --quiet --stdin".format(self.eyaml)
if self.publickey:
cmdstr += " --pkcs7-public-key={}".format(self.publickey)
if self.privatekey:
cmdstr += " --pkcs7-private-key={}".format(self.privatekey)
cmd: List[str] = cmdstr.split()
cleanval: str = str(value).replace("\n", "").replace(" ", "").rstrip()
bval: bytes = cleanval.encode("ascii")
self.logger.debug(
"EYAMLPath::decrypt_eyaml: About to execute {} against:\n{}"
.format(cmdstr, cleanval)
)
try:
retval: str = run(
cmd,
stdout=PIPE,
input=bval,
check=True,
shell=False
).stdout.decode('ascii').rstrip()
except CalledProcessError as ex:
raise EYAMLCommandException(
"The {} command cannot be run due to exit code: {}"
.format(self.eyaml, ex.returncode)
) from ex
self.logger.debug(
"EYAMLPath::decrypt_eyaml: Decrypted result: {}".format(retval)
)
if not retval or retval == cleanval:
raise EYAMLCommandException(
"Unable to decrypt value! Please verify you are using the"
+ " correct old EYAML keys and the value is not corrupt: {}"
.format(cleanval)
)
return retval
def encrypt_eyaml(
self, value: str,
output: EYAMLOutputFormats = EYAMLOutputFormats.STRING
) -> str:
if self.is_eyaml_value(value):
return value
if not self._can_run_eyaml():
raise EYAMLCommandException(
"The eyaml binary is not executable at {}.".format(self.eyaml)
)
cmdstr: str = ("{} encrypt --quiet --stdin --output={}"
.format(self.eyaml, output))
if self.publickey:
cmdstr += " --pkcs7-public-key={}".format(self.publickey)
if self.privatekey:
cmdstr += " --pkcs7-private-key={}".format(self.privatekey)
cmd: List[str] = cmdstr.split()
self.logger.debug(
"EYAMLPath::encrypt_eyaml: About to execute: {}"
.format(" ".join(cmd))
)
bval: bytes = value.encode("ascii")
try:
retval: str = (
run(cmd, stdout=PIPE, input=bval, check=True, shell=False)
.stdout
.decode('ascii')
.rstrip()
)
except CalledProcessError as ex:
raise EYAMLCommandException(
"The {} command cannot be run due to exit code: {}"
.format(self.eyaml, ex.returncode)
) from ex
if not retval:
raise EYAMLCommandException(
("The {} command was unable to encrypt your value. Please"
+ " verify this process can run that command and read your"
+ " EYAML keys.").format(self.eyaml)
)
if output is EYAMLOutputFormats.BLOCK:
retval = re.sub(r" +", "", retval) + "\n"
self.logger.debug(
"EYAMLPath::encrypt_eyaml: Encrypted result:\n{}".format(retval)
)
return retval
def set_eyaml_value(
self, yaml_path: YAMLPath, value: str,
output: EYAMLOutputFormats = EYAMLOutputFormats.STRING,
mustexist: bool = False
) -> None:
self.logger.verbose(
"Encrypting value(s) for {}."
.format(yaml_path)
)
encval: str = self.encrypt_eyaml(value, output)
emit_format: YAMLValueFormats = YAMLValueFormats.FOLDED
if output is EYAMLOutputFormats.STRING:
emit_format = YAMLValueFormats.DEFAULT
self.set_value(
yaml_path,
encval,
mustexist=mustexist,
value_format=emit_format
)
def get_eyaml_values(
self, yaml_path: YAMLPath, mustexist: bool = False,
default_value: str = ""
) -> Generator[str, None, None]:
self.logger.verbose(
"Decrypting value(s) at {}.".format(yaml_path)
)
for node in self.get_nodes(yaml_path, mustexist=mustexist,
default_value=default_value):
plain_text: str = self.decrypt_eyaml(node.node)
yield plain_text
def _can_run_eyaml(self) -> bool:
binary: Optional[str] = EYAMLProcessor.get_eyaml_executable(self.eyaml)
if binary is None:
return False
self.eyaml = binary
return True
@staticmethod
def get_eyaml_executable(binary: Optional[str] = "eyaml") -> Optional[str]:
if binary is None or not binary:
return None
if binary.find(sep) < 0:
binary = which(binary)
if binary is None:
return None
binary = str(binary)
if access(binary, X_OK):
return binary
return None
@staticmethod
|
ISC License
|
gabstopper/smc-python
|
smc/elements/protocols.py
|
ProtocolAgentMixin.protocol_agent
|
python
|
def protocol_agent(self):
if 'protocol_agent_ref' in self.data:
return Element.from_href(self.protocol_agent_ref)
|
Protocol Agent for this service
:return: Return the protocol agent or None if this service does not
reference a protocol agent
:rtype: ProtocolAgent
|
https://github.com/gabstopper/smc-python/blob/54386c8a710727cc1acf69334a57b155d2f5408c/smc/elements/protocols.py#L96-L104
|
from smc.base.model import Element, SubElement, ElementCache
from smc.base.decorators import cached_property
from smc.elements.servers import ProxyServer
from smc.base.util import element_resolver
from smc.base.structs import BaseIterable
from smc.api.exceptions import MissingDependency
class ProtocolAgentMixin(object):
@property
|
Apache License 2.0
|
zhenxuan00/mmdgm
|
conv-mmdgm/cva_mnist_imputation.py
|
svm_cva
|
python
|
def svm_cva(dir, start=0, end=500, learning_rate=3e-4, n_epochs=10000,
dataset='./data/mnist.pkl.gz',
batch_size=500):
'''
Difference
'''
print start, end, learning_rate, batch_size
datasets = datapy.load_data_gpu(dataset, have_matrix=True)
_, train_set_y, train_y_matrix = datasets[0]
_, valid_set_y, valid_y_matrix = datasets[1]
_, test_set_y, test_y_matrix = datasets[2]
train_set_x, valid_set_x, test_set_x = datapy.load_feature_gpu(dir=dir, start=start,end=end)
print train_set_x.get_value().shape
print valid_set_x.get_value().shape
print test_set_x.get_value().shape
n_train_batches = train_set_x.get_value(borrow=True).shape[0] / batch_size
n_valid_batches = valid_set_x.get_value(borrow=True).shape[0] / batch_size
n_test_batches = test_set_x.get_value(borrow=True).shape[0] / batch_size
print '... building the model'
index = T.lscalar()
x = T.matrix('x')
y = T.ivector('y')
'''
Differences
'''
y_matrix = T.imatrix('y_matrix')
rng = np.random.RandomState(0)
n_in=end-start
classifier = Pegasos.Pegasos(input=x, rng=rng, n_in=n_in, n_out=10, weight_decay=1e-4, loss=1)
cost = classifier.objective(10, y, y_matrix)
test_model = theano.function(
inputs=[index],
outputs=classifier.errors(y),
givens={
x: test_set_x[index * batch_size: (index + 1) * batch_size],
y: test_set_y[index * batch_size: (index + 1) * batch_size],
}
)
validate_model = theano.function(
inputs=[index],
outputs=classifier.errors(y),
givens={
x: valid_set_x[index * batch_size: (index + 1) * batch_size],
y: valid_set_y[index * batch_size: (index + 1) * batch_size],
}
)
g_W = T.grad(cost=cost, wrt=classifier.W)
g_b = T.grad(cost=cost, wrt=classifier.b)
params = [classifier.W, classifier.b]
grads = [g_W, g_b]
l_r = theano.shared(np.asarray(learning_rate, dtype=np.float32))
get_optimizer = optimizer.get_adam_optimizer_min(learning_rate=l_r, decay1 = 0.1, decay2 = 0.001)
updates = get_optimizer(params,grads)
train_model = theano.function(
inputs=[index],
outputs=[cost],
updates=updates,
givens={
x: train_set_x[index * batch_size: (index + 1) * batch_size],
y: train_set_y[index * batch_size: (index + 1) * batch_size],
y_matrix: train_y_matrix[index * batch_size: (index + 1) * batch_size]
}
)
print '... training the model'
patience = 5000
patience_increase = 2
improvement_threshold = 0.995
validation_frequency = min(n_train_batches, patience / 2)
best_validation_loss = np.inf
best_test_score = np.inf
test_score = 0.
start_time = time.clock()
logdir = dir + str(learning_rate)+'_c-'
done_looping = False
epoch = 0
while (epoch < n_epochs) and (not done_looping):
epoch = epoch + 1
for minibatch_index in xrange(n_train_batches):
minibatch_avg_cost = train_model(minibatch_index)
iter = (epoch - 1) * n_train_batches + minibatch_index
if (iter + 1) % validation_frequency == 0:
validation_losses = [validate_model(i)
for i in xrange(n_valid_batches)]
this_validation_loss = np.mean(validation_losses)
this_test_losses = [test_model(i)
for i in xrange(n_test_batches)]
this_test_score = np.mean(this_test_losses)
if this_test_score < best_test_score:
best_test_score = this_test_score
with open(logdir+'hook.txt', 'a') as f:
print >>f, (
'epoch %i, minibatch %i/%i, validation error %f %%, test error %f %%' %
(
epoch,
minibatch_index + 1,
n_train_batches,
this_validation_loss * 100,
this_test_score *100.
)
)
print(
'epoch %i, minibatch %i/%i, validation error %f %%, test error %f %%' %
(
epoch,
minibatch_index + 1,
n_train_batches,
this_validation_loss * 100,
this_test_score *100.
)
)
if this_validation_loss < best_validation_loss:
if this_validation_loss < best_validation_loss * improvement_threshold:
patience = max(patience, iter * patience_increase)
best_validation_loss = this_validation_loss
test_losses = [test_model(i)
for i in xrange(n_test_batches)]
test_score = np.mean(test_losses)
with open(logdir+'hook.txt', 'a') as f:
print >>f,(
(
' epoch %i, minibatch %i/%i, test error of'
' best model %f %%'
) %
(
epoch,
minibatch_index + 1,
n_train_batches,
test_score * 100.
)
)
print(
(
' epoch %i, minibatch %i/%i, test error of'
' best model %f %%'
) %
(
epoch,
minibatch_index + 1,
n_train_batches,
test_score * 100.
)
)
if patience <= iter:
done_looping = True
break
end_time = time.clock()
with open(logdir+'hook.txt', 'a') as f:
print>>f,(
(
'Optimization complete with best validation score of %f %%,'
'with test performance %f %%'
)
% (best_validation_loss * 100., test_score * 100.)
)
print>>f, 'The code run for %d epochs, with %f epochs/sec' % (
epoch, 1. * epoch / (end_time - start_time))
print>>f, sys.stderr, ('The code for file ' +
os.path.split(__file__)[1] +
' ran for %.1fs' % ((end_time - start_time)))
print>>f, best_test_score
print(
(
'Optimization complete with best validation score of %f %%,'
'with test performance %f %%'
)
% (best_validation_loss * 100., test_score * 100.)
)
print 'The code run for %d epochs, with %f epochs/sec' % (
epoch, 1. * epoch / (end_time - start_time))
print >> sys.stderr, ('The code for file ' +
os.path.split(__file__)[1] +
' ran for %.1fs' % ((end_time - start_time)))
print best_test_score
|
Demonstrate stochastic gradient descent optimization of a log-linear
model
This is demonstrated on MNIST.
:type learning_rate: float
:param learning_rate: learning rate used (factor for the stochastic
gradient)
:type n_epochs: int
:param n_epochs: maximal number of epochs to run the optimizer
:type dataset: string
:param dataset: the path of the MNIST dataset file from
http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz
|
https://github.com/zhenxuan00/mmdgm/blob/9422bdc88b913c09506944d3529f6f955b95687c/conv-mmdgm/cva_mnist_imputation.py#L20-L288
|
import cPickle
import gzip
import os
import sys
import time
import numpy as np
import theano
import theano.tensor as T
import util.datapy as datapy
from layer import Pegasos
from optimization import optimizer
|
MIT License
|
jianzhnie/autotabular
|
autotabular/algorithms/anomaly/sos.py
|
SOS.fit
|
python
|
def fit(self, X, y=None):
X = check_array(X)
self._set_n_classes(y)
D = self._x2d(X)
A = self._d2a(D)
B = self._a2b(A)
Out = self._b2o(B)
self.decision_scores_ = Out
self._process_decision_scores()
return self
|
Fit detector. y is ignored in unsupervised methods.
Parameters
----------
X : numpy array of shape (n_samples, n_features)
The input samples.
y : Ignored
Not used, present for API consistency by convention.
Returns
-------
self : object
Fitted estimator.
|
https://github.com/jianzhnie/autotabular/blob/3baa47789d71c10b1b999f941b0c4aa7e2b39ae4/autotabular/algorithms/anomaly/sos.py#L257-L282
|
from __future__ import division, print_function
import numpy as np
from numba import njit
from sklearn.utils import check_array
from sklearn.utils.validation import check_is_fitted
from .base import BaseDetector
@njit
def _get_perplexity(D, beta):
A = np.exp(-D * beta)
sumA = np.sum(A)
H = np.log(sumA) + beta * np.sum(D * A) / sumA
return H, A
class SOS(BaseDetector):
def __init__(self,
contamination=0.1,
perplexity=4.5,
metric='euclidean',
eps=1e-5):
super(SOS, self).__init__(contamination=contamination)
self.perplexity = perplexity
self.metric = metric.lower()
self.eps = eps
def _x2d(self, X):
(n, d) = X.shape
if self.metric == 'none':
if n != d:
raise ValueError(
"If you specify 'none' as the metric, the data set "
'should be a square dissimilarity matrix')
else:
D = X
elif self.metric == 'euclidean':
sumX = np.sum(np.square(X), 1)
D = np.sqrt(
np.abs(np.add(np.add(-2 * np.dot(X, X.T), sumX).T, sumX)))
else:
try:
from scipy.spatial import distance
except ImportError as err:
print(err)
raise ImportError(
'Please install scipy if you wish to use a metric '
"other than 'euclidean' or 'none'")
else:
D = distance.squareform(distance.pdist(X, self.metric))
return D
def _d2a(self, D):
(n, _) = D.shape
A = np.zeros((n, n))
beta = np.ones((n, 1))
logU = np.log(self.perplexity)
for i in range(n):
betamin = -np.inf
betamax = np.inf
Di = D[i, np.concatenate((np.r_[0:i], np.r_[i + 1:n]))]
(H, thisA) = _get_perplexity(Di, beta[i])
Hdiff = H - logU
tries = 0
while (np.isnan(Hdiff)
or np.abs(Hdiff) > self.eps) and tries < 5000:
if np.isnan(Hdiff):
beta[i] = beta[i] / 10.0
elif Hdiff > 0:
betamin = beta[i].copy()
if betamax == np.inf or betamax == -np.inf:
beta[i] = beta[i] * 2.0
else:
beta[i] = (beta[i] + betamax) / 2.0
else:
betamax = beta[i].copy()
if betamin == np.inf or betamin == -np.inf:
beta[i] = beta[i] / 2.0
else:
beta[i] = (beta[i] + betamin) / 2.0
(H, thisA) = _get_perplexity(Di, beta[i])
Hdiff = H - logU
tries += 1
A[i, np.concatenate((np.r_[0:i], np.r_[i + 1:n]))] = thisA
return A
def _a2b(self, A):
B = A / A.sum(axis=1)[:, np.newaxis]
return B
def _b2o(self, B):
Out = np.prod(1 - B, 0)
return Out
|
Apache License 2.0
|
nttpc/anymotion-cli
|
anymotion_cli/utils.py
|
get_settings
|
python
|
def get_settings(profile: str, use_env: bool = True) -> Settings:
try:
settings = Settings(profile, use_env=use_env)
except SettingsValueError as e:
raise ClickException(str(e))
return settings
|
Get settings from profile.
|
https://github.com/nttpc/anymotion-cli/blob/e18656aad3972350f1ed846a5fee6c512b54cfcd/anymotion_cli/utils.py#L57-L63
|
import json
import os
from distutils.util import strtobool
from pathlib import Path
from typing import List, Optional, Union
import click
from anymotion_sdk import Client, ClientValueError
from anymotion_sdk.session import HttpSession
from . import __version__
from .exceptions import ClickException, SettingsValueError
from .output import echo_request, echo_response, echo_warning
from .settings import Settings
from .state import State
def get_client(state: State) -> Client:
settings = get_settings(state.profile)
if not settings.is_ok:
command = click.style(f"{state.cli_name} configure", fg="cyan")
message = (
"The credentials is invalid or not set. "
f"Run {command} to set credentials."
)
raise ClickException(message)
session = HttpSession()
if hasattr(session, "user_agent"):
session.user_agent = f"{state.cli_name}/{__version__}"
try:
client = Client(
client_id=str(settings.client_id),
client_secret=str(settings.client_secret),
api_url=settings.api_url,
interval=settings.interval,
timeout=settings.timeout,
session=session,
)
except ClientValueError as e:
raise ClickException(str(e))
if state.verbose:
client.session.add_request_callback(echo_request)
client.session.add_response_callback(echo_response)
state.is_download = settings.is_download
state.is_open = settings.is_open
return client
|
MIT License
|
ujhin/python-upbit-client
|
upbit/utils.py
|
HTTPFutureExtractor.remaining_request
|
python
|
def remaining_request(headers: dict) -> dict:
remaining = headers['Remaining-Req']
return {
k: v
for k, v in [
param.split('=')
for param
in remaining.split('; ')
]
}
|
Check Request limit times
Please read the official Upbit Client document.
Documents: https://ujhin.github.io/upbit-client-docs/
|
https://github.com/ujhin/python-upbit-client/blob/911c38e7dcb8972286a858c0b2401a25de847146/upbit/utils.py#L8-L24
|
from typing import Union
class HTTPFutureExtractor:
@staticmethod
|
MIT License
|
prompt-toolkit/pyvim
|
pyvim/commands/handler.py
|
_go_to_line
|
python
|
def _go_to_line(editor, line):
b = editor.application.current_buffer
b.cursor_position = b.document.translate_row_col_to_index(max(0, int(line) - 1), 0)
|
Move cursor to this line in the current buffer.
|
https://github.com/prompt-toolkit/pyvim/blob/210816b4b1d2dc00606ec924dda29e49ac4cd87c/pyvim/commands/handler.py#L58-L63
|
from __future__ import unicode_literals
from .grammar import COMMAND_GRAMMAR
from .commands import call_command_handler, has_command_handler, substitute
__all__ = (
'handle_command',
)
def handle_command(editor, input_string):
m = COMMAND_GRAMMAR.match(input_string)
if m is None:
return
variables = m.variables()
command = variables.get('command')
go_to_line = variables.get('go_to_line')
shell_command = variables.get('shell_command')
range_start = variables.get('range_start')
range_end = variables.get('range_end')
search = variables.get('search')
replace = variables.get('replace')
flags = variables.get('flags', '')
if go_to_line is not None:
_go_to_line(editor, go_to_line)
elif shell_command is not None:
editor.application.run_system_command(shell_command)
elif has_command_handler(command):
call_command_handler(command, editor, variables)
elif command in ('s', 'substitute'):
flags = flags.lstrip('/')
substitute(editor, range_start, range_end, search, replace, flags)
else:
editor.show_message('Not an editor command: %s' % input_string)
return
editor.sync_with_prompt_toolkit()
|
BSD 3-Clause New or Revised License
|
ibm/pyxcli
|
pyxcli/mirroring/volume_recovery_manager.py
|
VolumeRecoveryManager.delete_mirror
|
python
|
def delete_mirror(self, resource_id):
self._delete_mirror(vol=resource_id)
|
delete a mirror by mirror name
|
https://github.com/ibm/pyxcli/blob/26544df4441ef7fef4900ec631bd2f1326e9b0f1/pyxcli/mirroring/volume_recovery_manager.py#L102-L104
|
from logging import getLogger
from pyxcli import XCLI_DEFAULT_LOGGER
from pyxcli.mirroring.recovery_manager import RecoveryManager, CHAR_LIMIT, InsufficientSnapshotSpaceRecoveryException, NoLastReplicatedSnapshotRecoveryException
logger = getLogger(XCLI_DEFAULT_LOGGER + '.mirroring')
class VolumeRecoveryManager(RecoveryManager):
def __init__(self, should_use_cache, xcli_client):
super(VolumeRecoveryManager, self).__init__(
should_use_cache, xcli_client)
def get_mirror_resources(self):
return self.action_entities.get_vol_mirrors()
def get_type_str(self):
return "volume"
def _does_resource_have_mapped_test_snapshot(self, volume_name,
test_snapshot_prefix):
snapshots = self.get_volume_snapshots_by_prefix(volume_name,
test_snapshot_prefix)
for snapshot in snapshots:
if self.is_volume_mapped(snapshot.name):
return True
return False
def get_volume_snapshots_by_prefix(self, volume, test_snapshot_prefix):
snapshots = list()
for snapshot in self.xcli_client.cmd.snapshot_list(vol=volume):
if snapshot.name.startswith(test_snapshot_prefix):
snapshots.append(snapshot)
return snapshots
def _unmap_and_delete_test_snapshots(self, device_id,
test_snapshot_prefix):
snapshots = self.get_volume_snapshots_by_prefix(device_id,
test_snapshot_prefix)
for snapshot in snapshots:
self.unmap_and_delete_volume(snapshot.name)
def _create_and_unlock_snapshot(self, vol, name, test_snapshot_prefix):
existing_snapshots = self.get_volume_snapshots_by_prefix(
vol, test_snapshot_prefix)
if len(existing_snapshots) == 0:
logger.debug("-> Creating and setting [r/w] attributes snapshot "
"[%s] for device [%s]." % (name, vol))
xcli_mirror = self.get_mirror_resources()[vol]
if self._is_sync_mirror(xcli_mirror):
self.xcli_client.cmd.snapshot_create(vol=vol, name=name)
else:
self.xcli_client.cmd.snapshot_duplicate(
snapshot=self._get_last_replicated_snapshot_name(vol),
name=name)
self.xcli_client.cmd.vol_unlock(vol=name)
else:
logger.debug("-> Setting [r/w] attributes for existing snapshot "
"[%s] of device [%s]." % (existing_snapshots[0].name,
vol))
self.xcli_client.cmd.vol_unlock(vol=existing_snapshots[0].name)
def create_mirror(self, resource_name, target_name, mirror_type,
slave_resource_name, create_slave='no', remote_pool=None,
rpo=None, remote_rpo=None, schedule=None,
remote_schedule=None, activate_mirror='no'):
return self._create_mirror('vol', resource_name, target_name,
mirror_type, slave_resource_name,
create_slave=create_slave,
remote_pool=remote_pool, rpo=rpo,
remote_rpo=remote_rpo, schedule=schedule,
remote_schedule=remote_schedule,
activate_mirror=activate_mirror)
|
Apache License 2.0
|
andrethemac/l76glnsv4
|
L76GNSV4.py
|
L76GNSS._mixhash
|
python
|
def _mixhash(self, keywords, sentence):
ret = {}
while len(keywords) - len(sentence) > 0:
sentence += ('',)
if len(keywords) == len(sentence):
ret = dict(zip(keywords, sentence))
try:
ret['Latitude'] = self._convert_coord(ret['Latitude'], ret['NS'])
except:
pass
try:
ret['Longitude'] = self._convert_coord(ret['Longitude'], ret['EW'])
except:
pass
return ret
else:
return None
|
return hash with keywords filled with sentence
|
https://github.com/andrethemac/l76glnsv4/blob/679ac6a6b871e6aa7b3e17960a2ea1dfde609854/L76GNSV4.py#L83-L102
|
from machine import Timer
import time
import gc
import binascii
class L76GNSS:
GPS_I2CADDR = const(0x10)
NMEA410 = const(410)
def __init__(self, pytrack=None, sda='P22', scl='P21', timeout=180, debug=False):
if pytrack is not None:
self.i2c = pytrack.i2c
else:
from machine import I2C
self.i2c = I2C(0, mode=I2C.MASTER, pins=(sda, scl))
self.chrono = Timer.Chrono()
self.timeout = timeout
self.timeout_status = True
self.reg = bytearray(1)
self.i2c.writeto(GPS_I2CADDR, self.reg)
self.fix = False
self.Latitude = None
self.Longitude = None
self.debug = debug
self.timeLastFix = 0
self.ttf = -1
self.lastmessage = {}
self.NMEAVersion = 301
self.ChipVersionID = None
self.release = 1.0
self.ReleaseString = None
self.BuildID = None
self.ProductModel = None
self.SDK = None
self.get_dt_release(debug=False)
self.get_chip_version(debug=False)
def _read(self):
reg = b""
while len(set(reg)) < 10:
reg = self.i2c.readfrom(GPS_I2CADDR, 255)
return reg
@staticmethod
def _convert_coord(coord, orientation):
coord = (float(coord) // 100) + ((float(coord) % 100) / 60)
if orientation == 'S' or orientation == 'W':
coord *= -1
return coord
def time_fixed(self):
return int(time.ticks_ms()/1000) - self.timeLastFix
|
MIT License
|
sphinx-doc/sphinx-intl
|
tests/path.py
|
path.write_text
|
python
|
def write_text(self, text, **kwargs):
f = open(self, 'w', **kwargs)
try:
f.write(text)
finally:
f.close()
|
Writes the given `text` to the file.
|
https://github.com/sphinx-doc/sphinx-intl/blob/491cf592271c29dfc3415ff3a9a0a890d7aeb4d3/tests/path.py#L123-L131
|
import os
import sys
import shutil
from codecs import open
from six import text_type
FILESYSTEMENCODING = sys.getfilesystemencoding() or sys.getdefaultencoding()
class path(text_type):
if sys.version_info < (3, 0):
def __new__(cls, s, encoding=FILESYSTEMENCODING, errors='strict'):
if isinstance(s, str):
s = s.decode(encoding, errors)
return text_type.__new__(cls, s)
return text_type.__new__(cls, s)
@property
def parent(self):
return self.__class__(os.path.dirname(self))
def abspath(self):
return self.__class__(os.path.abspath(self))
def isabs(self):
return os.path.isabs(self)
def isdir(self):
return os.path.isdir(self)
def isfile(self):
return os.path.isfile(self)
def islink(self):
return os.path.islink(self)
def ismount(self):
return os.path.ismount(self)
def rmtree(self, ignore_errors=False, onerror=None):
shutil.rmtree(self, ignore_errors=ignore_errors, onerror=onerror)
def copytree(self, destination, symlinks=False):
shutil.copytree(self, destination, symlinks=symlinks)
def movetree(self, destination):
shutil.move(self, destination)
move = movetree
def unlink(self):
os.unlink(self)
|
BSD 2-Clause Simplified License
|
react-native-skia/react-native-skia
|
build/util/java_action.py
|
IsExecutable
|
python
|
def IsExecutable(path):
return os.path.isfile(path) and os.access(path, os.X_OK)
|
Returns whether file at |path| exists and is executable.
Args:
path: absolute or relative path to test.
Returns:
True if the file at |path| exists, False otherwise.
|
https://github.com/react-native-skia/react-native-skia/blob/91ecc74444b163f128541dbc1a42e27a9c0fb40b/build/util/java_action.py#L16-L25
|
import os
import subprocess
import sys
EXIT_SUCCESS = 0
EXIT_FAILURE = 1
|
MIT License
|
wavefronthq/python-client
|
wavefront_api_client/models/maintenance_window.py
|
MaintenanceWindow.customer_id
|
python
|
def customer_id(self):
return self._customer_id
|
Gets the customer_id of this MaintenanceWindow. # noqa: E501
:return: The customer_id of this MaintenanceWindow. # noqa: E501
:rtype: str
|
https://github.com/wavefronthq/python-client/blob/e410ce0dd8a2334e995456f4f3d44e0f04664a3a/wavefront_api_client/models/maintenance_window.py#L193-L200
|
import pprint
import re
import six
from wavefront_api_client.configuration import Configuration
class MaintenanceWindow(object):
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'created_epoch_millis': 'int',
'creator_id': 'str',
'customer_id': 'str',
'end_time_in_seconds': 'int',
'event_name': 'str',
'host_tag_group_host_names_group_anded': 'bool',
'id': 'str',
'point_tag_filter': 'str',
'reason': 'str',
'relevant_customer_tags': 'list[str]',
'relevant_customer_tags_anded': 'bool',
'relevant_host_names': 'list[str]',
'relevant_host_tags': 'list[str]',
'relevant_host_tags_anded': 'bool',
'running_state': 'str',
'sort_attr': 'int',
'start_time_in_seconds': 'int',
'targets': 'list[str]',
'title': 'str',
'updated_epoch_millis': 'int',
'updater_id': 'str'
}
attribute_map = {
'created_epoch_millis': 'createdEpochMillis',
'creator_id': 'creatorId',
'customer_id': 'customerId',
'end_time_in_seconds': 'endTimeInSeconds',
'event_name': 'eventName',
'host_tag_group_host_names_group_anded': 'hostTagGroupHostNamesGroupAnded',
'id': 'id',
'point_tag_filter': 'pointTagFilter',
'reason': 'reason',
'relevant_customer_tags': 'relevantCustomerTags',
'relevant_customer_tags_anded': 'relevantCustomerTagsAnded',
'relevant_host_names': 'relevantHostNames',
'relevant_host_tags': 'relevantHostTags',
'relevant_host_tags_anded': 'relevantHostTagsAnded',
'running_state': 'runningState',
'sort_attr': 'sortAttr',
'start_time_in_seconds': 'startTimeInSeconds',
'targets': 'targets',
'title': 'title',
'updated_epoch_millis': 'updatedEpochMillis',
'updater_id': 'updaterId'
}
def __init__(self, created_epoch_millis=None, creator_id=None, customer_id=None, end_time_in_seconds=None, event_name=None, host_tag_group_host_names_group_anded=None, id=None, point_tag_filter=None, reason=None, relevant_customer_tags=None, relevant_customer_tags_anded=None, relevant_host_names=None, relevant_host_tags=None, relevant_host_tags_anded=None, running_state=None, sort_attr=None, start_time_in_seconds=None, targets=None, title=None, updated_epoch_millis=None, updater_id=None, _configuration=None):
if _configuration is None:
_configuration = Configuration()
self._configuration = _configuration
self._created_epoch_millis = None
self._creator_id = None
self._customer_id = None
self._end_time_in_seconds = None
self._event_name = None
self._host_tag_group_host_names_group_anded = None
self._id = None
self._point_tag_filter = None
self._reason = None
self._relevant_customer_tags = None
self._relevant_customer_tags_anded = None
self._relevant_host_names = None
self._relevant_host_tags = None
self._relevant_host_tags_anded = None
self._running_state = None
self._sort_attr = None
self._start_time_in_seconds = None
self._targets = None
self._title = None
self._updated_epoch_millis = None
self._updater_id = None
self.discriminator = None
if created_epoch_millis is not None:
self.created_epoch_millis = created_epoch_millis
if creator_id is not None:
self.creator_id = creator_id
if customer_id is not None:
self.customer_id = customer_id
self.end_time_in_seconds = end_time_in_seconds
if event_name is not None:
self.event_name = event_name
if host_tag_group_host_names_group_anded is not None:
self.host_tag_group_host_names_group_anded = host_tag_group_host_names_group_anded
if id is not None:
self.id = id
if point_tag_filter is not None:
self.point_tag_filter = point_tag_filter
self.reason = reason
self.relevant_customer_tags = relevant_customer_tags
if relevant_customer_tags_anded is not None:
self.relevant_customer_tags_anded = relevant_customer_tags_anded
if relevant_host_names is not None:
self.relevant_host_names = relevant_host_names
if relevant_host_tags is not None:
self.relevant_host_tags = relevant_host_tags
if relevant_host_tags_anded is not None:
self.relevant_host_tags_anded = relevant_host_tags_anded
if running_state is not None:
self.running_state = running_state
if sort_attr is not None:
self.sort_attr = sort_attr
self.start_time_in_seconds = start_time_in_seconds
if targets is not None:
self.targets = targets
self.title = title
if updated_epoch_millis is not None:
self.updated_epoch_millis = updated_epoch_millis
if updater_id is not None:
self.updater_id = updater_id
@property
def created_epoch_millis(self):
return self._created_epoch_millis
@created_epoch_millis.setter
def created_epoch_millis(self, created_epoch_millis):
self._created_epoch_millis = created_epoch_millis
@property
def creator_id(self):
return self._creator_id
@creator_id.setter
def creator_id(self, creator_id):
self._creator_id = creator_id
@property
|
Apache License 2.0
|
alliefitter/boto3_type_annotations
|
boto3_type_annotations_with_docs/boto3_type_annotations/medialive/paginator.py
|
DescribeSchedule.paginate
|
python
|
def paginate(self, ChannelId: str, PaginationConfig: Dict = None) -> Dict:
pass
|
Creates an iterator that will paginate through responses from :py:meth:`MediaLive.Client.describe_schedule`.
See also: `AWS API Documentation <https://docs.aws.amazon.com/goto/WebAPI/medialive-2017-10-14/DescribeSchedule>`_
**Request Syntax**
::
response_iterator = paginator.paginate(
ChannelId='string',
PaginationConfig={
'MaxItems': 123,
'PageSize': 123,
'StartingToken': 'string'
}
)
**Response Syntax**
::
{
'ScheduleActions': [
{
'ActionName': 'string',
'ScheduleActionSettings': {
'HlsTimedMetadataSettings': {
'Id3': 'string'
},
'InputSwitchSettings': {
'InputAttachmentNameReference': 'string'
},
'PauseStateSettings': {
'Pipelines': [
{
'PipelineId': 'PIPELINE_0'|'PIPELINE_1'
},
]
},
'Scte35ReturnToNetworkSettings': {
'SpliceEventId': 123
},
'Scte35SpliceInsertSettings': {
'Duration': 123,
'SpliceEventId': 123
},
'Scte35TimeSignalSettings': {
'Scte35Descriptors': [
{
'Scte35DescriptorSettings': {
'SegmentationDescriptorScte35DescriptorSettings': {
'DeliveryRestrictions': {
'ArchiveAllowedFlag': 'ARCHIVE_NOT_ALLOWED'|'ARCHIVE_ALLOWED',
'DeviceRestrictions': 'NONE'|'RESTRICT_GROUP0'|'RESTRICT_GROUP1'|'RESTRICT_GROUP2',
'NoRegionalBlackoutFlag': 'REGIONAL_BLACKOUT'|'NO_REGIONAL_BLACKOUT',
'WebDeliveryAllowedFlag': 'WEB_DELIVERY_NOT_ALLOWED'|'WEB_DELIVERY_ALLOWED'
},
'SegmentNum': 123,
'SegmentationCancelIndicator': 'SEGMENTATION_EVENT_NOT_CANCELED'|'SEGMENTATION_EVENT_CANCELED',
'SegmentationDuration': 123,
'SegmentationEventId': 123,
'SegmentationTypeId': 123,
'SegmentationUpid': 'string',
'SegmentationUpidType': 123,
'SegmentsExpected': 123,
'SubSegmentNum': 123,
'SubSegmentsExpected': 123
}
}
},
]
},
'StaticImageActivateSettings': {
'Duration': 123,
'FadeIn': 123,
'FadeOut': 123,
'Height': 123,
'Image': {
'PasswordParam': 'string',
'Uri': 'string',
'Username': 'string'
},
'ImageX': 123,
'ImageY': 123,
'Layer': 123,
'Opacity': 123,
'Width': 123
},
'StaticImageDeactivateSettings': {
'FadeOut': 123,
'Layer': 123
}
},
'ScheduleActionStartSettings': {
'FixedModeScheduleActionStartSettings': {
'Time': 'string'
},
'FollowModeScheduleActionStartSettings': {
'FollowPoint': 'END'|'START',
'ReferenceActionName': 'string'
}
}
},
]
}
**Response Structure**
- *(dict) --* An array of channel schedule actions.
- **ScheduleActions** *(list) --* The list of actions in the schedule.
- *(dict) --* Contains information on a single schedule action.
- **ActionName** *(string) --* The name of the action, must be unique within the schedule. This name provides the main reference to an action once it is added to the schedule. A name is unique if it is no longer in the schedule. The schedule is automatically cleaned up to remove actions with a start time of more than 1 hour ago (approximately) so at that point a name can be reused.
- **ScheduleActionSettings** *(dict) --* Settings for this schedule action.
- **HlsTimedMetadataSettings** *(dict) --* Action to insert HLS metadata
- **Id3** *(string) --* Base64 string formatted according to the ID3 specification: http://id3.org/id3v2.4.0-structure
- **InputSwitchSettings** *(dict) --* Action to switch the input
- **InputAttachmentNameReference** *(string) --* The name of the input attachment that should be switched to by this action.
- **PauseStateSettings** *(dict) --* Action to pause or unpause one or both channel pipelines
- **Pipelines** *(list) --* Placeholder documentation for __listOfPipelinePauseStateSettings
- *(dict) --* Settings for pausing a pipeline.
- **PipelineId** *(string) --* Pipeline ID to pause ("PIPELINE_0" or "PIPELINE_1").
- **Scte35ReturnToNetworkSettings** *(dict) --* Action to insert SCTE-35 return_to_network message
- **SpliceEventId** *(integer) --* The splice_event_id for the SCTE-35 splice_insert, as defined in SCTE-35.
- **Scte35SpliceInsertSettings** *(dict) --* Action to insert SCTE-35 splice_insert message
- **Duration** *(integer) --* Optional, the duration for the splice_insert, in 90 KHz ticks. To convert seconds to ticks, multiple the seconds by 90,000. If you enter a duration, there is an expectation that the downstream system can read the duration and cue in at that time. If you do not enter a duration, the splice_insert will continue indefinitely and there is an expectation that you will enter a return_to_network to end the splice_insert at the appropriate time.
- **SpliceEventId** *(integer) --* The splice_event_id for the SCTE-35 splice_insert, as defined in SCTE-35.
- **Scte35TimeSignalSettings** *(dict) --* Action to insert SCTE-35 time_signal message
- **Scte35Descriptors** *(list) --* The list of SCTE-35 descriptors accompanying the SCTE-35 time_signal.
- *(dict) --* Holds one set of SCTE-35 Descriptor Settings.
- **Scte35DescriptorSettings** *(dict) --* SCTE-35 Descriptor Settings.
- **SegmentationDescriptorScte35DescriptorSettings** *(dict) --* SCTE-35 Segmentation Descriptor.
- **DeliveryRestrictions** *(dict) --* Holds the four SCTE-35 delivery restriction parameters.
- **ArchiveAllowedFlag** *(string) --* Corresponds to SCTE-35 archive_allowed_flag.
- **DeviceRestrictions** *(string) --* Corresponds to SCTE-35 device_restrictions parameter.
- **NoRegionalBlackoutFlag** *(string) --* Corresponds to SCTE-35 no_regional_blackout_flag parameter.
- **WebDeliveryAllowedFlag** *(string) --* Corresponds to SCTE-35 web_delivery_allowed_flag parameter.
- **SegmentNum** *(integer) --* Corresponds to SCTE-35 segment_num. A value that is valid for the specified segmentation_type_id.
- **SegmentationCancelIndicator** *(string) --* Corresponds to SCTE-35 segmentation_event_cancel_indicator.
- **SegmentationDuration** *(integer) --* Corresponds to SCTE-35 segmentation_duration. Optional. The duration for the time_signal, in 90 KHz ticks. To convert seconds to ticks, multiple the seconds by 90,000. Enter time in 90 KHz clock ticks. If you do not enter a duration, the time_signal will continue until you insert a cancellation message.
- **SegmentationEventId** *(integer) --* Corresponds to SCTE-35 segmentation_event_id.
- **SegmentationTypeId** *(integer) --* Corresponds to SCTE-35 segmentation_type_id. One of the segmentation_type_id values listed in the SCTE-35 specification. On the console, enter the ID in decimal (for example, "52"). In the CLI, API, or an SDK, enter the ID in hex (for example, "0x34") or decimal (for example, "52").
- **SegmentationUpid** *(string) --* Corresponds to SCTE-35 segmentation_upid. Enter a string containing the hexadecimal representation of the characters that make up the SCTE-35 segmentation_upid value. Must contain an even number of hex characters. Do not include spaces between each hex pair. For example, the ASCII "ADS Information" becomes hex "41445320496e666f726d6174696f6e.
- **SegmentationUpidType** *(integer) --* Corresponds to SCTE-35 segmentation_upid_type. On the console, enter one of the types listed in the SCTE-35 specification, converted to a decimal. For example, "0x0C" hex from the specification is "12" in decimal. In the CLI, API, or an SDK, enter one of the types listed in the SCTE-35 specification, in either hex (for example, "0x0C" ) or in decimal (for example, "12").
- **SegmentsExpected** *(integer) --* Corresponds to SCTE-35 segments_expected. A value that is valid for the specified segmentation_type_id.
- **SubSegmentNum** *(integer) --* Corresponds to SCTE-35 sub_segment_num. A value that is valid for the specified segmentation_type_id.
- **SubSegmentsExpected** *(integer) --* Corresponds to SCTE-35 sub_segments_expected. A value that is valid for the specified segmentation_type_id.
- **StaticImageActivateSettings** *(dict) --* Action to activate a static image overlay
- **Duration** *(integer) --* The duration in milliseconds for the image to remain on the video. If omitted or set to 0 the duration is unlimited and the image will remain until it is explicitly deactivated.
- **FadeIn** *(integer) --* The time in milliseconds for the image to fade in. The fade-in starts at the start time of the overlay. Default is 0 (no fade-in).
- **FadeOut** *(integer) --* Applies only if a duration is specified. The time in milliseconds for the image to fade out. The fade-out starts when the duration time is hit, so it effectively extends the duration. Default is 0 (no fade-out).
- **Height** *(integer) --* The height of the image when inserted into the video, in pixels. The overlay will be scaled up or down to the specified height. Leave blank to use the native height of the overlay.
- **Image** *(dict) --* The location and filename of the image file to overlay on the video. The file must be a 32-bit BMP, PNG, or TGA file, and must not be larger (in pixels) than the input video.
- **PasswordParam** *(string) --* key used to extract the password from EC2 Parameter store
- **Uri** *(string) --* Uniform Resource Identifier - This should be a path to a file accessible to the Live system (eg. a http:// URI) depending on the output type. For example, a RTMP destination should have a uri simliar to: "rtmp://fmsserver/live".
- **Username** *(string) --* Documentation update needed
- **ImageX** *(integer) --* Placement of the left edge of the overlay relative to the left edge of the video frame, in pixels. 0 (the default) is the left edge of the frame. If the placement causes the overlay to extend beyond the right edge of the underlying video, then the overlay is cropped on the right.
- **ImageY** *(integer) --* Placement of the top edge of the overlay relative to the top edge of the video frame, in pixels. 0 (the default) is the top edge of the frame. If the placement causes the overlay to extend beyond the bottom edge of the underlying video, then the overlay is cropped on the bottom.
- **Layer** *(integer) --* The number of the layer, 0 to 7. There are 8 layers that can be overlaid on the video, each layer with a different image. The layers are in Z order, which means that overlays with higher values of layer are inserted on top of overlays with lower values of layer. Default is 0.
- **Opacity** *(integer) --* Opacity of image where 0 is transparent and 100 is fully opaque. Default is 100.
- **Width** *(integer) --* The width of the image when inserted into the video, in pixels. The overlay will be scaled up or down to the specified width. Leave blank to use the native width of the overlay.
- **StaticImageDeactivateSettings** *(dict) --* Action to deactivate a static image overlay
- **FadeOut** *(integer) --* The time in milliseconds for the image to fade out. Default is 0 (no fade-out).
- **Layer** *(integer) --* The image overlay layer to deactivate, 0 to 7. Default is 0.
- **ScheduleActionStartSettings** *(dict) --* The time for the action to start in the channel.
- **FixedModeScheduleActionStartSettings** *(dict) --* Holds the start time for the action.
- **Time** *(string) --* Start time for the action to start in the channel. (Not the time for the action to be added to the schedule: actions are always added to the schedule immediately.) UTC format: yyyy-mm-ddThh:mm:ss.nnnZ. All the letters are digits (for example, mm might be 01) except for the two constants "T" for time and "Z" for "UTC format".
- **FollowModeScheduleActionStartSettings** *(dict) --* Specifies an action to follow for scheduling this action.
- **FollowPoint** *(string) --* Identifies whether this action starts relative to the start or relative to the end of the reference action.
- **ReferenceActionName** *(string) --* The action name of another action that this one refers to.
:type ChannelId: string
:param ChannelId: **[REQUIRED]** Id of the channel whose schedule is being updated.
:type PaginationConfig: dict
:param PaginationConfig:
A dictionary that provides parameters to control pagination.
- **MaxItems** *(integer) --*
The total number of items to return. If the total number of items available is more than the value specified in max-items then a ``NextToken`` will be provided in the output that you can use to resume pagination.
- **PageSize** *(integer) --*
The size of each page.
- **StartingToken** *(string) --*
A token to specify where to start paginating. This is the ``NextToken`` from a previous response.
:rtype: dict
:returns:
|
https://github.com/alliefitter/boto3_type_annotations/blob/2a88aa562b1aee6e8a6cc30402980884b3707fbb/boto3_type_annotations_with_docs/boto3_type_annotations/medialive/paginator.py#L6-L185
|
from typing import Dict
from botocore.paginate import Paginator
class DescribeSchedule(Paginator):
|
MIT License
|
google/closure-linter
|
closure_linter/gjslint.py
|
_PrintSummary
|
python
|
def _PrintSummary(paths, error_records):
error_count = len(error_records)
all_paths = set(paths)
all_paths_count = len(all_paths)
if error_count is 0:
print '%d files checked, no errors found.' % all_paths_count
new_error_count = len([e for e in error_records if e.new_error])
error_paths = set([e.path for e in error_records])
error_paths_count = len(error_paths)
no_error_paths_count = all_paths_count - error_paths_count
if (error_count or new_error_count) and not FLAGS.quiet:
error_noun = 'error' if error_count == 1 else 'errors'
new_error_noun = 'error' if new_error_count == 1 else 'errors'
error_file_noun = 'file' if error_paths_count == 1 else 'files'
ok_file_noun = 'file' if no_error_paths_count == 1 else 'files'
print ('Found %d %s, including %d new %s, in %d %s (%d %s OK).' %
(error_count,
error_noun,
new_error_count,
new_error_noun,
error_paths_count,
error_file_noun,
no_error_paths_count,
ok_file_noun))
|
Print a summary of the number of errors and files.
|
https://github.com/google/closure-linter/blob/c09c885b4e4fec386ff81cebeb8c66c2b0643d49/closure_linter/gjslint.py#L183-L212
|
__author__ = ('robbyw@google.com (Robert Walker)',
'ajp@google.com (Andy Perelson)',
'nnaze@google.com (Nathan Naze)',)
import errno
import itertools
import os
import platform
import re
import sys
import time
import gflags as flags
from closure_linter import errorrecord
from closure_linter import runner
from closure_linter.common import erroraccumulator
from closure_linter.common import simplefileflags as fileflags
try:
import multiprocessing
except ImportError:
multiprocessing = None
FLAGS = flags.FLAGS
flags.DEFINE_boolean('unix_mode', False,
'Whether to emit warnings in standard unix format.')
flags.DEFINE_boolean('beep', True, 'Whether to beep when errors are found.')
flags.DEFINE_boolean('time', False, 'Whether to emit timing statistics.')
flags.DEFINE_boolean('quiet', False, 'Whether to minimize logged messages. '
'Most useful for per-file linting, such as that performed '
'by the presubmit linter service.')
flags.DEFINE_boolean('check_html', False,
'Whether to check javascript in html files.')
flags.DEFINE_boolean('summary', False,
'Whether to show an error count summary.')
flags.DEFINE_list('additional_extensions', None, 'List of additional file '
'extensions (not js) that should be treated as '
'JavaScript files.')
flags.DEFINE_boolean('multiprocess',
platform.system() is 'Linux' and bool(multiprocessing),
'Whether to attempt parallelized linting using the '
'multiprocessing module. Enabled by default on Linux '
'if the multiprocessing module is present (Python 2.6+). '
'Otherwise disabled by default. '
'Disabling may make debugging easier.')
flags.ADOPT_module_key_flags(fileflags)
flags.ADOPT_module_key_flags(runner)
GJSLINT_ONLY_FLAGS = ['--unix_mode', '--beep', '--nobeep', '--time',
'--check_html', '--summary', '--quiet']
def _MultiprocessCheckPaths(paths):
pool = multiprocessing.Pool()
path_results = pool.imap(_CheckPath, paths)
for results in path_results:
for result in results:
yield result
try:
pool.close()
pool.join()
del pool
except OSError as err:
if err.errno is not errno.EINTR:
raise err
def _CheckPaths(paths):
for path in paths:
results = _CheckPath(path)
for record in results:
yield record
def _CheckPath(path):
error_handler = erroraccumulator.ErrorAccumulator()
runner.Run(path, error_handler)
make_error_record = lambda err: errorrecord.MakeErrorRecord(path, err)
return map(make_error_record, error_handler.GetErrors())
def _GetFilePaths(argv):
suffixes = ['.js']
if FLAGS.additional_extensions:
suffixes += ['.%s' % ext for ext in FLAGS.additional_extensions]
if FLAGS.check_html:
suffixes += ['.html', '.htm']
return fileflags.GetFileList(argv, 'JavaScript', suffixes)
def _PrintFileSummary(paths, records):
paths = list(paths)
paths.sort()
for path in paths:
path_errors = [e for e in records if e.path == path]
print '%s: %d' % (path, len(path_errors))
def _PrintFileSeparator(path):
print '----- FILE : %s -----' % path
|
Apache License 2.0
|
landsat-pds/landsat_ingestor
|
ingestor/mtlutils.py
|
_checkstatus
|
python
|
def _checkstatus(status, line):
newstatus = 0
if status == 0:
if _islinetype(line, GRPSTART):
newstatus = 1
elif _isfinal(line):
newstatus = 4
elif status == 1:
if _islinetype(line, GRPSTART):
newstatus = 1
elif _islinetype(line, GRPEND):
newstatus = 3
elif _isassignment(line):
newstatus = 2
elif status == 2:
if _islinetype(line, GRPEND):
newstatus = 3
elif _isassignment(line):
newstatus = 2
elif status == 3:
if _islinetype(line, GRPSTART):
newstatus = 1
elif _islinetype(line, GRPEND):
newstatus = 3
elif _isfinal(line):
newstatus = 4
if newstatus != 0:
return newstatus
elif status != 4:
raise MTLParseError(
"Cannot parse the following line after status "
+ "'%s':\n%s" % (STATUSCODE[status], line))
|
Returns state/status after reading the next line.
The status codes are::
0 - BEGIN parsing; 1 - ENTER METADATA GROUP, 2 - READ METADATA LINE,
3 - END METDADATA GROUP, 4 - END PARSING
Permitted Transitions::
0 --> 1, 0 --> 4
1 --> 1, 1 --> 2, 1 --> 3
2 --> 2, 2 --> 3
3 --> 1, 1 --> 3, 3 --> 4
|
https://github.com/landsat-pds/landsat_ingestor/blob/c6514f506628257b8080bc15fe3effb4d7a541be/ingestor/mtlutils.py#L119-L167
|
from __future__ import division
import os.path, glob
import datetime
import re
import logging
import StringIO
LOGGER = logging.getLogger('pygaarst.mtlutils')
METAPATTERN = "*_MTL*"
GRPSTART = "GROUP = "
GRPEND = "END_GROUP = "
ASSIGNCHAR = " = "
FINAL = "END"
STATUSCODE = [
"begin",
"enter metadata group",
"add metadata item",
"leave metadata group",
"end"
]
class MTLParseError(Exception):
pass
def _islinetype(line, testchar):
return line.strip().startswith(testchar)
def _isassignment(line):
return ASSIGNCHAR in line
def _isfinal(line):
return line.strip() == FINAL
def _getgroupname(line):
return line.strip().split(GRPSTART)[-1]
def _getendgroupname(line):
return line.strip().split(GRPEND)[-1]
def _getmetadataitem(line):
return line.strip().split(ASSIGNCHAR)
|
Apache License 2.0
|
kodethon/kodrive
|
kodrive/cli.py
|
auth
|
python
|
def auth(**kwargs):
"""
kodrive auth <path> <device_id (client)>
1. make sure path has been added to config.xml, server
2. make sure path is not shared by someone
3. add device_id to folder in config.xml, server
4. add device to devices in config.xml, server
"""
option = 'add'
path = kwargs['path']
key = kwargs['key']
if kwargs['remove']:
option = 'remove'
if kwargs['yes']:
output, err = cli_syncthing_adapter.auth(option, key, path)
click.echo("%s" % output, err=err)
else:
verb = 'authorize' if not kwargs['remove'] else 'de-authorize'
if click.confirm("Are you sure you want to %s this device to access %s?" % (verb, path)):
output, err = cli_syncthing_adapter.auth(option, key, path)
if output:
click.echo("%s" % output, err=err)
|
Authorize device synchronization.
|
https://github.com/kodethon/kodrive/blob/325fe5e5870b7d4eb121dcc7e93be64aa16e7988/kodrive/cli.py#L132-L161
|
import click
import os, time, math, pdb
from . import cli_syncthing_adapter
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@click.version_option()
@click.group(
epilog="Run 'kodrive COMMAND --help' for more information on a command.",
context_settings=CONTEXT_SETTINGS
)
@click.pass_context
def main(ctx):
pass
@main.command()
@click.option('-i', '--init', is_flag=True, help="Init KodeDrive daemon.")
@click.option('-e', '--exit', is_flag=True, help="Exit KodeDrive daemon.")
@click.option('-c', '--client', is_flag=True, help="Set Kodedrive into client mode.")
@click.option('-s', '--server', is_flag=True, help="Set Kodedrive into server mode.")
@click.option('-r', '--restart', is_flag=True, help="Restart KodeDrive daemon.")
@click.option('-d', '--delay', type=int, help="Set remote device detection speed.", metavar=" <INTEGER>")
def sys(**kwargs):
output, err = cli_syncthing_adapter.sys(**kwargs)
if output:
click.echo("%s" % output, err=err)
else:
if not kwargs['init']:
click.echo(click.get_current_context().get_help())
@main.command()
def ls():
heading, body = cli_syncthing_adapter.ls()
if heading:
click.echo(heading)
if body:
click.echo(body.strip())
@main.command()
@click.argument('key', nargs=1)
@click.option(
'-i', '--interval', default=30,
nargs=1, metavar="<INTEGER>",
help="Specify sync interval in seconds."
)
@click.option(
'-t', '--tag', nargs=1,
metavar=" <TEXT>",
help="Associate this folder with a tag."
)
@click.option(
'-p', '--path',
type=click.Path(exists=True, writable=True, resolve_path=True),
default=".", nargs=1, metavar=" <PATH>",
help="Specify which folder to link."
)
@click.option(
'-y', '--yes', nargs=1, is_flag=True,
default=False,
help="Bypass confirmation step."
)
def link(**kwargs):
if kwargs['yes']:
output, err = cli_syncthing_adapter.link(**kwargs)
click.echo("%s" % output, err=err)
else:
if click.confirm("Are you sure you want to link %s?" % kwargs['path']):
output, err = cli_syncthing_adapter.link(**kwargs)
click.echo("%s" % output, err=err)
@main.command()
@click.argument('key', nargs=1)
@click.option(
'-R', '--remove',
is_flag=True,
help="Deauthorize a directory."
)
@click.option(
'-y', '--yes', nargs=1, is_flag=True,
default=False,
help="Bypass confirmation step."
)
@click.option(
'-p', '--path',
type=click.Path(exists=True, writable=True, resolve_path=True),
default=".", nargs=1, metavar=" <PATH>",
help="Specify which folder to link."
)
|
MIT License
|
jmcgeheeiv/pyfakefs
|
pyfakefs/tests/fake_stat_time_test.py
|
FakeStatTestBase.check_open_write_close_new_file
|
python
|
def check_open_write_close_new_file(self):
created, written, closed = self.open_write_close_new_file()
self.assertEqual(created.st_ctime, written.st_ctime)
self.assertLessExceptWindows(written.st_ctime, closed.st_ctime)
self.assertEqual(created.st_atime, written.st_atime)
self.assertLessEqual(written.st_atime, closed.st_atime)
self.assertEqual(created.st_mtime, written.st_mtime)
self.assertLess(written.st_mtime, closed.st_mtime)
|
When a file is created on opening, st_ctime is updated under Posix,
and st_mtime is updated on close.
|
https://github.com/jmcgeheeiv/pyfakefs/blob/589bae0c58298d92fea0e463ab5104166cd6e63c/pyfakefs/tests/fake_stat_time_test.py#L178-L192
|
import time
import unittest
from collections import namedtuple
from pyfakefs.tests.test_utils import RealFsTestCase
FileTime = namedtuple('FileTime', 'st_ctime, st_atime, st_mtime')
class FakeStatTestBase(RealFsTestCase):
def setUp(self):
super().setUp()
self.check_linux_and_windows()
self.file_path = self.make_path('some_file')
self.sleep_time = 1.1 if self.is_macos else 0.01
self.mode = ''
def stat_time(self, path):
stat = self.os.stat(path)
if self.use_real_fs():
time.sleep(self.sleep_time)
else:
time.time()
return FileTime(st_ctime=stat.st_ctime,
st_atime=stat.st_atime,
st_mtime=stat.st_mtime)
def assertLessExceptWindows(self, time1, time2):
if self.is_windows_fs:
self.assertLessEqual(time1, time2)
else:
self.assertLess(time1, time2)
def assertLessExceptPosix(self, time1, time2):
if self.is_windows_fs:
self.assertLess(time1, time2)
else:
self.assertEqual(time1, time2)
def open_close_new_file(self):
with self.mock_time():
with self.open(self.file_path, self.mode):
created = self.stat_time(self.file_path)
closed = self.stat_time(self.file_path)
return created, closed
def open_write_close_new_file(self):
with self.mock_time():
with self.open(self.file_path, self.mode) as f:
created = self.stat_time(self.file_path)
f.write('foo')
written = self.stat_time(self.file_path)
closed = self.stat_time(self.file_path)
return created, written, closed
def open_close(self):
with self.mock_time():
self.create_file(self.file_path)
before = self.stat_time(self.file_path)
with self.open(self.file_path, self.mode):
opened = self.stat_time(self.file_path)
closed = self.stat_time(self.file_path)
return before, opened, closed
def open_write_close(self):
with self.mock_time():
self.create_file(self.file_path)
before = self.stat_time(self.file_path)
with self.open(self.file_path, self.mode) as f:
opened = self.stat_time(self.file_path)
f.write('foo')
written = self.stat_time(self.file_path)
closed = self.stat_time(self.file_path)
return before, opened, written, closed
def open_flush_close(self):
with self.mock_time():
self.create_file(self.file_path)
before = self.stat_time(self.file_path)
with self.open(self.file_path, self.mode) as f:
opened = self.stat_time(self.file_path)
f.flush()
flushed = self.stat_time(self.file_path)
closed = self.stat_time(self.file_path)
return before, opened, flushed, closed
def open_write_flush(self):
with self.mock_time():
self.create_file(self.file_path)
before = self.stat_time(self.file_path)
with self.open(self.file_path, self.mode) as f:
opened = self.stat_time(self.file_path)
f.write('foo')
written = self.stat_time(self.file_path)
f.flush()
flushed = self.stat_time(self.file_path)
closed = self.stat_time(self.file_path)
return before, opened, written, flushed, closed
def open_read_flush(self):
with self.mock_time():
self.create_file(self.file_path)
before = self.stat_time(self.file_path)
with self.open(self.file_path, 'r') as f:
opened = self.stat_time(self.file_path)
f.read()
read = self.stat_time(self.file_path)
f.flush()
flushed = self.stat_time(self.file_path)
closed = self.stat_time(self.file_path)
return before, opened, read, flushed, closed
def open_read_close_new_file(self):
with self.mock_time():
with self.open(self.file_path, self.mode) as f:
created = self.stat_time(self.file_path)
f.read()
read = self.stat_time(self.file_path)
closed = self.stat_time(self.file_path)
return created, read, closed
def open_read_close(self):
with self.mock_time():
self.create_file(self.file_path)
before = self.stat_time(self.file_path)
with self.open(self.file_path, self.mode) as f:
opened = self.stat_time(self.file_path)
f.read()
read = self.stat_time(self.file_path)
closed = self.stat_time(self.file_path)
return before, opened, read, closed
def check_open_close_new_file(self):
created, closed = self.open_close_new_file()
self.assertEqual(created.st_ctime, closed.st_ctime)
self.assertEqual(created.st_atime, closed.st_atime)
self.assertEqual(created.st_mtime, closed.st_mtime)
|
Apache License 2.0
|
siviltaram/persona-dialogue-generation
|
parlai/mturk/core/agents.py
|
MTurkAgent.append_message
|
python
|
def append_message(self, message):
self.state.append_message(message)
|
Add a received message to the state
|
https://github.com/siviltaram/persona-dialogue-generation/blob/3cc800ffe3c5a8d16ed26522cda839acfab8d417/parlai/mturk/core/agents.py#L249-L251
|
import logging
import time
from queue import Queue
import uuid
from parlai.core.agents import Agent
import parlai.mturk.core.data_model as data_model
import parlai.mturk.core.shared_utils as shared_utils
MTURK_DISCONNECT_MESSAGE = '[DISCONNECT]'
TIMEOUT_MESSAGE = '[TIMEOUT]'
RETURN_MESSAGE = '[RETURNED]'
class AssignState():
STATUS_NONE = 'none'
STATUS_ONBOARDING = 'onboarding'
STATUS_WAITING = 'waiting'
STATUS_IN_TASK = 'in task'
STATUS_DONE = 'done'
STATUS_DISCONNECT = 'disconnect'
STATUS_PARTNER_DISCONNECT = 'partner disconnect'
STATUS_PARTNER_DISCONNECT_EARLY = 'partner disconnect early'
STATUS_EXPIRED = 'expired'
STATUS_RETURNED = 'returned'
def __init__(self, status=None):
if status is None:
status = self.STATUS_NONE
self.status = status
self.messages = []
self.last_command = None
self.message_ids = []
def clear_messages(self):
self.messages = []
self.message_ids = []
self.last_command = None
def append_message(self, message):
if message['message_id'] in self.message_ids:
return
self.message_ids.append(message['message_id'])
self.messages.append(message)
def set_last_command(self, command):
self.last_command = command
def get_last_command(self):
return self.last_command
def get_messages(self):
return self.messages
def set_status(self, status):
self.status = status
def get_status(self):
return self.status
def is_final(self):
return (self.status == self.STATUS_DISCONNECT or
self.status == self.STATUS_DONE or
self.status == self.STATUS_PARTNER_DISCONNECT or
self.status == self.STATUS_PARTNER_DISCONNECT_EARLY or
self.status == self.STATUS_RETURNED or
self.status == self.STATUS_EXPIRED)
def get_inactive_command_text(self):
command = data_model.COMMAND_INACTIVE_HIT
text = None
if self.status == self.STATUS_DISCONNECT:
text = ('You disconnected in the middle of this HIT and were '
'marked as inactive. As these HITs often require real-'
'time interaction, it is no longer available for '
'completion. Please return this HIT and accept a new one '
'if you would like to try again.')
elif self.status == self.STATUS_DONE:
command = data_model.COMMAND_INACTIVE_DONE
text = ('You disconnected after completing this HIT without '
'marking it as completed. Please press the done button '
'below to finish the HIT.')
elif self.status == self.STATUS_EXPIRED:
text = ('You disconnected in the middle of this HIT and the '
'HIT expired before you reconnected. It is no longer '
'available for completion. Please return this HIT and '
'accept a new one if you would like to try again.')
elif self.status == self.STATUS_PARTNER_DISCONNECT:
command = data_model.COMMAND_INACTIVE_DONE
text = ('One of your partners disconnected in the middle of the '
'HIT. We won\'t penalize you for their disconnect, so '
'please use the button below to mark the HIT as complete.')
elif self.status == self.STATUS_PARTNER_DISCONNECT_EARLY:
command = data_model.COMMAND_INACTIVE_HIT
text = ('One of your partners disconnected in the middle of the '
'HIT. We won\'t penalize you for their disconnect, but you'
' did not complete enough of the task to submit the HIT. '
'Please return this HIT and accept a new one if you would '
'like to try again.')
elif self.status == self.STATUS_RETURNED:
text = ('You disconnected from this HIT and then returned '
'it. As we have marked the HIT as returned, it is no '
'longer available for completion. Please accept a new '
'HIT if you would like to try again')
else:
text = ('Our server was unable to handle your reconnect properly '
'and thus this HIT no longer seems available for '
'completion. Please try to connect again or return this '
'HIT and accept a new one.')
return text, command
class MTurkAgent(Agent):
ASSIGNMENT_NOT_DONE = 'NotDone'
ASSIGNMENT_DONE = 'Submitted'
ASSIGNMENT_APPROVED = 'Approved'
ASSIGNMENT_REJECTED = 'Rejected'
MTURK_DISCONNECT_MESSAGE = MTURK_DISCONNECT_MESSAGE
TIMEOUT_MESSAGE = TIMEOUT_MESSAGE
RETURN_MESSAGE = RETURN_MESSAGE
def __init__(self, opt, mturk_manager, hit_id, assignment_id, worker_id):
super().__init__(opt)
self.conversation_id = None
self.mturk_manager = mturk_manager
self.db_logger = mturk_manager.db_logger
self.id = None
self.state = AssignState()
self.assignment_id = assignment_id
self.hit_id = hit_id
self.worker_id = worker_id
self.some_agent_disconnected = False
self.hit_is_expired = False
self.hit_is_abandoned = False
self.hit_is_returned = False
self.hit_is_complete = False
self.disconnected = False
self.task_group_id = mturk_manager.task_group_id
self.message_request_time = None
self.recieved_packets = {}
self.creation_time = time.time()
self.alived = True
self.feedback = None
self.msg_queue = Queue()
def _get_episode_done_msg(self, text):
return {
'id': self.id,
'text': text,
'episode_done': True
}
def set_status(self, status):
self.state.set_status(status)
if self.db_logger is not None:
if status == AssignState.STATUS_ONBOARDING:
self.db_logger.log_start_onboard(
self.worker_id, self.assignment_id, self.conversation_id)
elif status == AssignState.STATUS_WAITING:
self.db_logger.log_finish_onboard(
self.worker_id, self.assignment_id)
elif status == AssignState.STATUS_IN_TASK:
self.db_logger.log_start_task(
self.worker_id, self.assignment_id, self.conversation_id)
elif status == AssignState.STATUS_DONE:
self.db_logger.log_complete_assignment(
self.worker_id, self.assignment_id,
time.time() + self.mturk_manager.auto_approve_delay,
status)
elif status == AssignState.STATUS_PARTNER_DISCONNECT:
self.db_logger.log_complete_assignment(
self.worker_id, self.assignment_id,
time.time() + self.mturk_manager.auto_approve_delay,
status)
elif status == AssignState.STATUS_PARTNER_DISCONNECT_EARLY:
self.db_logger.log_complete_assignment(
self.worker_id, self.assignment_id,
time.time() + self.mturk_manager.auto_approve_delay,
status)
elif status == AssignState.STATUS_DISCONNECT:
self.db_logger.log_disconnect_assignment(
self.worker_id, self.assignment_id,
time.time() + self.mturk_manager.auto_approve_delay,
status)
elif status == AssignState.STATUS_EXPIRED:
self.db_logger.log_complete_assignment(
self.worker_id, self.assignment_id,
time.time() + self.mturk_manager.auto_approve_delay,
status)
elif status == AssignState.STATUS_RETURNED:
self.db_logger.log_abandon_assignment(
self.worker_id, self.assignment_id)
def get_status(self):
return self.state.get_status()
def submitted_hit(self):
return self.get_status() in [
AssignState.STATUS_DONE,
AssignState.STATUS_PARTNER_DISCONNECT
]
def is_final(self):
return self.state.is_final()
|
MIT License
|
pybuilder/pybuilder
|
src/main/python/pybuilder/_vendor/distlib/markers.py
|
Evaluator.evaluate
|
python
|
def evaluate(self, expr, context):
if isinstance(expr, string_types):
if expr[0] in '\'"':
result = expr[1:-1]
else:
if expr not in context:
raise SyntaxError('unknown variable: %s' % expr)
result = context[expr]
else:
assert isinstance(expr, dict)
op = expr['op']
if op not in self.operations:
raise NotImplementedError('op not implemented: %s' % op)
elhs = expr['lhs']
erhs = expr['rhs']
if _is_literal(expr['lhs']) and _is_literal(expr['rhs']):
raise SyntaxError('invalid comparison: %s %s %s' % (elhs, op, erhs))
lhs = self.evaluate(elhs, context)
rhs = self.evaluate(erhs, context)
if ((elhs == 'python_version' or erhs == 'python_version') and
op in ('<', '<=', '>', '>=', '===', '==', '!=', '~=')):
lhs = NV(lhs)
rhs = NV(rhs)
elif elhs == 'python_version' and op in ('in', 'not in'):
lhs = NV(lhs)
rhs = _get_versions(rhs)
result = self.operations[op](lhs, rhs)
return result
|
Evaluate a marker expression returned by the :func:`parse_requirement`
function in the specified context.
|
https://github.com/pybuilder/pybuilder/blob/de74b167c6c8ef679ed1f1a1ff79349d004c5785/src/main/python/pybuilder/_vendor/distlib/markers.py#L59-L91
|
import os
import re
import sys
import platform
from .compat import string_types
from .util import in_venv, parse_marker
from .version import NormalizedVersion as NV
__all__ = ['interpret']
_VERSION_PATTERN = re.compile(r'((\d+(\.\d+)*\w*)|\'(\d+(\.\d+)*\w*)\'|\"(\d+(\.\d+)*\w*)\")')
def _is_literal(o):
if not isinstance(o, string_types) or not o:
return False
return o[0] in '\'"'
def _get_versions(s):
result = []
for m in _VERSION_PATTERN.finditer(s):
result.append(NV(m.groups()[0]))
return set(result)
class Evaluator(object):
operations = {
'==': lambda x, y: x == y,
'===': lambda x, y: x == y,
'~=': lambda x, y: x == y or x > y,
'!=': lambda x, y: x != y,
'<': lambda x, y: x < y,
'<=': lambda x, y: x == y or x < y,
'>': lambda x, y: x > y,
'>=': lambda x, y: x == y or x > y,
'and': lambda x, y: x and y,
'or': lambda x, y: x or y,
'in': lambda x, y: x in y,
'not in': lambda x, y: x not in y,
}
|
Apache License 2.0
|
arelle/arelle
|
arelle/CntlrWebMain.py
|
localhostCertificate
|
python
|
def localhostCertificate():
return '''
-----BEGIN CERTIFICATE-----
MIIDljCCAn4CAQAwDQYJKoZIhvcNAQEEBQAwgZAxCzAJBgNVBAYTAlVTMRMwEQYD
VQQIEwpDYWxpZm9ybmlhMQ8wDQYDVQQHEwZFbmNpbm8xEzARBgNVBAoTCmFyZWxs
ZS5vcmcxDzANBgNVBAsTBmFyZWxsZTESMBAGA1UEAxMJbG9jYWxob3N0MSEwHwYJ
KoZIhvcNAQkBFhJzdXBwb3J0QGFyZWxsZS5vcmcwHhcNMTIwMTIwMDg0NjM1WhcN
MTQxMDE1MDg0NjM1WjCBkDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3Ju
aWExDzANBgNVBAcTBkVuY2lubzETMBEGA1UEChMKYXJlbGxlLm9yZzEPMA0GA1UE
CxMGYXJlbGxlMRIwEAYDVQQDEwlsb2NhbGhvc3QxITAfBgkqhkiG9w0BCQEWEnN1
cHBvcnRAYXJlbGxlLm9yZzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
AMJEq9zT4cdA2BII4TG4OJSlUP22xXqNAJdZZeB5rTIX4ePwIZ8KfFh/XWQ1/q5I
c/rkZ5TyC+SbEmQa/unvv1CypMAWWMfuguU6adOsxt+zFFMJndlE1lr3A2SBjHbD
vBGzGJJTivBzDPBIQ0SGcf32usOeotmE2PA11c5en8/IsRXm9+TA/W1xL60mfphW
9PIaJ+WF9rRROjKXVdQZTRFsNRs/Ag8o3jWEyWYCwR97+XkorYsAJs2TE/4zV+8f
8wKuhOrsy9KYFZz2piVWaEC0hbtDwX1CqN+1oDHq2bYqLygUSD/LbgK1lxM3ciVy
ewracPVHBErPlcJFxiOxAw0CAwEAATANBgkqhkiG9w0BAQQFAAOCAQEAM2np3UVY
6g14oeV0Z32Gn04+r6FV2D2bobxCVLIQDsWGEv1OkjVBJTu0bLsZQuNVZHEn5a+2
I0+MGME3HK1rx1c8MrAsr5u7ZLMNj7cjjtFWAUp9GugJyOmGK136o4/j1umtBojB
iVPvHsAvwZuommfME+AaBE/aJjPy5I3bSu8x65o1fuJPycrSeLAnLd/shCiZ31xF
QnJ9IaIU1HOusplC13A0tKhmRMGNz9v+Vqdj7J/kpdTH7FNMulrJTv/0ezTPjaOB
QhpLdqly7hWJ23blbQQv4ILT2CiPDotJslcKDT7GzvPoDu6rIs2MpsB/4RDYejYU
+3cu//C8LvhjkQ==
-----END CERTIFICATE-----
'''
|
Interface to QuickBooks server responding to *get* requests for a host certificate */quickbooks/localhost.crt* or */localhost.crt*.
(Supports QuickBooks protocol.)
:returns: self-signed certificate
|
https://github.com/arelle/arelle/blob/f9b83eb6c95be457c9fe07dda8e3f6207f0ec9af/arelle/CntlrWebMain.py#L521-L551
|
from arelle.webserver.bottle import Bottle, request, response, static_file
from arelle.Cntlr import LogFormatter
import os, io, sys, time, threading, uuid, zipfile
from arelle import Version
from arelle.FileSource import FileNamedStringIO
from arelle.PluginManager import pluginClassMethods
_os_pid = os.getpid()
GETorPOST = ('GET', 'POST')
GET = 'GET'
POST = 'POST'
def startWebserver(_cntlr, options):
global imagesDir, cntlr, optionsPrototype
cntlr = _cntlr
imagesDir = cntlr.imagesDir
optionValuesTypes = _STR_NUM_TYPES + (type(None),)
optionsPrototype = dict((option,value if isinstance(value,_STR_NUM_TYPES) else None)
for option in dir(options)
for value in (getattr(options, option),)
if isinstance(value,optionValuesTypes) and not option.startswith('_'))
host, sep, portServer = options.webserver.partition(":")
port, sep, server = portServer.partition(":")
app = Bottle()
pluginResult = None
for pluginMethod in pluginClassMethods("CntlrWebMain.StartWebServer"):
pluginResult = pluginMethod(app, cntlr, host, port, server)
break
if not (isinstance(pluginResult, str) and "skip-routes" in pluginResult):
app.route('/rest/login', GET, login_form)
app.route('/rest/login', POST, login_submit)
app.route('/rest/logout', GET, logout)
app.route('/favicon.ico', GET, arelleIcon)
app.route('/rest/xbrl/<file:path>/open', GETorPOST, validation)
app.route('/rest/xbrl/<file:path>/close', GETorPOST, validation)
app.route('/rest/xbrl/<file:path>/validation/xbrl', GETorPOST, validation)
app.route('/rest/xbrl/<file:path>/DTS', GETorPOST, validation)
app.route('/rest/xbrl/<file:path>/concepts', GETorPOST, validation)
app.route('/rest/xbrl/<file:path>/pre', GETorPOST, validation)
app.route('/rest/xbrl/<file:path>/table', GETorPOST, validation)
app.route('/rest/xbrl/<file:path>/cal', GETorPOST, validation)
app.route('/rest/xbrl/<file:path>/dim', GETorPOST, validation)
app.route('/rest/xbrl/<file:path>/facts', GETorPOST, validation)
app.route('/rest/xbrl/<file:path>/factTable', GETorPOST, validation)
app.route('/rest/xbrl/<file:path>/roleTypes', GETorPOST, validation)
app.route('/rest/xbrl/<file:path>/arcroleTypes', GETorPOST, validation)
app.route('/rest/xbrl/<file:path>/formulae', GETorPOST, validation)
app.route('/rest/xbrl/validation', GETorPOST, validation)
app.route('/rest/xbrl/view', GETorPOST, validation)
app.route('/rest/xbrl/open', GETorPOST, validation)
app.route('/rest/xbrl/close', GETorPOST, validation)
app.route('/images/<imgFile>', GET, image)
app.route('/rest/xbrl/diff', GET, diff)
app.route('/rest/configure', GET, configure)
app.route('/rest/stopWebServer', GET, stopWebServer)
app.route('/quickbooks/server.asmx', POST, quickbooksServer)
app.route('/rest/quickbooks/<qbReport>/xbrl-gl/<file:path>', GET, quickbooksGLrequest)
app.route('/rest/quickbooks/<qbReport>/xbrl-gl/<file:path>/view', GET, quickbooksGLrequest)
app.route('/rest/quickbooks/<qbReport>/xbrl-gl/view', GET, quickbooksGLrequest)
app.route('/rest/quickbooks/response', GET, quickbooksGLresponse)
app.route('/quickbooks/server.html', GET, quickbooksWebPage)
app.route('/quickbooks/localhost.crt', GET, localhostCertificate)
app.route('/localhost.crt', GET, localhostCertificate)
app.route('/rest/test/test', GETorPOST, testTest)
app.route('/help', GET, helpREST)
app.route('/about', GET, about)
app.route('/', GET, indexPageREST)
if server == "cgi":
app.route('<cgiAppPath:path>', GETorPOST, cgiInterface)
if not (isinstance(pluginResult, str) and "skip-run" in pluginResult):
if server == "wsgi":
return app
elif server == "cgi":
if sys.stdin is None:
sys.stdin = open(os.devnull, 'r')
app.run(server=server)
sys.exit(0)
elif server:
sys.path.insert(0,os.path.join(os.path.dirname(__file__),"webserver"))
app.run(host=host, port=port or 80, server=server)
else:
app.run(host=host, port=port or 80)
def cgiInterface(cgiAppPath):
if not request.query:
return indexPageCGI()
elif 'about' in request.query:
return about(cgiAppPath + "?image=arelle32.gif")
elif 'help' in request.query:
return helpREST()
elif 'image' in request.query:
return image(request.query.image)
else:
return indexPageCGI()
def login_form():
return _('''<html><body><form method="POST"><table>
<tr><td>Name:</td><td><input name="name" type="text" /></td></tr>
<tr><td>Password:</td><td><input name="password" type="password" /></td></tr>
<tr><td> </td><td><input type="submit" value="Submit" /></td></tr>
</table></form></body></html>''')
def login_submit():
name = request.forms.get('name')
password = request.forms.get('password')
if checkLogin(name, password):
return _("<p>You are logged in as user: {0}</p>").format(name)
else:
return _("<p>Login failed</p>")
def checkLogin(_user, _password):
global user
user = _user
return True
def logout():
global user
user = None
return _("<p>You are logged out.</p>")
def arelleIcon():
return static_file("arelle.ico", root=imagesDir, mimetype='image/vnd.microsoft.icon')
def image(imgFile):
return static_file(imgFile, root=imagesDir)
validationOptions = {
"efm": ("validateEFM", True),
"efm-pragmatic": ("disclosureSystemName", "efm-pragmatic"),
"efm-strict": ("disclosureSystemName", "efm-strict"),
"efm-all-years": ("disclosureSystemName", "efm-all-years"),
"esef": ("disclosureSystemName", "esef"),
"disclosure-system": ("disclosureSystemName", None),
"ifrs": ("gfmName", "ifrs"),
"hmrc": ("gfmName", "hmrc"),
"sbr-nl": ("gfmName", "sbr-nl"),
"utr": ("utrValidate", True),
"infoset": ("infosetValidate", True),
"import": ("importFiles", None),
}
validationKeyVarName = {
"disclosureSystem": "disclosureSystemName",
"roleTypes": "roleTypesFile",
"arcroleTypes": "arcroleTypesFile"
}
class Options():
def __init__(self):
for option, defaultValue in optionsPrototype.items():
setattr(self, option, defaultValue)
supportedViews = {'DTS', 'concepts', 'pre', 'table', 'cal', 'dim', 'facts', 'factTable', 'formulae', 'roleTypes', 'arcroleTypes'}
def validation(file=None):
errors = []
flavor = request.query.flavor or 'standard'
media = request.query.media or 'html'
requestPathParts = request.urlparts[2].split('/')
isValidation = 'validation' == requestPathParts[-1] or 'validation' == requestPathParts[-2]
view = request.query.view
viewArcrole = request.query.viewArcrole
if request.method == 'POST':
mimeType = request.get_header("Content-Type")
if mimeType.startswith("multipart/form-data"):
_upload = request.files.get("upload")
if not _upload or not _upload.filename.endswith(".zip"):
errors.append(_("POST file upload must be a zip file"))
sourceZipStream = None
else:
sourceZipStream = _upload.file
elif mimeType not in ('application/zip', 'application/x-zip', 'application/x-zip-compressed', 'multipart/x-zip'):
errors.append(_("POST must provide a zip file, Content-Type '{0}' not recognized as a zip file.").format(mimeType))
sourceZipStream = request.body
else:
sourceZipStream = None
if not view and not viewArcrole:
if requestPathParts[-1] in supportedViews:
view = requestPathParts[-1]
if isValidation:
if view or viewArcrole:
errors.append(_("Only validation or one view can be specified in one requested."))
if media not in ('xml', 'xhtml', 'html', 'json', 'text', 'zip') and not (sourceZipStream and media == 'zip'):
errors.append(_("Media '{0}' is not supported for validation (please select xhtml, html, xml, json or text)").format(media))
elif view or viewArcrole:
if media not in ('xml', 'xhtml', 'html', 'csv', 'xlsx', 'json'):
errors.append(_("Media '{0}' is not supported for view (please select xhtml, html, xml, csv, xlsx or json)").format(media))
elif requestPathParts[-1] not in ("open", "close"):
errors.append(_("Neither validation nor view requested, nothing to do."))
if (flavor not in ('standard', 'standard-except-formula', 'formula-compile-only', 'formula-compile-and-run')
and not flavor.startswith('edgar') and not flavor.startswith('sec')):
errors.append(_("Flavor '{0}' is not supported").format(flavor))
if view and view not in supportedViews:
errors.append(_("View '{0}' is not supported").format(view))
if errors:
errors.insert(0, _("URL: ") + (file or request.query.file or '(no file)'))
return errorReport(errors, media)
options = Options()
isFormulaOnly = False
for key, value in request.query.items():
if key == "file":
setattr(options, "entrypointFile", value)
elif key == "flavor":
if value.startswith("sec") or value.startswith("edgar"):
setattr(options, "validateEFM", True)
elif value == "formula-compile-only":
isFormulaOnly = True
setattr(options, "formulaAction", "validate")
elif value == "formula-compile-and-run":
isFormulaOnly = True
setattr(options, "formulaAction", "run")
elif value == "standard-except-formula":
setattr(options, "formulaAction", "none")
elif key in("media", "view", "viewArcrole"):
pass
elif key in validationOptions:
optionKey, optionValue = validationOptions[key]
setattr(options, optionKey, optionValue if optionValue is not None else value)
elif key in validationKeyVarName:
setattr(options, validationKeyVarName[key], value or True)
elif not value:
setattr(options, key, True)
else:
setattr(options, key, value)
if file:
setattr(options, "entrypointFile", file.replace(';','/'))
requestPathParts = set(request.urlparts[2].split('/'))
viewFile = None
if isValidation:
if not isFormulaOnly:
setattr(options, "validate", True)
elif view:
viewFile = FileNamedStringIO(media)
setattr(options, view + "File", viewFile)
elif viewArcrole:
viewFile = FileNamedStringIO(media)
setattr(options, "viewArcrole", viewArcrole)
setattr(options, "viewFile", viewFile)
return runOptionsAndGetResult(options, media, viewFile, sourceZipStream)
def runOptionsAndGetResult(options, media, viewFile, sourceZipStream=None):
addLogToZip = False
if media == "zip" and not viewFile:
responseZipStream = io.BytesIO()
if (hasattr(options, "saveOIMinstance") or
(getattr(options, "entrypointFile", "") or "").rpartition(".")[2] in ("json", "csv", "xlsx")):
plugins = (getattr(options, "plugins", "") or "").split("|")
if getattr(options, "entrypointFile", "").rpartition(".")[2] in ("json", "csv", "xlsx"):
if "loadFromOIM" not in plugins:
plugins.append("loadFromOIM")
addLogToZip = True
if getattr(options, "saveOIMinstance", "").rpartition(".")[2] in ("json", "csv", "xlsx"):
if "saveLoadableOIM" not in plugins:
plugins.append("saveLoadableOIM")
addLogToZip = True
setattr(options, "saveLoadableOIM", getattr(options, "saveOIMinstance"))
setattr(options, "saveOIMinstance", None)
setattr(options, "plugins", "|".join(p for p in plugins if p) or None)
else:
responseZipStream = None
successful = cntlr.run(options, sourceZipStream, responseZipStream)
if media == "xml":
response.content_type = 'text/xml; charset=UTF-8'
elif media == "csv":
response.content_type = 'text/csv; charset=UTF-8'
elif media == "json":
response.content_type = 'application/json; charset=UTF-8'
elif media == "text":
response.content_type = 'text/plain; charset=UTF-8'
elif media == "zip":
response.content_type = 'application/zip; charset=UTF-8'
else:
response.content_type = 'text/html; charset=UTF-8'
if successful and viewFile:
result = viewFile.getvalue().replace(" ","\u00A0").replace("­","\u00AD").replace("&","&")
viewFile.close()
elif media == "zip":
responseZipStream.seek(0)
if addLogToZip:
_zip = zipfile.ZipFile(responseZipStream, "a", zipfile.ZIP_DEFLATED, True)
_zip.writestr("log.txt", cntlr.logHandler.getText())
_zip.close()
responseZipStream.seek(0)
result = responseZipStream.read()
responseZipStream.close()
cntlr.logHandler.clearLogBuffer()
elif media == "xml":
result = cntlr.logHandler.getXml()
elif media == "json":
result = cntlr.logHandler.getJson()
elif media == "text":
_logFormat = request.query.logFormat
if _logFormat:
_stdLogFormatter = cntlr.logHandler.formatter
cntlr.logHandler.formatter = LogFormatter(_logFormat)
result = cntlr.logHandler.getText()
if _logFormat:
cntlr.logHandler.formatter = _stdLogFormatter
del _stdLogFormatter
else:
result = htmlBody(tableRows(cntlr.logHandler.getLines(), header=_("Messages")))
return result
def diff():
if not request.query.fromDTS or not request.query.toDTS or not request.query.report:
return _("From DTS, to DTS, and report must be specified")
options = Options()
setattr(options, "entrypointFile", request.query.fromDTS)
setattr(options, "diffFile", request.query.toDTS)
fh = FileNamedStringIO(request.query.report)
setattr(options, "versReportFile", fh)
cntlr.run(options)
reportContents = fh.getvalue()
fh.close()
response.content_type = 'text/xml; charset=UTF-8'
return reportContents
def configure():
if not request.query.proxy and not request.query.plugins and not request.query.packages and 'environment' not in request.query:
return _("proxy, plugins, packages or environment must be specified")
options = Options()
if request.query.proxy:
setattr(options, "proxy", request.query.proxy)
if request.query.plugins:
setattr(options, "plugins", request.query.plugins)
if request.query.packages:
setattr(options, "packages", request.query.packages)
if 'environment' in request.query:
setattr(options, "showEnvironment", True)
cntlr.run(options)
response.content_type = 'text/html; charset=UTF-8'
return htmlBody(tableRows(cntlr.logHandler.getLines(), header=_("Configuration Request")))
def stopWebServer():
def stopSoon(delaySeconds):
time.sleep(delaySeconds)
import signal
os.kill(_os_pid, signal.SIGTERM)
threading.Thread(target=stopSoon, args=(2.5,), daemon=True).start()
response.content_type = 'text/html; charset=UTF-8'
return htmlBody(tableRows((time.strftime("Received at %Y-%m-%d %H:%M:%S"),
"Good bye...",),
header=_("Stop Request")))
def testTest():
return "Results attached:\n" + multipartResponse((
("file1", "text/plain", "test text 1"),
("file2", "text/plain", "test text 2"),
("file3", "text/plain", "test text 3"),
))
def quickbooksServer():
from arelle import CntlrQuickBooks
response.content_type = 'text/xml; charset=UTF-8'
return CntlrQuickBooks.server(cntlr, request.body, request.urlparts)
def quickbooksGLrequest(qbReport=None, file=None):
from arelle.CntlrQuickBooks import supportedQbReports, qbRequest
from arelle.ModelValue import dateTime
errors = []
requestPathParts = request.urlparts[2].split('/')
viewRequested = "view" == requestPathParts[-1]
media = request.query.media or 'html'
fromDate = request.query.fromDate
toDate = request.query.toDate
if qbReport not in supportedQbReports:
errors.append(_("QuickBooks report '{0}' is not supported (please select from: {1})").format(
qbReport, ', '.join(supportedQbReports)))
if media not in ('xml', 'xhtml', 'html'):
errors.append(_("Media '{0}' is not supported for xbrl-gl (please select xhtml, html or xml)").format(media))
if not fromDate or dateTime(fromDate) is None:
errors.append(_("FromDate '{0}' missing or not valid").format(fromDate))
if not toDate or dateTime(toDate) is None:
errors.append(_("ToDate '{0}' missing or not valid").format(toDate))
if errors:
return errorReport(errors, media)
ticket = qbRequest(qbReport, fromDate, toDate, file)
result = htmlBody(tableRows([_("Request queued for QuickBooks...")], header=_("Quickbooks Request")), script='''
<script type="text/javascript">
<!--
var timer = setInterval("autoRefresh()", 1000 * 10);
function autoRefresh(){{location.href = "/rest/quickbooks/response?ticket={0}&media={1}&view={2}";}}
//-->
</script>
'''.format(ticket, media, viewRequested))
return result
def quickbooksGLresponse():
from arelle import CntlrQuickBooks
ticket = request.query.ticket
media = request.query.media
viewRequested = request.query.view
status = CntlrQuickBooks.qbRequestStatus.get(ticket)
if not status:
return htmlBody(tableRows([_("QuickBooks ticket not found, request canceled.")], header=_("Quickbooks Request")))
if status.startswith("ConnectionErrorMessage: "):
CntlrQuickBooks.qbRequestStatus.pop(ticket, None)
return errorReport([status[24:]], media)
if status != "Done" or ticket not in CntlrQuickBooks.xbrlInstances:
return htmlBody(tableRows([_("{0}, Waiting 20 seconds...").format(status)],
header=_("Quickbooks Request")),
script='''
<script type="text/javascript">
<!--
var timer = setInterval("autoRefresh()", 1000 * 20);
function autoRefresh(){{clearInterval(timer);self.location.reload(true);}}
//-->
</script>
''')
CntlrQuickBooks.qbRequestStatus.pop(ticket)
instanceUuid = CntlrQuickBooks.xbrlInstances[ticket]
CntlrQuickBooks.xbrlInstances.pop(ticket)
options = Options()
setattr(options, "entrypointFile", instanceUuid)
viewFile = FileNamedStringIO(media)
setattr(options, "factsFile", viewFile)
return runOptionsAndGetResult(options, media, viewFile)
def quickbooksWebPage():
return htmlBody(_('''<table width="700p">
<tr><th colspan="2">Arelle QuickBooks Global Ledger Interface</th></tr>
<tr><td>checkbox</td><td>Trial Balance.</td></tr>
<tr><td>close button</td><td>Done</td></tr>
</table>'''))
|
Apache License 2.0
|
dedsecinside/awesome-scripts
|
APIs/Flask Login using Facebook API/app.py
|
index
|
python
|
def index():
if request.method == 'POST':
if request.form['password'] == PASSWORD:
session['user'] = USER_NAME
return redirect(url_for('profile'))
if 'user' in session:
return redirect(url_for('profile'))
return render_template('index.html')
|
Show the current page.
Args:
|
https://github.com/dedsecinside/awesome-scripts/blob/856835e5ff5f8a6af2d74bb25800c620feb712e3/APIs/Flask Login using Facebook API/app.py#L29-L43
|
from flask import Flask, render_template, request, session, redirect, url_for, g
import os
import string
import random
import requests
app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(24)
redirect_url = r'http://localhost:5000/get-code'
url_token = r"https://powerful-inlet-11533.herokuapp.com/auth"
access_token = None
name = None
USER_NAME = None
PASSWORD = None
def state_key():
return ''.join(random.choices(string.ascii_uppercase + string.digits))
@app.route("/", methods=['GET', 'POST'])
@app.route("/index", methods=['GET', 'POST'])
|
MIT License
|
practical-formal-methods/queryfuzz
|
queryfuzz/engines/souffle/souffle.py
|
SouffleProgram.export_program_string
|
python
|
def export_program_string(self, core_path):
self.program_path = os.path.join(core_path, "program_" + str(self.program_number))
self.program_file_path = os.path.join(self.program_path, "orig_rules.dl")
self.logs.set_log_file_name("orig.log")
self.logs.set_log_file_path(self.program_path)
os.mkdir(self.program_path)
create_file(self.program_string, self.program_file_path)
if self.params["in_file_facts"] is False:
for fact in self.facts:
fact.generate_fact_file(self.program_path)
|
Export original program string
|
https://github.com/practical-formal-methods/queryfuzz/blob/330be12fb9567e4b94968ac17be030a390d02e9f/queryfuzz/engines/souffle/souffle.py#L304-L319
|
from queryfuzz.datalog.base_program import BaseProgram
from queryfuzz.engines.souffle.souffle_rule import SouffleRule
from queryfuzz.engines.souffle.souffle_fact import SouffleFact
from queryfuzz.engines.souffle.souffle_aggregate import SouffleAggregate
from queryfuzz.engines.souffle.souffle_subgoal import SouffleSubgoal
from queryfuzz.utils.file_operations import create_file
from copy import deepcopy
from termcolor import colored
import os
class SouffleProgram(BaseProgram):
def get_allowed_types(self):
self.allowed_types = deepcopy(self.params["souffle_types"])
def parse_program(self):
self.add_log_text("\tReading seed file: " + self.seed_program_file)
with open(self.seed_program_file, 'r') as f:
lines = f.read().splitlines()
for line in lines:
if line.find(".type") != -1:
self.type_declarations.append(line + " //Parsed entity")
continue
if line.find(".decl") != -1:
self.declarations.append(line + " //Parsed entity")
parsed_subgoal = SouffleSubgoal(randomness=self.randomness, arity=0, params=self.params)
parsed_subgoal.parse_subgoal_declaration(line)
self.add_log_text("\tParsing subgoal: " + line + " Arity: " + str(parsed_subgoal.get_arity()))
if parsed_subgoal.get_arity() != 0:
self.all_relations.append(parsed_subgoal)
for _type in parsed_subgoal.get_types():
if _type not in self.allowed_types: self.allowed_types.append(_type)
continue
if line.find(".input") != -1:
self.inputs.append(line + " //Parsed entity")
continue
if line.find(":-") != -1:
parsed_rule = SouffleRule(verbose=self.verbose, randomness=self.randomness, params=self.params)
parsed_rule.set_string(line + " //parsed rule")
self.all_rules.append(parsed_rule)
continue
if line[0:2] == "//" or line == "" or line.find(".output") != -1:
continue
self.other_things.append(line + " //Parsed entity")
def generate_cycle_breaker_rules(self):
if self.number_of_mixed_rules == 0: return 0
for i in range(self.number_of_cycle_breaker_rules):
cycle_breaker_rule = SouffleRule(verbose=self.verbose, randomness=self.randomness, params=self.params)
cycle_breaker_rule.generate_random_rule(ruleType="cycle breaker", allowed_types=self.allowed_types, available_relations=self.all_relations)
self.declarations.append(cycle_breaker_rule.get_declaration())
self.all_rules.append(cycle_breaker_rule)
self.cycle_breakers.append(cycle_breaker_rule.get_head())
def generate_mixed_rules(self):
for i in range(self.number_of_mixed_rules):
mixed_rule = SouffleRule(verbose=self.verbose, randomness=self.randomness, params=self.params)
mixed_rule.generate_random_rule(ruleType="mixed", allowed_types=self.allowed_types, available_relations=self.all_relations)
mixed_rule.add_negated_subgoals(available_relations=self.all_relations)
mixed_rule.generate_predicates()
mixed_rule.insert_operations_in_head()
aggregate = SouffleAggregate(parent_rule=mixed_rule,
verbose=self.verbose,
randomness=self.randomness,
params=self.params,
allowed_types=self.params["souffle_types"],
available_relations=self.all_relations)
if self.params["aggregate"]: mixed_rule.add_aggregate(aggregate.get_string())
mixed_rule.generate_heads(non_cyclic_relations=self.cycle_breakers)
disjunctive_rules = list()
for j in range(self.randomness.get_random_integer(0, self.params["max_number_of_disjunctions"])):
dis_mixed_rule = SouffleRule(verbose=self.verbose, randomness=self.randomness, params=self.params)
dis_mixed_rule.generate_disjunctive_rule(parent_rule=mixed_rule, available_relations=self.all_relations)
dis_mixed_rule.add_negated_subgoals(available_relations=self.all_relations)
dis_mixed_rule.generate_predicates()
dis_mixed_rule.insert_operations_in_head()
aggregate = SouffleAggregate(parent_rule=dis_mixed_rule,
verbose=self.verbose,
randomness=self.randomness,
params=self.params,
allowed_types=self.params["souffle_types"],
available_relations=self.all_relations)
if self.params["aggregate"]: dis_mixed_rule.add_aggregate(aggregate.get_string())
disjunctive_rules.append(dis_mixed_rule)
self.declarations.append(mixed_rule.get_declaration())
self.all_relations.append(deepcopy(mixed_rule.get_head()))
self.all_rules.append(mixed_rule)
self.all_rules = self.all_rules + disjunctive_rules
self.all_relations = self.all_relations + self.cycle_breakers
def generate_complex_rules(self):
for i in range(self.number_of_complex_rules):
complex_rule = SouffleRule(verbose=self.verbose, randomness=self.randomness, params=self.params)
complex_rule.generate_random_rule(ruleType="complex", allowed_types=self.allowed_types, available_relations=self.all_relations)
complex_rule.add_negated_subgoals(available_relations=self.all_relations)
disjunctive_rules = list()
for j in range(self.randomness.get_random_integer(0, self.params["max_number_of_disjunctions"])):
dis_complex_rule = SouffleRule(verbose=self.verbose, randomness=self.randomness, params=self.params)
dis_complex_rule.generate_disjunctive_rule(parent_rule=complex_rule, available_relations=self.all_relations)
dis_complex_rule.add_negated_subgoals(available_relations=self.all_relations)
disjunctive_rules.append(dis_complex_rule)
self.declarations.append(complex_rule.get_declaration())
self.all_relations.append(deepcopy(complex_rule.get_head()))
self.all_rules.append(complex_rule)
self.all_rules = self.all_rules + disjunctive_rules
def generate_simple_rules(self):
for i in range(self.number_of_simple_rules):
rule = SouffleRule(verbose=self.verbose, randomness=self.randomness, params=self.params)
rule.generate_random_rule(ruleType="simple", allowed_types=self.allowed_types, available_relations=self.all_relations)
disjunctive_rules = list()
for j in range(self.randomness.get_random_integer(0, self.params["max_number_of_disjunctions"])):
dis_simple_rule = SouffleRule(verbose=self.verbose, randomness=self.randomness, params=self.params)
dis_simple_rule.generate_disjunctive_rule(parent_rule=rule, available_relations=self.all_relations)
disjunctive_rules.append(dis_simple_rule)
self.declarations.append(rule.get_declaration())
self.all_relations.append(deepcopy(rule.get_head()))
self.all_rules.append(rule)
self.all_rules = self.all_rules + disjunctive_rules
def generate_facts(self):
for i in range(self.number_of_facts):
fact_table = SouffleFact(randomness=self.randomness, params=self.params)
self.declarations.append(fact_table.get_decleration())
self.facts.append(fact_table)
self.all_relations.append(fact_table.get_fact_as_a_relation())
if self.params["in_file_facts"] is False: self.inputs.append(fact_table.get_fact_input_string())
def pretty_print_program(self):
for decl in self.type_declarations: print(colored(decl, "green", attrs=["bold"]))
print("\n\n")
for decl in self.declarations: print(colored(decl, "red", attrs=["bold"]))
print("")
for _input in self.inputs: print(colored(_input, "green", attrs=["bold"]))
print("")
print(colored( ".output " + self.output_rule.get_head().get_name(), "green", attrs=["bold"]))
print("\n\n")
if self.params["in_file_facts"]:
for fact in self.facts:
for row in fact.get_fact_data(): print(colored(row, "yellow", attrs=["bold"]))
print("")
for thing in self.other_things:
print(colored(thing, "yellow", attrs=["bold"]))
print("")
for rule in self.all_rules:
rule_string = deepcopy(rule.get_string())
if rule_string.find("parsed rule") != -1:
rule_string = rule_string.replace("//parsed rule", "")
print(colored(rule_string, "blue", attrs=["bold"]), end="")
print(colored("//parsed rule", "green", attrs=["bold"]))
if rule_string.find("cycle breaker rule") != -1:
rule_string = rule_string.replace("//cycle breaker rule", "")
print(colored(rule_string, "blue", attrs=["bold"]), end="")
print(colored("//cycle breaker rule", "red", attrs=["bold"]))
if rule_string.find("mixed rule") != -1:
rule_string = rule_string.replace("//mixed rule", "")
print(colored(rule_string, "blue", attrs=["bold"]), end="")
print(colored("//mixed rule", "magenta", attrs=["bold"]))
if rule_string.find("complex rule") != -1:
rule_string = rule_string.replace("//complex rule", "")
print(colored(rule_string, "blue", attrs=["bold"]), end="")
print(colored("//complex rule", "red", attrs=["bold"]))
if rule_string.find("simple rule") != -1:
rule_string = rule_string.replace("//simple rule", "")
print(colored(rule_string, "blue", attrs=["bold"]), end="")
print(colored("//simple rule", "green", attrs=["bold"]))
if rule_string.find("transformed rule") != -1:
print(colored(rule_string, "yellow", attrs=["bold"]))
def create_program_string(self):
for type_decl in self.type_declarations:
self.program_string += type_decl + "\n"
for decl in self.declarations:
self.program_string += decl + "\n"
self.program_string += "\n\n"
for _input in self.inputs:
self.program_string += _input + "\n"
if self.params["in_file_facts"]:
self.program_string += "\n\n"
for fact in self.facts:
for row in fact.get_fact_data():
self.program_string += row + "\n"
for thing in self.other_things:
self.program_string += thing + "\n"
self.program_string += "\n\n"
for rule in self.all_rules:
self.program_string += rule.get_string() + "\n"
self.program_string += "\n" + ".output " + self.output_rule.get_head().get_name() + "\n"
def add_transformation_information(self, oracle):
self.program_string = "// TRANSFORMED PROGRAM\n"
self.program_string += "// Oracle: " + oracle + " \n\n"
|
Apache License 2.0
|
python-cmaketools/python-cmaketools
|
cmaketools/cmakebuilder.py
|
CMakeBuilder.get_generators
|
python
|
def get_generators(as_list=False):
return cmakeutil.get_generators(CMakeBuilder.path, as_list)
|
get available CMake generators
Parameter:
as_list str: True to return a list of dict of all generators. Each entry
consists of 'name', 'desc', and 'default'
Returns: str if as_list==False else dict[]
|
https://github.com/python-cmaketools/python-cmaketools/blob/c7988584ff3ee0a873a8cbb03997a80f16efc93b/cmaketools/cmakebuilder.py#L98-L108
|
import os
import re
from operator import itemgetter
from setuptools import Extension
from pathlib import Path as _Path, PurePath as _PurePath
from distutils import sysconfig
from . import cmakeutil
from . import gitutil
class CMakeBuilder:
path = cmakeutil.findexe("cmake")
@staticmethod
|
MIT License
|
xmyqsh/retinanet
|
lib/fast_rcnn/train.py
|
_process_boxes_scores
|
python
|
def _process_boxes_scores(cls_prob, bbox_pred, rois, im_scale, im_shape):
assert rois.shape[0] == bbox_pred.shape[0], 'rois and bbox_pred must have the same shape'
boxes = rois[:, 1:5]
scores = cls_prob
if cfg.TEST.BBOX_REG:
pred_boxes = bbox_transform_inv(boxes, deltas=bbox_pred)
pred_boxes = clip_boxes(pred_boxes, im_shape)
else:
pred_boxes = clip_boxes(boxes, im_shape)
return pred_boxes, scores
|
process the output tensors, to get the boxes and scores
|
https://github.com/xmyqsh/retinanet/blob/2aab1afe22d9f14b4ac5c469eef4cc097e8173da/lib/fast_rcnn/train.py#L341-L357
|
import numpy as np
import os
import tensorflow as tf
from tensorflow.python.client import timeline
import cv2
from .nms_wrapper import nms_wrapper
from ..roi_data_layer.layer import RoIDataLayer
from ..utils.timer import Timer
from ..gt_data_layer import roidb as gdl_roidb
from ..roi_data_layer import roidb as rdl_roidb
from ..fast_rcnn.config import cfg
from ..fast_rcnn.bbox_transform import clip_boxes, bbox_transform_inv
_DEBUG = False
class SolverWrapper(object):
def __init__(self, sess, network, imdb, roidb, output_dir, logdir, pretrained_model=None):
self.net = network
self.imdb = imdb
self.roidb = roidb
self.output_dir = output_dir
self.pretrained_model = pretrained_model
print 'Computing bounding-box regression targets...'
if cfg.TRAIN.BBOX_REG:
self.bbox_means, self.bbox_stds = rdl_roidb.add_bbox_regression_targets(roidb)
print 'done'
self.saver = tf.train.Saver(max_to_keep=100)
self.writer = tf.summary.FileWriter(logdir=logdir,
graph=tf.get_default_graph(),
flush_secs=5)
def snapshot(self, sess, iter):
net = self.net
if cfg.TRAIN.BBOX_REG and net.layers.has_key('bbox_pred') and cfg.TRAIN.BBOX_NORMALIZE_TARGETS:
with tf.variable_scope('Fast-RCNN', reuse=True):
with tf.variable_scope('bbox_pred'):
weights = tf.get_variable("weights")
biases = tf.get_variable("biases")
orig_0 = weights.eval()
orig_1 = biases.eval()
weights_shape = weights.get_shape().as_list()
sess.run(weights.assign(orig_0 * np.tile(self.bbox_stds, (weights_shape[0],1))))
sess.run(biases.assign(orig_1 * self.bbox_stds + self.bbox_means))
if not os.path.exists(self.output_dir):
os.makedirs(self.output_dir)
infix = ('_' + cfg.TRAIN.SNAPSHOT_INFIX
if cfg.TRAIN.SNAPSHOT_INFIX != '' else '')
filename = (cfg.TRAIN.SNAPSHOT_PREFIX + infix +
'_iter_{:d}'.format(iter+1) + '.ckpt')
filename = os.path.join(self.output_dir, filename)
self.saver.save(sess, filename)
print 'Wrote snapshot to: {:s}'.format(filename)
if cfg.TRAIN.BBOX_REG and net.layers.has_key('bbox_pred'):
sess.run(weights.assign(orig_0))
sess.run(biases.assign(orig_1))
def build_image_summary(self):
log_image_data = tf.placeholder(tf.uint8, [None, None, 3])
log_image_name = tf.placeholder(tf.string)
from tensorflow.python.ops import gen_logging_ops
from tensorflow.python.framework import ops as _ops
log_image = gen_logging_ops._image_summary(log_image_name, tf.expand_dims(log_image_data, 0), max_images=1)
_ops.add_to_collection(_ops.GraphKeys.SUMMARIES, log_image)
return log_image, log_image_data, log_image_name
def train_model(self, sess, max_iters, restore=False):
data_layer = get_data_layer(self.roidb, self.imdb.num_classes)
loss, cross_entropy, loss_box, = self.net.build_loss()
tf.summary.scalar('cls_loss', cross_entropy)
tf.summary.scalar('rgs_loss', loss_box)
tf.summary.scalar('loss', loss)
summary_op = tf.summary.merge_all()
log_image, log_image_data, log_image_name = self.build_image_summary()
if cfg.TRAIN.SOLVER == 'Adam':
opt = tf.train.AdamOptimizer(cfg.TRAIN.LEARNING_RATE)
elif cfg.TRAIN.SOLVER == 'RMS':
opt = tf.train.RMSPropOptimizer(cfg.TRAIN.LEARNING_RATE)
else:
lr = tf.Variable(cfg.TRAIN.LEARNING_RATE, trainable=False)
momentum = cfg.TRAIN.MOMENTUM
opt = tf.train.MomentumOptimizer(lr, momentum)
global_step = tf.Variable(0, trainable=False)
with_clip = True if self.net.name == 'RetinaNet_train_test' else False
if with_clip:
trainable_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'res3_5')
trainable_vars += tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Top-Down')
trainable_vars += tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'clsSubNet')
trainable_vars += tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'boxSubNet')
grads, norm = tf.clip_by_global_norm(tf.gradients(loss, trainable_vars), 4.0)
train_op = opt.apply_gradients(zip(grads, trainable_vars), global_step=global_step)
else:
trainable_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'res3_5')
trainable_vars += tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'Top-Down')
trainable_vars += tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'clsSubNet')
trainable_vars += tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'boxSubNet')
train_op = opt.minimize(loss, global_step=global_step, var_list=trainable_vars)
sess.run(tf.global_variables_initializer())
restore_iter = 0
if self.pretrained_model is not None and not restore:
try:
print ('Loading pretrained model '
'weights from {:s}').format(self.pretrained_model)
self.net.load(self.pretrained_model, sess, True)
except:
raise 'Check your pretrained model {:s}'.format(self.pretrained_model)
if restore:
try:
ckpt = tf.train.get_checkpoint_state(self.output_dir)
print 'Restoring from {}...'.format(ckpt.model_checkpoint_path),
self.saver.restore(sess, ckpt.model_checkpoint_path)
stem = os.path.splitext(os.path.basename(ckpt.model_checkpoint_path))[0]
restore_iter = int(stem.split('_')[-1])
sess.run(global_step.assign(restore_iter))
print 'done'
except:
raise 'Check your pretrained {:s}'.format(ckpt.model_checkpoint_path)
last_snapshot_iter = -1
timer = Timer()
for iter in range(restore_iter, max_iters):
timer.tic()
if iter != 0 and iter % cfg.TRAIN.STEPSIZE == 0:
sess.run(tf.assign(lr, lr.eval() * cfg.TRAIN.GAMMA))
blobs = data_layer.forward()
if (iter + 1) % (cfg.TRAIN.DISPLAY) == 0:
print 'image: %s' %(blobs['im_name']),
feed_dict={
self.net.data: blobs['data'],
self.net.im_info: blobs['im_info'],
self.net.gt_boxes: blobs['gt_boxes'],
}
'''
res_fetches = [self.net.get_output('cls_prob'), # FRCNN class prob
self.net.get_output('bbox_pred'), # FRCNN rgs output
self.net.get_output('rois')] # RPN rgs output
'''
res_fetches = []
fetch_list = [cross_entropy,
loss_box,
summary_op,
train_op] + res_fetches
if _DEBUG:
fetch_list = [cross_entropy,
loss_box,
summary_op] + res_fetches
fetch_list += [self.net.get_output('cls_score_reshape'), self.net.get_output('cls_prob_reshape')]
fetch_list += []
rpn_loss_cls_value, rpn_loss_box_value, loss_cls_value, loss_box_value, summary_str, cls_prob, bbox_pred, rois, rpn_cls_score_reshape_np, rpn_cls_prob_reshape_np = sess.run(fetches=fetch_list, feed_dict=feed_dict)
else:
fetch_list = [cross_entropy,
loss_box,
summary_op,
train_op] + res_fetches
fetch_list += []
loss_cls_value, loss_box_value, summary_str, _, = sess.run(fetches=fetch_list, feed_dict=feed_dict)
self.writer.add_summary(summary=summary_str, global_step=global_step.eval())
_diff_time = timer.toc(average=False)
'''
# image summary
if (iter) % cfg.TRAIN.LOG_IMAGE_ITERS == 0:
# plus mean
ori_im = np.squeeze(blobs['data']) + cfg.PIXEL_MEANS
ori_im = ori_im.astype(dtype=np.uint8, copy=False)
ori_im = _draw_gt_to_image(ori_im, blobs['gt_boxes'], blobs['gt_ishard'])
ori_im = _draw_dontcare_to_image(ori_im, blobs['dontcare_areas'])
# draw rects
# print 'rois:', rois.shape[0]
if cfg.TRAIN.BBOX_REG and cfg.TRAIN.BBOX_NORMALIZE_TARGETS:
bbox_pred = bbox_pred * np.tile(self.bbox_stds, (bbox_pred.shape[0], 1)) + \
np.tile(self.bbox_means, (bbox_pred.shape[0], 1))
boxes, scores = _process_boxes_scores(cls_prob, bbox_pred, rois, blobs['im_info'][0][2], ori_im.shape)
res = nms_wrapper(scores, boxes, threshold=0.7)
image = cv2.cvtColor(_draw_boxes_to_image(ori_im, res), cv2.COLOR_BGR2RGB)
log_image_name_str = ('%06d_' % iter ) + blobs['im_name']
log_image_summary_op = \
sess.run(log_image, \
feed_dict={log_image_name: log_image_name_str,\
log_image_data: image})
self.writer.add_summary(log_image_summary_op, global_step=global_step.eval())
'''
if (iter) % (cfg.TRAIN.DISPLAY) == 0:
print 'iter: %d / %d, total loss: %.4f, loss_cls: %.4f, loss_box: %.4f, lr: %f'% (iter, max_iters, loss_cls_value + loss_box_value , loss_cls_value, loss_box_value, lr.eval())
print 'speed: {:.3f}s / iter'.format(_diff_time)
if (iter+1) % cfg.TRAIN.SNAPSHOT_ITERS == 0:
last_snapshot_iter = iter
self.snapshot(sess, iter)
if last_snapshot_iter != iter:
self.snapshot(sess, iter)
def get_training_roidb(imdb):
if cfg.TRAIN.USE_FLIPPED:
print 'Appending horizontally-flipped training examples...'
imdb.append_flipped_images()
print 'done'
print 'Preparing training data...'
if cfg.TRAIN.HAS_RPN:
if cfg.IS_MULTISCALE:
print ('#### warning: multi-scale has not been tested.')
print ('#### warning: using single scale by setting IS_MULTISCALE: False.')
gdl_roidb.prepare_roidb(imdb)
else:
rdl_roidb.prepare_roidb(imdb)
else:
rdl_roidb.prepare_roidb(imdb)
print 'done'
return imdb.roidb
def get_data_layer(roidb, num_classes):
if cfg.TRAIN.HAS_RPN:
if cfg.IS_MULTISCALE:
raise "Calling caffe modules..."
else:
layer = RoIDataLayer(roidb, num_classes)
else:
layer = RoIDataLayer(roidb, num_classes)
return layer
|
MIT License
|
jest-community/jest-pytest
|
src/__tests__/integration/home-assistant/homeassistant/components/media_player/cast.py
|
CastDevice.new_connection_status
|
python
|
def new_connection_status(self, connection_status):
from pychromecast.socket_client import CONNECTION_STATUS_CONNECTED
new_available = connection_status.status == CONNECTION_STATUS_CONNECTED
if new_available != self._available:
_LOGGER.debug("Cast device availability changed: %s",
connection_status.status)
self._available = new_available
self.schedule_update_ha_state()
|
Handle updates of connection status.
|
https://github.com/jest-community/jest-pytest/blob/b197b0b31e3ca5c411202d97583cbd2d2b0b92e9/src/__tests__/integration/home-assistant/homeassistant/components/media_player/cast.py#L390-L402
|
import logging
import threading
from typing import Optional, Tuple
import voluptuous as vol
import attr
from homeassistant.exceptions import PlatformNotReady
from homeassistant.helpers.typing import HomeAssistantType, ConfigType
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import (dispatcher_send,
async_dispatcher_connect)
from homeassistant.components.media_player import (
MEDIA_TYPE_MUSIC, MEDIA_TYPE_TVSHOW, MEDIA_TYPE_MOVIE, SUPPORT_NEXT_TRACK,
SUPPORT_PAUSE, SUPPORT_PLAY_MEDIA, SUPPORT_PREVIOUS_TRACK,
SUPPORT_TURN_OFF, SUPPORT_TURN_ON, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET,
SUPPORT_STOP, SUPPORT_PLAY, MediaPlayerDevice, PLATFORM_SCHEMA)
from homeassistant.const import (
CONF_HOST, STATE_IDLE, STATE_OFF, STATE_PAUSED, STATE_PLAYING,
EVENT_HOMEASSISTANT_STOP)
import homeassistant.helpers.config_validation as cv
import homeassistant.util.dt as dt_util
REQUIREMENTS = ['pychromecast==2.1.0']
_LOGGER = logging.getLogger(__name__)
CONF_IGNORE_CEC = 'ignore_cec'
CAST_SPLASH = 'https://home-assistant.io/images/cast/splash.png'
DEFAULT_PORT = 8009
SUPPORT_CAST = SUPPORT_PAUSE | SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE | SUPPORT_TURN_ON | SUPPORT_TURN_OFF | SUPPORT_PREVIOUS_TRACK | SUPPORT_NEXT_TRACK | SUPPORT_PLAY_MEDIA | SUPPORT_STOP | SUPPORT_PLAY
INTERNAL_DISCOVERY_RUNNING_KEY = 'cast_discovery_running'
KNOWN_CHROMECAST_INFO_KEY = 'cast_known_chromecasts'
ADDED_CAST_DEVICES_KEY = 'cast_added_cast_devices'
SIGNAL_CAST_DISCOVERED = 'cast_discovered'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_HOST): cv.string,
vol.Optional(CONF_IGNORE_CEC, default=[]): vol.All(cv.ensure_list,
[cv.string])
})
@attr.s(slots=True, frozen=True)
class ChromecastInfo(object):
host = attr.ib(type=str)
port = attr.ib(type=int)
uuid = attr.ib(type=Optional[str], converter=attr.converters.optional(str),
default=None)
model_name = attr.ib(type=str, default='')
friendly_name = attr.ib(type=Optional[str], default=None)
@property
def is_audio_group(self) -> bool:
return self.port != DEFAULT_PORT
@property
def is_information_complete(self) -> bool:
return all(attr.astuple(self))
@property
def host_port(self) -> Tuple[str, int]:
return self.host, self.port
def _fill_out_missing_chromecast_info(info: ChromecastInfo) -> ChromecastInfo:
if info.is_information_complete or info.is_audio_group:
return info
from pychromecast import dial
http_device_status = dial.get_device_status(info.host)
if http_device_status is None:
return info
return ChromecastInfo(
host=info.host, port=info.port,
uuid=(info.uuid or http_device_status.uuid),
friendly_name=(info.friendly_name or http_device_status.friendly_name),
model_name=(info.model_name or http_device_status.model_name)
)
def _discover_chromecast(hass: HomeAssistantType, info: ChromecastInfo):
if info in hass.data[KNOWN_CHROMECAST_INFO_KEY]:
_LOGGER.debug("Discovered previous chromecast %s", info)
return
info = _fill_out_missing_chromecast_info(info)
_LOGGER.debug("Discovered chromecast %s", info)
if info.uuid is not None:
same_uuid = set(x for x in hass.data[KNOWN_CHROMECAST_INFO_KEY]
if info.uuid == x.uuid)
hass.data[KNOWN_CHROMECAST_INFO_KEY] -= same_uuid
hass.data[KNOWN_CHROMECAST_INFO_KEY].add(info)
dispatcher_send(hass, SIGNAL_CAST_DISCOVERED, info)
def _setup_internal_discovery(hass: HomeAssistantType) -> None:
if INTERNAL_DISCOVERY_RUNNING_KEY not in hass.data:
hass.data[INTERNAL_DISCOVERY_RUNNING_KEY] = threading.Lock()
if not hass.data[INTERNAL_DISCOVERY_RUNNING_KEY].acquire(blocking=False):
return
import pychromecast
def internal_callback(name):
mdns = listener.services[name]
_discover_chromecast(hass, ChromecastInfo(*mdns))
_LOGGER.debug("Starting internal pychromecast discovery.")
listener, browser = pychromecast.start_discovery(internal_callback)
def stop_discovery(event):
_LOGGER.debug("Stopping internal pychromecast discovery.")
pychromecast.stop_discovery(browser)
hass.data[INTERNAL_DISCOVERY_RUNNING_KEY].release()
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_discovery)
@callback
def _async_create_cast_device(hass: HomeAssistantType,
info: ChromecastInfo):
if info.uuid is None:
return CastDevice(info)
added_casts = hass.data[ADDED_CAST_DEVICES_KEY]
if info.uuid in added_casts:
return None
added_casts.add(info.uuid)
return CastDevice(info)
async def async_setup_platform(hass: HomeAssistantType, config: ConfigType,
async_add_devices, discovery_info=None):
import pychromecast
pychromecast.IGNORE_CEC += config.get(CONF_IGNORE_CEC, [])
hass.data.setdefault(ADDED_CAST_DEVICES_KEY, set())
hass.data.setdefault(KNOWN_CHROMECAST_INFO_KEY, set())
info = None
if discovery_info is not None:
info = ChromecastInfo(host=discovery_info['host'],
port=discovery_info['port'])
elif CONF_HOST in config:
info = ChromecastInfo(host=config[CONF_HOST],
port=DEFAULT_PORT)
@callback
def async_cast_discovered(discover: ChromecastInfo) -> None:
if info is not None and info.host_port != discover.host_port:
return
cast_device = _async_create_cast_device(hass, discover)
if cast_device is not None:
async_add_devices([cast_device])
async_dispatcher_connect(hass, SIGNAL_CAST_DISCOVERED,
async_cast_discovered)
for chromecast in list(hass.data[KNOWN_CHROMECAST_INFO_KEY]):
async_cast_discovered(chromecast)
if info is None or info.is_audio_group:
hass.async_add_job(_setup_internal_discovery, hass)
else:
info = await hass.async_add_job(_fill_out_missing_chromecast_info,
info)
if info.friendly_name is None:
raise PlatformNotReady
hass.async_add_job(_discover_chromecast, hass, info)
class CastStatusListener(object):
def __init__(self, cast_device, chromecast):
self._cast_device = cast_device
self._valid = True
chromecast.register_status_listener(self)
chromecast.socket_client.media_controller.register_status_listener(
self)
chromecast.register_connection_listener(self)
def new_cast_status(self, cast_status):
if self._valid:
self._cast_device.new_cast_status(cast_status)
def new_media_status(self, media_status):
if self._valid:
self._cast_device.new_media_status(media_status)
def new_connection_status(self, connection_status):
if self._valid:
self._cast_device.new_connection_status(connection_status)
def invalidate(self):
self._valid = False
class CastDevice(MediaPlayerDevice):
def __init__(self, cast_info):
self._cast_info = cast_info
self._chromecast = None
self.cast_status = None
self.media_status = None
self.media_status_received = None
self._available = False
self._status_listener = None
async def async_added_to_hass(self):
@callback
def async_cast_discovered(discover: ChromecastInfo):
if self._cast_info.uuid is None:
return
if self._cast_info.uuid != discover.uuid:
return
_LOGGER.debug("Discovered chromecast with same UUID: %s", discover)
self.hass.async_add_job(self.async_set_cast_info(discover))
async def async_stop(event):
await self._async_disconnect()
async_dispatcher_connect(self.hass, SIGNAL_CAST_DISCOVERED,
async_cast_discovered)
self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, async_stop)
self.hass.async_add_job(self.async_set_cast_info(self._cast_info))
async def async_will_remove_from_hass(self) -> None:
await self._async_disconnect()
if self._cast_info.uuid is not None:
self.hass.data[ADDED_CAST_DEVICES_KEY].remove(self._cast_info.uuid)
async def async_set_cast_info(self, cast_info):
import pychromecast
old_cast_info = self._cast_info
self._cast_info = cast_info
if self._chromecast is not None:
if old_cast_info.host_port == cast_info.host_port:
return
await self._async_disconnect()
_LOGGER.debug("Connecting to cast device %s", cast_info)
chromecast = await self.hass.async_add_job(
pychromecast._get_chromecast_from_host, attr.astuple(cast_info))
self._chromecast = chromecast
self._status_listener = CastStatusListener(self, chromecast)
self._available = True
self.cast_status = chromecast.status
self.media_status = chromecast.media_controller.status
_LOGGER.debug("Connection successful!")
self.async_schedule_update_ha_state()
async def _async_disconnect(self):
if self._chromecast is None:
return
_LOGGER.debug("Disconnecting from chromecast socket.")
self._available = False
self.async_schedule_update_ha_state()
await self.hass.async_add_job(self._chromecast.disconnect)
self._chromecast = None
self.cast_status = None
self.media_status = None
self.media_status_received = None
if self._status_listener is not None:
self._status_listener.invalidate()
self._status_listener = None
self.async_schedule_update_ha_state()
def new_cast_status(self, cast_status):
self.cast_status = cast_status
self.schedule_update_ha_state()
def new_media_status(self, media_status):
self.media_status = media_status
self.media_status_received = dt_util.utcnow()
self.schedule_update_ha_state()
|
MIT License
|
jonathanadams/home-assistant-configuration
|
custom_components/alexa_media/switch.py
|
DNDSwitch.icon
|
python
|
def icon(self):
return super()._icon("mdi:do-not-disturb", "mdi:do-not-disturb-off")
|
Return the icon of the switch.
|
https://github.com/jonathanadams/home-assistant-configuration/blob/04bacf53c37290ed22dd831d9359a70e44e01fcb/custom_components/alexa_media/switch.py#L304-L306
|
import logging
from typing import List
from homeassistant.components.switch import SwitchDevice
from homeassistant.exceptions import NoEntitySpecifiedError
from . import (
CONF_EMAIL,
CONF_EXCLUDE_DEVICES,
CONF_INCLUDE_DEVICES,
DATA_ALEXAMEDIA,
DOMAIN as ALEXA_DOMAIN,
hide_email,
hide_serial,
)
from .helpers import _catch_login_errors, add_devices, retry_async
_LOGGER = logging.getLogger(__name__)
@retry_async(limit=5, delay=5, catch_exceptions=True)
async def async_setup_platform(hass, config, add_devices_callback, discovery_info=None):
devices = []
SWITCH_TYPES = [
("dnd", DNDSwitch),
("shuffle", ShuffleSwitch),
("repeat", RepeatSwitch),
]
account = config[CONF_EMAIL]
include_filter = config.get(CONF_INCLUDE_DEVICES, [])
exclude_filter = config.get(CONF_EXCLUDE_DEVICES, [])
account_dict = hass.data[DATA_ALEXAMEDIA]["accounts"][account]
_LOGGER.debug("%s: Loading switches", hide_email(account))
if "switch" not in account_dict["entities"]:
(hass.data[DATA_ALEXAMEDIA]["accounts"][account]["entities"]["switch"]) = {}
for key, _ in account_dict["devices"]["media_player"].items():
if key not in account_dict["entities"]["media_player"]:
_LOGGER.debug(
"%s: Media player %s not loaded yet; delaying load",
hide_email(account),
hide_serial(key),
)
if devices:
await add_devices(
hide_email(account),
devices,
add_devices_callback,
include_filter,
exclude_filter,
)
return False
if key not in (
hass.data[DATA_ALEXAMEDIA]["accounts"][account]["entities"]["switch"]
):
(
hass.data[DATA_ALEXAMEDIA]["accounts"][account]["entities"]["switch"][
key
]
) = {}
for (switch_key, class_) in SWITCH_TYPES:
if (
switch_key == "dnd"
and not account_dict["devices"]["switch"][key].get("dnd")
) or (
switch_key in ["shuffle", "repeat"]
and "MUSIC_SKILL"
not in account_dict["devices"]["media_player"][key].get(
"capabilities"
)
):
_LOGGER.debug(
"%s: Skipping %s for %s",
hide_email(account),
switch_key,
hide_serial(key),
)
continue
alexa_client = class_(
account_dict["entities"]["media_player"][key], account
)
_LOGGER.debug(
"%s: Found %s %s switch with status: %s",
hide_email(account),
hide_serial(key),
switch_key,
alexa_client.is_on,
)
devices.append(alexa_client)
(
hass.data[DATA_ALEXAMEDIA]["accounts"][account]["entities"][
"switch"
][key][switch_key]
) = alexa_client
else:
for alexa_client in hass.data[DATA_ALEXAMEDIA]["accounts"][account][
"entities"
]["switch"][key].values():
_LOGGER.debug(
"%s: Skipping already added device: %s",
hide_email(account),
alexa_client,
)
return await add_devices(
hide_email(account),
devices,
add_devices_callback,
include_filter,
exclude_filter,
)
async def async_setup_entry(hass, config_entry, async_add_devices):
return await async_setup_platform(
hass, config_entry.data, async_add_devices, discovery_info=None
)
async def async_unload_entry(hass, entry) -> bool:
account = entry.data[CONF_EMAIL]
account_dict = hass.data[DATA_ALEXAMEDIA]["accounts"][account]
for key, switches in account_dict["entities"]["switch"].items():
for device in switches[key].values():
await device.async_remove()
return True
class AlexaMediaSwitch(SwitchDevice):
def __init__(self, client, switch_property, switch_function, account, name="Alexa"):
self._client = client
self._login = client._login
self._account = account
self._name = name
self._switch_property = switch_property
self._state = False
self._switch_function = switch_function
async def async_added_to_hass(self):
try:
if not self.enabled:
return
except AttributeError:
pass
self._listener = self.hass.bus.async_listen(
f"{ALEXA_DOMAIN}_{hide_email(self._login.email)}"[0:32], self._handle_event
)
async def async_will_remove_from_hass(self):
self._listener()
def _handle_event(self, event):
try:
if not self.enabled:
return
except AttributeError:
pass
if "queue_state" in event.data:
queue_state = event.data["queue_state"]
if queue_state["dopplerId"]["deviceSerialNumber"] == self._client.unique_id:
self._state = getattr(self._client, self._switch_property)
self.async_schedule_update_ha_state()
@_catch_login_errors
async def _set_switch(self, state, **kwargs):
try:
if not self.enabled:
return
except AttributeError:
pass
success = await self._switch_function(state)
if success:
setattr(self._client, self._switch_property, state)
_LOGGER.debug(
"Switch set to %s based on %s",
getattr(self._client, self._switch_property),
state,
)
self.async_schedule_update_ha_state()
elif self.should_poll:
_LOGGER.debug(
"Requesting update of %s due to %s switch to %s",
self._client,
self._name,
state,
)
await self._client.async_update()
@property
def is_on(self):
return self.available and getattr(self._client, self._switch_property)
async def async_turn_on(self, **kwargs):
await self._set_switch(True, **kwargs)
async def async_turn_off(self, **kwargs):
await self._set_switch(False, **kwargs)
@property
def available(self):
return getattr(self._client, self._switch_property) is not None
@property
def unique_id(self):
return self._client.unique_id + "_" + self._name
@property
def name(self):
return "{} {} switch".format(self._client.name, self._name)
@property
def device_class(self):
return "switch"
@property
def hidden(self):
return not self.available
@property
def should_poll(self):
return not (
self.hass.data[DATA_ALEXAMEDIA]["accounts"][self._account]["websocket"]
)
@_catch_login_errors
async def async_update(self):
try:
if not self.enabled:
return
except AttributeError:
pass
try:
self.async_schedule_update_ha_state()
except NoEntitySpecifiedError:
pass
@property
def device_info(self):
return {
"identifiers": {(ALEXA_DOMAIN, self._client.unique_id)},
"via_device": (ALEXA_DOMAIN, self._client.unique_id),
}
@property
def icon(self):
return self._icon()
def _icon(self, on=None, off=None):
return on if self.is_on else off
class DNDSwitch(AlexaMediaSwitch):
def __init__(self, client, account):
super().__init__(
client,
"dnd_state",
client.alexa_api.set_dnd_state,
account,
"do not disturb",
)
@property
|
MIT License
|
aparo/pyes
|
pyes/queryset.py
|
QuerySet.__getitem__
|
python
|
def __getitem__(self, k):
if not isinstance(k, (slice,) + integer_types):
raise TypeError
assert ((not isinstance(k, slice) and (k >= 0))
or (isinstance(k, slice) and (k.start is None or k.start >= 0)
and (k.stop is None or k.stop >= 0))), "Negative indexing is not supported."
if self._result_cache is None:
len(self)
return self._result_cache.__getitem__(k)
|
Retrieves an item or slice from the set of results.
|
https://github.com/aparo/pyes/blob/96965174760cb5aa5c92eac7ccff346fb5d53cf1/pyes/queryset.py#L234-L247
|
import copy
import six
from .es import ES
from .filters import ANDFilter, ORFilter, NotFilter, Filter, TermsFilter, TermFilter, RangeFilter, ExistsFilter
from .facets import Facet, TermFacet
from .aggs import Agg, TermsAgg
from .models import ElasticSearchModel
from .orm.exceptions import DoesNotExist, MultipleObjectsReturned
from .query import MatchAllQuery, BoolQuery, FilteredQuery, Search
from .utils import ESRange
from .utils.compat import integer_types
REPR_OUTPUT_SIZE = 20
def get_es_connection(es_url, es_kwargs):
if es_url:
es_kwargs.update(server=es_url)
return ES(**es_kwargs)
class ESModel(ElasticSearchModel):
def __init__(self, index, type, es_url=None, es_kwargs={}):
self._index = index
self._type = type
self.objects = QuerySet(self, es_url=es_url, es_kwargs=es_kwargs)
setattr(self, "DoesNotExist", DoesNotExist)
setattr(self, "MultipleObjectsReturned", MultipleObjectsReturned)
def generate_model(index, doc_type, es_url=None, es_kwargs={}):
MyModel = type('MyModel', (ElasticSearchModel,), {})
setattr(MyModel, "objects", QuerySet(MyModel, index=index, type=doc_type, es_url=es_url, es_kwargs=es_kwargs))
setattr(MyModel, "DoesNotExist", DoesNotExist)
setattr(MyModel, "MultipleObjectsReturned", MultipleObjectsReturned)
return MyModel
class QuerySet(object):
def __init__(self, model=None, using=None, index=None, type=None, es_url=None, es_kwargs={}):
self.es_url = es_url
self.es_kwargs = es_kwargs
if model is None and index and type:
model = ESModel(index, type, es_url=self.es_url, es_kwargs=self.es_kwargs)
self.model = model
self._index = index
if using:
self._index = using
self._type=type
self._queries = []
self._filters = []
self._facets = []
self._aggs = []
self._ordering = []
self._fields = []
self._size=None
self._start=0
self._result_cache = None
def _clear_ordering(self):
self._ordering=[]
@property
def index(self):
if self._index:
return self._index
return self.model._index
@property
def type(self):
if self._type:
return self._type
return self.model._type
def __deepcopy__(self, memo):
obj = self.__class__()
for k,v in self.__dict__.items():
if k in ('_iter','_result_cache'):
obj.__dict__[k] = None
else:
obj.__dict__[k] = copy.deepcopy(v, memo)
return obj
def __getstate__(self):
len(self)
obj_dict = self.__dict__.copy()
obj_dict['_iter'] = None
return obj_dict
def __repr__(self):
data = list(self[:REPR_OUTPUT_SIZE + 1])
if len(data) > REPR_OUTPUT_SIZE:
data[-1] = "...(remaining elements truncated)..."
return repr(data)
def _build_query(self):
if not self._queries and not self._filters:
return MatchAllQuery()
query = MatchAllQuery()
if self._queries:
if len(self._queries)==1:
query=self._queries[0]
else:
query=BoolQuery(must=self._queries)
if not self._filters:
return query
if len(self._filters)==1:
return FilteredQuery(query, self._filters[0])
return FilteredQuery(query, ANDFilter(self._filters))
def _build_search(self):
query=Search(self._build_query())
if self._ordering:
query.sort=self._ordering
if self._facets:
for facet in self._facets:
query.facet.add(facet)
if self._aggs:
for agg in self._aggs:
query.agg.add(agg)
if self._start is not None:
query.start = self._start
if self._size is not None:
query.size = self._size
return query
def _do_query(self):
return get_es_connection(self.es_url, self.es_kwargs).search(self._build_search(), indices=self.index, doc_types=self.type)
def __len__(self):
if self._result_cache is None:
self._result_cache = self._do_query()
return self._result_cache.total
def __iter__(self):
if self._result_cache is None:
len(self)
return iter(self._result_cache)
def __bool__(self):
return self.__nonzero__()
def __nonzero__(self):
if self._result_cache is not None:
len(self)
return bool(self._result_cache.total!=0)
try:
next(iter(self))
except StopIteration:
return False
return True
|
BSD 3-Clause New or Revised License
|
openstack/glance
|
glance/db/sqlalchemy/api.py
|
image_destroy
|
python
|
def image_destroy(context, image_id):
session = get_session()
with session.begin():
image_ref = _image_get(context, image_id, session=session)
_check_mutate_authorization(context, image_ref)
image_ref.delete(session=session)
delete_time = image_ref.deleted_at
_image_locations_delete_all(context, image_id, delete_time, session)
_image_property_delete_all(context, image_id, delete_time, session)
_image_member_delete_all(context, image_id, delete_time, session)
_image_tag_delete_all(context, image_id, delete_time, session)
return _normalize_locations(context, image_ref)
|
Destroy the image or raise if it does not exist.
|
https://github.com/openstack/glance/blob/ff8e3d4a0a00caff4949620e1ddf3e541a522923/glance/db/sqlalchemy/api.py#L185-L205
|
import datetime
import itertools
import threading
from oslo_config import cfg
from oslo_db import exception as db_exception
from oslo_db.sqlalchemy import session
from oslo_log import log as logging
from oslo_utils import excutils
import osprofiler.sqlalchemy
from retrying import retry
import six
from six.moves import range
import sqlalchemy
from sqlalchemy.ext.compiler import compiles
from sqlalchemy import MetaData, Table
import sqlalchemy.orm as sa_orm
from sqlalchemy import sql
import sqlalchemy.sql as sa_sql
from glance.common import exception
from glance.common import timeutils
from glance.common import utils
from glance.db.sqlalchemy.metadef_api import (resource_type
as metadef_resource_type_api)
from glance.db.sqlalchemy.metadef_api import (resource_type_association
as metadef_association_api)
from glance.db.sqlalchemy.metadef_api import namespace as metadef_namespace_api
from glance.db.sqlalchemy.metadef_api import object as metadef_object_api
from glance.db.sqlalchemy.metadef_api import property as metadef_property_api
from glance.db.sqlalchemy.metadef_api import tag as metadef_tag_api
from glance.db.sqlalchemy import models
from glance.db import utils as db_utils
from glance.i18n import _, _LW, _LI, _LE
sa_logger = None
LOG = logging.getLogger(__name__)
STATUSES = ['active', 'saving', 'queued', 'killed', 'pending_delete',
'deleted', 'deactivated', 'importing', 'uploading']
CONF = cfg.CONF
CONF.import_group("profiler", "glance.common.wsgi")
_FACADE = None
_LOCK = threading.Lock()
def _retry_on_deadlock(exc):
if isinstance(exc, db_exception.DBDeadlock):
LOG.warn(_LW("Deadlock detected. Retrying..."))
return True
return False
def _create_facade_lazily():
global _LOCK, _FACADE
if _FACADE is None:
with _LOCK:
if _FACADE is None:
_FACADE = session.EngineFacade.from_config(CONF)
if CONF.profiler.enabled and CONF.profiler.trace_sqlalchemy:
osprofiler.sqlalchemy.add_tracing(sqlalchemy,
_FACADE.get_engine(),
"db")
return _FACADE
def get_engine():
facade = _create_facade_lazily()
return facade.get_engine()
def get_session(autocommit=True, expire_on_commit=False):
facade = _create_facade_lazily()
return facade.get_session(autocommit=autocommit,
expire_on_commit=expire_on_commit)
def _validate_db_int(**kwargs):
max_int = (2 ** 31) - 1
for param_key, param_value in kwargs.items():
if param_value and param_value > max_int:
msg = _("'%(param)s' value out of range, "
"must not exceed %(max)d.") % {"param": param_key,
"max": max_int}
raise exception.Invalid(msg)
def clear_db_env():
global _FACADE
_FACADE = None
def _check_mutate_authorization(context, image_ref):
if not is_image_mutable(context, image_ref):
LOG.warn(_LW("Attempted to modify image user did not own."))
msg = _("You do not own this image")
if image_ref.visibility in ['private', 'shared']:
exc_class = exception.Forbidden
else:
exc_class = exception.ForbiddenPublicImage
raise exc_class(msg)
def image_create(context, values, v1_mode=False):
image = _image_update(context, values, None, purge_props=False)
if v1_mode:
image = db_utils.mutate_image_dict_to_v1(image)
return image
def image_update(context, image_id, values, purge_props=False,
from_state=None, v1_mode=False, atomic_props=None):
image = _image_update(context, values, image_id, purge_props,
from_state=from_state, atomic_props=atomic_props)
if v1_mode:
image = db_utils.mutate_image_dict_to_v1(image)
return image
def image_restore(context, image_id):
session = get_session()
with session.begin():
image_ref = _image_get(context, image_id, session=session)
if image_ref.status != 'pending_delete':
msg = (_('cannot restore the image from %s to active (wanted '
'from_state=pending_delete)') % image_ref.status)
raise exception.Conflict(msg)
query = session.query(models.Image).filter_by(id=image_id)
values = {'status': 'active', 'deleted': 0}
query.update(values, synchronize_session='fetch')
@retry(retry_on_exception=_retry_on_deadlock, wait_fixed=500,
stop_max_attempt_number=50)
|
Apache License 2.0
|
adw0rd/instagrapi
|
instagrapi/mixins/story.py
|
StoryMixin.story_delete
|
python
|
def story_delete(self, story_pk: int) -> bool:
assert self.user_id, "Login required"
media_id = self.media_id(story_pk)
self._stories_cache.pop(self.media_pk(media_id), None)
return self.media_delete(media_id)
|
Delete story
Parameters
----------
story_pk: int
Unique identifier of the story
Returns
-------
bool
A boolean value
|
https://github.com/adw0rd/instagrapi/blob/759533a285747105c25858e738f1b3bc1cef6953/instagrapi/mixins/story.py#L94-L111
|
import json
import shutil
from copy import deepcopy
from pathlib import Path
from typing import List
from urllib.parse import urlparse
import requests
from instagrapi import config
from instagrapi.exceptions import ClientNotFoundError, StoryNotFound, UserNotFound
from instagrapi.extractors import (
extract_story_gql,
extract_story_v1,
extract_user_short,
)
from instagrapi.types import Story, UserShort
class StoryMixin:
_stories_cache = {}
def story_pk_from_url(self, url: str) -> int:
path = urlparse(url).path
parts = [p for p in path.split("/") if p and p.isdigit()]
return int(parts[0])
def story_info_v1(self, story_pk: int) -> Story:
story_id = self.media_id(story_pk)
story_pk, user_id = story_id.split("_")
stories = self.user_stories_v1(user_id)
story_pk = int(story_pk)
for story in stories:
self._stories_cache[story.pk] = story
if story_pk in self._stories_cache:
return deepcopy(self._stories_cache[story_pk])
raise StoryNotFound(story_pk=story_pk, user_id=user_id)
def story_info(self, story_pk: int, use_cache: bool = True) -> Story:
if not use_cache or story_pk not in self._stories_cache:
story = self.story_info_v1(story_pk)
self._stories_cache[story_pk] = story
return deepcopy(self._stories_cache[story_pk])
|
MIT License
|
opendilab/gobigger
|
gobigger/players/human_player.py
|
HumanPlayer.get_keys_sort_by_balls
|
python
|
def get_keys_sort_by_balls(self):
items = self.balls.items()
backitems=[[v[1],v[0]] for v in items]
backitems.sort(reverse=True)
return [ backitems[i][1] for i in range(0,len(backitems))]
|
Overview:
Sort by ball size from largest to smallest
Return:
<list>: list of names
|
https://github.com/opendilab/gobigger/blob/2fae8678662a9be9d5d5797fd09815a9c920d215/gobigger/players/human_player.py#L120-L130
|
import uuid
from pygame.math import Vector2
import logging
from .base_player import BasePlayer
from gobigger.balls import FoodBall, ThornsBall, CloneBall, SporeBall
class HumanPlayer(BasePlayer):
def __init__(self, cfg, team_name, name, border, spore_settings):
self.team_name = team_name
self.name = name
self.border = border
self.balls = {}
self.ball_settings = cfg
self.spore_settings = spore_settings
self.stop_flag = False
def get_clone_num(self):
return len(self.balls)
def get_balls(self):
return list(self.balls.values())
def add_balls(self, balls):
if isinstance(balls, list):
for ball in balls:
self.balls[ball.name] = ball
elif isinstance(balls, CloneBall):
self.balls[balls.name] = balls
return True
def move(self, direction=None, duration=0.05):
if direction is not None:
self.stop_flag = False
for ball in self.balls.values():
ball.stop_flag = False
if self.stop_flag:
if self.get_clone_num() == 1:
for ball in self.balls.values():
try:
ball.move(given_acc=None, given_acc_center=None, duration=duration)
except:
import pdb; pdb.set_trace()
else:
centroid = self.cal_centroid()
for ball in self.balls.values():
given_acc_center = centroid - ball.position
if given_acc_center.length() == 0:
given_acc_center = Vector2(0.000001, 0.000001)
elif given_acc_center.length() > 1:
given_acc_center = given_acc_center.normalize()
given_acc_center *= 20
ball.move(given_acc=direction, given_acc_center=given_acc_center, duration=duration)
else:
if self.get_clone_num() == 1:
for ball in self.balls.values():
ball.move(given_acc=direction, given_acc_center=Vector2(0,0), duration=duration)
else:
centroid = self.cal_centroid()
for ball in self.balls.values():
given_acc_center = centroid - ball.position
if given_acc_center.length() == 0:
given_acc_center = Vector2(0.000001, 0.000001)
elif given_acc_center.length() > 1:
given_acc_center = given_acc_center.normalize()
given_acc_center *= 20
ball.move(given_acc=direction, given_acc_center=given_acc_center, duration=duration)
self.size_decay()
return True
def size_decay(self):
for ball in self.balls.values():
ball.size_decay()
return True
def eject(self):
ret = []
for ball in self.balls.values():
ret.append(ball.eject())
return ret
|
Apache License 2.0
|
f0lg0/oncogene
|
src/clientlinux.py
|
Client.sendClipBoard
|
python
|
def sendClipBoard(self):
cb = pyperclip.paste()
if len(cb) == 0:
self.client.send("/".encode("utf-8"))
else:
self.client.send(cb.encode("utf-8"))
|
Requirements:
- xsel
- xclip
|
https://github.com/f0lg0/oncogene/blob/e4ece3f18a98236a54d4278aee9571dc38a81f53/src/clientlinux.py#L191-L201
|
import socket
import subprocess
import sys
import os
import time
import platform
import threading
import pyperclip
from mss import mss
from zipfile import ZipFile
from pynput.keyboard import Key, Listener, Controller
class Client:
def __init__(self, server_ip, port, buffer_size, client_ip):
self.SERVER_IP = server_ip
self.PORT = port
self.BUFFER_SIZE = buffer_size
self.CLIENT_IP = client_ip
self.screenshot_counter = 0
self.keyLogger = True
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connectToServer(self):
self.client.connect((self.SERVER_IP, self.PORT))
def updateBuffer(self, size):
buff = ""
for counter in range(0, len(size)):
if size[counter].isdigit():
buff += size[counter]
return int(buff)
def saveBigFile(self, size, buff):
full = b''
while True:
if sys.getsizeof(full) >= size:
break
recvfile = self.client.recv(buff)
full += recvfile
return full
def sendHostInfo(self):
host = sys.platform
self.client.send(host.encode("utf-8"))
cpu = platform.processor()
system = platform.system()
machine = platform.machine()
with open('./logs/info.txt', 'w+') as f:
f.writelines(["CPU: " + cpu + '\n', "System: " + system + '\n', "Machine: " + machine + '\n'])
with open('./logs/info.txt', 'rb+') as f:
self.client.send(f.read())
os.remove('./logs/info.txt')
def screenshot(self):
sct = mss()
sct.shot(output = './logs/screen{}.png'.format(self.screenshot_counter))
picsize = os.path.getsize('./logs/screen{}.png'.format(self.screenshot_counter))
size = str(picsize)
self.client.send(size.encode("utf-8"))
screen = open('./logs/screen{}.png'.format(self.screenshot_counter), 'rb')
tosend = screen.read()
self.client.send(tosend)
screen.close()
os.remove('./logs/screen{}.png'.format(self.screenshot_counter))
self.screenshot_counter += 1
def receiveFile(self):
recvname = self.client.recv(self.BUFFER_SIZE)
name = recvname.decode("utf-8")
recvsize = self.client.recv(self.BUFFER_SIZE)
size = recvsize.decode("utf-8")
if int(size) <= self.BUFFER_SIZE:
recvfile = self.client.recv(self.BUFFER_SIZE)
with open(f'./logs/{name}', 'wb+') as f:
f.write(recvfile)
else:
buff = self.updateBuffer(size)
fullfile = self.saveBigFile(int(size), buff)
with open(f'./logs/{name}', 'wb+') as f:
f.write(fullfile)
def runFile(self):
exfile = self.client.recv(self.BUFFER_SIZE)
exfilepath = exfile.decode("utf-8")
try:
exec(open(exfilepath).read())
self.client.send("OK".encode("utf-8"))
except:
self.client.send("ERROR".encode("utf-8"))
def sendFile(self):
path = self.client.recv(self.BUFFER_SIZE).decode("utf-8")
filelist = os.listdir(path)
self.client.send("OK".encode("utf-8"))
time.sleep(0.1)
archname = './logs/files.zip'
archive = ZipFile(archname, 'w')
for file in filelist:
archive.write(path + '/' + file)
archive.close()
arcsize = os.path.getsize(archname)
self.client.send(str(arcsize).encode("utf-8"))
time.sleep(0.1)
with open('./logs/files.zip', 'rb') as to_send:
self.client.send(to_send.read())
os.remove(archname)
def stopKeyLogger(self):
keyboard = Controller()
keyboard.press(Key.esc)
keyboard.release(Key.esc)
self.keyLogger = False
def sendKeyLogs(self):
try:
archname = './logs/files.zip'
archive = ZipFile(archname, 'w')
archive.write('./logs/readable.txt')
archive.write('./logs/keycodes.txt')
archive.close()
self.client.send("[OK]".encode("utf-8"))
time.sleep(0.1)
arcsize = os.path.getsize(archname)
self.client.send(str(arcsize).encode("utf-8"))
time.sleep(0.1)
with open('./logs/files.zip', 'rb') as to_send:
self.client.send(to_send.read())
os.remove(archname)
except:
self.client.send("[ERROR]".encode("utf-8"))
|
MIT License
|
davesmeghead/visonic
|
custom_components/visonic/create_schema.py
|
create_parameters4
|
python
|
def create_parameters4(options: dict):
return {
vol.Optional(
CONF_B0_ENABLE_MOTION_PROCESSING,
default=create_default(options, CONF_B0_ENABLE_MOTION_PROCESSING, False),
): bool,
vol.Optional(
CONF_B0_MAX_TIME_FOR_TRIGGER_EVENT,
default=create_default(options, CONF_B0_MAX_TIME_FOR_TRIGGER_EVENT, 5),
): int,
vol.Optional(
CONF_B0_MIN_TIME_BETWEEN_TRIGGERS,
default=create_default(options, CONF_B0_MIN_TIME_BETWEEN_TRIGGERS, 30),
): int,
}
|
Create parameter set 4.
|
https://github.com/davesmeghead/visonic/blob/fd8ceb2636ae985ebfd6c0f0da71e2644c635b64/custom_components/visonic/create_schema.py#L209-L225
|
import logging
import voluptuous as vol
from typing import Any
from homeassistant.const import CONF_DEVICE, CONF_HOST, CONF_PATH, CONF_PORT, CONF_USERNAME, CONF_PASSWORD
from homeassistant.helpers import config_validation as cv
from homeassistant.util.yaml.objects import NodeListClass
from .const import (
CONF_EXCLUDE_SENSOR,
CONF_EXCLUDE_X10,
CONF_ENABLE_REMOTE_ARM,
CONF_ENABLE_REMOTE_DISARM,
CONF_ENABLE_SENSOR_BYPASS,
CONF_ARM_CODE_AUTO,
CONF_OVERRIDE_CODE,
CONF_FORCE_KEYPAD,
CONF_INSTANT_ARM_AWAY,
CONF_INSTANT_ARM_HOME,
CONF_AUTO_SYNC_TIME,
CONF_B0_ENABLE_MOTION_PROCESSING,
CONF_B0_MAX_TIME_FOR_TRIGGER_EVENT,
CONF_B0_MIN_TIME_BETWEEN_TRIGGERS,
CONF_DEVICE_BAUD,
CONF_DEVICE_TYPE,
CONF_DOWNLOAD_CODE,
CONF_FORCE_AUTOENROLL,
CONF_FORCE_STANDARD,
CONF_LANGUAGE,
CONF_MOTION_OFF_DELAY,
CONF_SIREN_SOUNDING,
CONF_LOG_CSV_FN,
CONF_LOG_CSV_TITLE,
CONF_LOG_DONE,
CONF_LOG_EVENT,
CONF_LOG_MAX_ENTRIES,
CONF_LOG_REVERSE,
CONF_LOG_XML_FN,
CONF_ALARM_NOTIFICATIONS,
DEFAULT_DEVICE_BAUD,
DEFAULT_DEVICE_HOST,
DEFAULT_DEVICE_PORT,
DEFAULT_DEVICE_USB,
AvailableNotifications,
AvailableNotificationConfig,
)
_LOGGER = logging.getLogger(__name__)
options = {}
def create_default(options: dict, key: str, default: Any):
if options is not None and key in options:
if isinstance(options[key], list) or isinstance(options[key], NodeListClass):
if CONF_SIREN_SOUNDING == key:
return list(options[key])
if CONF_ALARM_NOTIFICATIONS == key:
return list(options[key])
if len(options[key]) > 0:
my_string = ",".join(map(str, list(options[key])))
return my_string
else:
return ""
else:
return options[key]
else:
return default
def create_parameters1(options: dict):
return {
vol.Required(
CONF_LANGUAGE, default=create_default(options, CONF_LANGUAGE, "EN")
): vol.In(["EN", "FR", "NL"]),
vol.Optional(
CONF_EXCLUDE_SENSOR,
default=create_default(options, CONF_EXCLUDE_SENSOR, ""),
): str,
vol.Optional(
CONF_EXCLUDE_X10, default=create_default(options, CONF_EXCLUDE_X10, "")
): str,
vol.Optional(
CONF_DOWNLOAD_CODE, default=create_default(options, CONF_DOWNLOAD_CODE, "")
): str,
vol.Optional(
CONF_FORCE_STANDARD,
default=create_default(options, CONF_FORCE_STANDARD, False),
): bool,
vol.Optional(
CONF_FORCE_AUTOENROLL,
default=create_default(options, CONF_FORCE_AUTOENROLL, False),
): bool,
vol.Optional(
CONF_AUTO_SYNC_TIME,
default=create_default(options, CONF_AUTO_SYNC_TIME, True),
): bool,
}
available_siren_values = {
"intruder": "Intruder",
"tamper": "Tamper",
"fire": "Fire",
"emergency": "Emergency",
"gas": "Gas",
"flood": "Flood",
"x10": "X10",
"panic": "Panic",
}
def create_parameters2(options: dict):
return {
vol.Optional(
CONF_MOTION_OFF_DELAY,
default=create_default(options, CONF_MOTION_OFF_DELAY, 120),
): int,
vol.Optional(
CONF_SIREN_SOUNDING,
default=create_default(options, CONF_SIREN_SOUNDING, ["intruder"]),
): cv.multi_select(available_siren_values),
vol.Optional(
CONF_ALARM_NOTIFICATIONS,
default=create_default(options, CONF_ALARM_NOTIFICATIONS, [AvailableNotifications.CONNECTION_PROBLEM, AvailableNotifications.SIREN]),
): cv.multi_select(AvailableNotificationConfig),
vol.Optional(
CONF_OVERRIDE_CODE, default=create_default(options, CONF_OVERRIDE_CODE, "")
): str,
vol.Optional(
CONF_ARM_CODE_AUTO,
default=create_default(options, CONF_ARM_CODE_AUTO, False),
): bool,
vol.Optional(
CONF_FORCE_KEYPAD, default=create_default(options, CONF_FORCE_KEYPAD, False)
): bool,
vol.Optional(
CONF_INSTANT_ARM_AWAY,
default=create_default(options, CONF_INSTANT_ARM_AWAY, False),
): bool,
vol.Optional(
CONF_INSTANT_ARM_HOME,
default=create_default(options, CONF_INSTANT_ARM_HOME, False),
): bool,
vol.Optional(
CONF_ENABLE_REMOTE_ARM,
default=create_default(options, CONF_ENABLE_REMOTE_ARM, False),
): bool,
vol.Optional(
CONF_ENABLE_REMOTE_DISARM,
default=create_default(options, CONF_ENABLE_REMOTE_DISARM, False),
): bool,
vol.Optional(
CONF_ENABLE_SENSOR_BYPASS,
default=create_default(options, CONF_ENABLE_SENSOR_BYPASS, False),
): bool,
}
def create_parameters3(options: dict):
return {
vol.Optional(
CONF_LOG_EVENT, default=create_default(options, CONF_LOG_EVENT, False)
): bool,
vol.Optional(
CONF_LOG_DONE, default=create_default(options, CONF_LOG_DONE, False)
): bool,
vol.Optional(
CONF_LOG_REVERSE, default=create_default(options, CONF_LOG_REVERSE, False)
): bool,
vol.Optional(
CONF_LOG_CSV_TITLE,
default=create_default(options, CONF_LOG_CSV_TITLE, False),
): bool,
vol.Optional(
CONF_LOG_XML_FN,
default=create_default(options, CONF_LOG_XML_FN, "visonic_log_file.xml"),
): str,
vol.Optional(
CONF_LOG_CSV_FN,
default=create_default(options, CONF_LOG_CSV_FN, "visonic_log_file.csv"),
): str,
vol.Optional(
CONF_LOG_MAX_ENTRIES,
default=create_default(options, CONF_LOG_MAX_ENTRIES, 10000),
): int,
}
|
Apache License 2.0
|
wikimedia/pywikibot
|
pywikibot/proofreadpage.py
|
ProofreadPage.url_image
|
python
|
def url_image(self) -> str:
if not hasattr(self, '_url_image'):
if self.exists():
url = self.full_url()
else:
path = 'w/index.php?title={}&action=edit&redlink=1'
url = self.site.base_url(path.format(self.title(as_url=True)))
try:
response = http.fetch(url, charset='utf-8')
except Exception:
pywikibot.error('Error fetching HTML for {}.'.format(self))
raise
soup = _bs4_soup(response.text)
try:
self._url_image = soup.find(class_='prp-page-image')
self._url_image = self._url_image.find('img')
self._url_image = self._url_image['src']
except (TypeError, AttributeError):
raise ValueError('No prp-page-image src found for {}.'
.format(self))
else:
self._url_image = 'https:' + self._url_image
return self._url_image
|
Get the file url of the scan of ProofreadPage.
:return: file url of the scan ProofreadPage or None.
:raises Exception: in case of http errors
:raise ImportError: if bs4 is not installed, _bs4_soup() will raise
:raises ValueError: in case of no prp_page_image src found for scan
|
https://github.com/wikimedia/pywikibot/blob/5097f5b9a7ef9d39f35f17edd11faf3086a01d1d/pywikibot/proofreadpage.py#L568-L606
|
import json
import re
import time
from functools import partial
from http import HTTPStatus
from typing import Any, Optional, Union
from requests.exceptions import ReadTimeout
import pywikibot
from pywikibot import textlib
from pywikibot.backports import (
Callable,
Dict,
Iterable,
List,
Sequence,
Set,
Tuple,
)
from pywikibot.comms import http
from pywikibot.data.api import Request
from pywikibot.exceptions import Error, OtherPageSaveError
PAGES_FROM_LABEL_TYPE = Dict[str, Set['pywikibot.page.Page']]
OPT_INDEX_PAGE_TYPE = Any
OPT_INDEX_PAGE_LIST_TYPE = Any
INDEX_TYPE = Optional[Tuple[OPT_INDEX_PAGE_TYPE,
OPT_INDEX_PAGE_LIST_TYPE]]
try:
from bs4 import BeautifulSoup
except ImportError as e:
BeautifulSoup = e
def _bs4_soup(*args: Any, **kwargs: Any) -> None:
raise BeautifulSoup
else:
from bs4 import FeatureNotFound
try:
BeautifulSoup('', 'lxml')
except FeatureNotFound:
_bs4_soup = partial(BeautifulSoup, features='html.parser')
else:
_bs4_soup = partial(BeautifulSoup, features='lxml')
_logger = 'proofreadpage'
def decompose(fn: Callable) -> Callable:
def wrapper(self: 'ProofreadPage', *args: Any, **kwargs: Any) -> Any:
if not hasattr(self, '_full_header'):
self._decompose_page()
_res = fn(self, *args, **kwargs)
self._compose_page()
return _res
return wrapper
def check_if_cached(fn: Callable) -> Callable:
def wrapper(self: 'IndexPage', *args: Any, **kwargs: Any) -> Any:
if self._cached is False:
self._get_page_mappings()
return fn(self, *args, **kwargs)
return wrapper
class FullHeader:
p_header = re.compile(
r'<pagequality level="(?P<ql>\d)" user="(?P<user>.*?)" />'
r'(?P<has_div><div class="pagetext">)?(?P<header>.*)',
re.DOTALL)
TEMPLATE_V1 = ('<pagequality level="{0.ql}" user="{0.user}" />'
'<div class="pagetext">{0.header}\n\n\n')
TEMPLATE_V2 = ('<pagequality level="{0.ql}" user="{0.user}" />'
'{0.header}')
def __init__(self, text: Optional[str] = None) -> None:
self._text = text or ''
self._has_div = True
m = self.p_header.search(self._text)
if m:
self.ql = int(m.group('ql'))
self.user = m.group('user')
self.header = m.group('header')
if not m.group('has_div'):
self._has_div = False
else:
self.ql = ProofreadPage.NOT_PROOFREAD
self.user = ''
self.header = ''
def __str__(self) -> str:
if self._has_div:
return FullHeader.TEMPLATE_V1.format(self)
return FullHeader.TEMPLATE_V2.format(self)
class ProofreadPage(pywikibot.Page):
WITHOUT_TEXT = 0
NOT_PROOFREAD = 1
PROBLEMATIC = 2
PROOFREAD = 3
VALIDATED = 4
PROOFREAD_LEVELS = [
WITHOUT_TEXT,
NOT_PROOFREAD,
PROBLEMATIC,
PROOFREAD,
VALIDATED,
]
_FMT = ('{0.open_tag}{0._full_header}{0.close_tag}'
'{0._body}'
'{0.open_tag}{0._footer}%s{0.close_tag}')
open_tag = '<noinclude>'
close_tag = '</noinclude>'
p_open = re.compile(r'<noinclude>')
p_close = re.compile(r'(</div>|\n\n\n)?</noinclude>')
p_close_no_div = re.compile('</noinclude>')
_HOCR_CMD = ('https://phetools.toolforge.org/hocr_cgi.py?'
'cmd=hocr&book={book}&lang={lang}&user={user}')
_OCR_CMD = ('https://phetools.toolforge.org/ocr.php?'
'cmd=ocr&url={url_image}&lang={lang}&user={user}')
_WMFOCR_CMD = ('https://ocr.wmcloud.org/api.php?engine=tesseract&'
'langs[]={lang}&image={url_image}&uselang={lang}')
_GOCR_CMD = ('https://ws-google-ocr.toolforge.org/api.php?'
'image={url_image}&lang={lang}')
_MULTI_PAGE_EXT = ['djvu', 'pdf']
_PHETOOLS = 'phetools'
_WMFOCR = 'wmfOCR'
_GOOGLE_OCR = 'googleOCR'
_OCR_CMDS = {_PHETOOLS: _OCR_CMD,
_WMFOCR: _WMFOCR_CMD,
_GOOGLE_OCR: _GOCR_CMD,
}
_OCR_METHODS = list(_OCR_CMDS.keys())
def __init__(self, source, title: str = '') -> None:
if not isinstance(source, pywikibot.site.BaseSite):
site = source.site
else:
site = source
super().__init__(source, title)
if self.namespace() != site.proofread_page_ns:
raise ValueError('Page {} must belong to {} namespace'
.format(self.title(), site.proofread_page_ns))
if list(self.site.proofread_levels.keys()) != self.PROOFREAD_LEVELS:
raise ValueError('QLs do not match site values: {} != {}'
.format(self.site.proofread_levels.keys(),
self.PROOFREAD_LEVELS))
self._base, self._base_ext, self._num = self._parse_title()
self._multi_page = self._base_ext in self._MULTI_PAGE_EXT
@property
def _fmt(self) -> str:
return self._FMT % ('</div>' if self._full_header._has_div else '')
def _parse_title(self) -> Tuple[str, str, Optional[int]]:
left, sep, right = self.title(with_ns=False).rpartition('/')
num = None
if sep:
base = left
num = int(right)
else:
base = right
left, sep, right = base.rpartition('.')
ext = right if sep else ''
return base, ext, num
@property
def index(self) -> OPT_INDEX_PAGE_TYPE:
if not hasattr(self, '_index'):
index_ns = self.site.proofread_index_ns
what_links_here = [IndexPage(page) for page in
set(self.getReferences(namespaces=index_ns))]
if not what_links_here:
self._index = (None, [])
elif len(what_links_here) == 1:
self._index = (what_links_here.pop(), [])
else:
self._index = (None, what_links_here)
if self._num is not None:
for page in what_links_here:
if page.title(with_ns=False) == self._base:
what_links_here.remove(page)
self._index = (page, what_links_here)
break
page, others = self._index
if others:
pywikibot.warning('{} linked to several Index pages.'.format(self))
pywikibot.output('{}{!s}'.format(' ' * 9, [page] + others))
if page:
pywikibot.output(
'{}Selected Index: {}'.format(' ' * 9, page))
pywikibot.output('{}remaining: {!s}'.format(' ' * 9, others))
if not page:
pywikibot.warning('Page {} is not linked to any Index page.'
.format(self))
return page
@index.setter
def index(self, value: 'IndexPage') -> None:
if not isinstance(value, IndexPage):
raise TypeError('value {} must be an IndexPage object.'
.format(value))
self._index = (value, None)
@index.deleter
def index(self) -> None:
if hasattr(self, '_index'):
del self._index
@property
def quality_level(self) -> int:
if (self.content_model == 'proofread-page'
and hasattr(self, '_quality')):
return int(self._quality)
return self.ql
@property
@decompose
def ql(self) -> int:
return self._full_header.ql
@ql.setter
@decompose
def ql(self, value: int) -> None:
if value not in self.site.proofread_levels:
raise ValueError('Not valid QL value: {} (legal values: {})'
.format(value, self.site.proofread_levels))
self._full_header.ql = value
@property
@decompose
def user(self) -> str:
return self._full_header.user
@user.setter
@decompose
def user(self, value: str) -> None:
self._full_header.user = value
@property
@decompose
def status(self) -> Optional[str]:
try:
return self.site.proofread_levels[self.ql]
except KeyError:
pywikibot.warning('Not valid status set for {}: quality level = {}'
.format(self.title(as_link=True), self.ql))
return None
def without_text(self) -> None:
self.ql = self.WITHOUT_TEXT
def problematic(self) -> None:
self.ql = self.PROBLEMATIC
def not_proofread(self) -> None:
self.ql = self.NOT_PROOFREAD
def proofread(self) -> None:
self.ql = self.PROOFREAD
def validate(self) -> None:
self.ql = self.VALIDATED
@property
@decompose
def header(self) -> str:
return self._full_header.header
@header.setter
@decompose
def header(self, value: str) -> None:
self._full_header.header = value
@property
@decompose
def body(self) -> str:
return self._body
@body.setter
@decompose
def body(self, value: str) -> None:
self._body = value
@property
@decompose
def footer(self) -> str:
return self._footer
@footer.setter
@decompose
def footer(self, value: str) -> None:
self._footer = value
def _create_empty_page(self) -> None:
self._full_header = FullHeader()
self._body = ''
self._footer = ''
self.user = self.site.username()
self._compose_page()
@property
def text(self) -> str:
if getattr(self, '_text', None) is not None:
return self._text
if self.exists():
return super().text
self._text = self.preloadText()
self.user = self.site.username()
return self._text
@text.setter
def text(self, value: str) -> None:
self._text = value
if self._text:
self._decompose_page()
else:
self._create_empty_page()
@text.deleter
def text(self) -> None:
if hasattr(self, '_text'):
del self._text
def _decompose_page(self) -> None:
def _assert_len(len_oq: int, len_cq: int, title: str) -> None:
if (len_oq != len_cq) or (len_oq < 2 or len_cq < 2):
raise Error('ProofreadPage {}: invalid format'.format(title))
text = self.text
if not text:
self._create_empty_page()
return
_title = self.title(as_link=True)
open_queue = list(self.p_open.finditer(text))
close_queue = list(self.p_close.finditer(text))
_assert_len(len(open_queue), len(close_queue), _title)
f_open, f_close = open_queue[0], close_queue[0]
self._full_header = FullHeader(text[f_open.end():f_close.start()])
if not self._full_header._has_div:
close_queue = list(self.p_close_no_div.finditer(text))
_assert_len(len(open_queue), len(close_queue), _title)
l_open, l_close = open_queue[-1], close_queue[-1]
self._footer = text[l_open.end():l_close.start()]
self._body = text[f_close.end():l_open.start()]
def _compose_page(self) -> str:
self._text = self._fmt.format(self)
return self._text
def _page_to_json(self) -> str:
page_dict = {'header': self.header,
'body': self.body,
'footer': self.footer,
'level': {'level': self.ql, 'user': self.user},
}
return json.dumps(page_dict, ensure_ascii=False)
def save(self, *args: Any, **kwargs: Any) -> None:
summary = kwargs.pop('summary', '')
summary = self.pre_summary + summary
kwargs['contentformat'] = 'application/json'
kwargs['contentmodel'] = 'proofread-page'
text = self._page_to_json()
super().save(*args, text=text, summary=summary, **kwargs)
@property
def pre_summary(self) -> str:
return '/* {0.status} */ '.format(self)
@property
|
MIT License
|
sberbank-ai-lab/lightautoml
|
lightautoml/transformers/categorical.py
|
MultiClassTargetEncoder.score_func
|
python
|
def score_func(candidates: np.ndarray, target: np.ndarray) -> int:
target = target[:, np.newaxis, np.newaxis]
scores = -np.log(np.take_along_axis(candidates, target, axis=1)).mean(axis=0)[0]
idx = scores.argmin()
return idx
|
Args:
candidates: np.ndarray.
target: np.ndarray.
Returns:
index of best encoder.
|
https://github.com/sberbank-ai-lab/lightautoml/blob/51a4e2bd0ebffbe0817fb50434280f8e7c40fa4c/lightautoml/transformers/categorical.py#L552-L568
|
from itertools import combinations
from typing import List
from typing import Optional
from typing import Sequence
from typing import Union
from typing import cast
import numpy as np
from pandas import DataFrame
from pandas import Series
from sklearn.preprocessing import OneHotEncoder
from sklearn.utils.murmurhash import murmurhash3_32
from ..dataset.base import LAMLDataset
from ..dataset.np_pd_dataset import CSRSparseDataset
from ..dataset.np_pd_dataset import NumpyDataset
from ..dataset.np_pd_dataset import PandasDataset
from ..dataset.roles import CategoryRole
from ..dataset.roles import NumericRole
from .base import LAMLTransformer
NumpyOrPandas = Union[NumpyDataset, PandasDataset]
NumpyOrSparse = Union[NumpyDataset, CSRSparseDataset]
def categorical_check(dataset: LAMLDataset):
roles = dataset.roles
features = dataset.features
for f in features:
assert roles[f].name == "Category", "Only categories accepted in this transformer"
def oof_task_check(dataset: LAMLDataset):
task = dataset.task
assert task.name in [
"binary",
"reg",
], "Only binary and regression tasks supported in this transformer"
def multiclass_task_check(dataset: LAMLDataset):
task = dataset.task
assert task.name in ["multiclass"], "Only multiclass tasks supported in this transformer"
def encoding_check(dataset: LAMLDataset):
roles = dataset.roles
features = dataset.features
for f in features:
assert roles[
f
].label_encoded, "Transformer should be applied to category only after label encoding. Feat {0} is {1}".format(
f, roles[f]
)
class LabelEncoder(LAMLTransformer):
_fit_checks = (categorical_check,)
_transform_checks = ()
_fname_prefix = "le"
_fillna_val = 0
def __init__(self, subs: Optional[int] = None, random_state: int = 42):
self.subs = subs
self.random_state = random_state
self._output_role = CategoryRole(np.int32, label_encoded=True)
def _get_df(self, dataset: NumpyOrPandas) -> DataFrame:
dataset = dataset.to_pandas()
df = dataset.data
if self.subs is not None and df.shape[0] >= self.subs:
subs = df.sample(n=self.subs, random_state=self.random_state)
else:
subs = df
return subs
def fit(self, dataset: NumpyOrPandas):
super().fit(dataset)
roles = dataset.roles
subs = self._get_df(dataset)
self.dicts = {}
for i in subs.columns:
role = roles[i]
co = role.unknown
cnts = (
subs[i]
.value_counts(dropna=False)
.reset_index()
.sort_values([i, "index"], ascending=[False, True])
.set_index("index")
)
vals = cnts[cnts > co].index.values
self.dicts[i] = Series(np.arange(vals.shape[0], dtype=np.int32) + 1, index=vals)
return self
def transform(self, dataset: NumpyOrPandas) -> NumpyDataset:
super().transform(dataset)
dataset = dataset.to_pandas()
df = dataset.data
new_arr = np.empty(dataset.shape, dtype=self._output_role.dtype)
for n, i in enumerate(df.columns):
if i in self.dicts:
new_arr[:, n] = df[i].map(self.dicts[i]).fillna(self._fillna_val).values
else:
new_arr[:, n] = df[i].values.astype(self._output_role.dtype)
output = dataset.empty().to_numpy()
output.set_data(new_arr, self.features, self._output_role)
return output
class OHEEncoder(LAMLTransformer):
_fit_checks = (categorical_check, encoding_check)
_transform_checks = ()
_fname_prefix = "ohe"
@property
def features(self) -> List[str]:
return self._features
def __init__(
self,
make_sparse: Optional[bool] = None,
total_feats_cnt: Optional[int] = None,
dtype: type = np.float32,
):
self.make_sparse = make_sparse
self.total_feats_cnt = total_feats_cnt
self.dtype = dtype
if self.make_sparse is None:
assert self.total_feats_cnt is not None, "Param total_feats_cnt should be defined if make_sparse is None"
def fit(self, dataset: NumpyOrPandas):
for check_func in self._fit_checks:
check_func(dataset)
dataset = dataset.to_numpy()
data = dataset.data
max_idx = data.max(axis=0)
min_idx = data.min(axis=0)
if self.make_sparse is None:
fill_rate = self.total_feats_cnt / (self.total_feats_cnt - max_idx.shape[0] + max_idx.sum())
self.make_sparse = fill_rate < 0.2
self.ohe = OneHotEncoder(
categories=[np.arange(x, y + 1, dtype=np.int32) for (x, y) in zip(min_idx, max_idx)],
dtype=self.dtype,
sparse=self.make_sparse,
handle_unknown="ignore",
)
self.ohe.fit(data)
features = []
for cats, name in zip(self.ohe.categories_, dataset.features):
features.extend(["ohe_{0}__{1}".format(x, name) for x in cats])
self._features = features
return self
def transform(self, dataset: NumpyOrPandas) -> NumpyOrSparse:
super().transform(dataset)
dataset = dataset.to_numpy()
data = dataset.data
data = self.ohe.transform(data)
output = dataset.empty()
if self.make_sparse:
output = output.to_csr()
output.set_data(data, self.features, NumericRole(self.dtype))
return output
class FreqEncoder(LabelEncoder):
_fit_checks = (categorical_check,)
_transform_checks = ()
_fname_prefix = "freq"
_fillna_val = 1
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._output_role = NumericRole(np.float32)
def fit(self, dataset: NumpyOrPandas):
LAMLTransformer.fit(self, dataset)
dataset = dataset.to_pandas()
df = dataset.data
self.dicts = {}
for i in df.columns:
cnts = df[i].value_counts(dropna=False)
self.dicts[i] = cnts[cnts > 1]
return self
class TargetEncoder(LAMLTransformer):
_fit_checks = (categorical_check, oof_task_check, encoding_check)
_transform_checks = ()
_fname_prefix = "oof"
def __init__(self, alphas: Sequence[float] = (0.5, 1.0, 2.0, 5.0, 10.0, 50.0, 250.0, 1000.0)):
self.alphas = alphas
@staticmethod
def binary_score_func(candidates: np.ndarray, target: np.ndarray) -> int:
target = target[:, np.newaxis]
scores = -(target * np.log(candidates) + (1 - target) * np.log(1 - candidates)).mean(axis=0)
idx = scores.argmin()
return idx
@staticmethod
def reg_score_func(candidates: np.ndarray, target: np.ndarray) -> int:
target = target[:, np.newaxis]
scores = ((target - candidates) ** 2).mean(axis=0)
idx = scores.argmin()
return idx
def fit(self, dataset: NumpyOrPandas):
super().fit_transform(dataset)
def fit_transform(self, dataset: NumpyOrPandas) -> NumpyDataset:
super().fit(dataset)
dataset = dataset.to_numpy()
data = dataset.data
target = dataset.target.astype(np.int32)
score_func = self.binary_score_func if dataset.task.name == "binary" else self.reg_score_func
folds = dataset.folds
n_folds = folds.max() + 1
alphas = np.array(self.alphas)[np.newaxis, :]
self.encodings = []
prior = target.mean()
f_sum = np.zeros(n_folds, dtype=np.float64)
f_count = np.zeros(n_folds, dtype=np.float64)
np.add.at(f_sum, folds, target)
np.add.at(f_count, folds, 1)
folds_prior = (f_sum.sum() - f_sum) / (f_count.sum() - f_count)
oof_feats = np.zeros(data.shape, dtype=np.float32)
for n in range(data.shape[1]):
vec = data[:, n]
enc_dim = vec.max() + 1
f_sum = np.zeros((enc_dim, n_folds), dtype=np.float64)
f_count = np.zeros((enc_dim, n_folds), dtype=np.float64)
np.add.at(f_sum, (vec, folds), target)
np.add.at(f_count, (vec, folds), 1)
t_sum = f_sum.sum(axis=1, keepdims=True)
t_count = f_count.sum(axis=1, keepdims=True)
oof_sum = t_sum - f_sum
oof_count = t_count - f_count
candidates = (
(oof_sum[vec, folds, np.newaxis] + alphas * folds_prior[folds, np.newaxis])
/ (oof_count[vec, folds, np.newaxis] + alphas)
).astype(np.float32)
idx = score_func(candidates, target)
oof_feats[:, n] = candidates[:, idx]
enc = ((t_sum[:, 0] + alphas[0, idx] * prior) / (t_count[:, 0] + alphas[0, idx])).astype(np.float32)
self.encodings.append(enc)
output = dataset.empty()
self.output_role = NumericRole(np.float32, prob=output.task.name == "binary")
output.set_data(oof_feats, self.features, self.output_role)
return output
def transform(self, dataset: NumpyOrPandas) -> NumpyOrSparse:
super().transform(dataset)
dataset = dataset.to_numpy()
data = dataset.data
out = np.zeros(data.shape, dtype=np.float32)
for n, enc in enumerate(self.encodings):
out[:, n] = enc[data[:, n]]
output = dataset.empty()
output.set_data(out, self.features, self.output_role)
return output
class MultiClassTargetEncoder(LAMLTransformer):
_fit_checks = (categorical_check, multiclass_task_check, encoding_check)
_transform_checks = ()
_fname_prefix = "multioof"
@property
def features(self) -> List[str]:
return self._features
def __init__(self, alphas: Sequence[float] = (0.5, 1.0, 2.0, 5.0, 10.0, 50.0, 250.0, 1000.0)):
self.alphas = alphas
@staticmethod
|
Apache License 2.0
|
demisto/demisto-py
|
demisto_client/demisto_api/models/entry_history.py
|
EntryHistory.content_date
|
python
|
def content_date(self, content_date):
self._content_date = content_date
|
Sets the content_date of this EntryHistory.
:param content_date: The content_date of this EntryHistory. # noqa: E501
:type: datetime
|
https://github.com/demisto/demisto-py/blob/95d29e07693d27c133f7fe6ef9da13e4b6dbf542/demisto_client/demisto_api/models/entry_history.py#L76-L84
|
import pprint
import re
import six
class EntryHistory(object):
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'content_date': 'datetime',
'contents': 'str',
'contents_format': 'str',
'user': 'str'
}
attribute_map = {
'content_date': 'contentDate',
'contents': 'contents',
'contents_format': 'contentsFormat',
'user': 'user'
}
def __init__(self, content_date=None, contents=None, contents_format=None, user=None):
self._content_date = None
self._contents = None
self._contents_format = None
self._user = None
self.discriminator = None
if content_date is not None:
self.content_date = content_date
if contents is not None:
self.contents = contents
if contents_format is not None:
self.contents_format = contents_format
if user is not None:
self.user = user
@property
def content_date(self):
return self._content_date
@content_date.setter
|
Apache License 2.0
|
erensezener/aima-based-irl
|
Other_AIMA_Scripts/logic.py
|
pl_resolution
|
python
|
def pl_resolution(KB, alpha):
clauses = KB.clauses + conjuncts(to_cnf(~alpha))
new = set()
while True:
n = len(clauses)
pairs = [(clauses[i], clauses[j]) for i in range(n) for j in range(i+1, n)]
for (ci, cj) in pairs:
resolvents = pl_resolve(ci, cj)
if FALSE in resolvents: return True
new.union_update(set(resolvents))
if new.issubset(set(clauses)): return False
for c in new:
if c not in clauses: clauses.append(c)
|
Propositional Logic Resolution: say if alpha follows from KB. [Fig. 7.12]
|
https://github.com/erensezener/aima-based-irl/blob/fbbe28986cec0b5e58fef0f00338a180ed03759a/Other_AIMA_Scripts/logic.py#L482-L495
|
from __future__ import generators
import re
from Other_AIMA_Scripts import agents
from utils import *
class KB:
def __init__(self, sentence=None):
abstract
def tell(self, sentence):
abstract
def ask(self, query):
try:
return self.ask_generator(query).next()
except StopIteration:
return False
def ask_generator(self, query):
abstract
def retract(self, sentence):
abstract
class PropKB(KB):
def __init__(self, sentence=None):
self.clauses = []
if sentence:
self.tell(sentence)
def tell(self, sentence):
self.clauses.extend(conjuncts(to_cnf(sentence)))
def ask_generator(self, query):
if not tt_entails(Expr('&', *self.clauses), query):
return
yield {}
def retract(self, sentence):
for c in conjuncts(to_cnf(sentence)):
if c in self.clauses:
self.clauses.remove(c)
class KB_Agent(agents.Agent):
def __init__(self, KB):
t = 0
def program(percept):
KB.tell(self.make_percept_sentence(percept, t))
action = KB.ask(self.make_action_query(t))
KB.tell(self.make_action_sentence(action, t))
t = t + 1
return action
self.program = program
def make_percept_sentence(self, percept, t):
return(Expr("Percept")(percept, t))
def make_action_query(self, t):
return(expr("ShouldDo(action, %d)" % t))
def make_action_sentence(self, action, t):
return(Expr("Did")(action, t))
class Expr:
def __init__(self, op, *args):
assert isinstance(op, str) or (isnumber(op) and not args)
self.op = num_or_str(op)
self.args = map(expr, args)
def __call__(self, *args):
assert is_symbol(self.op) and not self.args
return Expr(self.op, *args)
def __repr__(self):
if len(self.args) == 0:
return str(self.op)
elif is_symbol(self.op):
return '%s(%s)' % (self.op, ', '.join(map(repr, self.args)))
elif len(self.args) == 1:
return self.op + repr(self.args[0])
else:
return '(%s)' % (' '+self.op+' ').join(map(repr, self.args))
def __eq__(self, other):
return (other is self) or (isinstance(other, Expr)
and self.op == other.op and self.args == other.args)
def __hash__(self):
return hash(self.op) ^ hash(tuple(self.args))
def __lt__(self, other): return Expr('<', self, other)
def __le__(self, other): return Expr('<=', self, other)
def __ge__(self, other): return Expr('>=', self, other)
def __gt__(self, other): return Expr('>', self, other)
def __add__(self, other): return Expr('+', self, other)
def __sub__(self, other): return Expr('-', self, other)
def __and__(self, other): return Expr('&', self, other)
def __div__(self, other): return Expr('/', self, other)
def __truediv__(self, other):return Expr('/', self, other)
def __invert__(self): return Expr('~', self)
def __lshift__(self, other): return Expr('<<', self, other)
def __rshift__(self, other): return Expr('>>', self, other)
def __mul__(self, other): return Expr('*', self, other)
def __neg__(self): return Expr('-', self)
def __or__(self, other): return Expr('|', self, other)
def __pow__(self, other): return Expr('**', self, other)
def __xor__(self, other): return Expr('^', self, other)
def __mod__(self, other): return Expr('<=>', self, other)
def expr(s):
if isinstance(s, Expr): return s
if isnumber(s): return Expr(s)
s = s.replace('==>', '>>').replace('<==', '<<')
s = s.replace('<=>', '%').replace('=/=', '^')
s = re.sub(r'([a-zA-Z0-9_.]+)', r'Expr("\1")', s)
return eval(s, {'Expr':Expr})
def is_symbol(s):
return isinstance(s, str) and s[0].isalpha()
def is_var_symbol(s):
return is_symbol(s) and s[0].islower()
def is_prop_symbol(s):
return is_symbol(s) and s[0].isupper() and s != 'TRUE' and s != 'FALSE'
TRUE, FALSE, ZERO, ONE, TWO = map(Expr, ['TRUE', 'FALSE', 0, 1, 2])
A, B, C, F, G, P, Q, x, y, z = map(Expr, 'ABCFGPQxyz')
def tt_entails(kb, alpha):
return tt_check_all(kb, alpha, prop_symbols(kb & alpha), {})
def tt_check_all(kb, alpha, symbols, model):
if not symbols:
if pl_true(kb, model): return pl_true(alpha, model)
else: return True
assert result != None
else:
P, rest = symbols[0], symbols[1:]
return (tt_check_all(kb, alpha, rest, extend(model, P, True)) and
tt_check_all(kb, alpha, rest, extend(model, P, False)))
def prop_symbols(x):
if not isinstance(x, Expr):
return []
elif is_prop_symbol(x.op):
return [x]
else:
s = set(())
for arg in x.args:
for symbol in prop_symbols(arg):
s.add(symbol)
return list(s)
def tt_true(alpha):
return tt_entails(TRUE, expr(alpha))
def pl_true(exp, model={}):
op, args = exp.op, exp.args
if exp == TRUE:
return True
elif exp == FALSE:
return False
elif is_prop_symbol(op):
return model.get(exp)
elif op == '~':
p = pl_true(args[0], model)
if p == None: return None
else: return not p
elif op == '|':
result = False
for arg in args:
p = pl_true(arg, model)
if p == True: return True
if p == None: result = None
return result
elif op == '&':
result = True
for arg in args:
p = pl_true(arg, model)
if p == False: return False
if p == None: result = None
return result
p, q = args
if op == '>>':
return pl_true(~p | q, model)
elif op == '<<':
return pl_true(p | ~q, model)
pt = pl_true(p, model)
if pt == None: return None
qt = pl_true(q, model)
if qt == None: return None
if op == '<=>':
return pt == qt
elif op == '^':
return pt != qt
else:
raise ValueError, "illegal operator in logic expression" + str(exp)
def to_cnf(s):
if isinstance(s, str): s = expr(s)
s = eliminate_implications(s)
s = move_not_inwards(s)
return distribute_and_over_or(s)
def eliminate_implications(s):
if not s.args or is_symbol(s.op): return s
args = map(eliminate_implications, s.args)
a, b = args[0], args[-1]
if s.op == '>>':
return (b | ~a)
elif s.op == '<<':
return (a | ~b)
elif s.op == '<=>':
return (a | ~b) & (b | ~a)
else:
return Expr(s.op, *args)
def move_not_inwards(s):
if s.op == '~':
NOT = lambda b: move_not_inwards(~b)
a = s.args[0]
if a.op == '~': return move_not_inwards(a.args[0])
if a.op =='&': return NaryExpr('|', *map(NOT, a.args))
if a.op =='|': return NaryExpr('&', *map(NOT, a.args))
return s
elif is_symbol(s.op) or not s.args:
return s
else:
return Expr(s.op, *map(move_not_inwards, s.args))
def distribute_and_over_or(s):
if s.op == '|':
s = NaryExpr('|', *s.args)
if len(s.args) == 0:
return FALSE
if len(s.args) == 1:
return distribute_and_over_or(s.args[0])
conj = find_if((lambda d: d.op == '&'), s.args)
if not conj:
return NaryExpr(s.op, *s.args)
others = [a for a in s.args if a is not conj]
if len(others) == 1:
rest = others[0]
else:
rest = NaryExpr('|', *others)
return NaryExpr('&', *map(distribute_and_over_or,
[(c|rest) for c in conj.args]))
elif s.op == '&':
return NaryExpr('&', *map(distribute_and_over_or, s.args))
else:
return s
_NaryExprTable = {'&':TRUE, '|':FALSE, '+':ZERO, '*':ONE}
def NaryExpr(op, *args):
arglist = []
for arg in args:
if arg.op == op: arglist.extend(arg.args)
else: arglist.append(arg)
if len(args) == 1:
return args[0]
elif len(args) == 0:
return _NaryExprTable[op]
else:
return Expr(op, *arglist)
def conjuncts(s):
if isinstance(s, Expr) and s.op == '&':
return s.args
else:
return [s]
def disjuncts(s):
if isinstance(s, Expr) and s.op == '|':
return s.args
else:
return [s]
|
MIT License
|
att-comdev/drydock
|
drydock_provisioner/orchestrator/actions/orchestrator.py
|
BaseAction._split_action
|
python
|
def _split_action(self):
target_nodes = self.orchestrator.get_target_nodes(self.task)
if len(target_nodes) > 1:
self.logger.info(
"Found multiple target nodes in task %s, splitting..." % str(
self.task.get_id()))
split_tasks = dict()
with concurrent.futures.ThreadPoolExecutor() as te:
for n in target_nodes:
split_task = self.orchestrator.create_task(
design_ref=self.task.design_ref,
action=hd_fields.OrchestratorAction.PrepareNodes,
node_filter=self.orchestrator.
create_nodefilter_from_nodelist([n]))
self.task.register_subtask(split_task)
action = self.__class__(split_task, self.orchestrator,
self.state_manager)
split_tasks[split_task.get_id().bytes] = te.submit(
action.start)
return split_tasks
|
Start a parallel action for each node in scope.
Start a threaded instance of this action for each node in
scope of this action's task. A subtask will be created for each
action. Returns all a list of concurrent.futures managed
threads running the actions.
:returns: dictionary of subtask_id.bytes => Future instance
|
https://github.com/att-comdev/drydock/blob/506e06623a5f1c11c0d34f2089851cc8381f06ae/drydock_provisioner/orchestrator/actions/orchestrator.py#L61-L92
|
import time
import datetime
import logging
import concurrent.futures
import uuid
import drydock_provisioner.config as config
import drydock_provisioner.error as errors
import drydock_provisioner.objects.fields as hd_fields
class BaseAction(object):
def __init__(self, task, orchestrator, state_manager):
self.task = task
self.orchestrator = orchestrator
self.state_manager = state_manager
self.logger = logging.getLogger(
config.config_mgr.conf.logging.global_logger_name)
def _parallelize_subtasks(self, fn, subtask_id_list, *args, **kwargs):
task_futures = dict()
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as te:
for t in subtask_id_list:
task_futures[t.bytes] = te.submit(fn, t, *args, **kwargs)
return task_futures
|
Apache License 2.0
|
hanrancode/imagedt
|
imagedt/tensorflow/lite/lite_wrapper.py
|
Lite_Wrapper.predict
|
python
|
def predict(self, input_data):
self.interpreter.set_tensor(self.input_details[0]['index'], input_data)
self.interpreter.invoke()
predictions = np.squeeze(self.interpreter.get_tensor(self.output_details[0]['index']))
pre_class = predictions.argsort()[::-1][0]
conf = predictions[pre_class]
return pre_class, conf
|
input data : should be cv mat array (axis=0)
|
https://github.com/hanrancode/imagedt/blob/78c9e671526422f28bd564cad9879ef95f12b454/imagedt/tensorflow/lite/lite_wrapper.py#L33-L43
|
from __future__ import absolute_import
from __future__ import print_function
import numpy as np
from tensorflow.contrib.lite.python import interpreter as interpreter_wrapper
class Lite_Wrapper(object):
def __init__(self, model_path):
super(Lite_Wrapper, self).__init__()
self.model_path = model_path
self.load_model()
self._check_model_type()
def load_model(self):
self.interpreter = interpreter_wrapper.Interpreter(model_path=self.model_path)
self.interpreter.allocate_tensors()
self.input_details = self.interpreter.get_input_details()
self.output_details = self.interpreter.get_output_details()
def _check_model_type(self):
try:
self.input_details[0]['dtype'] == type(np.float32(1.0))
self.height = input_details[0]['shape'][1]
self.width = input_details[0]['shape'][2]
except Exception as e:
print ("Only support test float tflite model for now, Please check model type!")
|
Apache License 2.0
|
martin68/apt-smart
|
apt_smart/__init__.py
|
AptMirrorUpdater.dumb_update
|
python
|
def dumb_update(self, *args):
timer = Timer()
logger.info("Updating package lists of %s ..", self.context)
self.context.execute('apt-get', 'update', *args, sudo=True)
logger.info("Finished updating package lists of %s in %s.", self.context, timer)
|
Update the system's package lists (by running ``apt-get update``).
:param args: Command line arguments to ``apt-get update`` (zero or more strings).
The :func:`dumb_update()` method doesn't do any error handling or
retrying, if that's what you're looking for then you need
:func:`smart_update()` instead.
|
https://github.com/martin68/apt-smart/blob/7085f398e08a703759d7e81a898f1e237796f232/apt_smart/__init__.py#L745-L758
|
import fnmatch
import logging
import os
import sys
import time
import calendar
try:
from enum import Enum
except ImportError:
from flufl.enum import Enum
from capturer import CaptureOutput
from executor.contexts import ChangeRootContext, LocalContext
from humanfriendly import AutomaticSpinner, Timer, compact, format_timespan, pluralize
try:
from property_manager3 import (
PropertyManager,
cached_property,
key_property,
lazy_property,
mutable_property,
set_property,
)
except ImportError:
from property_manager import (
PropertyManager,
cached_property,
key_property,
lazy_property,
mutable_property,
set_property,
)
from six import text_type
from six.moves.urllib.parse import urlparse
from apt_smart.http import NotFoundError, fetch_concurrent, fetch_url, get_default_concurrency
from apt_smart.releases import coerce_release
from apt_smart.releases import discover_releases
__version__ = '7.1.3'
SOURCES_LIST_ENCODING = 'UTF-8'
MAX_MIRRORS = 50
URL_CHAR_LEN = 34
LAST_UPDATED_DEFAULT = 60 * 60 * 24 * 7 * 4
logger = logging.getLogger(__name__)
class AptMirrorUpdater(PropertyManager):
repr_properties = (
'architecture',
'backend',
'blacklist',
'concurrency',
'context',
'distribution_codename',
'distributor_id',
'max_mirrors',
'old_releases_url',
'security_url',
)
@mutable_property
def architecture(self):
value = self.context.capture('dpkg', '--print-architecture')
set_property(self, 'architecture', value)
return value
@cached_property
def available_mirrors(self):
mirrors = set()
if self.release_is_eol:
logger.warning("Skipping mirror discovery because %s is EOL.", self.release)
else:
if self.read_custom_mirror_file:
mirrors.update(self.read_custom_mirror_file)
logger.info("Custom mirrors added from file:")
for mirror in mirrors:
logger.info(mirror.mirror_url)
logger.info("Adding BASE_URL mirror:")
if self.distributor_id == 'debian':
base_url_prefix = self.backend.BASE_URL.split('/dists/codename-updates/Release')[0]
mirrors.add(CandidateMirror(mirror_url=base_url_prefix, updater=self))
elif self.distributor_id == 'ubuntu':
base_url_prefix = self.backend.BASE_URL.split('/dists/codename-security/Release')[0]
mirrors.add(CandidateMirror(mirror_url=base_url_prefix, updater=self))
elif self.distributor_id == 'linuxmint':
base_url_prefix = self.backend.BASE_URL.split('/dists/codename/Release')[0]
mirrors.add(CandidateMirror(mirror_url=base_url_prefix, updater=self))
logger.info(base_url_prefix)
for candidate in self.backend.discover_mirrors():
if any(fnmatch.fnmatch(candidate.mirror_url, pattern) for pattern in self.blacklist) and normalize_mirror_url(candidate.mirror_url) != base_url_prefix:
logger.warning("Ignoring blacklisted mirror %s.", candidate.mirror_url)
else:
candidate.updater = self
mirrors.add(candidate)
try:
mirrors.add(CandidateMirror(mirror_url=self.current_mirror, updater=self))
except Exception as e:
logger.warning("Failed to add current mirror to set of available mirrors! (%s)", e)
return sorted(mirrors, key=lambda c: c.sort_key, reverse=True)
@cached_property
def backend(self):
logger.debug("Checking whether %s platform is supported ..", self.distributor_id.capitalize())
module_path = "%s.backends.%s" % (__name__, self.distributor_id)
try:
__import__(module_path)
except ImportError:
msg = "%s platform is unsupported! (only Debian and Ubuntu are supported)"
raise EnvironmentError(msg % self.distributor_id.capitalize())
else:
return sys.modules[module_path]
@cached_property
def best_mirror(self):
logger.debug("Selecting best %s mirror ..", self.distributor_id.capitalize())
if self.release_is_eol:
logger.info("%s is EOL, using %s.", self.release, self.old_releases_url)
return self.old_releases_url
else:
return self.ranked_mirrors[0].mirror_url
@cached_property
def blacklist(self):
return set()
@mutable_property
def concurrency(self):
return get_default_concurrency()
@mutable_property(cached=True)
def context(self):
return LocalContext()
@mutable_property(cached=True)
def current_mirror(self):
if self.ubuntu_mode and self.distribution_codename:
return self.current_mirror
else:
logger.debug("Parsing %s to find current mirror of %s ..", self.main_sources_list, self.context)
return find_current_mirror(self.get_sources_list())
@mutable_property
def distribution_codename_old(self):
return self.context.distribution_codename
@mutable_property(cached=True)
def distribution_codename(self):
for line in self.get_sources_list().splitlines():
tokens = line.split()
if (len(tokens) >= 4
and tokens[0] in ('deb', 'deb-src')
and tokens[1].startswith(('http://', 'https://', 'ftp://', 'mirror://'))
and 'main' in tokens[3:]):
matches = [release for release in discover_releases() if tokens[2].lower() in release.codename.lower()]
if len(matches) != 1:
continue
if self.ubuntu_mode and matches[0].distributor_id == 'linuxmint':
self.current_mirror = tokens[1]
continue
if self.ubuntu_mode:
logging.info("In Ubuntu Mode, pretend to be %s" % coerce_release(tokens[2]))
return tokens[2]
raise EnvironmentError("Failed to determine the distribution codename using apt's package resource list!")
@mutable_property(cached=True)
def distributor_id(self):
return self.release.distributor_id
@cached_property
def main_sources_list(self):
if self.context.exists('/etc/apt/sources.list.d/official-package-repositories.list'):
logger.debug("/etc/apt/sources.list.d/official-package-repositories.list exists,\
use it as main_sources_list instead of /etc/apt/sources.list")
return '/etc/apt/sources.list.d/official-package-repositories.list'
else:
return '/etc/apt/sources.list'
@mutable_property
def max_mirrors(self):
return MAX_MIRRORS
@mutable_property
def url_char_len(self):
return URL_CHAR_LEN
@mutable_property
def ubuntu_mode(self):
return False
@mutable_property
def old_releases_url(self):
return self.backend.OLD_RELEASES_URL
@mutable_property
def base_url(self):
return self.backend.BASE_URL.replace('codename', self.distribution_codename)
@mutable_property
def base_last_updated(self):
@cached_property
def ranked_mirrors(self):
timer = Timer()
mirrors = sorted(self.available_mirrors, key=lambda c: c.sort_key, reverse=True)
"""
if self.max_mirrors and len(mirrors) > self.max_mirrors:
mirrors = mirrors[:self.max_mirrors]
"""
mapping = dict((c.release_gpg_url, c) for c in mirrors)
num_mirrors = pluralize(len(mapping), "mirror")
logger.info("Checking %s for availability and performance ..", num_mirrors)
with AutomaticSpinner(label="Checking mirrors"):
for url, data, elapsed_time in fetch_concurrent(mapping.keys(), concurrency=self.concurrency):
candidate = mapping[url]
candidate.release_gpg_contents = data
candidate.release_gpg_latency = elapsed_time
logger.info("Start retrieving :attr:`base_last_updated` using is_available")
self.base_last_updated = 0
if self.release_is_eol:
self.base_last_updated = int(time.time())
logger.warning("%s is EOL, so using time.time() as :attr:`base_last_updated`: %i",
self.release, self.base_last_updated)
elif mapping[self.base_url].is_available:
logger.debug(":attr:`base_last_updated`: %i", self.base_last_updated)
mapping[self.base_url].last_updated = 0
else:
self.base_last_updated = int(time.time())
logger.warning("%s is not available, so using time.time() as :attr:`base_last_updated`: %i",
self.base_url, self.base_last_updated)
update_mapping = dict((c.archive_update_in_progress_url, c) for c in mirrors if c.is_available)
logger.info("Checking %s for Archive-Update-in-Progress marker ..",
pluralize(len(update_mapping), "mirror"))
with AutomaticSpinner(label="Checking mirrors"):
for url, data, elapsed_time in fetch_concurrent(update_mapping.keys(), concurrency=self.concurrency):
update_mapping[url].is_updating = data is not None
mirrors = list(mapping.values())
logger.info("Finished checking %s (took %s).", num_mirrors, timer)
if not any(c.is_available for c in mirrors):
raise Exception("It looks like all %s are unavailable!" % num_mirrors)
if all(c.is_updating for c in mirrors):
logger.warning("It looks like all %s are being updated?!", num_mirrors)
if any(fnmatch.fnmatch(mapping[self.base_url].mirror_url, pattern) for pattern in self.blacklist):
logger.warning("Ignoring blacklisted BASE_URL mirror %s.", mapping[self.base_url].mirror_url)
mirrors.remove(mapping[self.base_url])
return sorted(mirrors, key=lambda c: c.sort_key, reverse=True)
@cached_property
def release(self):
return coerce_release(self.distribution_codename)
@cached_property
def release_is_eol(self):
release_is_eol = None
logger.debug("Checking whether %s is EOL ..", self.release)
if hasattr(self.backend, 'get_eol_date'):
eol_date = self.backend.get_eol_date(self)
if eol_date:
release_is_eol = (time.time() >= eol_date)
source = "custom EOL dates"
if release_is_eol is None and self.release.eol_date:
release_is_eol = self.release.is_eol
source = "known EOL dates"
if release_is_eol is None:
release_is_eol = (self.validate_mirror(self.security_url) == MirrorStatus.MAYBE_EOL)
source = "security mirror"
if release_is_eol and self.distributor_id == 'linuxmint':
logger.info(
"%s seems EOL (based on %s), but for Linux Mint no OLD_RELEASES_URL, so act as not EOL.",
self.release, source,
)
release_is_eol = False
return release_is_eol
if release_is_eol:
logger.info("%s seems EOL, checking %s MirrorStatus to confirm.", self.release, self.old_releases_url)
release_is_eol = (self.validate_mirror(self.old_releases_url) == MirrorStatus.AVAILABLE)
if not release_is_eol:
source = "%s is not available" % self.old_releases_url
logger.info(
"%s is %s (based on %s).", self.release,
"EOL" if release_is_eol else "supported", source,
)
return release_is_eol
@mutable_property
def security_url(self):
return self.backend.SECURITY_URL
@cached_property
def stable_mirror(self):
if self.release_is_eol:
logger.debug("%s is EOL, falling back to %s.", self.release, self.old_releases_url)
return self.old_releases_url
else:
try:
logger.debug("Trying to select current mirror as stable mirror ..")
return self.current_mirror
except Exception:
logger.debug("Failed to determine current mirror, selecting best mirror instead ..")
return self.best_mirror
@cached_property
def validated_mirrors(self):
return {}
@mutable_property
def custom_mirror_file_path(self):
return None
@cached_property
def read_custom_mirror_file(self):
if self.custom_mirror_file_path is None:
return {}
else:
logger.info("The file path you input is %s", self.custom_mirror_file_path)
mirrors = set()
with open(self.custom_mirror_file_path) as f:
for line in f:
if line.strip().startswith(('http://', 'https://', 'ftp://')):
mirrors.add(CandidateMirror(mirror_url=line.strip(), updater=self))
return mirrors
def change_mirror(self, new_mirror=None, update=True):
timer = Timer()
if new_mirror:
logger.info("Changing mirror of %s to %s ..", self.context, new_mirror)
else:
logger.info("Changing mirror of %s to best available mirror ..", self.context)
new_mirror = self.best_mirror
logger.info("Selected mirror: %s", new_mirror)
sources_list = self.get_sources_list()
mirrors_to_replace = [normalize_mirror_url(self.current_mirror)]
if self.release_is_eol:
logger.debug("Replacing %s URLs as well ..", self.security_url)
mirrors_to_replace.append(normalize_mirror_url(self.security_url))
else:
logger.debug("Not replacing %s URLs.", self.security_url)
lines = sources_list.splitlines()
sources_list_options = self.get_sources_list_options
for i, line in enumerate(lines):
tokens = line.split()
if (len(tokens) >= 4
and tokens[0] in ('deb', 'deb-src')
and normalize_mirror_url(tokens[1]) in mirrors_to_replace):
tokens[1] = new_mirror
if i in sources_list_options:
tokens.insert(1, '[' + sources_list_options[i] + ']')
lines[i] = u' '.join(tokens)
self.install_sources_list(u'\n'.join(lines))
del self.current_mirror
self.clear_package_lists()
if update:
self.smart_update(switch_mirrors=False)
logger.info("Finished changing mirror of %s in %s.", self.context, timer)
def clear_package_lists(self):
timer = Timer()
logger.info("Clearing package list cache of %s ..", self.context)
self.context.execute(
'find /var/lib/apt/lists -type f -name lock -prune -o -type f -print0 | xargs -0 rm -f',
sudo=True,
)
logger.info("Successfully cleared package list cache of %s in %s.", self.context, timer)
def create_chroot(self, directory, codename=None, arch=None):
logger.debug("Checking if chroot already exists (%s) ..", directory)
if self.context.exists(directory) and self.context.list_entries(directory):
logger.info("The chroot already exists, skipping initialization.")
first_run = False
else:
if not self.context.find_program('debootstrap'):
logger.info("Installing `debootstrap' program ..")
self.context.execute('apt-get', 'install', '--yes', 'debootstrap', sudo=True)
timer = Timer()
debootstrap_command = ['debootstrap']
if arch:
debootstrap_command.append('--arch=%s' % arch)
release_chroot = None
keyring_chroot = ''
codename_chroot = ''
best_mirror_chroot = None
generate_sources_list_chroot = None
if codename and codename != self.distribution_codename:
updater_chroot = AptMirrorUpdater()
updater_chroot.distribution_codename = codename
if updater_chroot.distributor_id == 'linuxmint':
msg = "It seems no sense to create chroot of Linux Mint, " "please specify a codename of Ubuntu or Debian " "to create chroot."
raise ValueError(msg)
if not self.context.exists(updater_chroot.release.keyring_file):
if updater_chroot.distributor_id == 'ubuntu':
self.context.execute('apt-get', 'install', '--yes', 'ubuntu-keyring', sudo=True)
elif updater_chroot.distributor_id == 'debian':
self.context.execute('apt-get', 'install', '--yes', 'debian-archive-keyring', sudo=True)
release_chroot = updater_chroot.release
keyring_chroot = updater_chroot.release.keyring_file
codename_chroot = codename
best_mirror_chroot = updater_chroot.best_mirror
else:
if self.distributor_id == 'linuxmint':
msg = "It seems no sense to create chroot of Linux Mint, " "please use -C to specify a codename of Ubuntu or Debian " "to create chroot."
raise ValueError(msg)
release_chroot = self.release
keyring_chroot = self.release.keyring_file
codename_chroot = self.distribution_codename
best_mirror_chroot = self.best_mirror
logger.info("Creating %s chroot in %s ..", release_chroot, directory)
debootstrap_command.append('--keyring=%s' % keyring_chroot)
debootstrap_command.append(codename_chroot)
debootstrap_command.append(directory)
debootstrap_command.append(best_mirror_chroot)
self.context.execute(*debootstrap_command, sudo=True)
logger.info("Took %s to create %s chroot.", timer, release_chroot)
first_run = True
self.context = ChangeRootContext(
chroot=directory,
environment=dict(LC_ALL='C'),
)
del self.current_mirror
del self.stable_mirror
if codename and codename != self.distribution_codename:
updater_chroot.context = self.context
del updater_chroot.current_mirror
del updater_chroot.stable_mirror
generate_sources_list_chroot = updater_chroot.generate_sources_list()
else:
generate_sources_list_chroot = self.generate_sources_list()
if first_run:
self.context.execute('apt-get', 'install', '--yes', 'lsb-release', sudo=True)
self.context.execute('apt-get', 'clean', sudo=True)
logger.debug("sources.list for chroot generated:")
logger.debug(generate_sources_list_chroot)
self.install_sources_list(generate_sources_list_chroot)
self.smart_update()
return self.context
|
MIT License
|
unofficial-memsource/memsource-cli-client
|
memsource_cli/models/search_tm_segment_dto.py
|
SearchTMSegmentDto.id
|
python
|
def id(self, id):
self._id = id
|
Sets the id of this SearchTMSegmentDto.
:param id: The id of this SearchTMSegmentDto. # noqa: E501
:type: str
|
https://github.com/unofficial-memsource/memsource-cli-client/blob/a6639506b74e95476da87f4375953448b76ea90c/memsource_cli/models/search_tm_segment_dto.py#L148-L156
|
import pprint
import re
import six
from memsource_cli.models.search_tm_client_dto import SearchTMClientDto
from memsource_cli.models.search_tm_domain_dto import SearchTMDomainDto
from memsource_cli.models.search_tm_project_dto import SearchTMProjectDto
from memsource_cli.models.search_tm_sub_domain_dto import SearchTMSubDomainDto
from memsource_cli.models.tag_metadata import TagMetadata
from memsource_cli.models.user_reference import UserReference
class SearchTMSegmentDto(object):
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'id': 'str',
'text': 'str',
'lang': 'str',
'rtl': 'bool',
'modified_at': 'int',
'created_at': 'int',
'modified_by': 'UserReference',
'created_by': 'UserReference',
'filename': 'str',
'project': 'SearchTMProjectDto',
'client': 'SearchTMClientDto',
'domain': 'SearchTMDomainDto',
'sub_domain': 'SearchTMSubDomainDto',
'tag_metadata': 'list[TagMetadata]',
'previous_segment': 'str',
'next_segment': 'str',
'key': 'str'
}
attribute_map = {
'id': 'id',
'text': 'text',
'lang': 'lang',
'rtl': 'rtl',
'modified_at': 'modifiedAt',
'created_at': 'createdAt',
'modified_by': 'modifiedBy',
'created_by': 'createdBy',
'filename': 'filename',
'project': 'project',
'client': 'client',
'domain': 'domain',
'sub_domain': 'subDomain',
'tag_metadata': 'tagMetadata',
'previous_segment': 'previousSegment',
'next_segment': 'nextSegment',
'key': 'key'
}
def __init__(self, id=None, text=None, lang=None, rtl=None, modified_at=None, created_at=None, modified_by=None, created_by=None, filename=None, project=None, client=None, domain=None, sub_domain=None, tag_metadata=None, previous_segment=None, next_segment=None, key=None):
self._id = None
self._text = None
self._lang = None
self._rtl = None
self._modified_at = None
self._created_at = None
self._modified_by = None
self._created_by = None
self._filename = None
self._project = None
self._client = None
self._domain = None
self._sub_domain = None
self._tag_metadata = None
self._previous_segment = None
self._next_segment = None
self._key = None
self.discriminator = None
if id is not None:
self.id = id
if text is not None:
self.text = text
if lang is not None:
self.lang = lang
if rtl is not None:
self.rtl = rtl
if modified_at is not None:
self.modified_at = modified_at
if created_at is not None:
self.created_at = created_at
if modified_by is not None:
self.modified_by = modified_by
if created_by is not None:
self.created_by = created_by
if filename is not None:
self.filename = filename
if project is not None:
self.project = project
if client is not None:
self.client = client
if domain is not None:
self.domain = domain
if sub_domain is not None:
self.sub_domain = sub_domain
if tag_metadata is not None:
self.tag_metadata = tag_metadata
if previous_segment is not None:
self.previous_segment = previous_segment
if next_segment is not None:
self.next_segment = next_segment
if key is not None:
self.key = key
@property
def id(self):
return self._id
@id.setter
|
Apache License 2.0
|
hackatbrown/2015.hackatbrown.org
|
hack-at-brown-2015/cssutils/serialize.py
|
Preferences.useMinified
|
python
|
def useMinified(self):
self.importHrefFormat = 'string'
self.indent = u''
self.keepComments = False
self.keepEmptyRules = False
self.keepUnknownAtRules = False
self.keepUsedNamespaceRulesOnly = True
self.lineNumbers = False
self.lineSeparator = u''
self.listItemSpacer = u''
self.omitLastSemicolon = True
self.omitLeadingZero = True
self.paranthesisSpacer = u''
self.propertyNameSpacer = u''
self.selectorCombinatorSpacer = u''
self.spacer = u''
self.validOnly = False
|
Set options resulting in a minified stylesheet.
You may want to set preferences with this convenience method
and override specific settings you want adjusted afterwards.
|
https://github.com/hackatbrown/2015.hackatbrown.org/blob/6e6e10b010421228deb562909a1c8bb4272b759f/hack-at-brown-2015/cssutils/serialize.py#L151-L172
|
__all__ = ['CSSSerializer', 'Preferences']
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
from cssutils.helper import normalize
import codecs
import cssutils
import helper
import re
import xml.dom
def _escapecss(e):
s = e.object[e.start:e.end]
return u''.join([ur'\%s ' % str(hex(ord(x)))[2:]
.upper() for x in s]), e.end
codecs.register_error('escapecss', _escapecss)
class Preferences(object):
def __init__(self, **initials):
self.useDefaults()
for key, value in initials.items():
if value:
self.__setattr__(key, value)
def __repr__(self):
return u"cssutils.css.%s(%s)" % (self.__class__.__name__,
u', '.join(['\n %s=%r' % (p, self.__getattribute__(p)) for p in self.__dict__]
))
def __str__(self):
return u"<cssutils.css.%s object %s at 0x%x" % (self.__class__.__name__,
u' '.join(['%s=%r' % (p, self.__getattribute__(p)) for p in self.__dict__]
),
id(self))
def useDefaults(self):
self.defaultAtKeyword = True
self.defaultPropertyName = True
self.defaultPropertyPriority = True
self.importHrefFormat = None
self.indent = 4 * u' '
self.indentClosingBrace = True
self.indentSpecificities = False
self.keepAllProperties = True
self.keepComments = True
self.keepEmptyRules = False
self.keepUnknownAtRules = True
self.keepUsedNamespaceRulesOnly = False
self.lineNumbers = False
self.lineSeparator = u'\n'
self.listItemSpacer = u' '
self.normalizedVarNames = True
self.omitLastSemicolon = True
self.omitLeadingZero = False
self.paranthesisSpacer = u' '
self.propertyNameSpacer = u' '
self.resolveVariables = True
self.selectorCombinatorSpacer = u' '
self.spacer = u' '
self.validOnly = False
|
MIT License
|
localdatascrapers/localdatascrapers
|
philly/models.py
|
SchemaField.is_many_to_many_lookup
|
python
|
def is_many_to_many_lookup(self):
return self.is_lookup and not self.is_type('int') and not self.is_type('lookup')
|
Returns True if this SchemaField is a many-to-many lookup.
|
https://github.com/localdatascrapers/localdatascrapers/blob/770048b6f072798ad103bcab715437237d4b9355/philly/models.py#L140-L144
|
import datetime
import re
import time
import unicodedata
import urllib
from django.contrib.gis.db import models
from django.conf import settings
from django.db import connections, transaction
from django.db.models import Q
from connections import get_connection_name
from constants import (STATUS_CHOICES, STATUS_LIVE, USER_SCHEMAS, NEIGHBOR_MESSAGE_SCHEMAS, UGC, RemovalReasons)
def field_mapping(schema_id_list, db):
result = {}
for sf in SchemaField.objects.using(db).filter(schema__id__in=(schema_id_list)).values('schema', 'name', 'real_name'):
result.setdefault(sf['schema'], {})[sf['name']] = sf['real_name']
return result
class SchemaManager(models.Manager):
def for_metro(self, short_name):
return self.using(get_connection_name(short_name))
class PublicSchemaManager(SchemaManager):
def get_queryset(self):
return super(PublicSchemaManager, self).get_queryset().filter(is_public=True)
BUCKET_CHOICES = (
(0, 'From the Web'),
(1, 'Public records'),
(3, 'Neighbor messages'),
)
class FakeSchema(object):
def __init__(self, slug, name, plural_name):
self.slug = slug
self.name = name
self.plural_name = plural_name
self.is_active = True
def is_neighbor_message(self):
return True
class Schema(models.Model):
bucket = models.SmallIntegerField(choices=BUCKET_CHOICES)
name = models.CharField(max_length=100)
plural_name = models.CharField(max_length=100)
indefinite_article = models.CharField(max_length=2)
slug = models.CharField(max_length=32, unique=True)
min_date = models.DateField()
last_updated = models.DateField()
date_name = models.CharField(max_length=32)
date_name_plural = models.CharField(max_length=32)
is_public = models.BooleanField(db_index=True)
is_active = models.BooleanField()
has_newsitem_detail = models.BooleanField()
allow_comments = models.BooleanField()
has_linkable_locations = models.BooleanField()
pattern = models.CharField(max_length=32, blank=True)
launch_date = models.DateField()
def __unicode__(self):
return self.name
def url(self):
return '/%s/' % self.slug
def is_new(self):
return datetime.date.today() - self.launch_date < datetime.timedelta(days=7)
def is_neighbor_content(self):
return self.slug in USER_SCHEMAS
def is_neighbor_message(self):
return self.slug in NEIGHBOR_MESSAGE_SCHEMAS
def pattern_slug(self):
return 'neighbor-message' if self.slug in NEIGHBOR_MESSAGE_SCHEMAS else self.slug
class SchemaInfo(models.Model):
schema = models.ForeignKey(Schema)
short_description = models.TextField()
summary = models.TextField()
source = models.TextField()
grab_bag_headline = models.CharField(max_length=128, blank=True)
grab_bag = models.TextField(blank=True)
short_source = models.CharField(max_length=128)
update_frequency = models.CharField(max_length=64)
intro = models.TextField()
def __unicode__(self):
return unicode(self.schema)
class SchemaField(models.Model):
schema = models.ForeignKey(Schema)
name = models.CharField(max_length=32)
real_name = models.CharField(max_length=10)
pretty_name = models.CharField(max_length=32)
pretty_name_plural = models.CharField(max_length=32)
pattern_slot = models.CharField(max_length=32)
display = models.BooleanField()
is_lookup = models.BooleanField()
display_order = models.SmallIntegerField()
display_format = models.CharField(max_length=50, blank=True)
display_api = models.BooleanField(default=False)
def __unicode__(self):
return u'%s - %s' % (self.schema, self.name)
def _get_slug(self):
return self.name.replace('_', '-')
slug = property(_get_slug)
def _datatype(self):
return self.real_name[:-2]
datatype = property(_datatype)
def is_type(self, *data_types):
for t in data_types:
if t == self.real_name[:-2]:
return True
return False
|
Apache License 2.0
|
xiaohangzhan/mix-and-match
|
caffe/python/caffe/classifier.py
|
Classifier.predict
|
python
|
def predict(self, inputs, oversample=True):
input_ = np.zeros((len(inputs),
self.image_dims[0],
self.image_dims[1],
inputs[0].shape[2]),
dtype=np.float32)
for ix, in_ in enumerate(inputs):
input_[ix] = caffe.io.resize_image(in_, self.image_dims)
if oversample:
input_ = caffe.io.oversample(input_, self.crop_dims)
else:
center = np.array(self.image_dims) / 2.0
crop = np.tile(center, (1, 2))[0] + np.concatenate([
-self.crop_dims / 2.0,
self.crop_dims / 2.0
])
input_ = input_[:, crop[0]:crop[2], crop[1]:crop[3], :]
caffe_in = np.zeros(np.array(input_.shape)[[0, 3, 1, 2]],
dtype=np.float32)
for ix, in_ in enumerate(input_):
caffe_in[ix] = self.transformer.preprocess(self.inputs[0], in_)
out = self.forward_all(**{self.inputs[0]: caffe_in})
predictions = out[self.outputs[0]]
if oversample:
predictions = predictions.reshape((len(predictions) / 10, 10, -1))
predictions = predictions.mean(1)
return predictions
|
Predict classification probabilities of inputs.
Parameters
----------
inputs : iterable of (H x W x K) input ndarrays.
oversample : boolean
average predictions across center, corners, and mirrors
when True (default). Center-only prediction when False.
Returns
-------
predictions: (N x C) ndarray of class probabilities for N images and C
classes.
|
https://github.com/xiaohangzhan/mix-and-match/blob/8d4c9df80ef281b4112bf27d8901700dcedc798f/caffe/python/caffe/classifier.py#L47-L97
|
import numpy as np
import caffe
class Classifier(caffe.Net):
def __init__(self, model_file, pretrained_file, image_dims=None,
mean=None, input_scale=None, raw_scale=None,
channel_swap=None):
caffe.Net.__init__(self, model_file, pretrained_file, caffe.TEST)
in_ = self.inputs[0]
self.transformer = caffe.io.Transformer(
{in_: self.blobs[in_].data.shape})
self.transformer.set_transpose(in_, (2, 0, 1))
if mean is not None:
self.transformer.set_mean(in_, mean)
if input_scale is not None:
self.transformer.set_input_scale(in_, input_scale)
if raw_scale is not None:
self.transformer.set_raw_scale(in_, raw_scale)
if channel_swap is not None:
self.transformer.set_channel_swap(in_, channel_swap)
self.crop_dims = np.array(self.blobs[in_].data.shape[2:])
if not image_dims:
image_dims = self.crop_dims
self.image_dims = image_dims
|
MIT License
|
purestorage-openconnect/py-pure-client
|
pypureclient/flasharray/FA_2_6/api/hosts_api.py
|
HostsApi.api26_hosts_performance_balance_get_with_http_info
|
python
|
def api26_hosts_performance_balance_get_with_http_info(
self,
authorization=None,
x_request_id=None,
filter=None,
limit=None,
names=None,
offset=None,
sort=None,
total_item_count=None,
async_req=False,
_return_http_data_only=False,
_preload_content=True,
_request_timeout=None,
):
if names is not None:
if not isinstance(names, list):
names = [names]
if sort is not None:
if not isinstance(sort, list):
sort = [sort]
params = {k: v for k, v in six.iteritems(locals()) if v is not None}
if params.get('filter'):
params['filter'] = str(params['filter'])
if params.get('sort'):
params['sort'] = [str(_x) for _x in params['sort']]
if 'limit' in params and params['limit'] < 1:
raise ValueError("Invalid value for parameter `limit` when calling `api26_hosts_performance_balance_get`, must be a value greater than or equal to `1`")
if 'offset' in params and params['offset'] < 0:
raise ValueError("Invalid value for parameter `offset` when calling `api26_hosts_performance_balance_get`, must be a value greater than or equal to `0`")
collection_formats = {}
path_params = {}
query_params = []
if 'filter' in params:
query_params.append(('filter', params['filter']))
if 'limit' in params:
query_params.append(('limit', params['limit']))
if 'names' in params:
query_params.append(('names', params['names']))
collection_formats['names'] = 'csv'
if 'offset' in params:
query_params.append(('offset', params['offset']))
if 'sort' in params:
query_params.append(('sort', params['sort']))
collection_formats['sort'] = 'csv'
if 'total_item_count' in params:
query_params.append(('total_item_count', params['total_item_count']))
header_params = {}
if 'authorization' in params:
header_params['Authorization'] = params['authorization']
if 'x_request_id' in params:
header_params['X-Request-ID'] = params['x_request_id']
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(
['application/json'])
header_params['Content-Type'] = self.api_client.select_header_content_type(
['application/json'])
auth_settings = []
return self.api_client.call_api(
'/api/2.6/hosts/performance/balance', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='HostPerformanceBalanceGetResponse',
auth_settings=auth_settings,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
collection_formats=collection_formats,
)
|
List host performance balance
Displays the I/O balance statistics for host paths.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.api26_hosts_performance_balance_get_with_http_info(async_req=True)
>>> result = thread.get()
:param str authorization: Access token (in JWT format) required to use any API endpoint (except `/oauth2`, `/login`, and `/logout`)
:param str x_request_id: Supplied by client during request or generated by server.
:param str filter: Narrows down the results to only the response objects that satisfy the filter criteria.
:param int limit: Limits the size of the response to the specified number of objects on each page. To return the total number of resources, set `limit=0`. The total number of resources is returned as a `total_item_count` value. If the page size requested is larger than the system maximum limit, the server returns the maximum limit, disregarding the requested page size.
:param list[str] names: Performs the operation on the unique name specified. Enter multiple names in comma-separated format. For example, `name01,name02`.
:param int offset: The starting position based on the results of the query in relation to the full set of response objects returned.
:param list[str] sort: Returns the response objects in the order specified. Set `sort` to the name in the response by which to sort. Sorting can be performed on any of the names in the response, and the objects can be sorted in ascending or descending order. By default, the response objects are sorted in ascending order. To sort in descending order, append the minus sign (`-`) to the name. A single request can be sorted on multiple objects. For example, you can sort all volumes from largest to smallest volume size, and then sort volumes of the same size in ascending order by volume name. To sort on multiple names, list the names as comma-separated values.
:param bool total_item_count: If set to `true`, the `total_item_count` matching the specified query parameters is calculated and returned in the response. If set to `false`, the `total_item_count` is `null` in the response. This may speed up queries where the `total_item_count` is large. If not specified, defaults to `false`.
:param bool async_req: Request runs in separate thread and method returns multiprocessing.pool.ApplyResult.
:param bool _return_http_data_only: Returns only data field.
:param bool _preload_content: Response is converted into objects.
:param int _request_timeout: Total request timeout in seconds.
It can also be a tuple of (connection time, read time) timeouts.
:return: HostPerformanceBalanceGetResponse
If the method is called asynchronously,
returns the request thread.
|
https://github.com/purestorage-openconnect/py-pure-client/blob/2d9fdef0b73321cea9613e7d1eb881b42845099b/pypureclient/flasharray/FA_2_6/api/hosts_api.py#L652-L766
|
from __future__ import absolute_import
import re
import six
from typing import List, Optional
from .. import models
class HostsApi(object):
def __init__(self, api_client):
self.api_client = api_client
def api26_hosts_delete_with_http_info(
self,
authorization=None,
x_request_id=None,
names=None,
async_req=False,
_return_http_data_only=False,
_preload_content=True,
_request_timeout=None,
):
if names is not None:
if not isinstance(names, list):
names = [names]
params = {k: v for k, v in six.iteritems(locals()) if v is not None}
if params.get('filter'):
params['filter'] = str(params['filter'])
if params.get('sort'):
params['sort'] = [str(_x) for _x in params['sort']]
collection_formats = {}
path_params = {}
query_params = []
if 'names' in params:
query_params.append(('names', params['names']))
collection_formats['names'] = 'csv'
header_params = {}
if 'authorization' in params:
header_params['Authorization'] = params['authorization']
if 'x_request_id' in params:
header_params['X-Request-ID'] = params['x_request_id']
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(
['application/json'])
header_params['Content-Type'] = self.api_client.select_header_content_type(
['application/json'])
auth_settings = []
return self.api_client.call_api(
'/api/2.6/hosts', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None,
auth_settings=auth_settings,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
collection_formats=collection_formats,
)
def api26_hosts_get_with_http_info(
self,
authorization=None,
x_request_id=None,
continuation_token=None,
filter=None,
limit=None,
names=None,
offset=None,
sort=None,
total_item_count=None,
async_req=False,
_return_http_data_only=False,
_preload_content=True,
_request_timeout=None,
):
if names is not None:
if not isinstance(names, list):
names = [names]
if sort is not None:
if not isinstance(sort, list):
sort = [sort]
params = {k: v for k, v in six.iteritems(locals()) if v is not None}
if params.get('filter'):
params['filter'] = str(params['filter'])
if params.get('sort'):
params['sort'] = [str(_x) for _x in params['sort']]
if 'limit' in params and params['limit'] < 1:
raise ValueError("Invalid value for parameter `limit` when calling `api26_hosts_get`, must be a value greater than or equal to `1`")
if 'offset' in params and params['offset'] < 0:
raise ValueError("Invalid value for parameter `offset` when calling `api26_hosts_get`, must be a value greater than or equal to `0`")
collection_formats = {}
path_params = {}
query_params = []
if 'continuation_token' in params:
query_params.append(('continuation_token', params['continuation_token']))
if 'filter' in params:
query_params.append(('filter', params['filter']))
if 'limit' in params:
query_params.append(('limit', params['limit']))
if 'names' in params:
query_params.append(('names', params['names']))
collection_formats['names'] = 'csv'
if 'offset' in params:
query_params.append(('offset', params['offset']))
if 'sort' in params:
query_params.append(('sort', params['sort']))
collection_formats['sort'] = 'csv'
if 'total_item_count' in params:
query_params.append(('total_item_count', params['total_item_count']))
header_params = {}
if 'authorization' in params:
header_params['Authorization'] = params['authorization']
if 'x_request_id' in params:
header_params['X-Request-ID'] = params['x_request_id']
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(
['application/json'])
header_params['Content-Type'] = self.api_client.select_header_content_type(
['application/json'])
auth_settings = []
return self.api_client.call_api(
'/api/2.6/hosts', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='HostGetResponse',
auth_settings=auth_settings,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
collection_formats=collection_formats,
)
def api26_hosts_host_groups_delete_with_http_info(
self,
authorization=None,
x_request_id=None,
group_names=None,
member_names=None,
async_req=False,
_return_http_data_only=False,
_preload_content=True,
_request_timeout=None,
):
if group_names is not None:
if not isinstance(group_names, list):
group_names = [group_names]
if member_names is not None:
if not isinstance(member_names, list):
member_names = [member_names]
params = {k: v for k, v in six.iteritems(locals()) if v is not None}
if params.get('filter'):
params['filter'] = str(params['filter'])
if params.get('sort'):
params['sort'] = [str(_x) for _x in params['sort']]
collection_formats = {}
path_params = {}
query_params = []
if 'group_names' in params:
query_params.append(('group_names', params['group_names']))
collection_formats['group_names'] = 'csv'
if 'member_names' in params:
query_params.append(('member_names', params['member_names']))
collection_formats['member_names'] = 'csv'
header_params = {}
if 'authorization' in params:
header_params['Authorization'] = params['authorization']
if 'x_request_id' in params:
header_params['X-Request-ID'] = params['x_request_id']
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(
['application/json'])
header_params['Content-Type'] = self.api_client.select_header_content_type(
['application/json'])
auth_settings = []
return self.api_client.call_api(
'/api/2.6/hosts/host-groups', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None,
auth_settings=auth_settings,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
collection_formats=collection_formats,
)
def api26_hosts_host_groups_get_with_http_info(
self,
authorization=None,
x_request_id=None,
continuation_token=None,
filter=None,
group_names=None,
limit=None,
member_names=None,
offset=None,
sort=None,
total_item_count=None,
async_req=False,
_return_http_data_only=False,
_preload_content=True,
_request_timeout=None,
):
if group_names is not None:
if not isinstance(group_names, list):
group_names = [group_names]
if member_names is not None:
if not isinstance(member_names, list):
member_names = [member_names]
if sort is not None:
if not isinstance(sort, list):
sort = [sort]
params = {k: v for k, v in six.iteritems(locals()) if v is not None}
if params.get('filter'):
params['filter'] = str(params['filter'])
if params.get('sort'):
params['sort'] = [str(_x) for _x in params['sort']]
if 'limit' in params and params['limit'] < 1:
raise ValueError("Invalid value for parameter `limit` when calling `api26_hosts_host_groups_get`, must be a value greater than or equal to `1`")
if 'offset' in params and params['offset'] < 0:
raise ValueError("Invalid value for parameter `offset` when calling `api26_hosts_host_groups_get`, must be a value greater than or equal to `0`")
collection_formats = {}
path_params = {}
query_params = []
if 'continuation_token' in params:
query_params.append(('continuation_token', params['continuation_token']))
if 'filter' in params:
query_params.append(('filter', params['filter']))
if 'group_names' in params:
query_params.append(('group_names', params['group_names']))
collection_formats['group_names'] = 'csv'
if 'limit' in params:
query_params.append(('limit', params['limit']))
if 'member_names' in params:
query_params.append(('member_names', params['member_names']))
collection_formats['member_names'] = 'csv'
if 'offset' in params:
query_params.append(('offset', params['offset']))
if 'sort' in params:
query_params.append(('sort', params['sort']))
collection_formats['sort'] = 'csv'
if 'total_item_count' in params:
query_params.append(('total_item_count', params['total_item_count']))
header_params = {}
if 'authorization' in params:
header_params['Authorization'] = params['authorization']
if 'x_request_id' in params:
header_params['X-Request-ID'] = params['x_request_id']
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(
['application/json'])
header_params['Content-Type'] = self.api_client.select_header_content_type(
['application/json'])
auth_settings = []
return self.api_client.call_api(
'/api/2.6/hosts/host-groups', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='MemberNoIdAllGetResponse',
auth_settings=auth_settings,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
collection_formats=collection_formats,
)
def api26_hosts_host_groups_post_with_http_info(
self,
authorization=None,
x_request_id=None,
group_names=None,
member_names=None,
async_req=False,
_return_http_data_only=False,
_preload_content=True,
_request_timeout=None,
):
if group_names is not None:
if not isinstance(group_names, list):
group_names = [group_names]
if member_names is not None:
if not isinstance(member_names, list):
member_names = [member_names]
params = {k: v for k, v in six.iteritems(locals()) if v is not None}
if params.get('filter'):
params['filter'] = str(params['filter'])
if params.get('sort'):
params['sort'] = [str(_x) for _x in params['sort']]
collection_formats = {}
path_params = {}
query_params = []
if 'group_names' in params:
query_params.append(('group_names', params['group_names']))
collection_formats['group_names'] = 'csv'
if 'member_names' in params:
query_params.append(('member_names', params['member_names']))
collection_formats['member_names'] = 'csv'
header_params = {}
if 'authorization' in params:
header_params['Authorization'] = params['authorization']
if 'x_request_id' in params:
header_params['X-Request-ID'] = params['x_request_id']
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(
['application/json'])
header_params['Content-Type'] = self.api_client.select_header_content_type(
['application/json'])
auth_settings = []
return self.api_client.call_api(
'/api/2.6/hosts/host-groups', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='MemberNoIdAllResponse',
auth_settings=auth_settings,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
collection_formats=collection_formats,
)
def api26_hosts_patch_with_http_info(
self,
host=None,
authorization=None,
x_request_id=None,
names=None,
async_req=False,
_return_http_data_only=False,
_preload_content=True,
_request_timeout=None,
):
if names is not None:
if not isinstance(names, list):
names = [names]
params = {k: v for k, v in six.iteritems(locals()) if v is not None}
if params.get('filter'):
params['filter'] = str(params['filter'])
if params.get('sort'):
params['sort'] = [str(_x) for _x in params['sort']]
if host is None:
raise TypeError("Missing the required parameter `host` when calling `api26_hosts_patch`")
collection_formats = {}
path_params = {}
query_params = []
if 'names' in params:
query_params.append(('names', params['names']))
collection_formats['names'] = 'csv'
header_params = {}
if 'authorization' in params:
header_params['Authorization'] = params['authorization']
if 'x_request_id' in params:
header_params['X-Request-ID'] = params['x_request_id']
form_params = []
local_var_files = {}
body_params = None
if 'host' in params:
body_params = params['host']
header_params['Accept'] = self.api_client.select_header_accept(
['application/json'])
header_params['Content-Type'] = self.api_client.select_header_content_type(
['application/json'])
auth_settings = []
return self.api_client.call_api(
'/api/2.6/hosts', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='HostResponse',
auth_settings=auth_settings,
async_req=async_req,
_return_http_data_only=_return_http_data_only,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
collection_formats=collection_formats,
)
|
BSD 2-Clause Simplified License
|
pmelchior/scarlet
|
scarlet/detect.py
|
draw_box
|
python
|
def draw_box(box, ax, color):
rect = patches.Rectangle(
box.origin[::-1], box.shape[1], box.shape[0],
linewidth=1, edgecolor=color, facecolor="none")
ax.add_patch(rect)
|
Draw a box on an axis
Parameters
----------
box: `scarlet.bbox.Box`
The box to draw
ax: `matplotlib.Axis`
The axis on which to draw the box
color: `str`
The name of the color to use for the box
|
https://github.com/pmelchior/scarlet/blob/134fac69465c2eea46b6909c6f401e1b17cdd85b/scarlet/detect.py#L68-L83
|
import logging
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np
from .bbox import Box, overlapped_slices
from .interpolation import get_filter_coords, get_filter_bounds
from .operator import prox_monotonic_mask
from .wavelet import starlet_reconstruction, starlet_transform, get_multiresolution_support
logger = logging.getLogger("scarlet.detect")
def bounds_to_bbox(bounds):
return Box(
(bounds[1]+1-bounds[0], bounds[3]+1-bounds[2]),
origin=(bounds[0], bounds[2])
)
def box_intersect(box1, box2):
overlap = box1 & box2
return overlap.shape[0] != 0 and overlap.shape[1] != 0
def footprint_intersect(footprint1, box1, footprint2, box2):
if not box_intersect(box1, box2):
return False
slices1, slices2 = overlapped_slices(box1, box2)
overlap = footprint1[slices1] * footprint2[slices2]
return np.sum(overlap) > 0
|
MIT License
|
gmr/tredis
|
tredis/strings.py
|
StringsMixin.setbit
|
python
|
def setbit(self, key, offset, bit):
if 0 < bit > 1:
raise ValueError('bit must be 1 or 0, not {}'.format(bit))
return self._execute([b'SETBIT', key, ascii(offset), ascii(bit)])
|
Sets or clears the bit at offset in the string value stored at key.
The bit is either set or cleared depending on value, which can be
either 0 or 1. When key does not exist, a new string value is created.
The string is grown to make sure it can hold a bit at offset. The
offset argument is required to be greater than or equal to 0, and
smaller than 2 :sup:`32` (this limits bitmaps to 512MB). When the
string at key is grown, added bits are set to 0.
.. warning:: When setting the last possible bit (offset equal to
2 :sup:`32` -1) and the string value stored at key does not yet hold
a string value, or holds a small string value, Redis needs to
allocate all intermediate memory which can block the server for some
time. On a 2010 MacBook Pro, setting bit number 2 :sup:`32` -1
(512MB allocation) takes ~300ms, setting bit number 2 :sup:`30` -1
(128MB allocation) takes ~80ms, setting bit number 2 :sup:`28` -1
(32MB allocation) takes ~30ms and setting bit number 2 :sup:`26` -1
(8MB allocation) takes ~8ms. Note that once this first allocation is
done, subsequent calls to :meth:`~tredis.RedisClient.setbit` for the
same key will not have the allocation overhead.
.. versionadded:: 0.2.0
.. note:: **Time complexity**: ``O(1)``
:param key: The key to get the bit from
:type key: :class:`str`, :class:`bytes`
:param int offset: The bit offset to fetch the bit from
:param int bit: The value (``0`` or ``1``) to set for the bit
:rtype: int
:raises: :exc:`~tredis.exceptions.RedisError`
|
https://github.com/gmr/tredis/blob/2e91c6a58a35460be0525c51ac6a98fde3b506ad/tredis/strings.py#L551-L587
|
if 'ascii' not in dir(__builtins__):
from tredis.compat import ascii
BITOP_AND = b'&'
BITOP_OR = b'|'
BITOP_XOR = b'^'
BITOP_NOT = b'~'
_BITOPTS = {
BITOP_AND: b'AND',
BITOP_OR: b'OR',
BITOP_XOR: b'XOR',
BITOP_NOT: b'NOT',
}
class StringsMixin(object):
def append(self, key, value):
return self._execute([b'APPEND', key, value])
def bitcount(self, key, start=None, end=None):
command = [b'BITCOUNT', key]
if start is not None and end is None:
raise ValueError('Can not specify start without an end')
elif start is None and end is not None:
raise ValueError('Can not specify start without an end')
elif start is not None and end is not None:
command += [ascii(start), ascii(end)]
return self._execute(command)
def bitop(self, operation, dest_key, *keys):
if (operation not in _BITOPTS.keys()
and operation not in _BITOPTS.values()):
raise ValueError('Invalid operation value: {}'.format(operation))
elif operation in [b'~', b'NOT'] and len(keys) > 1:
raise ValueError('NOT can only be used with 1 key')
if operation in _BITOPTS.keys():
operation = _BITOPTS[operation]
return self._execute([b'BITOP', operation, dest_key] + list(keys))
def bitpos(self, key, bit, start=None, end=None):
if 0 < bit > 1:
raise ValueError('bit must be 1 or 0, not {}'.format(bit))
command = [b'BITPOS', key, ascii(bit)]
if start is not None and end is None:
raise ValueError('Can not specify start without an end')
elif start is None and end is not None:
raise ValueError('Can not specify start without an end')
elif start is not None and end is not None:
command += [ascii(start), ascii(end)]
return self._execute(command)
def decr(self, key):
return self._execute([b'DECR', key])
def decrby(self, key, decrement):
return self._execute([b'DECRBY', key, ascii(decrement)])
def get(self, key):
return self._execute([b'GET', key])
def getbit(self, key, offset):
return self._execute([b'GETBIT', key, ascii(offset)])
def getrange(self, key, start, end):
return self._execute([b'GETRANGE', key, ascii(start), ascii(end)])
def getset(self, key, value):
return self._execute([b'GETSET', key, value])
def incr(self, key):
return self._execute([b'INCR', key])
def incrby(self, key, increment):
return self._execute([b'INCRBY', key, ascii(increment)])
def incrbyfloat(self, key, increment):
return self._execute([b'INCRBYFLOAT', key, ascii(increment)])
def mget(self, *keys):
return self._execute([b'MGET'] + list(keys))
def mset(self, mapping):
command = [b'MSET']
for key, value in mapping.items():
command += [key, value]
return self._execute(command, b'OK')
def msetnx(self, mapping):
command = [b'MSETNX']
for key, value in mapping.items():
command += [key, value]
return self._execute(command, 1)
def psetex(self, key, milliseconds, value):
return self._execute(
[b'PSETEX', key, ascii(milliseconds), value], b'OK')
def set(self, key, value, ex=None, px=None, nx=False, xx=False):
command = [b'SET', key, value]
if ex:
command += [b'EX', ascii(ex).encode('ascii')]
if px:
command += [b'PX', ascii(px).encode('ascii')]
if nx:
command.append(b'NX')
if xx:
command.append(b'XX')
return self._execute(command, b'OK')
|
BSD 3-Clause New or Revised License
|
foglamp/foglamp
|
python/foglamp/common/statistics.py
|
Statistics.update_bulk
|
python
|
async def update_bulk(self, stat_list):
if not isinstance(stat_list, dict):
raise TypeError('stat_list must be a dict')
try:
payload = {"updates": []}
for k, v in stat_list.items():
payload_item = PayloadBuilder() .WHERE(["key", "=", k]) .EXPR(["value", "+", v]) .payload()
payload['updates'].append(json.loads(payload_item))
await self._storage.update_tbl("statistics", json.dumps(payload, sort_keys=False))
except Exception as ex:
_logger.exception('Unable to bulk update statistics %s', str(ex))
raise
|
Bulk update statistics table keys and their values
Args:
stat_list: dict containing statistics keys and increment values
Returns:
None
|
https://github.com/foglamp/foglamp/blob/918dff88b440e6ad580efdaa5f0fbdf4143a73d4/python/foglamp/common/statistics.py#L52-L75
|
import json
from foglamp.common import logger
from foglamp.common.storage_client.payload_builder import PayloadBuilder
from foglamp.common.storage_client.storage_client import StorageClientAsync
__author__ = "Ashwin Gopalakrishnan, Ashish Jabble, Mark Riddoch, Amarendra K Sinha"
__copyright__ = "Copyright (c) 2017 OSIsoft, LLC"
__license__ = "Apache 2.0"
__version__ = "${VERSION}"
_logger = logger.setup(__name__)
async def create_statistics(storage=None):
stat = Statistics(storage)
await stat._init()
return stat
class Statistics(object):
_shared_state = {}
_storage = None
_registered_keys = None
def __init__(self, storage=None):
self.__dict__ = self._shared_state
if self._storage is None:
if not isinstance(storage, StorageClientAsync):
raise TypeError('Must be a valid Async Storage object')
self._storage = storage
async def _init(self):
if self._registered_keys is None:
await self._load_keys()
|
Apache License 2.0
|
soco/soco
|
soco/alarms.py
|
Alarms.update
|
python
|
def update(self, zone=None):
if zone is None:
zone = self._last_zone_used or discovery.any_soco()
self._last_zone_used = zone
response = zone.alarmClock.ListAlarms()
current_alarm_list_version = response["CurrentAlarmListVersion"]
if self.last_alarm_list_version:
alarm_list_uid, alarm_list_id = current_alarm_list_version.split(":")
if self.last_uid != alarm_list_uid:
matching_zone = next(
(z for z in zone.all_zones if z.uid == alarm_list_uid), None
)
if not matching_zone:
raise SoCoException(
"Alarm list UID {} does not match {}".format(
current_alarm_list_version, self.last_alarm_list_version
)
)
if int(alarm_list_id) <= self.last_id:
return
self.last_alarm_list_version = current_alarm_list_version
new_alarms = parse_alarm_payload(response, zone)
for alarm_id, kwargs in new_alarms.items():
existing_alarm = self.alarms.get(alarm_id)
if existing_alarm:
existing_alarm.update(**kwargs)
else:
new_alarm = Alarm(**kwargs)
new_alarm._alarm_id = alarm_id
self.alarms[alarm_id] = new_alarm
for alarm_id in list(self.alarms):
if not new_alarms.get(alarm_id):
self.alarms.pop(alarm_id)
|
Update all alarms and current alarm list version.
Raises:
SoCoException: If the 'CurrentAlarmListVersion' value is unexpected.
May occur if the provided zone is from a different household.
|
https://github.com/soco/soco/blob/bc20bc5ba733fa2db4ab29f521a49f5ff2678cb7/soco/alarms.py#L132-L180
|
import logging
import re
from datetime import datetime
from . import discovery
from .core import _SocoSingletonBase, PLAY_MODES
from .exceptions import SoCoException
from .xml import XML
log = logging.getLogger(__name__)
TIME_FORMAT = "%H:%M:%S"
def is_valid_recurrence(text):
if text in ("DAILY", "ONCE", "WEEKDAYS", "WEEKENDS"):
return True
return re.search(r"^ON_[0-6]{1,7}$", text) is not None
class Alarms(_SocoSingletonBase):
_class_group = "Alarms"
def __init__(self):
self.alarms = {}
self._last_zone_used = None
self._last_alarm_list_version = None
self.last_uid = None
self.last_id = 0
@property
def last_alarm_list_version(self):
return self._last_alarm_list_version
@last_alarm_list_version.setter
def last_alarm_list_version(self, alarm_list_version):
self.last_uid, last_id = alarm_list_version.split(":")
self.last_id = int(last_id)
self._last_alarm_list_version = alarm_list_version
def __iter__(self):
for alarm in list(self.alarms.values()):
yield alarm
def __len__(self):
return len(self.alarms)
def __getitem__(self, alarm_id):
return self.alarms[alarm_id]
def get(self, alarm_id):
return self.alarms.get(alarm_id)
|
MIT License
|
olitheolix/aiokubernetes
|
aiokubernetes/models/v1_persistent_volume_claim_status.py
|
V1PersistentVolumeClaimStatus.__eq__
|
python
|
def __eq__(self, other):
if not isinstance(other, V1PersistentVolumeClaimStatus):
return False
return self.__dict__ == other.__dict__
|
Returns true if both objects are equal
|
https://github.com/olitheolix/aiokubernetes/blob/266718b210dff2a9b2212183261ea89adf89115e/aiokubernetes/models/v1_persistent_volume_claim_status.py#L190-L195
|
import pprint
import re
from aiokubernetes.models.v1_persistent_volume_claim_condition import V1PersistentVolumeClaimCondition
class V1PersistentVolumeClaimStatus(object):
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'access_modes': 'list[str]',
'capacity': 'dict(str, str)',
'conditions': 'list[V1PersistentVolumeClaimCondition]',
'phase': 'str'
}
attribute_map = {
'access_modes': 'accessModes',
'capacity': 'capacity',
'conditions': 'conditions',
'phase': 'phase'
}
def __init__(self, access_modes=None, capacity=None, conditions=None, phase=None):
self._access_modes = None
self._capacity = None
self._conditions = None
self._phase = None
self.discriminator = None
if access_modes is not None:
self.access_modes = access_modes
if capacity is not None:
self.capacity = capacity
if conditions is not None:
self.conditions = conditions
if phase is not None:
self.phase = phase
@property
def access_modes(self):
return self._access_modes
@access_modes.setter
def access_modes(self, access_modes):
self._access_modes = access_modes
@property
def capacity(self):
return self._capacity
@capacity.setter
def capacity(self, capacity):
self._capacity = capacity
@property
def conditions(self):
return self._conditions
@conditions.setter
def conditions(self, conditions):
self._conditions = conditions
@property
def phase(self):
return self._phase
@phase.setter
def phase(self, phase):
self._phase = phase
def to_dict(self):
result = {}
for attr, _ in self.swagger_types.items():
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
return pprint.pformat(self.to_dict())
def __repr__(self):
return self.to_str()
|
Apache License 2.0
|
pysmt/pysmt
|
pysmt/shortcuts.py
|
Xor
|
python
|
def Xor(left, right):
return get_env().formula_manager.Xor(left, right)
|
Returns the XOR of left and right
:param left: Specify the left BV
:type left: FNode
:param right: Specify the right BV
:type right: FNode
:returns: The XOR of left and right
|
https://github.com/pysmt/pysmt/blob/ade4dc2a825727615033a96d31c71e9f53ce4764/pysmt/shortcuts.py#L344-L353
|
import warnings
warnings.filterwarnings('default', module='pysmt')
import pysmt.configuration as config
import pysmt.environment
import pysmt.typing as types
import pysmt.smtlib.parser
import pysmt.smtlib.script
import pysmt.smtlib.printers
from pysmt.typing import INT, BOOL, REAL, BVType, FunctionType, ArrayType, Type
assert INT or BOOL or REAL or BVType or FunctionType or ArrayType or Type
def get_env():
return pysmt.environment.get_env()
def reset_env():
return pysmt.environment.reset_env()
get_env().enable_infix_notation = True
def get_type(formula):
return get_env().stc.get_type(formula)
def simplify(formula):
return get_env().simplifier.simplify(formula)
def substitute(formula, subs):
return get_env().substituter.substitute(formula, subs)
def serialize(formula, threshold=None):
return get_env().serializer.serialize(formula,
threshold=threshold)
def get_free_variables(formula):
return get_env().fvo.get_free_variables(formula)
def get_atoms(formula):
return get_env().ao.get_atoms(formula)
def get_formula_size(formula, measure=None):
return get_env().sizeo.get_size(formula, measure)
def ForAll(variables, formula):
return get_env().formula_manager.ForAll(variables, formula)
def Exists(variables, formula):
return get_env().formula_manager.Exists(variables, formula)
def Function(vname, params):
return get_env().formula_manager.Function(vname, params)
def Not(formula):
return get_env().formula_manager.Not(formula)
def Implies(left, right):
return get_env().formula_manager.Implies(left, right)
def Iff(left, right):
return get_env().formula_manager.Iff(left, right)
def GE(left, right):
return get_env().formula_manager.GE(left, right)
def Minus(left, right):
return get_env().formula_manager.Minus(left, right)
def Times(*args):
return get_env().formula_manager.Times(*args)
def Pow(left, right):
return get_env().formula_manager.Pow(left, right)
def Div(left, right):
return get_env().formula_manager.Div(left, right)
def Equals(left, right):
return get_env().formula_manager.Equals(left, right)
def NotEquals(left, right):
return get_env().formula_manager.NotEquals(left, right)
def GT(left, right):
return get_env().formula_manager.GT(left, right)
def LE(left, right):
return get_env().formula_manager.LE(left, right)
def LT(left, right):
return get_env().formula_manager.LT(left, right)
def Ite(iff, left, right):
return get_env().formula_manager.Ite(iff, left, right)
def Symbol(name, typename=types.BOOL):
return get_env().formula_manager.Symbol(name, typename)
def FreshSymbol(typename=types.BOOL, template=None):
return get_env().formula_manager.FreshSymbol(typename, template)
def Int(value):
return get_env().formula_manager.Int(value)
def Bool(value):
return get_env().formula_manager.Bool(value)
def Real(value):
return get_env().formula_manager.Real(value)
def String(value):
return get_env().formula_manager.String(value)
def TRUE():
return get_env().formula_manager.TRUE()
def FALSE():
return get_env().formula_manager.FALSE()
def And(*args):
return get_env().formula_manager.And(*args)
def Or(*args):
return get_env().formula_manager.Or(*args)
def Plus(*args):
return get_env().formula_manager.Plus(*args)
def ToReal(formula):
return get_env().formula_manager.ToReal(formula)
def AtMostOne(*args):
return get_env().formula_manager.AtMostOne(*args)
def ExactlyOne(*args):
return get_env().formula_manager.ExactlyOne(*args)
def AllDifferent(*args):
return get_env().formula_manager.AllDifferent(*args)
|
Apache License 2.0
|
kuri65536/python-for-android
|
python-modules/twisted/twisted/test/test_journal.py
|
Service.addtime
|
python
|
def addtime(self, journal):
journal.executeCommand(AddTime())
|
Set a key 'time' with the current time.
|
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-modules/twisted/twisted/test/test_journal.py#L78-L80
|
from twisted.trial import unittest
from twisted.persisted.journal.base import ICommand, MemoryJournal, serviceCommand, ServiceWrapperCommand, command, Wrappable
from twisted.persisted.journal.picklelog import DirDBMLog
from zope.interface import implements
import shutil, os.path
class AddTime:
implements(ICommand)
def execute(self, svc, cmdtime):
svc.values["time"] = cmdtime
class Counter(Wrappable):
objectType = "counter"
def __init__(self, uid):
self.uid = uid
self.x = 0
def getUid(self):
return self.uid
def _increment(self):
self.x += 1
increment = command("_increment")
class Service:
def __init__(self, logpath, journalpath):
log = DirDBMLog(logpath)
self.journal = MemoryJournal(log, self, journalpath, self._gotData)
self.journal.updateFromLog()
def _gotData(self, result):
if result is None:
self.values = {}
self.counters = {}
else:
self.values, self.counters = result
def _makeCounter(self, id):
c = Counter(id)
self.counters[id] = c
return c
makeCounter = serviceCommand("_makeCounter")
def loadObject(self, type, id):
if type != "counter": raise ValueError
return self.counters[id]
def _add(self, key, value):
self.values[key] = value
def _delete(self, key):
del self.values[key]
def get(self, key):
return self.values[key]
|
Apache License 2.0
|
encode-dcc/snovault
|
src/snovault/elasticsearch/uuid_queue/queues/redis_queues.py
|
RedisQueueMeta.update_errors_count
|
python
|
def update_errors_count(self, len_values):
self._client.incrby(self._key_errorscount, len_values)
|
Update errors for indexed uuids
|
https://github.com/encode-dcc/snovault/blob/75e77bb7445f6de57d2e389942255435fade06dc/src/snovault/elasticsearch/uuid_queue/queues/redis_queues.py#L219-L221
|
import time
from redis import StrictRedis
from .base_queue import (
BaseQueue,
BaseQueueMeta,
)
REDIS_LIST = 'REDIS_LIST'
REDIS_LIST_PIPE = 'REDIS_LIST_PIPE'
REDIS_SET = 'REDIS_SET'
REDIS_SET_PIPE = 'REDIS_SET_PIPE'
REDIS_SET_PIPE_EXEC = 'REDIS_SET_PIPE_EXEC'
PD_RESTARTS = 'pd:srvrs'
class RedisClient(StrictRedis):
def __init__(self, queue_options):
super().__init__(
encoding="utf-8",
decode_responses=True,
db=queue_options.get('db', 0),
host=queue_options['host'],
port=queue_options['port'],
socket_timeout=5,
)
def get_queue(self, queue_name, queue_type, is_worker=False):
if queue_type == REDIS_LIST:
queue_class = RedisListQueue
elif queue_type == REDIS_LIST_PIPE:
queue_class = RedisListPipeQueue
elif queue_type == REDIS_SET:
queue_class = RedisSetQueue
elif queue_type == REDIS_SET_PIPE:
queue_class = RedisSetPipeQueue
elif queue_type == REDIS_SET_PIPE_EXEC:
queue_class = RedisSetPipeExecQueue
else:
raise ValueError('Queue %s is not available' % queue_type)
return queue_class(queue_name, self, is_worker=is_worker)
class RedisQueueMeta(BaseQueueMeta):
def __init__(self, queue_name, client, is_worker=False):
self._base_id = int(time.time() * 1000000)
self._client = client
if not is_worker:
restarts = self.get_server_restarts()
self.queue_name = queue_name + str(restarts)
self._setup_redis_keys()
self.set_args(kill_workers=True)
self._init_persistant_data()
else:
self.queue_name = queue_name
self._setup_redis_keys()
def _init_persistant_data(self):
self._client.incrby(PD_RESTARTS, 1)
def get_server_restarts(self):
cnt = self._client.get(PD_RESTARTS)
if not cnt:
self._client.set(PD_RESTARTS, 0)
cnt = 0
else:
cnt = int(self._client.get(PD_RESTARTS))
return cnt
def add_errors(self, errors):
errors_added = 0
for error in errors:
err_uuid = error['uuid']
error_key = self._key_uuid_errors + ':' + str(err_uuid)
self._client.hmset(error_key, error)
self._client.lpush(self._key_errors, err_uuid)
errors_added += 1
return errors_added
def has_errors(self):
errors_count = int(self._client.get(self._key_errorscount))
errors_list_count = self._client.llen(self._key_errors)
if errors_count or errors_list_count:
return True
return False
def pop_errors(self):
errors = []
err_uuids = self._client.lrange(self._key_errors, 0, -1)
self._client.delete(self._key_errors)
for err_uuid in err_uuids:
uuid_error_key = self._key_uuid_errors + ':' + err_uuid
error_hash = self._client.hgetall(uuid_error_key)
errors.append(error_hash)
self._client.delete(uuid_error_key)
self._client.set(self._key_errorscount, 0)
return errors
def add_worker_conn(self, worker_id):
self._client.lpush(self._key_workers, worker_id)
worker_conn_key = self._key_worker_conn + ':' + worker_id
self._client.hmset(worker_conn_key, BaseQueueMeta._get_blank_worker())
def _get_worker_conn(self, worker_id):
worker_conn_key = self._key_worker_conn + ':' + worker_id
return self._client.hgetall(worker_conn_key)
def _get_worker_ids(self):
return self._client.lrange(self._key_workers, 0, -1)
def get_worker_conns(self):
worker_conns = {}
worker_ids = self._get_worker_ids()
for worker_id in worker_ids:
worker_conns[worker_id] = self._get_worker_conn(worker_id)
return worker_conns
def get_worker_conn_count(self):
return self._client.llen(self._key_workers)
def update_worker_conn(self, worker_id, uuid_cnt, get_cnt):
worker_conn_key = self._key_worker_conn + ':' + worker_id
worker_conn = self._get_worker_conn(worker_id)
if worker_conn:
worker_conn['uuid_cnt'] = uuid_cnt
worker_conn['get_cnt'] = get_cnt
self._client.hmset(worker_conn_key, worker_conn)
def save_work_results(self, worker_id, results):
worker_conn = self._get_worker_conn(worker_id)
results['errors'] = len(results['errors'])
if worker_conn:
results_count = int(worker_conn.get('results_count', 0))
results_count += 1
worker_res_key = '{}:{}:{}'.format(
self._key_worker_results,
worker_id,
results_count,
)
self._client.hmset(worker_res_key, results)
worker_conn['results_count'] = results_count
worker_conn_key = self._key_worker_conn + ':' + worker_id
self._client.hmset(worker_conn_key, worker_conn)
def get_uuid_count(self):
try:
uuid_count = int(self._client.get(self._key_uuidcount))
except TypeError:
return 0
return uuid_count
def has_uuids(self, errs_cnt=0):
added_cnt = int(self._client.get(self._key_addedcount))
success_cnt = int(self._client.get(self._key_successescount))
errors_cnt = errs_cnt + int(self._client.get(self._key_errorscount))
cnt = added_cnt - (success_cnt + errors_cnt)
return cnt > 0
def update_uuid_count(self, len_values):
if len_values > 0:
self._client.incrby(self._key_addedcount, len_values)
self._client.incrby(self._key_uuidcount, len_values)
def update_success_count(self, len_values):
self._client.incrby(self._key_successescount, len_values)
|
MIT License
|
wavefronthq/python-client
|
wavefront_api_client/models/module.py
|
Module.__eq__
|
python
|
def __eq__(self, other):
if not isinstance(other, Module):
return False
return self.to_dict() == other.to_dict()
|
Returns true if both objects are equal
|
https://github.com/wavefronthq/python-client/blob/e410ce0dd8a2334e995456f4f3d44e0f04664a3a/wavefront_api_client/models/module.py#L293-L298
|
import pprint
import re
import six
from wavefront_api_client.configuration import Configuration
class Module(object):
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'annotations': 'list[Annotation]',
'class_loader': 'ClassLoader',
'declared_annotations': 'list[Annotation]',
'descriptor': 'ModuleDescriptor',
'layer': 'ModuleLayer',
'name': 'str',
'named': 'bool',
'packages': 'list[str]'
}
attribute_map = {
'annotations': 'annotations',
'class_loader': 'classLoader',
'declared_annotations': 'declaredAnnotations',
'descriptor': 'descriptor',
'layer': 'layer',
'name': 'name',
'named': 'named',
'packages': 'packages'
}
def __init__(self, annotations=None, class_loader=None, declared_annotations=None, descriptor=None, layer=None, name=None, named=None, packages=None, _configuration=None):
if _configuration is None:
_configuration = Configuration()
self._configuration = _configuration
self._annotations = None
self._class_loader = None
self._declared_annotations = None
self._descriptor = None
self._layer = None
self._name = None
self._named = None
self._packages = None
self.discriminator = None
if annotations is not None:
self.annotations = annotations
if class_loader is not None:
self.class_loader = class_loader
if declared_annotations is not None:
self.declared_annotations = declared_annotations
if descriptor is not None:
self.descriptor = descriptor
if layer is not None:
self.layer = layer
if name is not None:
self.name = name
if named is not None:
self.named = named
if packages is not None:
self.packages = packages
@property
def annotations(self):
return self._annotations
@annotations.setter
def annotations(self, annotations):
self._annotations = annotations
@property
def class_loader(self):
return self._class_loader
@class_loader.setter
def class_loader(self, class_loader):
self._class_loader = class_loader
@property
def declared_annotations(self):
return self._declared_annotations
@declared_annotations.setter
def declared_annotations(self, declared_annotations):
self._declared_annotations = declared_annotations
@property
def descriptor(self):
return self._descriptor
@descriptor.setter
def descriptor(self, descriptor):
self._descriptor = descriptor
@property
def layer(self):
return self._layer
@layer.setter
def layer(self, layer):
self._layer = layer
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
@property
def named(self):
return self._named
@named.setter
def named(self, named):
self._named = named
@property
def packages(self):
return self._packages
@packages.setter
def packages(self, packages):
self._packages = packages
def to_dict(self):
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(Module, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
return pprint.pformat(self.to_dict())
def __repr__(self):
return self.to_str()
|
Apache License 2.0
|
qiskit/qiskit-aqua-interfaces
|
qiskit_aqua_interfaces/user_interface/base_controller.py
|
BaseController.get_combobox_parameters
|
python
|
def get_combobox_parameters(self, section_name, property_name):
from qiskit.aqua.parser import JSONSchema
values = None
types = ['string']
combobox_state = 'readonly'
if JSONSchema.NAME == property_name and BaseModel.is_pluggable_section(section_name):
values = self.model.get_pluggable_section_names(section_name)
elif JSONSchema.BACKEND == section_name and property_name in (JSONSchema.NAME, JSONSchema.PROVIDER):
values = []
if JSONSchema.PROVIDER == property_name:
combobox_state = 'normal'
for provider, _ in self.model.providers.items():
values.append(provider)
else:
provider_name = self.model.get_section_property(JSONSchema.BACKEND, JSONSchema.PROVIDER)
values = self.model.providers.get(provider_name, [])
else:
values = self.model.get_property_default_values(section_name, property_name)
types = self.model.get_property_types(section_name, property_name)
return combobox_state, types, values
|
get combobox parameters
|
https://github.com/qiskit/qiskit-aqua-interfaces/blob/d062c77822f88594b73de3b0c83b9cb9374d1799/qiskit_aqua_interfaces/user_interface/base_controller.py#L372-L395
|
from abc import ABC, abstractmethod
import os
import threading
import queue
import tkinter as tk
from tkinter import messagebox
import ast
import json
import logging
from .guiprovider import GUIProvider
from .base_model import BaseModel
from ._customwidgets import (EntryPopup, ComboboxPopup, TextPopup)
logger = logging.getLogger(__name__)
class BaseController(ABC):
@abstractmethod
def __init__(self, guiprovider, model) -> None:
self._view = None
self._guiprovider = guiprovider
self._model = model
self._filemenu = None
self._title = tk.StringVar()
self._sections_view = None
self._empty_view = None
self._sections_view_title = tk.StringVar()
self._properties_view = None
self._text_view = None
self._outputview = None
self._progress = None
self._button_text = None
self._start_button = None
self._thread_queue = queue.Queue()
self._thread = None
self._command = GUIProvider.START
self._process_stop = False
self._validate_integer_command = None
self._validate_float_command = None
@property
def view(self):
return self._view
@view.setter
def view(self, val):
self._view = val
self._validate_integer_command = self._view.register(BaseController._cb_validate_integer)
self._validate_float_command = self._view.register(BaseController._cb_validate_float)
@staticmethod
def _cb_validate_integer(action, index, value_if_allowed,
prior_value, text, validation_type, trigger_type, widget_name):
if action != '1' or value_if_allowed == '+' or value_if_allowed == '-':
return True
ret = True
try:
int(value_if_allowed)
except ValueError:
ret = False
return ret
@staticmethod
def _cb_validate_float(action, index, value_if_allowed,
prior_value, text, validation_type, trigger_type, widget_name):
if action != '1' or value_if_allowed == '+' or value_if_allowed == '-':
return True
ret = True
if value_if_allowed is not None:
index = value_if_allowed.find('e')
if index == 0:
return False
if index > 0:
try:
float(value_if_allowed[:index])
except ValueError:
ret = False
if ret and index < len(value_if_allowed) - 1:
right = value_if_allowed[index + 1:]
if right not in ('+', '-'):
try:
int(right)
except ValueError:
ret = False
return ret
try:
float(value_if_allowed)
except ValueError:
ret = False
return ret
@property
def outputview(self):
return self._outputview
@outputview.setter
def outputview(self, outputview):
self._outputview = outputview
@property
def model(self):
return self._model
def new_input(self):
ret = True
try:
self.stop()
self.outputview.clear()
self._start_button.state(['disabled'])
self._title.set('')
self._sections_view.clear()
self._sections_view.show_add_button(True)
self._sections_view.show_remove_button(False)
self._text_view.clear()
self._sections_view_title.set('')
self._properties_view.clear()
self._properties_view.show_remove_button(False)
self._empty_view.tkraise()
section_names = self.model.new()
self._sections_view.populate(section_names)
self._start_button.state(['!disabled'])
missing = self.get_sections_names_missing()
self._sections_view.show_add_button(bool(missing))
except Exception as ex:
self.outputview.clear()
self.outputview.write_line(str(ex))
ret = False
return ret
def open_file(self, filename):
ret = True
try:
self.stop()
self.outputview.clear()
self._start_button.state(['disabled'])
self._title.set('')
self._sections_view.clear()
self._sections_view.show_add_button(True)
self._sections_view.show_remove_button(False)
self._text_view.clear()
self._sections_view_title.set('')
self._properties_view.clear()
self._properties_view.show_remove_button(False)
self._empty_view.tkraise()
try:
self.model.load_file(filename)
except Exception as ex:
messagebox.showerror("Error", str(ex))
if self.model.get_filename() is None or isinstance(ex, FileNotFoundError):
ret = False
self._title.set(os.path.basename(filename))
section_names = self.model.get_section_names()
self._sections_view.populate(section_names)
self._start_button.state(['!disabled'])
missing = self.get_sections_names_missing()
self._sections_view.show_add_button(bool(missing))
except Exception as ex:
self.outputview.clear()
self.outputview.write_line(str(ex))
ret = False
return ret
def is_empty(self):
return self.model.is_empty()
def save_file(self):
filename = self.model.get_filename()
if not filename:
self.outputview.write_line("No file to save.")
return False
try:
self.model.save_to_file(filename)
self.outputview.write_line("Saved file: {}".format(filename))
return True
except Exception as ex:
messagebox.showerror("Error", str(ex))
return False
def save_file_as(self, filename):
try:
self.model.save_to_file(filename)
self.open_file(filename)
return True
except Exception as ex:
messagebox.showerror("Error", str(ex))
return False
@abstractmethod
def cb_section_select(self, section_name):
pass
def cb_property_select(self, section_name, property_name):
from qiskit.aqua.parser import JSONSchema
_show_remove = property_name not in (JSONSchema.PROVIDER, JSONSchema.NAME) if section_name == JSONSchema.BACKEND else property_name != JSONSchema.NAME
self._properties_view.show_remove_button(_show_remove)
def cb_section_add(self, section_name):
try:
if section_name is None:
section_name = ''
section_name = section_name.lower().strip()
if not section_name:
return False
self.model.set_section(section_name)
missing = self.get_sections_names_missing()
self._sections_view.show_add_button(bool(missing))
except Exception as ex:
messagebox.showerror("Error", str(ex))
return False
return True
def validate_section_add(self, section_name):
try:
if section_name in self.model.get_section_names():
return'Duplicate section name'
except Exception as ex:
return str(ex)
return None
def cb_section_remove(self, section_name):
try:
self._sections_view.show_remove_button(False)
self.model.delete_section(section_name)
missing = self.get_sections_names_missing()
self._sections_view.show_add_button(bool(missing))
self._sections_view_title.set('')
self._properties_view.clear()
self._text_view.clear()
self._empty_view.tkraise()
except Exception as ex:
messagebox.showerror("Error", str(ex))
return False
return True
@abstractmethod
def cb_section_defaults(self, section_name):
pass
def get_sections_names_missing(self):
try:
section_names = self.model.get_section_names()
default_sections = self.model.get_default_sections()
return list(set(default_sections.keys()) - set(section_names))
except Exception as ex:
self.outputview.write_line(str(ex))
def get_property_names_missing(self, section_name):
try:
properties = self.model.get_section_properties(section_name)
default_properties = self.model.get_section_default_properties(
section_name)
if default_properties is None:
return None
return list(set(default_properties.keys()) - set(properties.keys()))
except Exception as ex:
self.outputview.write_line(str(ex))
def shows_add_button(self, section_name):
if self.model.allows_additional_properties(section_name):
return True
missing = self.get_property_names_missing(section_name)
return missing
def on_property_add(self, section_name, property_name):
try:
return self.cb_property_set(section_name,
property_name,
self.model.get_property_default_value(section_name,
property_name))
except Exception as ex:
messagebox.showerror("Error", str(ex))
return False
@abstractmethod
def cb_property_set(self, section_name, property_name, value):
pass
def validate_property_add(self, section_name, property_name):
try:
value = self.model.get_section_property(section_name, property_name)
if value is not None:
return 'Duplicate property name'
except Exception as ex:
return str(ex)
return None
@abstractmethod
def cb_section_property_remove(self, section_name, property_name):
pass
def cb_text_set(self, section_name, value):
try:
self.model.set_section_text(section_name, value)
self._text_view.show_defaults_button(
not self.model.default_properties_equals_properties(section_name))
except Exception as ex:
self.outputview.write_line(str(ex))
return False
return True
|
Apache License 2.0
|
rapid7/vm-console-client-python
|
rapid7vmconsole/models/features.py
|
Features.adaptive_security
|
python
|
def adaptive_security(self, adaptive_security):
self._adaptive_security = adaptive_security
|
Sets the adaptive_security of this Features.
Whether Adaptive Security features are available. # noqa: E501
:param adaptive_security: The adaptive_security of this Features. # noqa: E501
:type: bool
|
https://github.com/rapid7/vm-console-client-python/blob/55e1f573967bce27cc9a2d10c12a949b1142c2b3/rapid7vmconsole/models/features.py#L120-L129
|
import pprint
import re
import six
class Features(object):
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'adaptive_security': 'bool',
'agents': 'bool',
'dynamic_discovery': 'bool',
'early_access': 'bool',
'engine_pool': 'bool',
'insight_platform': 'bool',
'mobile': 'bool',
'multitenancy': 'bool',
'policy_editor': 'bool',
'policy_manager': 'bool',
'remediation_analytics': 'bool',
'reporting': 'LicenseReporting',
'scanning': 'LicenseScanning'
}
attribute_map = {
'adaptive_security': 'adaptiveSecurity',
'agents': 'agents',
'dynamic_discovery': 'dynamicDiscovery',
'early_access': 'earlyAccess',
'engine_pool': 'enginePool',
'insight_platform': 'insightPlatform',
'mobile': 'mobile',
'multitenancy': 'multitenancy',
'policy_editor': 'policyEditor',
'policy_manager': 'policyManager',
'remediation_analytics': 'remediationAnalytics',
'reporting': 'reporting',
'scanning': 'scanning'
}
def __init__(self, adaptive_security=None, agents=None, dynamic_discovery=None, early_access=None, engine_pool=None, insight_platform=None, mobile=None, multitenancy=None, policy_editor=None, policy_manager=None, remediation_analytics=None, reporting=None, scanning=None):
self._adaptive_security = None
self._agents = None
self._dynamic_discovery = None
self._early_access = None
self._engine_pool = None
self._insight_platform = None
self._mobile = None
self._multitenancy = None
self._policy_editor = None
self._policy_manager = None
self._remediation_analytics = None
self._reporting = None
self._scanning = None
self.discriminator = None
if adaptive_security is not None:
self.adaptive_security = adaptive_security
if agents is not None:
self.agents = agents
if dynamic_discovery is not None:
self.dynamic_discovery = dynamic_discovery
if early_access is not None:
self.early_access = early_access
if engine_pool is not None:
self.engine_pool = engine_pool
if insight_platform is not None:
self.insight_platform = insight_platform
if mobile is not None:
self.mobile = mobile
if multitenancy is not None:
self.multitenancy = multitenancy
if policy_editor is not None:
self.policy_editor = policy_editor
if policy_manager is not None:
self.policy_manager = policy_manager
if remediation_analytics is not None:
self.remediation_analytics = remediation_analytics
if reporting is not None:
self.reporting = reporting
if scanning is not None:
self.scanning = scanning
@property
def adaptive_security(self):
return self._adaptive_security
@adaptive_security.setter
|
MIT License
|
pytest-dev/py
|
py/_path/local.py
|
LocalPath.lstat
|
python
|
def lstat(self):
return Stat(self, py.error.checked_call(os.lstat, self.strpath))
|
Return an os.lstat() tuple.
|
https://github.com/pytest-dev/py/blob/2f03e5a7fd9eb95db110cfd1bf40b987757f9d48/py/_path/local.py#L556-L558
|
from __future__ import with_statement
from contextlib import contextmanager
import sys, os, atexit, io, uuid
import py
from py._path import common
from py._path.common import iswin32, fspath
from stat import S_ISLNK, S_ISDIR, S_ISREG
from os.path import abspath, normpath, isabs, exists, isdir, isfile, islink, dirname
if sys.version_info > (3,0):
def map_as_list(func, iter):
return list(map(func, iter))
else:
map_as_list = map
ALLOW_IMPORTLIB_MODE = sys.version_info > (3,5)
if ALLOW_IMPORTLIB_MODE:
import importlib
class Stat(object):
def __getattr__(self, name):
return getattr(self._osstatresult, "st_" + name)
def __init__(self, path, osstatresult):
self.path = path
self._osstatresult = osstatresult
@property
def owner(self):
if iswin32:
raise NotImplementedError("XXX win32")
import pwd
entry = py.error.checked_call(pwd.getpwuid, self.uid)
return entry[0]
@property
def group(self):
if iswin32:
raise NotImplementedError("XXX win32")
import grp
entry = py.error.checked_call(grp.getgrgid, self.gid)
return entry[0]
def isdir(self):
return S_ISDIR(self._osstatresult.st_mode)
def isfile(self):
return S_ISREG(self._osstatresult.st_mode)
def islink(self):
st = self.path.lstat()
return S_ISLNK(self._osstatresult.st_mode)
class PosixPath(common.PathBase):
def chown(self, user, group, rec=0):
uid = getuserid(user)
gid = getgroupid(group)
if rec:
for x in self.visit(rec=lambda x: x.check(link=0)):
if x.check(link=0):
py.error.checked_call(os.chown, str(x), uid, gid)
py.error.checked_call(os.chown, str(self), uid, gid)
def readlink(self):
return py.error.checked_call(os.readlink, self.strpath)
def mklinkto(self, oldname):
py.error.checked_call(os.link, str(oldname), str(self))
def mksymlinkto(self, value, absolute=1):
if absolute:
py.error.checked_call(os.symlink, str(value), self.strpath)
else:
base = self.common(value)
relsource = self.__class__(value).relto(base)
reldest = self.relto(base)
n = reldest.count(self.sep)
target = self.sep.join(('..', )*n + (relsource, ))
py.error.checked_call(os.symlink, target, self.strpath)
def getuserid(user):
import pwd
if not isinstance(user, int):
user = pwd.getpwnam(user)[2]
return user
def getgroupid(group):
import grp
if not isinstance(group, int):
group = grp.getgrnam(group)[2]
return group
FSBase = not iswin32 and PosixPath or common.PathBase
class LocalPath(FSBase):
class ImportMismatchError(ImportError):
sep = os.sep
class Checkers(common.Checkers):
def _stat(self):
try:
return self._statcache
except AttributeError:
try:
self._statcache = self.path.stat()
except py.error.ELOOP:
self._statcache = self.path.lstat()
return self._statcache
def dir(self):
return S_ISDIR(self._stat().mode)
def file(self):
return S_ISREG(self._stat().mode)
def exists(self):
return self._stat()
def link(self):
st = self.path.lstat()
return S_ISLNK(st.mode)
def __init__(self, path=None, expanduser=False):
if path is None:
self.strpath = py.error.checked_call(os.getcwd)
else:
try:
path = fspath(path)
except TypeError:
raise ValueError("can only pass None, Path instances "
"or non-empty strings to LocalPath")
if expanduser:
path = os.path.expanduser(path)
self.strpath = abspath(path)
def __hash__(self):
s = self.strpath
if iswin32:
s = s.lower()
return hash(s)
def __eq__(self, other):
s1 = fspath(self)
try:
s2 = fspath(other)
except TypeError:
return False
if iswin32:
s1 = s1.lower()
try:
s2 = s2.lower()
except AttributeError:
return False
return s1 == s2
def __ne__(self, other):
return not (self == other)
def __lt__(self, other):
return fspath(self) < fspath(other)
def __gt__(self, other):
return fspath(self) > fspath(other)
def samefile(self, other):
other = fspath(other)
if not isabs(other):
other = abspath(other)
if self == other:
return True
if not hasattr(os.path, "samefile"):
return False
return py.error.checked_call(
os.path.samefile, self.strpath, other)
def remove(self, rec=1, ignore_errors=False):
if self.check(dir=1, link=0):
if rec:
if iswin32:
self.chmod(0o700, rec=1)
import shutil
py.error.checked_call(
shutil.rmtree, self.strpath,
ignore_errors=ignore_errors)
else:
py.error.checked_call(os.rmdir, self.strpath)
else:
if iswin32:
self.chmod(0o700)
py.error.checked_call(os.remove, self.strpath)
def computehash(self, hashtype="md5", chunksize=524288):
try:
try:
import hashlib as mod
except ImportError:
if hashtype == "sha1":
hashtype = "sha"
mod = __import__(hashtype)
hash = getattr(mod, hashtype)()
except (AttributeError, ImportError):
raise ValueError("Don't know how to compute %r hash" %(hashtype,))
f = self.open('rb')
try:
while 1:
buf = f.read(chunksize)
if not buf:
return hash.hexdigest()
hash.update(buf)
finally:
f.close()
def new(self, **kw):
obj = object.__new__(self.__class__)
if not kw:
obj.strpath = self.strpath
return obj
drive, dirname, basename, purebasename,ext = self._getbyspec(
"drive,dirname,basename,purebasename,ext")
if 'basename' in kw:
if 'purebasename' in kw or 'ext' in kw:
raise ValueError("invalid specification %r" % kw)
else:
pb = kw.setdefault('purebasename', purebasename)
try:
ext = kw['ext']
except KeyError:
pass
else:
if ext and not ext.startswith('.'):
ext = '.' + ext
kw['basename'] = pb + ext
if ('dirname' in kw and not kw['dirname']):
kw['dirname'] = drive
else:
kw.setdefault('dirname', dirname)
kw.setdefault('sep', self.sep)
obj.strpath = normpath(
"%(dirname)s%(sep)s%(basename)s" % kw)
return obj
def _getbyspec(self, spec):
res = []
parts = self.strpath.split(self.sep)
args = filter(None, spec.split(',') )
append = res.append
for name in args:
if name == 'drive':
append(parts[0])
elif name == 'dirname':
append(self.sep.join(parts[:-1]))
else:
basename = parts[-1]
if name == 'basename':
append(basename)
else:
i = basename.rfind('.')
if i == -1:
purebasename, ext = basename, ''
else:
purebasename, ext = basename[:i], basename[i:]
if name == 'purebasename':
append(purebasename)
elif name == 'ext':
append(ext)
else:
raise ValueError("invalid part specification %r" % name)
return res
def dirpath(self, *args, **kwargs):
if not kwargs:
path = object.__new__(self.__class__)
path.strpath = dirname(self.strpath)
if args:
path = path.join(*args)
return path
return super(LocalPath, self).dirpath(*args, **kwargs)
def join(self, *args, **kwargs):
sep = self.sep
strargs = [fspath(arg) for arg in args]
strpath = self.strpath
if kwargs.get('abs'):
newargs = []
for arg in reversed(strargs):
if isabs(arg):
strpath = arg
strargs = newargs
break
newargs.insert(0, arg)
actual_sep = "" if strpath.endswith(sep) else sep
for arg in strargs:
arg = arg.strip(sep)
if iswin32:
arg = arg.strip('/')
arg = arg.replace('/', sep)
strpath = strpath + actual_sep + arg
actual_sep = sep
obj = object.__new__(self.__class__)
obj.strpath = normpath(strpath)
return obj
def open(self, mode='r', ensure=False, encoding=None):
if ensure:
self.dirpath().ensure(dir=1)
if encoding:
return py.error.checked_call(io.open, self.strpath, mode, encoding=encoding)
return py.error.checked_call(open, self.strpath, mode)
def _fastjoin(self, name):
child = object.__new__(self.__class__)
child.strpath = self.strpath + self.sep + name
return child
def islink(self):
return islink(self.strpath)
def check(self, **kw):
if not kw:
return exists(self.strpath)
if len(kw) == 1:
if "dir" in kw:
return not kw["dir"] ^ isdir(self.strpath)
if "file" in kw:
return not kw["file"] ^ isfile(self.strpath)
return super(LocalPath, self).check(**kw)
_patternchars = set("*?[" + os.path.sep)
def listdir(self, fil=None, sort=None):
if fil is None and sort is None:
names = py.error.checked_call(os.listdir, self.strpath)
return map_as_list(self._fastjoin, names)
if isinstance(fil, py.builtin._basestring):
if not self._patternchars.intersection(fil):
child = self._fastjoin(fil)
if exists(child.strpath):
return [child]
return []
fil = common.FNMatcher(fil)
names = py.error.checked_call(os.listdir, self.strpath)
res = []
for name in names:
child = self._fastjoin(name)
if fil is None or fil(child):
res.append(child)
self._sortlist(res, sort)
return res
def size(self):
return self.stat().size
def mtime(self):
return self.stat().mtime
def copy(self, target, mode=False, stat=False):
if self.check(file=1):
if target.check(dir=1):
target = target.join(self.basename)
assert self!=target
copychunked(self, target)
if mode:
copymode(self.strpath, target.strpath)
if stat:
copystat(self, target)
else:
def rec(p):
return p.check(link=0)
for x in self.visit(rec=rec):
relpath = x.relto(self)
newx = target.join(relpath)
newx.dirpath().ensure(dir=1)
if x.check(link=1):
newx.mksymlinkto(x.readlink())
continue
elif x.check(file=1):
copychunked(x, newx)
elif x.check(dir=1):
newx.ensure(dir=1)
if mode:
copymode(x.strpath, newx.strpath)
if stat:
copystat(x, newx)
def rename(self, target):
target = fspath(target)
return py.error.checked_call(os.rename, self.strpath, target)
def dump(self, obj, bin=1):
f = self.open('wb')
import pickle
try:
py.error.checked_call(pickle.dump, obj, f, bin)
finally:
f.close()
def mkdir(self, *args):
p = self.join(*args)
py.error.checked_call(os.mkdir, fspath(p))
return p
def write_binary(self, data, ensure=False):
if ensure:
self.dirpath().ensure(dir=1)
with self.open('wb') as f:
f.write(data)
def write_text(self, data, encoding, ensure=False):
if ensure:
self.dirpath().ensure(dir=1)
with self.open('w', encoding=encoding) as f:
f.write(data)
def write(self, data, mode='w', ensure=False):
if ensure:
self.dirpath().ensure(dir=1)
if 'b' in mode:
if not py.builtin._isbytes(data):
raise ValueError("can only process bytes")
else:
if not py.builtin._istext(data):
if not py.builtin._isbytes(data):
data = str(data)
else:
data = py.builtin._totext(data, sys.getdefaultencoding())
f = self.open(mode)
try:
f.write(data)
finally:
f.close()
def _ensuredirs(self):
parent = self.dirpath()
if parent == self:
return self
if parent.check(dir=0):
parent._ensuredirs()
if self.check(dir=0):
try:
self.mkdir()
except py.error.EEXIST:
if self.check(dir=0):
raise
return self
def ensure(self, *args, **kwargs):
p = self.join(*args)
if kwargs.get('dir', 0):
return p._ensuredirs()
else:
p.dirpath()._ensuredirs()
if not p.check(file=1):
p.open('w').close()
return p
def stat(self, raising=True):
if raising == True:
return Stat(self, py.error.checked_call(os.stat, self.strpath))
try:
return Stat(self, os.stat(self.strpath))
except KeyboardInterrupt:
raise
except Exception:
return None
|
MIT License
|
jest-community/jest-pytest
|
src/__tests__/integration/home-assistant/homeassistant/components/vacuum/__init__.py
|
VacuumDevice.start_pause
|
python
|
def start_pause(self, **kwargs):
raise NotImplementedError()
|
Start, pause or resume the cleaning task.
|
https://github.com/jest-community/jest-pytest/blob/b197b0b31e3ca5c411202d97583cbd2d2b0b92e9/src/__tests__/integration/home-assistant/homeassistant/components/vacuum/__init__.py#L344-L346
|
import asyncio
from datetime import timedelta
from functools import partial
import logging
import voluptuous as vol
from homeassistant.components import group
from homeassistant.const import (
ATTR_BATTERY_LEVEL, ATTR_COMMAND, ATTR_ENTITY_ID, SERVICE_TOGGLE,
SERVICE_TURN_OFF, SERVICE_TURN_ON, STATE_ON)
from homeassistant.loader import bind_hass
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.config_validation import PLATFORM_SCHEMA
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.entity import ToggleEntity
from homeassistant.helpers.icon import icon_for_battery_level
_LOGGER = logging.getLogger(__name__)
DOMAIN = 'vacuum'
DEPENDENCIES = ['group']
SCAN_INTERVAL = timedelta(seconds=20)
GROUP_NAME_ALL_VACUUMS = 'all vacuum cleaners'
ENTITY_ID_ALL_VACUUMS = group.ENTITY_ID_FORMAT.format('all_vacuum_cleaners')
ATTR_BATTERY_ICON = 'battery_icon'
ATTR_CLEANED_AREA = 'cleaned_area'
ATTR_FAN_SPEED = 'fan_speed'
ATTR_FAN_SPEED_LIST = 'fan_speed_list'
ATTR_PARAMS = 'params'
ATTR_STATUS = 'status'
SERVICE_CLEAN_SPOT = 'clean_spot'
SERVICE_LOCATE = 'locate'
SERVICE_RETURN_TO_BASE = 'return_to_base'
SERVICE_SEND_COMMAND = 'send_command'
SERVICE_SET_FAN_SPEED = 'set_fan_speed'
SERVICE_START_PAUSE = 'start_pause'
SERVICE_STOP = 'stop'
VACUUM_SERVICE_SCHEMA = vol.Schema({
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
})
VACUUM_SET_FAN_SPEED_SERVICE_SCHEMA = VACUUM_SERVICE_SCHEMA.extend({
vol.Required(ATTR_FAN_SPEED): cv.string,
})
VACUUM_SEND_COMMAND_SERVICE_SCHEMA = VACUUM_SERVICE_SCHEMA.extend({
vol.Required(ATTR_COMMAND): cv.string,
vol.Optional(ATTR_PARAMS): vol.Any(cv.Dict, cv.ensure_list),
})
SERVICE_TO_METHOD = {
SERVICE_TURN_ON: {'method': 'async_turn_on'},
SERVICE_TURN_OFF: {'method': 'async_turn_off'},
SERVICE_TOGGLE: {'method': 'async_toggle'},
SERVICE_START_PAUSE: {'method': 'async_start_pause'},
SERVICE_RETURN_TO_BASE: {'method': 'async_return_to_base'},
SERVICE_CLEAN_SPOT: {'method': 'async_clean_spot'},
SERVICE_LOCATE: {'method': 'async_locate'},
SERVICE_STOP: {'method': 'async_stop'},
SERVICE_SET_FAN_SPEED: {'method': 'async_set_fan_speed',
'schema': VACUUM_SET_FAN_SPEED_SERVICE_SCHEMA},
SERVICE_SEND_COMMAND: {'method': 'async_send_command',
'schema': VACUUM_SEND_COMMAND_SERVICE_SCHEMA},
}
DEFAULT_NAME = 'Vacuum cleaner robot'
SUPPORT_TURN_ON = 1
SUPPORT_TURN_OFF = 2
SUPPORT_PAUSE = 4
SUPPORT_STOP = 8
SUPPORT_RETURN_HOME = 16
SUPPORT_FAN_SPEED = 32
SUPPORT_BATTERY = 64
SUPPORT_STATUS = 128
SUPPORT_SEND_COMMAND = 256
SUPPORT_LOCATE = 512
SUPPORT_CLEAN_SPOT = 1024
SUPPORT_MAP = 2048
@bind_hass
def is_on(hass, entity_id=None):
entity_id = entity_id or ENTITY_ID_ALL_VACUUMS
return hass.states.is_state(entity_id, STATE_ON)
@bind_hass
def turn_on(hass, entity_id=None):
data = {ATTR_ENTITY_ID: entity_id} if entity_id else None
hass.services.call(DOMAIN, SERVICE_TURN_ON, data)
@bind_hass
def turn_off(hass, entity_id=None):
data = {ATTR_ENTITY_ID: entity_id} if entity_id else None
hass.services.call(DOMAIN, SERVICE_TURN_OFF, data)
@bind_hass
def toggle(hass, entity_id=None):
data = {ATTR_ENTITY_ID: entity_id} if entity_id else None
hass.services.call(DOMAIN, SERVICE_TOGGLE, data)
@bind_hass
def locate(hass, entity_id=None):
data = {ATTR_ENTITY_ID: entity_id} if entity_id else None
hass.services.call(DOMAIN, SERVICE_LOCATE, data)
@bind_hass
def clean_spot(hass, entity_id=None):
data = {ATTR_ENTITY_ID: entity_id} if entity_id else None
hass.services.call(DOMAIN, SERVICE_CLEAN_SPOT, data)
@bind_hass
def return_to_base(hass, entity_id=None):
data = {ATTR_ENTITY_ID: entity_id} if entity_id else None
hass.services.call(DOMAIN, SERVICE_RETURN_TO_BASE, data)
@bind_hass
def start_pause(hass, entity_id=None):
data = {ATTR_ENTITY_ID: entity_id} if entity_id else None
hass.services.call(DOMAIN, SERVICE_START_PAUSE, data)
@bind_hass
def stop(hass, entity_id=None):
data = {ATTR_ENTITY_ID: entity_id} if entity_id else None
hass.services.call(DOMAIN, SERVICE_STOP, data)
@bind_hass
def set_fan_speed(hass, fan_speed, entity_id=None):
data = {ATTR_ENTITY_ID: entity_id} if entity_id else {}
data[ATTR_FAN_SPEED] = fan_speed
hass.services.call(DOMAIN, SERVICE_SET_FAN_SPEED, data)
@bind_hass
def send_command(hass, command, params=None, entity_id=None):
data = {ATTR_ENTITY_ID: entity_id} if entity_id else {}
data[ATTR_COMMAND] = command
if params is not None:
data[ATTR_PARAMS] = params
hass.services.call(DOMAIN, SERVICE_SEND_COMMAND, data)
@asyncio.coroutine
def async_setup(hass, config):
component = EntityComponent(
_LOGGER, DOMAIN, hass, SCAN_INTERVAL, GROUP_NAME_ALL_VACUUMS)
yield from component.async_setup(config)
@asyncio.coroutine
def async_handle_vacuum_service(service):
method = SERVICE_TO_METHOD.get(service.service)
target_vacuums = component.async_extract_from_service(service)
params = service.data.copy()
params.pop(ATTR_ENTITY_ID, None)
update_tasks = []
for vacuum in target_vacuums:
yield from getattr(vacuum, method['method'])(**params)
if not vacuum.should_poll:
continue
update_tasks.append(vacuum.async_update_ha_state(True))
if update_tasks:
yield from asyncio.wait(update_tasks, loop=hass.loop)
for service in SERVICE_TO_METHOD:
schema = SERVICE_TO_METHOD[service].get(
'schema', VACUUM_SERVICE_SCHEMA)
hass.services.async_register(
DOMAIN, service, async_handle_vacuum_service,
schema=schema)
return True
class VacuumDevice(ToggleEntity):
@property
def supported_features(self):
raise NotImplementedError()
@property
def status(self):
return None
@property
def battery_level(self):
return None
@property
def battery_icon(self):
charging = False
if self.status is not None:
charging = 'charg' in self.status.lower()
return icon_for_battery_level(
battery_level=self.battery_level, charging=charging)
@property
def fan_speed(self):
return None
@property
def fan_speed_list(self):
raise NotImplementedError()
@property
def state_attributes(self):
data = {}
if self.status is not None:
data[ATTR_STATUS] = self.status
if self.battery_level is not None:
data[ATTR_BATTERY_LEVEL] = self.battery_level
data[ATTR_BATTERY_ICON] = self.battery_icon
if self.fan_speed is not None:
data[ATTR_FAN_SPEED] = self.fan_speed
data[ATTR_FAN_SPEED_LIST] = self.fan_speed_list
return data
def turn_on(self, **kwargs):
raise NotImplementedError()
def async_turn_on(self, **kwargs):
return self.hass.async_add_job(partial(self.turn_on, **kwargs))
def turn_off(self, **kwargs):
raise NotImplementedError()
def async_turn_off(self, **kwargs):
return self.hass.async_add_job(partial(self.turn_off, **kwargs))
def return_to_base(self, **kwargs):
raise NotImplementedError()
def async_return_to_base(self, **kwargs):
return self.hass.async_add_job(partial(self.return_to_base, **kwargs))
def stop(self, **kwargs):
raise NotImplementedError()
def async_stop(self, **kwargs):
return self.hass.async_add_job(partial(self.stop, **kwargs))
def clean_spot(self, **kwargs):
raise NotImplementedError()
def async_clean_spot(self, **kwargs):
return self.hass.async_add_job(partial(self.clean_spot, **kwargs))
def locate(self, **kwargs):
raise NotImplementedError()
def async_locate(self, **kwargs):
return self.hass.async_add_job(partial(self.locate, **kwargs))
def set_fan_speed(self, fan_speed, **kwargs):
raise NotImplementedError()
def async_set_fan_speed(self, fan_speed, **kwargs):
return self.hass.async_add_job(
partial(self.set_fan_speed, fan_speed, **kwargs))
|
MIT License
|
ictu/quality-time
|
components/server/src/routes/external/notification.py
|
post_new_notification_destination
|
python
|
def post_new_notification_destination(report_uuid: ReportId, database: Database):
data = ReportData(latest_datamodel(database), latest_reports(database), report_uuid)
if "notification_destinations" not in data.report:
data.report["notification_destinations"] = {}
data.report["notification_destinations"][(notification_destination_uuid := uuid())] = dict(
webhook="", name="Microsoft Teams webhook", sleep_duration=0
)
delta_description = f"{{user}} created a new destination for notifications in report '{data.report_name}'."
uuids = [report_uuid, notification_destination_uuid]
result = insert_new_report(database, delta_description, (data.report, uuids))
result["new_destination_uuid"] = notification_destination_uuid
return result
|
Create a new notification destination.
|
https://github.com/ictu/quality-time/blob/4bd5df14f584dcc174276da0d2ddb6fcfaf1d427/components/server/src/routes/external/notification.py#L15-L27
|
import bottle
from pymongo.database import Database
from database.datamodels import latest_datamodel
from database.reports import insert_new_report, latest_reports
from model.data import ReportData
from routes.plugins.auth_plugin import EDIT_REPORT_PERMISSION
from server_utilities.functions import uuid
from server_utilities.type import ReportId, NotificationDestinationId
@bottle.post("/api/v3/report/<report_uuid>/notification_destination/new", permissions_required=[EDIT_REPORT_PERMISSION])
|
Apache License 2.0
|
hyperiongray/trio-chrome-devtools-protocol
|
trio_cdp/generated/profiler.py
|
set_sampling_interval
|
python
|
async def set_sampling_interval(
interval: int
) -> None:
session = get_session_context('profiler.set_sampling_interval')
return await session.execute(cdp.profiler.set_sampling_interval(interval))
|
Changes CPU profiler sampling interval. Must be called before CPU profiles recording started.
:param interval: New sampling interval in microseconds.
|
https://github.com/hyperiongray/trio-chrome-devtools-protocol/blob/f41ca685b5c390f288592d135660c177fba5a945/trio_cdp/generated/profiler.py#L48-L57
|
from __future__ import annotations
import typing
from ..context import get_connection_context, get_session_context
import cdp.profiler
from cdp.profiler import (
ConsoleProfileFinished,
ConsoleProfileStarted,
CoverageRange,
FunctionCoverage,
PositionTickInfo,
Profile,
ProfileNode,
ScriptCoverage,
ScriptTypeProfile,
TypeObject,
TypeProfileEntry
)
async def disable() -> None:
session = get_session_context('profiler.disable')
return await session.execute(cdp.profiler.disable())
async def enable() -> None:
session = get_session_context('profiler.enable')
return await session.execute(cdp.profiler.enable())
async def get_best_effort_coverage() -> typing.List[ScriptCoverage]:
session = get_session_context('profiler.get_best_effort_coverage')
return await session.execute(cdp.profiler.get_best_effort_coverage())
|
MIT License
|
terrapower/armi
|
armi/runLog.py
|
RunLogger.getDuplicatesFilter
|
python
|
def getDuplicatesFilter(self):
for f in self.filters:
if isinstance(f, DeduplicationFilter):
return f
return None
|
This object should have a no-duplicates filter. If it exists, find it.
|
https://github.com/terrapower/armi/blob/b4fceeb5c3c7f2feeaa8c9ac05aa635e5f1a15a0/armi/runLog.py#L536-L542
|
from __future__ import print_function
from glob import glob
import collections
import logging
import operator
import os
import sys
from armi import context
_ADD_LOG_METHOD_STR = """def {0}(self, message, *args, **kws):
if self.isEnabledFor({1}):
self._log({1}, message, args, **kws)
logging.Logger.{0} = {0}"""
_WHITE_SPACE = " " * 6
SEP = "|"
STDERR_LOGGER_NAME = "ARMI_ERROR"
STDOUT_LOGGER_NAME = "ARMI"
class _RunLog:
STDERR_NAME = "{0}.{1:04d}.stderr"
STDOUT_NAME = "{0}.{1:04d}.stdout"
def __init__(self, mpiRank=0):
self._mpiRank = mpiRank
self._verbosity = logging.INFO
self.initialErr = None
self.logLevels = None
self._logLevelNumbers = []
self.logger = None
self.stderrLogger = None
self.setNullLoggers()
self._setLogLevels()
def setNullLoggers(self):
self.logger = NullLogger("NULL")
self.stderrLogger = NullLogger("NULL2", isStderr=True)
def _setLogLevels(self):
_rank = "" if self._mpiRank == 0 else "-{:>03d}".format(self._mpiRank)
self.logLevels = collections.OrderedDict(
[
("debug", (logging.DEBUG, "[dbug{}] ".format(_rank))),
("extra", (15, "[xtra{}] ".format(_rank))),
("info", (logging.INFO, "[info{}] ".format(_rank))),
("important", (25, "[impt{}] ".format(_rank))),
("prompt", (27, "[prmt{}] ".format(_rank))),
("warning", (logging.WARNING, "[warn{}] ".format(_rank))),
("error", (logging.ERROR, "[err {}] ".format(_rank))),
("header", (100, "".format(_rank))),
]
)
self._logLevelNumbers = sorted([l[0] for l in self.logLevels.values()])
global _WHITE_SPACE
_WHITE_SPACE = " " * len(max([l[1] for l in self.logLevels.values()]))
for longLogString, (logValue, shortLogString) in self.logLevels.items():
logging.addLevelName(logValue, shortLogString.upper())
logging.addLevelName(logValue, shortLogString)
try:
getattr(logging, longLogString.upper())
except AttributeError:
setattr(logging, longLogString.upper(), logValue)
try:
getattr(logging, longLogString)
except AttributeError:
exec(_ADD_LOG_METHOD_STR.format(longLogString, logValue))
def log(self, msgType, msg, single=False, label=None):
msgLevel = msgType if isinstance(msgType, int) else self.logLevels[msgType][0]
msg = str(msg)
self.logger.log(msgLevel, msg, single=single, label=label)
def getDuplicatesFilter(self):
if not self.logger or not isinstance(self.logger, logging.Logger):
return None
return self.logger.getDuplicatesFilter()
def clearSingleWarnings(self):
dupsFilter = self.getDuplicatesFilter()
if dupsFilter:
dupsFilter.singleMessageCounts.clear()
def warningReport(self):
self.logger.warningReport()
def getLogVerbosityRank(self, level):
try:
return self.logLevels[level][0]
except KeyError:
log_strs = list(self.logLevels.keys())
raise KeyError(
"{} is not a valid verbosity level: {}".format(level, log_strs)
)
def setVerbosity(self, level):
if isinstance(level, str):
self._verbosity = self.getLogVerbosityRank(level)
elif isinstance(level, int):
if level in self._logLevelNumbers:
self._verbosity = level
elif level < self._logLevelNumbers[0]:
self._verbosity = self._logLevelNumbers[0]
else:
for i in range(len(self._logLevelNumbers) - 1, -1, -1):
if level >= self._logLevelNumbers[i]:
self._verbosity = self._logLevelNumbers[i]
break
else:
raise TypeError("Invalid verbosity rank {}.".format(level))
if self.logger is not None:
for handler in self.logger.handlers:
handler.setLevel(self._verbosity)
self.logger.setLevel(self._verbosity)
def getVerbosity(self):
return self._verbosity
def restoreStandardStreams(self):
if self.initialErr is not None and self._mpiRank > 0:
sys.stderr = self.initialErr
def startLog(self, name):
self.logger = logging.getLogger(STDOUT_LOGGER_NAME + SEP + str(self._mpiRank))
if self._verbosity != logging.INFO:
self.setVerbosity(self._verbosity)
if self._mpiRank != 0:
filePath = os.path.join(
context.LOG_DIR, _RunLog.STDERR_NAME.format(name, self._mpiRank)
)
self.stderrLogger = logging.getLogger(STDERR_LOGGER_NAME)
h = logging.FileHandler(filePath, delay=True)
fmt = "%(message)s"
form = logging.Formatter(fmt)
h.setFormatter(form)
h.setLevel(logging.WARNING)
self.stderrLogger.handlers = [h]
self.stderrLogger.setLevel(logging.WARNING)
self.initialErr = sys.stderr
sys.stderr = self.stderrLogger
def close(mpiRank=None):
mpiRank = context.MPI_RANK if mpiRank is None else mpiRank
if mpiRank == 0:
try:
concatenateLogs()
except IOError as ee:
warning("Failed to concatenate logs due to IOError.")
error(ee)
else:
if LOG.stderrLogger:
_ = [h.close() for h in LOG.stderrLogger.handlers]
if LOG.logger:
_ = [h.close() for h in LOG.logger.handlers]
LOG.setNullLoggers()
LOG.restoreStandardStreams()
def concatenateLogs(logDir=None):
if logDir is None:
logDir = context.LOG_DIR
stdoutFiles = sorted(glob(os.path.join(logDir, "*.stdout")))
if not len(stdoutFiles):
info("No log files found to concatenate.")
return
info("Concatenating {0} log files".format(len(stdoutFiles)))
for stdoutName in stdoutFiles:
rank = int(stdoutName.split(".")[-2])
with open(stdoutName, "r") as logFile:
data = logFile.read()
if data:
rankId = "\n{0} RANK {1:03d} STDOUT {2}\n".format(
"-" * 10, rank, "-" * 60
)
print(rankId, file=sys.stdout)
print(data, file=sys.stdout)
try:
os.remove(stdoutName)
except OSError:
warning("Could not delete {0}".format(stdoutName))
stderrName = stdoutName[:-3] + "err"
if os.path.exists(stderrName):
with open(stderrName) as logFile:
data = logFile.read()
if data:
rankId = "\n{0} RANK {1:03d} STDERR {2}\n".format(
"-" * 10, rank, "-" * 60
)
print(rankId, file=sys.stderr)
print(data, file=sys.stderr)
try:
os.remove(stderrName)
except OSError:
warning("Could not delete {0}".format(stderrName))
def raw(msg):
LOG.log("header", msg, single=False, label=msg)
def extra(msg, single=False, label=None):
LOG.log("extra", msg, single=single, label=label)
def debug(msg, single=False, label=None):
LOG.log("debug", msg, single=single, label=label)
def info(msg, single=False, label=None):
LOG.log("info", msg, single=single, label=label)
def important(msg, single=False, label=None):
LOG.log("important", msg, single=single, label=label)
def warning(msg, single=False, label=None):
LOG.log("warning", msg, single=single, label=label)
def error(msg, single=False, label=None):
LOG.log("error", msg, single=single, label=label)
def header(msg, single=False, label=None):
LOG.log("header", msg, single=single, label=label)
def warningReport():
LOG.warningReport()
def setVerbosity(level):
LOG.setVerbosity(level)
def getVerbosity():
return LOG.getVerbosity()
class DeduplicationFilter(logging.Filter):
def __init__(self, *args, **kwargs):
logging.Filter.__init__(self, *args, **kwargs)
self.singleMessageCounts = {}
self.singleWarningMessageCounts = {}
def filter(self, record):
msg = str(record.msg)
single = getattr(record, "single", False)
label = getattr(record, "label", msg)
label = msg if label is None else label
if single:
if record.levelno in (logging.WARNING, logging.CRITICAL):
if label not in self.singleWarningMessageCounts:
self.singleWarningMessageCounts[label] = 1
else:
self.singleWarningMessageCounts[label] += 1
return False
else:
if label not in self.singleMessageCounts:
self.singleMessageCounts[label] = 1
else:
self.singleMessageCounts[label] += 1
return False
record.msg = msg.rstrip().replace("\n", "\n" + _WHITE_SPACE)
return True
class RunLogger(logging.Logger):
FMT = "%(levelname)s%(message)s"
def __init__(self, *args, **kwargs):
if SEP in args[0]:
mpiRank = int(args[0].split(SEP)[-1].strip())
args = (args[0].split(SEP)[0],)
else:
mpiRank = context.MPI_RANK
logging.Logger.__init__(self, *args, **kwargs)
self.allowStopDuplicates()
if mpiRank == 0:
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.INFO)
self.setLevel(logging.INFO)
else:
filePath = os.path.join(
context.LOG_DIR, _RunLog.STDOUT_NAME.format(args[0], mpiRank)
)
handler = logging.FileHandler(filePath, delay=True)
handler.setLevel(logging.WARNING)
self.setLevel(logging.WARNING)
form = logging.Formatter(RunLogger.FMT)
handler.setFormatter(form)
self.addHandler(handler)
def log(self, msgType, msg, single=False, label=None):
msgLevel = msgType if isinstance(msgType, int) else LOG.logLevels[msgType][0]
logging.Logger.log(
self, msgLevel, str(msg), extra={"single": single, "label": label}
)
def _log(self, *args, **kwargs):
if "extra" not in kwargs:
kwargs["extra"] = {}
if "single" not in kwargs["extra"]:
msg = args[1]
single = kwargs.pop("single", False)
label = kwargs.pop("label", None)
label = msg if label is None else label
kwargs["extra"]["single"] = single
kwargs["extra"]["label"] = label
logging.Logger._log(self, *args, **kwargs)
def allowStopDuplicates(self):
for f in self.filters:
if isinstance(f, DeduplicationFilter):
return
self.addFilter(DeduplicationFilter())
def write(self, msg, **kwargs):
self.error(msg)
def flush(self, *args, **kwargs):
pass
def close(self):
self.handlers.clear()
del self
|
Apache License 2.0
|
torchsynth/torchsynth
|
torchsynth/module.py
|
SynthModule.to
|
python
|
def to(self, device: Optional[torch.device] = None, **kwargs):
self._update_device(device)
return super().to(device=device, **kwargs)
|
This function overrides the :func:`~torch.nn.Module.to` call in
:class:`torch.nn.Module`. It ensures that the related values
:class:`~torchsynth.parameter.ModuleParameterRange` and
:class:`~torchsynth.parameter.ModuleParameter`, as well as
:attr:`~.SynthModule.synthconfig` are also transferred to the correct
device.
Args:
device: device to send this module to
|
https://github.com/torchsynth/torchsynth/blob/a2fdb489ca2a548b4a6b2e532fb64d2f814ada6c/torchsynth/module.py#L234-L247
|
import copy
from typing import Any, Dict, List, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import tensor
from torch import Tensor as T
import torchsynth.util as util
from torchsynth.config import BASE_REPRODUCIBLE_BATCH_SIZE, SynthConfig
from torchsynth.parameter import ModuleParameter, ModuleParameterRange
from torchsynth.signal import Signal
class SynthModule(nn.Module):
default_parameter_ranges: Optional[List[ModuleParameterRange]] = None
def __init__(
self,
synthconfig: SynthConfig,
device: Optional[torch.device] = None,
**kwargs: Dict[str, T],
):
nn.Module.__init__(self)
self.synthconfig = synthconfig
self.device = device
self.synthconfig.to(device)
self.torchparameters: nn.ParameterDict = nn.ParameterDict()
self.parameter_ranges = []
self.seed: Optional[int] = None
if self.default_parameter_ranges is not None:
assert isinstance(self.default_parameter_ranges, list)
self.parameter_ranges = copy.deepcopy(self.default_parameter_ranges)
self._parameter_ranges_dict: Dict[str, ModuleParameterRange] = {
p.name: p for p in self.parameter_ranges
}
assert len(self._parameter_ranges_dict) == len(self.parameter_ranges)
self.add_parameters(
[
ModuleParameter(
value=None,
parameter_name=parameter_range.name,
data=torch.rand((self.synthconfig.batch_size,), device=device),
parameter_range=parameter_range,
)
for parameter_range in self.parameter_ranges
]
)
if kwargs:
for name, data in kwargs.items():
if data.device != self.device:
data = data.to(self.device)
self.set_parameter(name, data)
@property
def batch_size(self) -> T:
assert self.synthconfig.batch_size.ndim == 0
return self.synthconfig.batch_size
@property
def sample_rate(self) -> T:
assert self.synthconfig.sample_rate.ndim == 0
return self.synthconfig.sample_rate
@property
def nyquist(self):
return self.sample_rate / 2.0
@property
def eps(self) -> float:
return self.synthconfig.eps
@property
def buffer_size(self) -> T:
assert self.synthconfig.buffer_size.ndim == 0
return self.synthconfig.buffer_size
def to_buffer_size(self, signal: Signal) -> Signal:
return util.fix_length(signal, self.buffer_size)
def seconds_to_samples(self, seconds: T) -> T:
return seconds * self.sample_rate
def output(self, *args: Any, **kwargs: Any) -> Signal:
raise NotImplementedError("Derived classes must override this method")
def forward(self, *args: Any, **kwargs: Any) -> Signal:
signal = self.output(*args, **kwargs)
buffered = self.to_buffer_size(signal)
return buffered
def add_parameters(self, parameters: List[ModuleParameter]):
for parameter in parameters:
assert parameter.parameter_name not in self.torchparameters
assert parameter.shape == (self.batch_size,)
self.torchparameters[parameter.parameter_name] = parameter
def get_parameter(self, parameter_id: str) -> ModuleParameter:
value = self.torchparameters[parameter_id]
assert value.shape == (self.batch_size,)
return value
def get_parameter_0to1(self, parameter_id: str) -> T:
value = self.torchparameters[parameter_id]
assert value.shape == (self.batch_size,)
return value
def set_parameter(self, parameter_id: str, value: T):
value = value.to(self.device)
self.torchparameters[parameter_id].to_0to1(value)
value = self.torchparameters[parameter_id].data
assert torch.all(0.0 <= value) and torch.all(value <= 1.0)
assert value.shape == (self.batch_size,)
def set_parameter_0to1(self, parameter_id: str, value: T):
value = value.to(self.device)
assert torch.all(0.0 <= value) and torch.all(value <= 1.0)
assert value.shape == (self.batch_size,)
self.torchparameters[parameter_id].data = value
def p(self, parameter_id: str) -> T:
value = self.torchparameters[parameter_id].from_0to1()
assert value.shape == (self.batch_size,)
return value
|
Apache License 2.0
|
thunlp/openprompt
|
openprompt/prompts/knowledgeable_verbalizer.py
|
KnowledgeableVerbalizer.add_prefix
|
python
|
def add_prefix(label_words, prefix):
new_label_words = []
for words in label_words:
new_label_words.append([prefix + word.lstrip(prefix) for word in words])
return new_label_words
|
r"""add prefix to label words. For example, if a label words is in the middle of a template,
the prefix should be ' '.
|
https://github.com/thunlp/openprompt/blob/5d3d5dce8c4babe9a265b69576e63eec2d067fe3/openprompt/prompts/knowledgeable_verbalizer.py#L48-L55
|
import os
from openprompt.prompts.manual_template import ManualTemplate
from transformers.tokenization_utils import PreTrainedTokenizer
from transformers.utils.dummy_pt_objects import PreTrainedModel
from openprompt.data_utils.data_utils import InputFeatures
import re
from openprompt.prompts.manual_verbalizer import ManualVerbalizer
from typing import *
import torch
import torch.nn as nn
import torch.nn.functional as F
from openprompt.utils.logging import logger
class KnowledgeableVerbalizer(ManualVerbalizer):
def __init__(self,
tokenizer: PreTrainedTokenizer = None,
classes: Sequence[str] = None,
prefix: Optional[str] = " ",
multi_token_handler: Optional[str] = "first",
max_token_split: Optional[int] = -1,
verbalizer_lr: Optional[float]=5e-2,
candidate_frac: Optional[float]=0.5,
**kwargs):
super().__init__(classes=classes, prefix=prefix, multi_token_handler=multi_token_handler, **kwargs)
self.max_token_split = max_token_split
self.verbalizer_lr = verbalizer_lr
self.candidate_frac = candidate_frac
def on_label_words_set(self):
self.generate_parameters()
@staticmethod
|
Apache License 2.0
|
andremiras/etherollapp
|
src/etherollapp/etheroll/controller.py
|
Controller.bind_screen_manager_on_current_screen
|
python
|
def bind_screen_manager_on_current_screen(self):
def on_pre_add_widget(screen_manager, screen):
if type(screen) is SwitchAccountScreen and not self.screen_manager.has_screen(screen.name):
screen.bind(current_account=self.setter('current_account'))
screen.ids.send_id.bind(
current_account=self.setter('current_account'))
screen.ids.send_id.bind(on_send=self.on_send)
self.screen_manager.bind(on_pre_add_widget=on_pre_add_widget)
|
SwitchAccountScreen.current_account -> self.current_account.
|
https://github.com/andremiras/etherollapp/blob/2ccc30fad736a6fee0cba8b99c521bee6ad13087/src/etherollapp/etheroll/controller.py#L154-L164
|
from dotenv import load_dotenv
from eth_utils import to_checksum_address
from kivy.app import App
from kivy.clock import Clock, mainthread
from kivy.logger import Logger
from kivy.properties import ObjectProperty, StringProperty
from kivy.uix.floatlayout import FloatLayout
from kivy.utils import platform
from kivymd.bottomsheet import MDListBottomSheet
from kivymd.theming import ThemeManager
from raven import Client
from requests.exceptions import ConnectionError
from etherollapp.etheroll.constants import ENV_PATH
from etherollapp.etheroll.flashqrcode import FlashQrCodeScreen
from etherollapp.etheroll.settings import Settings
from etherollapp.etheroll.settings_screen import SettingsScreen
from etherollapp.etheroll.switchaccount import SwitchAccountScreen
from etherollapp.etheroll.ui_utils import Dialog, load_kv_from_py
from etherollapp.etheroll.utils import run_in_thread
from etherollapp.osc.osc_app_server import OscAppServer
from etherollapp.sentry_utils import configure_sentry
from etherollapp.service.utils import start_roll_polling_service
load_kv_from_py(__file__)
class Controller(FloatLayout):
current_account = ObjectProperty(allownone=True)
current_account_string = StringProperty(allownone=True)
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.disabled = True
Clock.schedule_once(self._after_init)
self._account_passwords = {}
def _after_init(self, dt):
Clock.schedule_once(self.preload_account_utils)
self.bind_roll_button()
self.bind_current_account_string()
self.bind_chances_roll_under()
self.bind_wager_property()
self.bind_profit_property()
self.bind_screen_manager_on_current_screen()
self.bind_keyboard()
self.register_screens()
def on_keyboard(self, window, key, *args):
if key == 27:
if Dialog.dialogs:
Dialog.dismiss_all_dialogs()
return True
from etherollapp.etheroll.ui_utils import SubScreen
current_screen = self.screen_manager.current_screen
if isinstance(current_screen, SubScreen):
current_screen.on_back()
return True
return False
def on_current_account(self, instance, current_account):
self.current_account_string = (
current_account and f'0x{current_account.address.hex()}')
@property
def pyetheroll(self):
from pyetheroll.etheroll import Etheroll
chain_id = Settings.get_stored_network()
return Etheroll.get_or_create(chain_id)
@property
def account_utils(self):
from eth_accounts.account_utils import AccountUtils
keystore_dir = Settings.get_keystore_path()
return AccountUtils.get_or_create(keystore_dir)
def preload_account_utils(self, dt):
account_utils = self.account_utils
self.disabled = False
return account_utils
def bind_wager_property(self):
roll_under_recap = self.roll_screen.ids.roll_under_recap_id
bet_size = self.roll_screen.ids.bet_size_id
bet_size_input = bet_size.ids.bet_size_input_id
bet_size_input.bind(text=roll_under_recap.setter('wager_property'))
roll_under_recap.wager_property = bet_size_input.text
def bind_chances_roll_under(self):
roll_under_recap = self.roll_screen.ids.roll_under_recap_id
chance_of_winning = self.roll_screen.ids.chance_of_winning_id
chances_input = chance_of_winning.ids.chances_input_id
chances_input.bind(text=roll_under_recap.setter('roll_under_property'))
roll_under_recap.roll_under_property = chances_input.text
def bind_roll_button(self):
roll_button = self.roll_screen.ids.roll_button_id
roll_button.bind(on_release=lambda instance: self.roll())
def bind_current_account_string(self):
roll_screen = self.roll_screen
self.bind(
current_account_string=roll_screen.setter('current_account_string')
)
def bind_keyboard(self):
from kivy.core.window import Window
Window.bind(on_keyboard=self.on_keyboard)
def bind_profit_property(self):
chance_of_winning = self.roll_screen.ids.chance_of_winning_id
chances_input = chance_of_winning.ids.chances_input_id
chances_input.bind(
text=lambda instance, value: self.update_profit_property())
bet_size = self.roll_screen.ids.bet_size_id
bet_size_input = bet_size.ids.bet_size_input_id
bet_size_input.bind(
text=lambda instance, value: self.update_profit_property())
self.update_profit_property()
|
MIT License
|
tensorflow/tensor2tensor
|
tensor2tensor/models/image_transformer.py
|
imagetransformer_bas8l_8h_big_uncond_dr03_imgnet
|
python
|
def imagetransformer_bas8l_8h_big_uncond_dr03_imgnet():
hparams = imagetransformer_base_14l_8h_big_dr01()
hparams.num_decoder_layers = 8
hparams.num_heads = 8
hparams.hidden_size = 512
hparams.filter_size = 2048
hparams.layer_prepostprocess_dropout = 0.3
return hparams
|
big 1d model for conditional image generation.
|
https://github.com/tensorflow/tensor2tensor/blob/c22a226704e5887862bf9edd9f269892c9016ad4/tensor2tensor/models/image_transformer.py#L857-L866
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
from tensor2tensor.layers import common_hparams
from tensor2tensor.layers import common_image_attention as cia
from tensor2tensor.layers import common_layers
from tensor2tensor.layers import modalities
from tensor2tensor.utils import registry
from tensor2tensor.utils import t2t_model
import tensorflow.compat.v1 as tf
@registry.register_model
class Imagetransformer(t2t_model.T2TModel):
def body(self, features):
hparams = copy.copy(self._hparams)
targets = features["targets"]
if (hparams.likelihood == cia.DistributionType.DMOL and
hparams.num_channels != 1):
raise ValueError("When using DMOL for the likelihood, bottom function "
" must be identity and num_channels must be 1.")
if (not tf.get_variable_scope().reuse and
hparams.mode != tf.estimator.ModeKeys.PREDICT):
tf.summary.image("targets", tf.to_float(targets), max_outputs=1)
losses = []
decoder_input, rows, cols = cia.prepare_decoder(targets, hparams)
if not hparams.unconditional:
inputs = features["inputs"]
decoder_input += tf.reshape(
inputs,
[common_layers.shape_list(targets)[0], 1, 1, hparams.hidden_size])
decoder_output = cia.transformer_decoder_layers(
decoder_input,
None,
hparams.num_decoder_layers or hparams.num_hidden_layers,
hparams,
attention_type=hparams.dec_attention_type,
losses=losses,
name="decoder")
output = cia.create_output(decoder_output, rows, cols, targets, hparams)
if losses:
return output, {"extra_loss": tf.add_n(losses)}
else:
return output
def loss(self, logits, features):
if self._hparams.likelihood == cia.DistributionType.DMOL:
return common_layers.dml_loss(logits, features["targets"])
return super(Imagetransformer, self).loss(logits, features)
def sample(self, features):
if self._hparams.likelihood == cia.DistributionType.DMOL:
logits, losses = self(features)
samples = common_layers.sample_from_discretized_mix_logistic(
logits, seed=None)
return samples, logits, losses
return super(Imagetransformer, self).sample(features)
def _slow_greedy_infer(self, features, decode_length):
if self._hparams.likelihood == cia.DistributionType.DMOL:
raise NotImplementedError("Decoding is not currently available for DMOL.")
return super(Imagetransformer, self)._slow_greedy_infer(features,
decode_length)
@registry.register_model
class ImagetransformerMoe(t2t_model.T2TModel):
@staticmethod
def use_body_sharded():
return True
def body_sharded(self, sharded_features):
dp = self._data_parallelism
hparams = copy.copy(self._hparams)
inputs = sharded_features["inputs"]
targets = sharded_features["targets"]
q_padding, kv_padding = "VALID", "VALID"
if hparams.q_filter_width > 1:
q_padding = "LEFT"
if hparams.kv_filter_width > 1:
kv_padding = "LEFT"
decoder_input, rows, cols = dp(cia.prepare_decoder_inputs,
inputs, targets, hparams)
del q_padding, kv_padding
decoder_output, extra_loss = cia.transformer_layers_sharded(
dp,
self._ps_devices,
decoder_input,
hparams.num_hidden_layers,
hparams,
self_attention_bias=None,
enc_output=None,
attention_type=hparams.dec_attention_type,
name="decoder")
output = dp(cia.create_output, decoder_output, rows, cols, targets, hparams)
return output, extra_loss
@registry.register_hparams
def image_transformer_base():
hparams = common_hparams.basic_params1()
hparams.hidden_size = 512
hparams.batch_size = 4
hparams.max_length = 3075
hparams.dropout = 0.0
hparams.clip_grad_norm = 0.
hparams.optimizer_adam_epsilon = 1e-9
hparams.learning_rate_decay_scheme = "noam"
hparams.learning_rate = 0.1
hparams.learning_rate_warmup_steps = 4000
hparams.initializer_gain = 0.2
hparams.num_hidden_layers = 6
hparams.initializer = "uniform_unit_scaling"
hparams.weight_decay = 0.0
hparams.optimizer_adam_beta1 = 0.9
hparams.optimizer_adam_beta2 = 0.98
hparams.label_smoothing = 0.0
hparams.bottom["targets"] = modalities.image_channel_embeddings_bottom
hparams.top["targets"] = modalities.identity_top
hparams.norm_type = "layer"
hparams.layer_prepostprocess_dropout = 0.0
hparams.add_hparam("filter_size", 512)
hparams.add_hparam("num_heads", 8)
hparams.add_hparam("attention_key_channels", 0)
hparams.add_hparam("attention_value_channels", 0)
hparams.add_hparam("ffn_layer", "conv_hidden_relu")
hparams.add_hparam("attention_dropout", 0.0)
hparams.add_hparam("relu_dropout", 0.0)
hparams.add_hparam("pos", "timing")
hparams.add_hparam("nbr_decoder_problems", 1)
hparams.add_hparam("num_output_layers", 3)
hparams.add_hparam("block_size", 1)
hparams.add_hparam("gap_sizes", [2, 4, 8, 16, 32, 64, 2, 4, 8, 16, 32, 64])
hparams.add_hparam("img_len", 32)
hparams.add_hparam("num_channels", 3)
hparams.add_hparam("local_and_global_att", False)
hparams.add_hparam("block_length", 256)
hparams.add_hparam("block_width", 128)
hparams.add_hparam("num_encoder_layers", 4)
hparams.add_hparam("num_decoder_layers", 12)
hparams.add_hparam("dec_attention_type", cia.AttentionType.LOCAL_1D)
hparams.add_hparam("block_raster_scan", False)
hparams.add_hparam("q_filter_width", 1)
hparams.add_hparam("kv_filter_width", 1)
hparams.add_hparam("likelihood", cia.DistributionType.CAT)
hparams.add_hparam("unconditional", False)
hparams.add_hparam("num_mixtures", 10)
hparams.add_hparam("moe_overhead_train", 1.0)
hparams.add_hparam("moe_overhead_eval", 2.0)
hparams.moe_num_experts = 8
hparams.moe_loss_coef = 1e-3
hparams.add_hparam("shared_rel", False)
return hparams
@registry.register_hparams
def imagetransformer_base():
hparams = image_transformer_base()
return hparams
@registry.register_hparams
def imagetransformer_cifar10_base():
hparams = image_transformer_base()
hparams.batch_size = 4
hparams.num_heads = 4
hparams.num_decoder_layers = 12
hparams.block_length = 256
hparams.hidden_size = 512
hparams.filter_size = 2048
hparams.learning_rate = 0.5
hparams.learning_rate_warmup_steps = 4000
hparams.layer_preprocess_sequence = "none"
hparams.layer_postprocess_sequence = "dan"
hparams.layer_prepostprocess_dropout = 0.3
hparams.unconditional = True
return hparams
@registry.register_hparams
def imagetransformer_cifar10_base_dmol():
hparams = image_transformer_base()
hparams.likelihood = cia.DistributionType.DMOL
hparams.num_channels = 1
hparams.bottom["targets"] = modalities.image_channel_compress_targets_bottom
hparams.top["targets"] = modalities.identity_top
hparams.num_heads = 8
hparams.batch_size = 8
hparams.sampling_method = "random"
hparams.layer_preprocess_sequence = "n"
hparams.layer_postprocess_sequence = "da"
hparams.summarize_grads = True
hparams.hidden_size = 256
hparams.filter_size = 512
hparams.attention_key_channels = 512
hparams.attention_value_channels = 512
hparams.num_decoder_layers = 12
hparams.layer_prepostprocess_dropout = 0.1
hparams.learning_rate = 0.1
hparams.layer_preprocess_sequence = "none"
hparams.layer_postprocess_sequence = "dan"
hparams.pos = "emb"
hparams.unconditional = True
return hparams
@registry.register_hparams
def imagetransformer_base_tpu():
hparams = imagetransformer_bas8l_8h_big_uncond_dr03_imgnet()
update_hparams_for_tpu(hparams)
hparams.batch_size = 4
hparams.num_heads = 4
hparams.num_decoder_layers = 12
hparams.block_length = 128
hparams.hidden_size = 512
hparams.filter_size = 2048
hparams.learning_rate = 0.2
hparams.learning_rate_warmup_steps = 6000
hparams.layer_preprocess_sequence = "none"
hparams.layer_postprocess_sequence = "dan"
hparams.layer_prepostprocess_dropout = 0.3
return hparams
@registry.register_hparams
def imagetransformer_base_imagenet_tpu():
hparams = imagetransformer_base_tpu()
hparams.batch_size = 4
hparams.num_heads = 4
hparams.num_decoder_layers = 12
hparams.block_length = 128
hparams.layer_preprocess_sequence = "none"
hparams.layer_postprocess_sequence = "dan"
hparams.layer_prepostprocess_dropout = 0.1
return hparams
@registry.register_hparams
def imagetransformer_imagenet32_base():
hparams = imagetransformer_cifar10_base()
hparams.batch_size = 4
hparams.layer_prepostprocess_dropout = 0.1
return hparams
@registry.register_hparams
def imagetransformer_base_rel():
hparams = imagetransformer_base()
hparams.dec_attention_type = cia.AttentionType.RELATIVE_LOCAL_1D
return hparams
@registry.register_hparams
def imagetransformer_sep_channels():
hparams = imagetransformer_base()
hparams.num_heads = 4
hparams.attention_key_channels = hparams.attention_value_channels = 0
hparams.hidden_size = 256
hparams.filter_size = 512
hparams.num_hidden_layers = 6
return hparams
@registry.register_hparams
def imagetransformer_sep_channels_8l():
hparams = imagetransformer_base()
hparams.num_heads = 4
hparams.attention_key_channels = hparams.attention_value_channels = 0
hparams.hidden_size = 256
hparams.filter_size = 256
hparams.num_hidden_layers = 8
hparams.sampling_method = "random"
return hparams
@registry.register_hparams
def imagetransformer_sep_channels_8l_multipos3():
hparams = imagetransformer_sep_channels_8l()
hparams.q_filter_width = 3
hparams.kv_filter_width = 3
return hparams
@registry.register_hparams
def imagetransformer_base_8l_8h_big_cond_dr03_dan():
hparams = imagetransformer_sep_channels_8l()
hparams.block_width = 256
hparams.block_length = 256
hparams.hidden_size = 512
hparams.num_heads = 8
hparams.filter_size = 2048
hparams.batch_size = 4
hparams.max_length = 3075
hparams.layer_preprocess_sequence = "none"
hparams.layer_postprocess_sequence = "dan"
hparams.num_decoder_layers = 8
hparams.layer_prepostprocess_dropout = 0.3
return hparams
@registry.register_hparams
def imagetransformer_base_10l_8h_big_uncond_dr03_dan_64():
hparams = imagetransformer_base_10l_8h_big_cond_dr03_dan()
hparams.unconditional = True
hparams.max_length = 14000
hparams.batch_size = 1
hparams.img_len = 64
hparams.layer_prepostprocess_dropout = 0.1
return hparams
@registry.register_hparams
def imagetransformerpp_sep_channels_8l_8h():
hparams = imagetransformer_base()
hparams.likelihood = cia.DistributionType.DMOL
hparams.num_channels = 1
hparams.bottom["targets"] = modalities.image_channel_compress_targets_bottom
hparams.top["targets"] = modalities.identity_top
hparams.num_heads = 8
hparams.batch_size = 4
hparams.attention_key_channels = hparams.attention_value_channels = 0
hparams.hidden_size = 512
hparams.filter_size = 512
hparams.num_hidden_layers = 8
hparams.sampling_method = "random"
hparams.layer_preprocess_sequence = "n"
hparams.layer_postprocess_sequence = "da"
hparams.summarize_grads = True
hparams.learning_rate = 0.1
return hparams
@registry.register_hparams
def imagetransformerpp_base_8l_8h_big_cond_dr03_dan():
hparams = imagetransformerpp_sep_channels_8l_8h()
hparams.hidden_size = 512
hparams.num_heads = 8
hparams.filter_size = 2048
hparams.batch_size = 4
hparams.max_length = 3075
hparams.layer_prepostprocess_dropout = 0.3
hparams.layer_preprocess_sequence = "none"
hparams.layer_postprocess_sequence = "dan"
hparams.summarize_grads = True
hparams.learning_rate = 0.01
return hparams
@registry.register_hparams
def imagetransformerpp_base_8l_8h_big_cond_dr03_dan_a():
hparams = imagetransformerpp_base_8l_8h_big_cond_dr03_dan()
hparams.learning_rate = 0.1
return hparams
@registry.register_hparams
def imagetransformerpp_base_10l_8h_big_uncond_dr03_dan():
hparams = imagetransformerpp_base_8l_8h_big_cond_dr03_dan_a()
hparams.unconditional = True
hparams.num_decoder_layers = 10
return hparams
@registry.register_hparams
def imagetransformerpp_base_10l_8h_big_uncond_dr03_dan_a():
hparams = imagetransformerpp_base_10l_8h_big_uncond_dr03_dan()
hparams.learning_rate = 0.01
return hparams
@registry.register_hparams
def imagetransformerpp_base_10l_8h_big_uncond_dr03_dan_b():
hparams = imagetransformerpp_base_10l_8h_big_uncond_dr03_dan()
hparams.learning_rate = 0.1
hparams.hidden_size = 256
hparams.attention_key_channels = 512
hparams.attention_value_channels = 512
hparams.filter_size = 1024
return hparams
@registry.register_hparams
def imagetransformerpp_base_10l_8h_big_uncond_dr03_dan_g():
hparams = imagetransformerpp_base_10l_8h_big_uncond_dr03_dan_b()
hparams.filter_size = 512
hparams.layer_prepostprocess_dropout = 0.1
hparams.learning_rate = 0.1
hparams.layer_preprocess_sequence = "none"
hparams.layer_postprocess_sequence = "dan"
hparams.pos = "emb"
return hparams
@registry.register_hparams
def imagetransformerpp_base_12l_8h_big_uncond_dr03_dan_k():
hparams = imagetransformerpp_base_10l_8h_big_uncond_dr03_dan_g()
hparams.num_decoder_layers = 12
return hparams
@registry.register_hparams
def imagetransformerpp_base_12l_8h_big_uncond_dr03_dan_l():
hparams = imagetransformerpp_base_10l_8h_big_uncond_dr03_dan_g()
hparams.num_decoder_layers = 12
hparams.clip_grad_norm = 40.
return hparams
@registry.register_hparams
def imagetransformerpp_base_12l_8h_big_uncond_dr03_dan_m():
hparams = imagetransformerpp_base_12l_8h_big_uncond_dr03_dan_k()
hparams.batch_size = 8
return hparams
@registry.register_hparams
def imagetransformerpp_base_12l_8h_big_uncond_dr03_dan_m_rel():
hparams = imagetransformerpp_base_12l_8h_big_uncond_dr03_dan_k()
hparams.batch_size = 8
hparams.dec_attention_type = cia.AttentionType.RELATIVE_LOCAL_1D
return hparams
@registry.register_hparams
def imagetransformerpp_base_12l_8h_big_uncond_dr03_dan_m_relsh():
hparams = imagetransformerpp_base_12l_8h_big_uncond_dr03_dan_m_rel()
hparams.shared_rel = True
return hparams
@registry.register_hparams
def imagetransformerpp_base_14l_8h_big_uncond_dr03_dan_p():
hparams = imagetransformerpp_base_12l_8h_big_uncond_dr03_dan_l()
hparams.num_decoder_layers = 14
hparams.batch_size = 8
hparams.layer_prepostprocess_dropout = 0.2
return hparams
@registry.register_hparams
def imagetransformerpp_base_12l_8h_big_uncond_dr03_dan_m_bs1():
hparams = imagetransformerpp_base_12l_8h_big_uncond_dr03_dan_m()
hparams.batch_size = 1
return hparams
@registry.register_hparams
def imagetransformerpp_base_14l_8h_big_uncond_dr03_dan_p_bs1():
hparams = imagetransformerpp_base_14l_8h_big_uncond_dr03_dan_p()
hparams.batch_size = 1
return hparams
@registry.register_hparams
def imagetransformerpp_base_5l_8h_big_uncond_dr00_dan_g_bs1():
hparams = imagetransformerpp_base_10l_8h_big_uncond_dr03_dan_g()
hparams.max_length = 66000
hparams.batch_size = 1
hparams.num_decoder_layers = 5
hparams.hidden_size = 128
hparams.filter_size = 128
hparams.attention_key_channels = 64
hparams.attention_value_channels = 64
hparams.layer_prepostprocess_dropout = 0.0
return hparams
@registry.register_hparams
def imagetransformerpp_base_5l_8h_dr00_dan_g_bs1_adafactor():
hparams = imagetransformerpp_base_5l_8h_big_uncond_dr00_dan_g_bs1()
hparams.optimizer = "Adafactor"
hparams.learning_rate_schedule = "rsqrt_decay"
return hparams
@registry.register_hparams
def imagetransformerpp_base_6l_8h_dr00_dan_g_bs1_adafactor():
hparams = imagetransformerpp_base_5l_8h_dr00_dan_g_bs1_adafactor()
hparams.num_decoder_layers = 6
return hparams
@registry.register_hparams
def imagetransformerpp_base_14l_8h_big_uncond_dr03_dan_eval():
hparams = imagetransformerpp_base_12l_8h_big_uncond_dr03_dan_l()
hparams.num_decoder_layers = 14
hparams.batch_size = 8
return hparams
@registry.register_hparams
def imagetransformer_base_8l_8h_big_cond_dr03_dan_128():
hparams = imagetransformer_base_8l_8h_big_cond_dr03_dan()
hparams.block_width = 128
hparams.block_length = 128
return hparams
@registry.register_hparams
def imagetransformer_base_10l_8h_big_cond_dr03_dan():
hparams = imagetransformer_base_8l_8h_big_cond_dr03_dan()
hparams.num_decoder_layers = 10
return hparams
@registry.register_hparams
def imagetransformer_base_10l_8h_big_uncond_dr03_dan():
hparams = imagetransformer_base_10l_8h_big_cond_dr03_dan()
hparams.num_decoder_layers = 10
return hparams
@registry.register_hparams
def imagetransformer_base_8l_8h_big_cond_dr03_dan_dilated():
hparams = imagetransformer_base_8l_8h_big_cond_dr03_dan()
hparams.gap_sizes = [0, 16, 64, 0, 16, 64, 128, 0]
hparams.dec_attention_type = cia.AttentionType.DILATED
hparams.block_length = 128
hparams.block_width = 128
hparams.add_hparam("num_memory_blocks", 1)
return hparams
@registry.register_hparams
def imagetransformer_base_8l_8h_big_cond_dr03_dan_dilated_b():
hparams = imagetransformer_base_8l_8h_big_cond_dr03_dan_dilated()
hparams.block_width = 64
hparams.num_memory_blocks = 2
return hparams
@registry.register_hparams
def imagetransformer_base_8l_8h_big_cond_dr03_dan_dilated_c():
hparams = imagetransformer_base_8l_8h_big_cond_dr03_dan_dilated()
hparams.block_width = 32
hparams.num_memory_blocks = 4
return hparams
@registry.register_hparams
def imagetransformer_base_8l_8h_big_cond_dr03_dan_dilated_d():
hparams = imagetransformer_base_8l_8h_big_cond_dr03_dan_dilated()
hparams.gap_sizes = [0, 16, 64, 16, 64, 128, 256, 0]
return hparams
@registry.register_hparams
def imagetransformer_base_12l_8h_big():
hparams = imagetransformer_sep_channels_8l_8h()
hparams.filter_size = 1024
hparams.num_decoder_layers = 12
hparams.batch_size = 1
hparams.hidden_size = 512
hparams.learning_rate_warmup_steps = 4000
hparams.sampling_method = "random"
hparams.beam_size = 1
hparams.block_width = 256
return hparams
@registry.register_hparams
def imagetransformer1d_base_8l_64by64():
hparams = image_transformer_base()
hparams.num_heads = 8
hparams.hidden_size = 512
hparams.filter_size = 2048
hparams.num_decoder_layers = 8
hparams.batch_size = 1
hparams.block_length = 512
hparams.block_width = 768
hparams.layer_prepostprocess_dropout = 0.1
hparams.max_length = 14000
hparams.unconditional = int(False)
return hparams
@registry.register_hparams
def imagetransformer1d_base_12l_64by64():
hparams = image_transformer_base()
hparams.num_heads = 8
hparams.hidden_size = 512
hparams.filter_size = 2048
hparams.num_decoder_layers = 12
hparams.batch_size = 1
hparams.block_length = 512
hparams.block_width = 768
hparams.layer_prepostprocess_dropout = 0.1
hparams.max_length = 14000
hparams.unconditional = int(False)
return hparams
@registry.register_hparams
def imagetransformer_base_14l_8h_big():
hparams = imagetransformer_base_12l_8h_big()
hparams.num_decoder_layers = 14
return hparams
@registry.register_hparams
def imagetransformer_base_14l_8h_big_dr01():
hparams = imagetransformer_base_14l_8h_big()
hparams.layer_prepostprocess_dropout = 0.1
return hparams
@registry.register_hparams
def imagetransformer_base_12l_8h_big_uncond():
hparams = imagetransformer_base_12l_8h_big()
hparams.unconditional = True
return hparams
@registry.register_hparams
def imagetransformer_base_14l_8h_big_uncond():
hparams = imagetransformer_base_12l_8h_big_uncond()
hparams.num_decoder_layers = 14
return hparams
@registry.register_hparams
def imagetransformer_sep_channels_12l_16h_imagenet_large():
hparams = imagetransformer_sep_channels_8l_8h()
hparams.num_hidden_layers = 12
hparams.batch_size = 1
hparams.filter_size = 2048
hparams.num_heads = 16
hparams.learning_rate_warmup_steps = 16000
hparams.sampling_method = "random"
hparams.learning_rate = 0.1
return hparams
@registry.register_hparams
def imagetransformer_sep_channels_16l_16h_imgnet_lrg_loc():
hparams = imagetransformer_sep_channels_12l_16h_imagenet_large()
hparams.num_hidden_layers = 16
hparams.local_attention = True
hparams.batch_size = 1
hparams.block_length = 256
return hparams
@registry.register_hparams
def imagetransformer_sep_channels_16l_16h_imgnet_lrg_loc_128():
hparams = imagetransformer_sep_channels_12l_16h_imagenet_large()
hparams.num_hidden_layers = 16
hparams.local_attention = True
hparams.batch_size = 1
hparams.block_length = 128
return hparams
@registry.register_hparams
def imagetransformer_sep_output_channels_8l_local_and_global_att():
hparams = imagetransformer_sep_channels_8l()
hparams.sampling_method = "random"
hparams.local_and_global_att = True
return hparams
@registry.register_hparams
def imagetransformer_base_10l_16h_big_uncond_dr01_imgnet():
hparams = imagetransformer_base_14l_8h_big_dr01()
hparams.num_decoder_layers = 10
hparams.num_heads = 16
hparams.hidden_size = 1024
hparams.filter_size = 4096
hparams.batch_size = 1
hparams.layer_prepostprocess_dropout = 0.1
return hparams
@registry.register_hparams
def imagetransformer_base_10l_16h_big_dr01_imgnet():
hparams = imagetransformer_base_14l_8h_big_dr01()
hparams.num_decoder_layers = 10
hparams.num_heads = 16
hparams.hidden_size = 1024
hparams.filter_size = 4096
hparams.batch_size = 1
hparams.unconditional = False
hparams.layer_prepostprocess_dropout = 0.1
return hparams
@registry.register_hparams
def imagetransformer_sep_channels_8l_8h():
hparams = imagetransformer_base()
hparams.num_heads = 8
hparams.batch_size = 1
hparams.attention_key_channels = hparams.attention_value_channels = 0
hparams.hidden_size = 512
hparams.filter_size = 512
hparams.num_hidden_layers = 8
hparams.sampling_method = "random"
return hparams
@registry.register_hparams
def imagetransformer_sep_channels_8l_8h_local_and_global_att():
hparams = imagetransformer_sep_channels_8l_8h()
hparams.num_heads = 8
hparams.batch_size = 1
hparams.attention_key_channels = hparams.attention_value_channels = 0
hparams.hidden_size = 256
hparams.filter_size = 256
hparams.num_hidden_layers = 4
hparams.sampling_method = "random"
hparams.local_and_global_att = True
return hparams
@registry.register_hparams
|
Apache License 2.0
|
tempocollaboration/timeevolvingmpo
|
time_evolving_mpo/dynamics.py
|
Dynamics.shape
|
python
|
def shape(self) -> ndarray:
return copy(self._shape)
|
Numpy shape of the states.
|
https://github.com/tempocollaboration/timeevolvingmpo/blob/36fe2a95499732c27f3a11edb42c6ad2e8190a8e/time_evolving_mpo/dynamics.py#L108-L110
|
from typing import Dict, List, Optional, Text, Tuple
from copy import copy
import numpy as np
from numpy import ndarray
from time_evolving_mpo.base_api import BaseAPIClass
from time_evolving_mpo.config import NpDtype, NpDtypeReal
from time_evolving_mpo.file_formats import assert_tempo_dynamics_dict
from time_evolving_mpo.util import save_object, load_object
class Dynamics(BaseAPIClass):
def __init__(
self,
times: Optional[List[float]] = None,
states: Optional[List[ndarray]] = None,
name: Optional[Text] = None,
description: Optional[Text] = None,
description_dict: Optional[Dict] = None) -> None:
if times is None:
times = []
if states is None:
states = []
assert isinstance(times, list), "Argument `times` must be a list."
assert isinstance(states, list), "Argument `states` must be a list."
assert len(times) == len(states), "Lists `times` and `states` must have the same length."
self._times = []
self._states = []
self._expectation_operators = []
self._expectation_lists = []
self._shape = None
for time, state in zip(times, states):
self.add(time, state)
super().__init__(name, description, description_dict)
def __str__(self) -> Text:
ret = []
ret.append(super().__str__())
ret.append(" length = {} timesteps \n".format(len(self)))
if len(self) > 0:
ret.append(" min time = {} \n".format(
np.min(self._times)))
ret.append(" max time = {} \n".format(
np.max(self._times)))
return "".join(ret)
def __len__(self) -> int:
return len(self._times)
def _sort(self) -> None:
tuples = zip(self._times, self._states)
__times, __states = zip(*sorted(tuples))
self._times = list(__times)
self._states = list(__states)
@property
def times(self) -> ndarray:
return np.array(self._times, dtype=NpDtypeReal)
@property
def states(self) -> ndarray:
return np.array(self._states, dtype=NpDtype)
@property
|
Apache License 2.0
|
lanpa/tensorboardx
|
tensorboardX/beholder/beholder.py
|
Beholder.update
|
python
|
def update(self, trainable=None, arrays=None, frame=None):
new_config = self._get_config()
if True or self._enough_time_has_passed(self.previous_config['FPS']):
self.last_update_time = time.time()
final_image = self._update_frame(
trainable, arrays, frame, new_config)
self._update_recording(final_image, new_config)
|
Creates a frame and writes it to disk.
Args:
trainable: a list of namedtuple (tensors, name).
arrays: a list of namedtuple (tensors, name).
frame: lalala
|
https://github.com/lanpa/tensorboardx/blob/054f1f3aa5e8313be42450f5e9ce1fc1799252a7/tensorboardX/beholder/beholder.py#L163-L178
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ..proto.summary_pb2 import Summary
from ..proto.summary_pb2 import SummaryMetadata
from ..proto.tensor_pb2 import TensorProto
from ..proto.tensor_shape_pb2 import TensorShapeProto
import os
import time
import numpy as np
from .file_system_tools import read_pickle, write_pickle, write_file
from .shared_config import PLUGIN_NAME, TAG_NAME, SUMMARY_FILENAME, DEFAULT_CONFIG, CONFIG_FILENAME, SUMMARY_COLLECTION_KEY_NAME, SECTION_INFO_FILENAME
from . import video_writing
class Beholder(object):
def __init__(self, logdir):
self.PLUGIN_LOGDIR = logdir + '/plugins/' + PLUGIN_NAME
self.is_recording = False
self.video_writer = video_writing.VideoWriter(
self.PLUGIN_LOGDIR,
outputs=[video_writing.FFmpegVideoOutput, video_writing.PNGVideoOutput])
self.last_image_shape = []
self.last_update_time = time.time()
self.config_last_modified_time = -1
self.previous_config = dict(DEFAULT_CONFIG)
if not os.path.exists(self.PLUGIN_LOGDIR + '/config.pkl'):
os.makedirs(self.PLUGIN_LOGDIR)
write_pickle(DEFAULT_CONFIG,
'{}/{}'.format(self.PLUGIN_LOGDIR, CONFIG_FILENAME))
def _get_config(self):
filename = '{}/{}'.format(self.PLUGIN_LOGDIR, CONFIG_FILENAME)
modified_time = os.path.getmtime(filename)
if modified_time != self.config_last_modified_time:
config = read_pickle(filename, default=self.previous_config)
self.previous_config = config
else:
config = self.previous_config
self.config_last_modified_time = modified_time
return config
def _write_summary(self, frame):
path = '{}/{}'.format(self.PLUGIN_LOGDIR, SUMMARY_FILENAME)
smd = SummaryMetadata()
tensor = TensorProto(
dtype='DT_FLOAT',
float_val=frame.reshape(-1).tolist(),
tensor_shape=TensorShapeProto(
dim=[TensorShapeProto.Dim(size=frame.shape[0]),
TensorShapeProto.Dim(size=frame.shape[1]),
TensorShapeProto.Dim(size=frame.shape[2])]
)
)
summary = Summary(value=[Summary.Value(
tag=TAG_NAME, metadata=smd, tensor=tensor)]).SerializeToString()
write_file(summary, path)
@staticmethod
def stats(tensor_and_name):
imgstats = []
for (img, name) in tensor_and_name:
immax = img.max()
immin = img.min()
imgstats.append(
{
'height': img.shape[0],
'max': str(immax),
'mean': str(img.mean()),
'min': str(immin),
'name': name,
'range': str(immax - immin),
'shape': str((img.shape[1], img.shape[2]))
})
return imgstats
def _get_final_image(self, config, trainable=None, arrays=None, frame=None):
if config['values'] == 'frames':
final_image = frame
elif config['values'] == 'arrays':
final_image = np.concatenate([arr for arr, _ in arrays])
stat = self.stats(arrays)
write_pickle(
stat, '{}/{}'.format(self.PLUGIN_LOGDIR, SECTION_INFO_FILENAME))
elif config['values'] == 'trainable_variables':
final_image = np.concatenate([arr for arr, _ in trainable])
stat = self.stats(trainable)
write_pickle(
stat, '{}/{}'.format(self.PLUGIN_LOGDIR, SECTION_INFO_FILENAME))
if len(final_image.shape) == 2:
final_image = np.expand_dims(final_image, -1)
return final_image
def _enough_time_has_passed(self, FPS):
if FPS == 0:
return False
else:
earliest_time = self.last_update_time + (1.0 / FPS)
return time.time() >= earliest_time
def _update_frame(self, trainable, arrays, frame, config):
final_image = self._get_final_image(config, trainable, arrays, frame)
self._write_summary(final_image)
self.last_image_shape = final_image.shape
return final_image
def _update_recording(self, frame, config):
should_record = config['is_recording']
if should_record:
if not self.is_recording:
self.is_recording = True
print('Starting recording using %s',
self.video_writer.current_output().name())
self.video_writer.write_frame(frame)
elif self.is_recording:
self.is_recording = False
self.video_writer.finish()
print('Finished recording')
|
MIT License
|
scanse/sweep-3d-scanner
|
scanner/scan_utils.py
|
polar_to_cartesian
|
python
|
def polar_to_cartesian(radius, angle_deg):
theta = np.deg2rad(angle_deg)
x = radius * np.cos(theta)
y = radius * np.sin(theta)
return(x, y)
|
Converts polar coordinate sample to cartesian coordinates
:param radius:
:param angle_deg:
|
https://github.com/scanse/sweep-3d-scanner/blob/2d245517b04ca49ea3d1238d1625fa0c993274c0/scanner/scan_utils.py#L7-L16
|
import argparse
import numpy as np
import transformations as tf
|
MIT License
|
neurodata/hyppo
|
hyppo/independence/_utils.py
|
_CheckInputs.check_dim_xy
|
python
|
def check_dim_xy(self):
if self.x.ndim == 1:
self.x = self.x[:, np.newaxis]
elif self.x.ndim != 2:
raise ValueError(
"Expected a 2-D array `x`, found shape " "{}".format(self.x.shape)
)
if self.y.ndim == 1:
self.y = self.y[:, np.newaxis]
elif self.y.ndim != 2:
raise ValueError(
"Expected a 2-D array `y`, found shape " "{}".format(self.y.shape)
)
self._check_nd_indeptest()
return self.x, self.y
|
Convert x and y to proper dimensions
|
https://github.com/neurodata/hyppo/blob/7c4df6d14c8f331ab1f26db1c8b5801a5844ebe3/hyppo/independence/_utils.py#L28-L45
|
import numpy as np
from ..tools import check_ndarray_xy, check_reps, contains_nan, convert_xy_float64
class _CheckInputs:
def __init__(self, x, y, reps=None):
self.x = x
self.y = y
self.reps = reps
def __call__(self):
check_ndarray_xy(self.x, self.y)
contains_nan(self.x)
contains_nan(self.y)
self.x, self.y = self.check_dim_xy()
self.x, self.y = convert_xy_float64(self.x, self.y)
self._check_min_samples()
self._check_variance()
if self.reps:
check_reps(self.reps)
return self.x, self.y
|
MIT License
|
scikit-hep/uproot4
|
src/uproot/model.py
|
class_named
|
python
|
def class_named(classname, version=None, custom_classes=None):
if custom_classes is None:
classes = uproot.classes
where = "the 'custom_classes' dict"
else:
where = "uproot.classes"
cls = classes.get(classname)
if cls is None:
raise ValueError("no class named {0} in {1}".format(classname, where))
if version is not None and isinstance(cls, DispatchByVersion):
versioned_cls = cls.class_of_version(version)
if versioned_cls is not None:
return versioned_cls
else:
raise ValueError(
"no class named {0} with version {1} in {2}".format(
classname, version, where
)
)
else:
return cls
|
Returns a class with a given C++ (decoded) classname.
If ``version`` is None, no attempt is made to find a specific version.
* If the class is a :doc:`uproot.model.DispatchByVersion`, then this is
object returned.
* If the class is a versionless model, then this is the object returned.
If ``version`` is an integer, an attempt is made to find the specific
version.
* If the class is a :doc:`uproot.model.DispatchByVersion`, then it is
queried for a versioned model.
* If the class is a versionless model, then this is the object returned.
If ``custom_classes`` are provided, then these are searched (exclusively)
for the class. If ``custom_classes`` is None, then ``uproot.classes`` is
used.
No classes are created if a class is not found (an error is raised).
|
https://github.com/scikit-hep/uproot4/blob/e0db77a2a10d701cb48f72e9f0d7867e1589572d/src/uproot/model.py#L242-L287
|
from __future__ import absolute_import
import re
import sys
import weakref
import numpy
import uproot
bootstrap_classnames = [
"TStreamerInfo",
"TStreamerElement",
"TStreamerArtificial",
"TStreamerBase",
"TStreamerBasicPointer",
"TStreamerBasicType",
"TStreamerLoop",
"TStreamerObject",
"TStreamerObjectAny",
"TStreamerObjectAnyPointer",
"TStreamerObjectPointer",
"TStreamerSTL",
"TStreamerSTLstring",
"TStreamerString",
"TList",
"TObjArray",
"TClonesArray",
"TObjString",
]
never_from_streamers = [
"TString",
"TList",
]
np_uint8 = numpy.dtype("u1")
def bootstrap_classes():
import uproot.models.TList
import uproot.models.TObjArray
import uproot.models.TObjString
import uproot.streamers
custom_classes = {}
for classname in bootstrap_classnames:
custom_classes[classname] = uproot.classes[classname]
return custom_classes
def reset_classes():
if uproot._util.py2:
reload = __builtins__["reload"]
else:
from importlib import reload
uproot.classes = {}
uproot.unknown_classes = {}
reload(uproot.streamers)
reload(uproot.models.TObject)
reload(uproot.models.TString)
reload(uproot.models.TArray)
reload(uproot.models.TNamed)
reload(uproot.models.TList)
reload(uproot.models.THashList)
reload(uproot.models.TObjArray)
reload(uproot.models.TObjString)
reload(uproot.models.TAtt)
reload(uproot.models.TDatime)
reload(uproot.models.TRef)
reload(uproot.models.TTable)
reload(uproot.models.TTree)
reload(uproot.models.TBranch)
reload(uproot.models.TLeaf)
reload(uproot.models.TBasket)
reload(uproot.models.RNTuple)
reload(uproot.models.TH)
reload(uproot.models.TGraph)
_classname_regularize = re.compile(r"\s*(<|>|::)\s*")
_classname_encode_pattern = re.compile(br"[^a-zA-Z0-9]+")
_classname_decode_antiversion = re.compile(br".*_([0-9a-f][0-9a-f])+_v([0-9]+)$")
_classname_decode_version = re.compile(br".*_v([0-9]+)$")
_classname_decode_pattern = re.compile(br"_(([0-9a-f][0-9a-f])+)_")
if uproot._util.py2:
def _classname_decode_convert(hex_characters):
g = hex_characters.group(1)
return b"".join(
chr(int(g[i : i + 2], 16)) for i in uproot._util.range(0, len(g), 2)
)
def _classname_encode_convert(bad_characters):
g = bad_characters.group(0)
return b"_" + b"".join("{0:02x}".format(ord(x)).encode() for x in g) + b"_"
else:
def _classname_decode_convert(hex_characters):
g = hex_characters.group(1)
return bytes(int(g[i : i + 2], 16) for i in uproot._util.range(0, len(g), 2))
def _classname_encode_convert(bad_characters):
g = bad_characters.group(0)
return b"_" + b"".join("{0:02x}".format(x).encode() for x in g) + b"_"
def classname_regularize(classname):
if classname is None:
return classname
else:
return re.sub(_classname_regularize, r"\1", classname)
def classname_decode(encoded_classname):
if encoded_classname.startswith("Unknown_"):
raw = encoded_classname[8:].encode()
elif encoded_classname.startswith("Model_"):
raw = encoded_classname[6:].encode()
else:
raise ValueError("not an encoded classname: {0}".format(encoded_classname))
if _classname_decode_antiversion.match(raw) is not None:
version = None
else:
m = _classname_decode_version.match(raw)
if m is None:
version = None
else:
version = int(m.group(1))
raw = raw[: -len(m.group(1)) - 2]
out = _classname_decode_pattern.sub(_classname_decode_convert, raw)
return out.decode(), version
def classname_encode(classname, version=None, unknown=False):
if unknown:
prefix = "Unknown_"
else:
prefix = "Model_"
if classname.startswith(prefix):
raise ValueError("classname is already encoded: {0}".format(classname))
if version is None:
v = ""
else:
v = "_v" + str(version)
raw = classname.encode()
out = _classname_encode_pattern.sub(_classname_encode_convert, raw)
return prefix + out.decode() + v
def classname_version(encoded_classname):
raw = encoded_classname.encode()
if _classname_decode_antiversion.match(raw) is not None:
return None
else:
m = _classname_decode_version.match(raw)
if m is None:
return None
else:
return int(m.group(1))
|
BSD 3-Clause New or Revised License
|
openforcefield/openff-qcsubmit
|
openff/qcsubmit/factories.py
|
BaseDatasetFactory.remove_workflow_component
|
python
|
def remove_workflow_component(self, component_name: str) -> None:
components = self.get_workflow_components(component_name=component_name)
if not components:
raise MissingWorkflowComponentError(
f"The requested component {component_name} "
f"could not be removed as it was not registered."
)
for component in components:
self.workflow.remove(component)
|
Find and remove any components via its type attribute.
Args:
component_name:
The name of the component to be gathered from the workflow.
Raises:
MissingWorkflowComponentError: If the component could not be found by its component name in the workflow.
|
https://github.com/openforcefield/openff-qcsubmit/blob/4a239bfe606b541b4088a0f95da252ed21526197/openff/qcsubmit/factories.py#L195-L215
|
import abc
import os
from typing import Dict, List, Optional, Tuple, Type, TypeVar, Union
import tqdm
from openff.toolkit import topology as off
from openff.toolkit.utils import GLOBAL_TOOLKIT_REGISTRY, ToolkitRegistry
from pydantic import Field, validator
from qcportal.models.common_models import DriverEnum
from typing_extensions import Literal
from openff.qcsubmit.common_structures import CommonBase, Metadata, MoleculeAttributes
from openff.qcsubmit.datasets import (
BasicDataset,
OptimizationDataset,
TorsiondriveDataset,
)
from openff.qcsubmit.exceptions import (
ComponentRequirementError,
DihedralConnectionError,
DriverError,
InvalidWorkflowComponentError,
LinearTorsionError,
MissingWorkflowComponentError,
MolecularComplexError,
)
from openff.qcsubmit.procedures import GeometricProcedure
from openff.qcsubmit.serializers import deserialize, serialize
from openff.qcsubmit.workflow_components import (
ComponentResult,
Components,
CustomWorkflowComponent,
get_component,
)
T = TypeVar("T", bound=BasicDataset)
class BaseDatasetFactory(CommonBase, abc.ABC):
type: Literal["BaseDatasetFactory"] = Field(
"BaseDatasetFactory",
description="The type of dataset factory which corresponds to the dataset made.",
)
workflow: List[Components] = Field(
[],
description="The set of workflow components and their settings which will be executed in order on the input molecules to make the dataset.",
)
@classmethod
def from_file(cls, file_name: str):
data = deserialize(file_name=file_name)
return cls(**data)
@classmethod
@abc.abstractmethod
def _dataset_type(cls) -> Type[BasicDataset]:
...
def _molecular_complex_filter(
self, dataset: T, molecule: off.Molecule, toolkit_registry: ToolkitRegistry
) -> None:
try:
dataset.filtered_molecules["MolecularComplexRemoval"].add_molecule(
molecule=molecule
)
except KeyError:
dataset.filter_molecules(
molecules=[
molecule,
],
component="MolecularComplexRemoval",
component_settings={},
component_provenance=self.provenance(toolkit_registry=toolkit_registry),
)
def _no_dihedrals_filter(
self, dataset: T, molecule: off.Molecule, toolkit_registry: ToolkitRegistry
) -> None:
try:
dataset.filtered_molecules["NoDihedralRemoval"].add_molecule(
molecule=molecule
)
except KeyError:
dataset.filter_molecules(
molecules=[
molecule,
],
component="NoDihedralRemoval",
component_settings={},
component_provenance=self.provenance(toolkit_registry=toolkit_registry),
)
def provenance(self, toolkit_registry: ToolkitRegistry) -> Dict[str, str]:
from openff import qcsubmit, toolkit
provenance = {
"openff-qcsubmit": qcsubmit.__version__,
"openff-toolkit": toolkit.__version__,
}
for tk in toolkit_registry.registered_toolkits:
if tk.__class__.__name__ != "BuiltInToolkitWrapper":
provenance[tk.__class__.__name__] = tk.toolkit_version
return provenance
def clear_workflow(self) -> None:
self.workflow = []
def add_workflow_components(self, *components: Components) -> None:
for component in components:
if issubclass(type(component), CustomWorkflowComponent):
try:
component.is_available()
self.workflow.append(component)
except ModuleNotFoundError as e:
raise ComponentRequirementError(
f"The component {component.type} could not be added to "
f"the workflow due to missing requirements"
) from e
else:
raise InvalidWorkflowComponentError(
f"Component {component} rejected as it is not a sub "
f"class of CustomWorkflowComponent."
)
def get_workflow_components(self, component_name: str) -> List[Components]:
components = [
component
for component in self.workflow
if component.type.lower() == component_name.lower()
]
if not components:
raise MissingWorkflowComponentError(
f"The requested component {component_name} "
f"was not registered into the workflow."
)
return components
|
MIT License
|
mingpan/generative_map
|
gen_map.py
|
GenMap._minimize_loss
|
python
|
def _minimize_loss(self, val, val_rec, z_s_mu, z_s_log_var, z_val_mu, z_val_log_var, learning_rate, val_log_var):
loss_rec = loss_rec_normal(val, val_rec, log_var=val_log_var)
loss_kl = loss_kl_normal(z_val_mu, z_val_log_var, z_s_mu, z_s_log_var)
self.cost_1 = tf.reduce_mean(loss_rec / self.reconstruction_dim)
self.cost_2 = tf.reduce_mean(loss_kl / self.latent_dim)
self.cost = self.cost_1 + self.cost_2
self.train_op = tf.train.AdamOptimizer(learning_rate).minimize(self.cost)
|
Minimize the loss of VAE, which contains kl-divergence term and reconstruction term.
|
https://github.com/mingpan/generative_map/blob/bcace4533cb1576f4b39e281ee182f940d438b06/gen_map.py#L73-L80
|
import numpy as np
import tensorflow as tf
from ops import build_fnn, dcgan_decode, dcgan_encode
from ops import loss_rec_normal, loss_reg_normal, loss_kl_normal
class GenMap(object):
def __init__(self, arch_encoder_attribute, image_size, dim_features=512, num_conv_layer=4,
transfer_fct=tf.nn.relu, learning_rate=1e-3, batch_size=100, rec_log_var=0.,
training=False, reconstruct_size=(64, 64, 3)):
self.transfer_fct = transfer_fct
self.learning_rate = learning_rate
self.batch_size = batch_size
self.dim_attribute = arch_encoder_attribute[0]
self.latent_dim = arch_encoder_attribute[-1]
self.reconstruction_dim = np.prod(reconstruct_size)
self.x = tf.placeholder(tf.float32, [None, self.dim_attribute], name="pose_input")
y_shape = [None]
y_shape.extend(image_size)
self.y = tf.placeholder(tf.float32, y_shape, name="image_input")
self.y_small = tf.placeholder(tf.float32, [None, self.reconstruction_dim], name="image_reconstruct")
arch_encoder_x = arch_encoder_attribute.copy()
arch_encoder_x[-1] = arch_encoder_x[-1] * 2
z_x_all = build_fnn(self.x, arch_encoder_x, transfer_fct, scope="encoder_x")
self.z_x_mean, z_x_log_sigma_sq = tf.split(z_x_all, num_or_size_splits=2, axis=1)
self.z_x_log_sigma_sq = tf.zeros_like(z_x_log_sigma_sq)
epsilon_x = tf.random_normal((self.batch_size, self.latent_dim))
self.z_x = self.z_x_mean + (tf.sqrt(tf.exp(self.z_x_log_sigma_sq)) * epsilon_x)
self.z_y_mean, self.z_y_log_sigma_sq = dcgan_encode(final_channel=dim_features,
num_layer=num_conv_layer,
inputs=self.y,
output_size=self.latent_dim,
activation=transfer_fct,
scope="encoder_y",
training=training)
epsilon_y = tf.random_normal((self.batch_size, self.latent_dim))
self.z_y = self.z_y_mean + (tf.sqrt(tf.exp(self.z_y_log_sigma_sq)) * epsilon_y)
y_rec_pre = dcgan_decode(inputs=self.z_y,
output_size=reconstruct_size,
num_layer=num_conv_layer,
channel_start=dim_features,
activation=transfer_fct,
scope="decoder_y",
training=training)
self.alpha = tf.get_variable("image_variance_log", initializer=rec_log_var * tf.ones((1,)), trainable=False)
self.y_rec = (1 + 2e-6) * tf.sigmoid(y_rec_pre) - 1e-6
self._minimize_loss(self.y_small, self.y_rec, self.z_x_mean, self.z_x_log_sigma_sq,
self.z_y_mean, self.z_y_log_sigma_sq, learning_rate, self.alpha)
self.saver = tf.train.Saver(max_to_keep=1)
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
self.sess = tf.Session(config=config)
self.sess.run(tf.global_variables_initializer())
|
MIT License
|
anaconda-platform/chalmers
|
chalmers/commands/set.py
|
split_try_eval
|
python
|
def split_try_eval(item):
if '=' not in item:
raise TypeError("Chalmers can not set '%s' as a definition variable\n"
"The parameter must contain an '='" % (item))
key, value = item.split('=', 1)
return key, try_eval(value)
|
split key=value pairs, then eval the value
|
https://github.com/anaconda-platform/chalmers/blob/029ac223660f267a04047b63d6ccfefa3d012b2e/chalmers/commands/set.py#L57-L63
|
from __future__ import unicode_literals, print_function
from argparse import RawDescriptionHelpFormatter
import logging
from chalmers import errors
from chalmers.program import Program
from chalmers.utils import try_eval, set_nested_key
log = logging.getLogger('chalmers.set')
|
MIT License
|
twopirllc/pandas-ta
|
pandas_ta/overlap/hilo.py
|
hilo
|
python
|
def hilo(high, low, close, high_length=None, low_length=None, mamode=None, offset=None, **kwargs):
high_length = int(high_length) if high_length and high_length > 0 else 13
low_length = int(low_length) if low_length and low_length > 0 else 21
mamode = mamode.lower() if isinstance(mamode, str) else "sma"
_length = max(high_length, low_length)
high = verify_series(high, _length)
low = verify_series(low, _length)
close = verify_series(close, _length)
offset = get_offset(offset)
if high is None or low is None or close is None: return
m = close.size
hilo = Series(npNaN, index=close.index)
long = Series(npNaN, index=close.index)
short = Series(npNaN, index=close.index)
high_ma = ma(mamode, high, length=high_length)
low_ma = ma(mamode, low, length=low_length)
for i in range(1, m):
if close.iloc[i] > high_ma.iloc[i - 1]:
hilo.iloc[i] = long.iloc[i] = low_ma.iloc[i]
elif close.iloc[i] < low_ma.iloc[i - 1]:
hilo.iloc[i] = short.iloc[i] = high_ma.iloc[i]
else:
hilo.iloc[i] = hilo.iloc[i - 1]
long.iloc[i] = short.iloc[i] = hilo.iloc[i - 1]
if offset != 0:
hilo = hilo.shift(offset)
long = long.shift(offset)
short = short.shift(offset)
if "fillna" in kwargs:
hilo.fillna(kwargs["fillna"], inplace=True)
long.fillna(kwargs["fillna"], inplace=True)
short.fillna(kwargs["fillna"], inplace=True)
if "fill_method" in kwargs:
hilo.fillna(method=kwargs["fill_method"], inplace=True)
long.fillna(method=kwargs["fill_method"], inplace=True)
short.fillna(method=kwargs["fill_method"], inplace=True)
_props = f"_{high_length}_{low_length}"
data = {f"HILO{_props}": hilo, f"HILOl{_props}": long, f"HILOs{_props}": short}
df = DataFrame(data, index=close.index)
df.name = f"HILO{_props}"
df.category = "overlap"
return df
|
Indicator: Gann HiLo (HiLo)
|
https://github.com/twopirllc/pandas-ta/blob/bc3b292bf1cc1d5f2aba50bb750a75209d655b37/pandas_ta/overlap/hilo.py#L8-L64
|
from numpy import nan as npNaN
from pandas import DataFrame, Series
from .ma import ma
from pandas_ta.utils import get_offset, verify_series
|
MIT License
|
parashardhapola/scarf
|
scarf/assay.py
|
Assay.iter_normed_feature_wise
|
python
|
def iter_normed_feature_wise(
self,
cell_key: Optional[str],
feat_key: Optional[str],
batch_size: int,
msg: Optional[str],
**norm_params,
) -> Generator[pd.DataFrame, None, None]:
from .utils import tqdmbar
if cell_key is None:
cell_idx = np.array(list(range(self.cells.N)))
else:
cell_idx = self.cells.active_index(cell_key)
if feat_key is None:
feat_idx = np.array(list(range(self.feats.N)))
else:
feat_idx = self.feats.active_index(feat_key)
if msg is None:
msg = ""
data = self.normed(
cell_idx=cell_idx,
feat_idx=feat_idx,
**norm_params,
)
logger.debug("Will iterate over data of shape: ", data.shape)
chunks = np.array_split(
np.arange(0, data.shape[1]), int(data.shape[1] / batch_size)
)
for chunk in tqdmbar(chunks, desc=msg, total=len(chunks)):
yield pd.DataFrame(
controlled_compute(data[:, chunk], self.nthreads),
columns=feat_idx[chunk],
)
|
This generator iterates over all the features marked by `feat_key` in batches.
Args:
cell_key: Name of the key (column) from cell attribute table. The data will be fetched
for only those cells that have a True value in this column. If None then all the cells are used
feat_key: Name of the key (column) from feature attribute table. The data will be fetched
for only those features that have a True value in this column. If None then all the features are
used
batch_size: Number of genes to be loaded in the memory at a time.
msg: Message to be displayed in the progress bar
Returns:
|
https://github.com/parashardhapola/scarf/blob/95d27b05a07973214cf71a2e5af3c3a089791093/scarf/assay.py#L487-L537
|
import numpy as np
import dask.array as daskarr
import zarr
from .metadata import MetaData
from .utils import show_dask_progress, controlled_compute, logger
from scipy.sparse import csr_matrix, vstack
from typing import Tuple, List, Generator, Optional
import pandas as pd
__all__ = ["Assay", "RNAassay", "ATACassay", "ADTassay"]
def norm_dummy(_, counts: daskarr) -> daskarr:
return counts
def norm_lib_size(assay, counts: daskarr) -> daskarr:
return assay.sf * counts / assay.scalar.reshape(-1, 1)
def norm_lib_size_log(assay, counts: daskarr) -> daskarr:
return np.log1p(assay.sf * counts / assay.scalar.reshape(-1, 1))
def norm_clr(_, counts: daskarr) -> daskarr:
f = np.exp(np.log1p(counts).sum(axis=0) / len(counts))
return np.log1p(counts / f)
def norm_tf_idf(assay, counts: daskarr) -> daskarr:
tf = counts / assay.n_term_per_doc.reshape(-1, 1)
idf = np.log2(1 + (assay.n_docs / (assay.n_docs_per_term + 1)))
return tf * idf
class Assay:
def __init__(
self,
z: zarr.group,
name: str,
cell_data: MetaData,
nthreads: int,
min_cells_per_feature: int = 10,
):
self.name = name
self.z = z[self.name]
self.cells = cell_data
self.nthreads = nthreads
self.rawData = daskarr.from_zarr(self.z["counts"], inline_array=True)
self.feats = MetaData(self.z["featureData"])
self.attrs = self.z.attrs
if "percentFeatures" not in self.attrs:
self.attrs["percentFeatures"] = {}
self.normMethod = norm_dummy
self.sf = None
self._ini_feature_props(min_cells_per_feature)
def normed(
self, cell_idx: np.ndarray = None, feat_idx: np.ndarray = None, **kwargs
) -> daskarr:
if cell_idx is None:
cell_idx = self.cells.active_index("I")
if feat_idx is None:
feat_idx = self.feats.active_index("I")
counts = self.rawData[:, feat_idx][cell_idx, :]
return self.normMethod(self, counts)
def to_raw_sparse(self, cell_key) -> csr_matrix:
from .utils import tqdmbar
sm = None
for i in tqdmbar(
self.rawData[self.cells.active_index(cell_key), :].blocks,
total=self.rawData.numblocks[0],
desc=f"INFO: Converting raw data from {self.name} assay into CSR format",
):
s = csr_matrix(controlled_compute(i, self.nthreads))
if sm is None:
sm = s
else:
sm = vstack([sm, s])
return sm
def _ini_feature_props(self, min_cells: int) -> None:
if "nCells" in self.feats.columns and "dropOuts" in self.feats.columns:
pass
else:
ncells = show_dask_progress(
(self.rawData > 0).sum(axis=0),
f"({self.name}) Computing nCells and dropOuts",
self.nthreads,
)
self.feats.insert("nCells", ncells, overwrite=True)
self.feats.insert(
"dropOuts",
abs(self.cells.N - self.feats.fetch("nCells")),
overwrite=True,
)
self.feats.update_key(ncells > min_cells, "I")
def add_percent_feature(self, feat_pattern: str, name: str) -> None:
if name in self.attrs["percentFeatures"]:
if self.attrs["percentFeatures"][name] == feat_pattern:
return None
else:
logger.info(f"Pattern for percentage feature {name} updated.")
self.attrs["percentFeatures"] = {
**{k: v for k, v in self.attrs["percentFeatures"].items()},
**{name: feat_pattern},
}
feat_idx = sorted(
self.feats.get_index_by(self.feats.grep(feat_pattern), "names")
)
if len(feat_idx) == 0:
logger.warning(
f"No matches found for pattern {feat_pattern}."
f" Will not add/update percentage feature"
)
return None
total = show_dask_progress(
self.rawData[:, feat_idx].sum(axis=1),
f"({self.name}) Computing {name}",
self.nthreads,
)
if total.sum() == 0:
logger.warning(
f"Percentage feature {name} not added because not detected in any cell"
)
return None
self.cells.insert(
name,
100 * total / self.cells.fetch_all(self.name + "_nCounts"),
overwrite=True,
)
def _verify_keys(self, cell_key: str, feat_key: str) -> None:
if cell_key not in self.cells.columns or self.cells.get_dtype(cell_key) != bool:
raise ValueError(
f"ERROR: Either {cell_key} does not exist or is not bool type"
)
if feat_key not in self.feats.columns or self.feats.get_dtype(feat_key) != bool:
raise ValueError(
f"ERROR: Either {feat_key} does not exist or is not bool type"
)
def _get_cell_feat_idx(
self, cell_key: str, feat_key: str
) -> Tuple[np.ndarray, np.ndarray]:
self._verify_keys(cell_key, feat_key)
cell_idx = self.cells.active_index(cell_key)
feat_idx = self.feats.active_index(feat_key)
return cell_idx, feat_idx
@staticmethod
def _create_subset_hash(cell_idx: np.ndarray, feat_idx: np.ndarray) -> int:
return hash(tuple([hash(tuple(cell_idx)), hash(tuple(feat_idx))]))
@staticmethod
def _get_summary_stats_loc(cell_key: str) -> Tuple[str, str]:
return f"stats_{cell_key}", f"summary_stats_{cell_key}"
def _validate_stats_loc(
self,
stats_loc: str,
cell_idx: np.ndarray,
feat_idx: np.ndarray,
delete_on_fail: bool = True,
) -> bool:
subset_hash = self._create_subset_hash(cell_idx, feat_idx)
if stats_loc in self.z:
attrs = self.z[stats_loc].attrs
if "subset_hash" in attrs and attrs["subset_hash"] == subset_hash:
return True
else:
if delete_on_fail:
del self.z[stats_loc]
return False
else:
return False
def _load_stats_loc(self, cell_key: str) -> str:
cell_idx, feat_idx = self._get_cell_feat_idx(cell_key, "I")
identifier, stats_loc = self._get_summary_stats_loc(cell_key)
if self._validate_stats_loc(stats_loc, cell_idx, feat_idx) is False:
raise KeyError(
f"Summary statistics have not been calculated for cell key: {cell_key}"
)
if identifier not in self.feats.locations:
self.feats.mount_location(self.z[stats_loc], identifier)
else:
logger.debug(f"Location ({stats_loc}) already mounted")
return identifier
def save_normalized_data(
self,
cell_key: str,
feat_key: str,
batch_size: int,
location: str,
log_transform: bool,
renormalize_subset: bool,
update_keys: bool,
) -> daskarr:
from .writers import dask_to_zarr
if feat_key != "I":
feat_key = cell_key + "__" + feat_key
cell_idx, feat_idx = self._get_cell_feat_idx(cell_key, feat_key)
subset_hash = self._create_subset_hash(cell_idx, feat_idx)
subset_params = {
"log_transform": log_transform,
"renormalize_subset": renormalize_subset,
}
if location in self.z:
if (
subset_hash == self.z[location].attrs["subset_hash"]
and subset_params == self.z[location].attrs["subset_params"]
):
logger.info(
f"Using existing normalized data with cell key {cell_key} and feat key {feat_key}"
)
if update_keys:
self.attrs["latest_feat_key"] = (
feat_key.split("__", 1)[1] if feat_key != "I" else "I"
)
self.attrs["latest_cell_key"] = cell_key
return daskarr.from_zarr(self.z[location + "/data"], inline_array=True)
else:
self.z.create_group(location, overwrite=True)
vals = self.normed(
cell_idx,
feat_idx,
log_transform=log_transform,
renormalize_subset=renormalize_subset,
)
dask_to_zarr(vals, self.z, location + "/data", batch_size, self.nthreads)
self.z[location].attrs["subset_hash"] = subset_hash
self.z[location].attrs["subset_params"] = subset_params
if update_keys:
self.attrs["latest_feat_key"] = (
feat_key.split("__", 1)[1] if feat_key != "I" else "I"
)
self.attrs["latest_cell_key"] = cell_key
return daskarr.from_zarr(self.z[location + "/data"], inline_array=True)
|
BSD 3-Clause New or Revised License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.