hexsha stringlengths 40 40 | size int64 4 996k | ext stringclasses 8
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 6 130 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 245 | max_issues_repo_name stringlengths 6 130 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 245 | max_forks_repo_name stringlengths 6 130 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 4 996k | avg_line_length float64 1.33 58.2k | max_line_length int64 2 323k | alphanum_fraction float64 0 0.97 | content_no_comment stringlengths 0 946k | is_comment_constant_removed bool 2
classes | is_sharp_comment_removed bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f7f7334d1c20c11af6d89fb9cc93933ed93f73a1 | 1,692 | py | Python | Machine Learning A-Z/Part 7 - Natural Language Processing/Section 36 - Natural Language Processing/natural_language_processing.py | lifehouse11amber2/Machine-Learning-A-Z-hands-on-Python-And-R-in-data-Science | 6ae9d490466546405517c07406526a4f3fcd9710 | [
"MIT"
] | 23 | 2020-05-29T08:38:03.000Z | 2022-02-25T20:43:09.000Z | Machine Learning A-Z/Part 7 - Natural Language Processing/Section 36 - Natural Language Processing/natural_language_processing.py | garciamilord/Machine-Learning-A-Z-hands-on-Python-And-R-in-data-Science | d804e7eeace1e5187b156b2fa3e71125b2a3448a | [
"MIT"
] | null | null | null | Machine Learning A-Z/Part 7 - Natural Language Processing/Section 36 - Natural Language Processing/natural_language_processing.py | garciamilord/Machine-Learning-A-Z-hands-on-Python-And-R-in-data-Science | d804e7eeace1e5187b156b2fa3e71125b2a3448a | [
"MIT"
] | 22 | 2020-12-05T15:14:43.000Z | 2022-03-12T23:28:49.000Z | # Natural Language Processing
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Restaurant_Reviews.tsv', delimiter = '\t', quoting = 3)
# Cleaning the texts
import re
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
corpus = []
for i in range(0, 1000):
review = re.sub('[^a-zA-Z]', ' ', dataset['Review'][i])
review = review.lower()
review = review.split()
ps = PorterStemmer()
review = [ps.stem(word) for word in review if not word in set(stopwords.words('english'))]
review = ' '.join(review)
corpus.append(review)
# Creating the Bag of Words model
from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer(max_features = 1500)
X = cv.fit_transform(corpus).toarray()
y = dataset.iloc[:, 1].values
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 0)
# Fitting Naive Bayes to the Training set
from sklearn.naive_bayes import GaussianNB
classifier = GaussianNB()
classifier.fit(X_train, y_train)
# Predicting the Test set results
y_pred = classifier.predict(X_test)
# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
# naive based classifer
# true positive= 55
# false positive = 42
# true Negative = 91
# false negative = 12
#Accuracy score
AS=(55+91)/200 #.73
#Precision
P=54/(55+42) #0.57
#Recall
R=55/(55+12) # 0.82
#F1 Score
2*P*R/(P+R) #0.67 | 26.030769 | 94 | 0.735225 |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv('Restaurant_Reviews.tsv', delimiter = '\t', quoting = 3)
import re
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
corpus = []
for i in range(0, 1000):
review = re.sub('[^a-zA-Z]', ' ', dataset['Review'][i])
review = review.lower()
review = review.split()
ps = PorterStemmer()
review = [ps.stem(word) for word in review if not word in set(stopwords.words('english'))]
review = ' '.join(review)
corpus.append(review)
from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer(max_features = 1500)
X = cv.fit_transform(corpus).toarray()
y = dataset.iloc[:, 1].values
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 0)
from sklearn.naive_bayes import GaussianNB
classifier = GaussianNB()
classifier.fit(X_train, y_train)
y_pred = classifier.predict(X_test)
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
AS=(55+91)/200
P=54/(55+42)
R=55/(55+12)
2*P*R/(P+R) | true | true |
f7f7357fab8832ac539d527238dda69853cd1514 | 1,184 | py | Python | Back/user/forms.py | BUYA-GH/heavenhold | 1814e12a4071f3e6ebd2920ab22718beb4e511ca | [
"Apache-2.0"
] | null | null | null | Back/user/forms.py | BUYA-GH/heavenhold | 1814e12a4071f3e6ebd2920ab22718beb4e511ca | [
"Apache-2.0"
] | null | null | null | Back/user/forms.py | BUYA-GH/heavenhold | 1814e12a4071f3e6ebd2920ab22718beb4e511ca | [
"Apache-2.0"
] | null | null | null | from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from .models import User
class UserCreationForm(forms.ModelForm):
password1 = forms.CharField(label='Password',widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation',widget=forms.PasswordInput)
class Meta:
model = User
fields = ('email', 'gamecode', 'guild', 'guild_member')
def clean_password2(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self,commit=True):
user = super().save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserChangeForm(forms.ModelForm):
password = ReadOnlyPasswordHashField()
class Meta:
model = User
fields = ('email', 'password', 'gamecode', 'guild', 'guild_member')
def clean_password(self):
return self.initial['password'] | 32.888889 | 89 | 0.678209 | from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from .models import User
class UserCreationForm(forms.ModelForm):
password1 = forms.CharField(label='Password',widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation',widget=forms.PasswordInput)
class Meta:
model = User
fields = ('email', 'gamecode', 'guild', 'guild_member')
def clean_password2(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self,commit=True):
user = super().save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserChangeForm(forms.ModelForm):
password = ReadOnlyPasswordHashField()
class Meta:
model = User
fields = ('email', 'password', 'gamecode', 'guild', 'guild_member')
def clean_password(self):
return self.initial['password'] | true | true |
f7f736ac5c0500a5ccbc31d0b4a87511d470887c | 2,600 | py | Python | examples/dagster_examples/intro_tutorial/serialization_strategy.py | naralogics/dagster | 16d599daa380b800149474fcaff2311b3f8f269a | [
"Apache-2.0"
] | null | null | null | examples/dagster_examples/intro_tutorial/serialization_strategy.py | naralogics/dagster | 16d599daa380b800149474fcaff2311b3f8f269a | [
"Apache-2.0"
] | null | null | null | examples/dagster_examples/intro_tutorial/serialization_strategy.py | naralogics/dagster | 16d599daa380b800149474fcaff2311b3f8f269a | [
"Apache-2.0"
] | null | null | null | import csv
from dagster import (
Selector,
SerializationStrategy,
execute_pipeline,
input_hydration_config,
pipeline,
solid,
usable_as_dagster_type,
)
class CsvSerializationStrategy(SerializationStrategy):
def __init__(self):
super(CsvSerializationStrategy, self).__init__(
'csv_strategy', read_mode='r', write_mode='w'
)
def serialize(self, value, write_file_obj):
fieldnames = value[0]
writer = csv.DictWriter(write_file_obj, fieldnames)
writer.writeheader()
writer.writerows(value)
def deserialize(self, read_file_obj):
reader = csv.DictReader(read_file_obj)
return LessSimpleDataFrame([row for row in reader])
@input_hydration_config(Selector({'pickle': str}))
def less_simple_data_frame_input_hydration_config(context, selector):
with open(selector['pickle'], 'r') as fd:
lines = [row for row in csv.DictReader(fd)]
context.log.info('Read {n_lines} lines'.format(n_lines=len(lines)))
return LessSimpleDataFrame(lines)
@usable_as_dagster_type(
name='LessSimpleDataFrame',
description=(
'A naive representation of a data frame, e.g., as returned by '
'csv.DictReader.'
),
serialization_strategy=CsvSerializationStrategy(),
input_hydration_config=less_simple_data_frame_input_hydration_config,
)
class LessSimpleDataFrame(list):
pass
@solid
def read_csv(context, csv_path: str) -> LessSimpleDataFrame:
with open(csv_path, 'r') as fd:
lines = [row for row in csv.DictReader(fd)]
context.log.info('Read {n_lines} lines'.format(n_lines=len(lines)))
return LessSimpleDataFrame(lines)
@solid
def sort_by_calories(context, cereals: LessSimpleDataFrame):
sorted_cereals = sorted(cereals, key=lambda cereal: cereal['calories'])
context.log.info(
'Least caloric cereal: {least_caloric}'.format(
least_caloric=sorted_cereals[0]['name']
)
)
context.log.info(
'Most caloric cereal: {most_caloric}'.format(
most_caloric=sorted_cereals[-1]['name']
)
)
return LessSimpleDataFrame(sorted_cereals)
@pipeline
def serialization_strategy_pipeline():
sort_by_calories(read_csv())
if __name__ == '__main__':
environment_dict = {
'solids': {
'read_csv': {'inputs': {'csv_path': {'value': 'cereal.csv'}}}
},
'storage': {'filesystem': {}},
}
result = execute_pipeline(
serialization_strategy_pipeline, environment_dict=environment_dict
)
assert result.success
| 27.659574 | 75 | 0.68 | import csv
from dagster import (
Selector,
SerializationStrategy,
execute_pipeline,
input_hydration_config,
pipeline,
solid,
usable_as_dagster_type,
)
class CsvSerializationStrategy(SerializationStrategy):
def __init__(self):
super(CsvSerializationStrategy, self).__init__(
'csv_strategy', read_mode='r', write_mode='w'
)
def serialize(self, value, write_file_obj):
fieldnames = value[0]
writer = csv.DictWriter(write_file_obj, fieldnames)
writer.writeheader()
writer.writerows(value)
def deserialize(self, read_file_obj):
reader = csv.DictReader(read_file_obj)
return LessSimpleDataFrame([row for row in reader])
@input_hydration_config(Selector({'pickle': str}))
def less_simple_data_frame_input_hydration_config(context, selector):
with open(selector['pickle'], 'r') as fd:
lines = [row for row in csv.DictReader(fd)]
context.log.info('Read {n_lines} lines'.format(n_lines=len(lines)))
return LessSimpleDataFrame(lines)
@usable_as_dagster_type(
name='LessSimpleDataFrame',
description=(
'A naive representation of a data frame, e.g., as returned by '
'csv.DictReader.'
),
serialization_strategy=CsvSerializationStrategy(),
input_hydration_config=less_simple_data_frame_input_hydration_config,
)
class LessSimpleDataFrame(list):
pass
@solid
def read_csv(context, csv_path: str) -> LessSimpleDataFrame:
with open(csv_path, 'r') as fd:
lines = [row for row in csv.DictReader(fd)]
context.log.info('Read {n_lines} lines'.format(n_lines=len(lines)))
return LessSimpleDataFrame(lines)
@solid
def sort_by_calories(context, cereals: LessSimpleDataFrame):
sorted_cereals = sorted(cereals, key=lambda cereal: cereal['calories'])
context.log.info(
'Least caloric cereal: {least_caloric}'.format(
least_caloric=sorted_cereals[0]['name']
)
)
context.log.info(
'Most caloric cereal: {most_caloric}'.format(
most_caloric=sorted_cereals[-1]['name']
)
)
return LessSimpleDataFrame(sorted_cereals)
@pipeline
def serialization_strategy_pipeline():
sort_by_calories(read_csv())
if __name__ == '__main__':
environment_dict = {
'solids': {
'read_csv': {'inputs': {'csv_path': {'value': 'cereal.csv'}}}
},
'storage': {'filesystem': {}},
}
result = execute_pipeline(
serialization_strategy_pipeline, environment_dict=environment_dict
)
assert result.success
| true | true |
f7f7374ec3cb970060e338dbf2c44fef2ca8280c | 1,134 | py | Python | tests/storage/cases/test_KT1VHqKm6KjUqspTAmWiBJbTDBjbn8PAfGvr.py | juztin/pytezos-1 | 7e608ff599d934bdcf129e47db43dbdb8fef9027 | [
"MIT"
] | 1 | 2021-05-20T16:52:08.000Z | 2021-05-20T16:52:08.000Z | tests/storage/cases/test_KT1VHqKm6KjUqspTAmWiBJbTDBjbn8PAfGvr.py | juztin/pytezos-1 | 7e608ff599d934bdcf129e47db43dbdb8fef9027 | [
"MIT"
] | 1 | 2020-12-30T16:44:56.000Z | 2020-12-30T16:44:56.000Z | tests/storage/cases/test_KT1VHqKm6KjUqspTAmWiBJbTDBjbn8PAfGvr.py | juztin/pytezos-1 | 7e608ff599d934bdcf129e47db43dbdb8fef9027 | [
"MIT"
] | 1 | 2022-03-20T19:01:00.000Z | 2022-03-20T19:01:00.000Z | from unittest import TestCase
from tests import get_data
from pytezos.michelson.converter import build_schema, decode_micheline, encode_micheline, micheline_to_michelson
class StorageTestKT1VHqKm6KjUqspTAmWiBJbTDBjbn8PAfGvr(TestCase):
@classmethod
def setUpClass(cls):
cls.maxDiff = None
cls.contract = get_data('storage/carthagenet/KT1VHqKm6KjUqspTAmWiBJbTDBjbn8PAfGvr.json')
def test_storage_encoding_KT1VHqKm6KjUqspTAmWiBJbTDBjbn8PAfGvr(self):
type_expr = self.contract['script']['code'][1]
val_expr = self.contract['script']['storage']
schema = build_schema(type_expr)
decoded = decode_micheline(val_expr, type_expr, schema)
actual = encode_micheline(decoded, schema)
self.assertEqual(val_expr, actual)
def test_storage_schema_KT1VHqKm6KjUqspTAmWiBJbTDBjbn8PAfGvr(self):
_ = build_schema(self.contract['script']['code'][0])
def test_storage_format_KT1VHqKm6KjUqspTAmWiBJbTDBjbn8PAfGvr(self):
_ = micheline_to_michelson(self.contract['script']['code'])
_ = micheline_to_michelson(self.contract['script']['storage'])
| 40.5 | 112 | 0.749559 | from unittest import TestCase
from tests import get_data
from pytezos.michelson.converter import build_schema, decode_micheline, encode_micheline, micheline_to_michelson
class StorageTestKT1VHqKm6KjUqspTAmWiBJbTDBjbn8PAfGvr(TestCase):
@classmethod
def setUpClass(cls):
cls.maxDiff = None
cls.contract = get_data('storage/carthagenet/KT1VHqKm6KjUqspTAmWiBJbTDBjbn8PAfGvr.json')
def test_storage_encoding_KT1VHqKm6KjUqspTAmWiBJbTDBjbn8PAfGvr(self):
type_expr = self.contract['script']['code'][1]
val_expr = self.contract['script']['storage']
schema = build_schema(type_expr)
decoded = decode_micheline(val_expr, type_expr, schema)
actual = encode_micheline(decoded, schema)
self.assertEqual(val_expr, actual)
def test_storage_schema_KT1VHqKm6KjUqspTAmWiBJbTDBjbn8PAfGvr(self):
_ = build_schema(self.contract['script']['code'][0])
def test_storage_format_KT1VHqKm6KjUqspTAmWiBJbTDBjbn8PAfGvr(self):
_ = micheline_to_michelson(self.contract['script']['code'])
_ = micheline_to_michelson(self.contract['script']['storage'])
| true | true |
f7f73815845e4a757af05db650704b3bfcd93c76 | 1,683 | py | Python | migrations/versions/000000000000_create_table_checksum_and_logs.py | brighthive/data-resource-api | a012fc0743f1ce2b72ddacf348c57adf44245cfa | [
"MIT"
] | 4 | 2019-02-14T01:07:54.000Z | 2019-11-04T17:28:35.000Z | migrations/versions/000000000000_create_table_checksum_and_logs.py | brighthive/data-resource-api | a012fc0743f1ce2b72ddacf348c57adf44245cfa | [
"MIT"
] | 39 | 2019-05-30T22:08:46.000Z | 2022-02-17T02:47:00.000Z | migrations/versions/000000000000_create_table_checksum_and_logs.py | brighthive/data-resource-api | a012fc0743f1ce2b72ddacf348c57adf44245cfa | [
"MIT"
] | 1 | 2020-04-29T18:16:20.000Z | 2020-04-29T18:16:20.000Z | """Create table checksum_and_logs
Revision ID: c84467455016
Revises:
Create Date: 2020-02-14 20:31:39.065035
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = "000000000000"
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"checksums",
sa.Column("data_resource", sa.String(), nullable=False),
sa.Column("model_checksum", sa.String(), nullable=False),
sa.Column("date_modified", sa.DateTime(), nullable=True),
sa.Column(
"descriptor_json", postgresql.JSONB(astext_type=sa.Text()), nullable=True
),
sa.PrimaryKeyConstraint("data_resource"),
)
op.create_table(
"logs",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("logger", sa.String(), nullable=True),
sa.Column("level", sa.String(), nullable=True),
sa.Column("trace", sa.String(), nullable=True),
sa.Column("msg", sa.String(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint("id"),
)
op.create_table(
"migrations",
sa.Column("file_name", sa.String(), nullable=False),
sa.Column("file_blob", sa.LargeBinary(), nullable=False),
sa.PrimaryKeyConstraint("file_name"),
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table("logs")
op.drop_table("checksums")
# ### end Alembic commands ###
| 31.166667 | 85 | 0.639929 | import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
revision = "000000000000"
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
sa.Column("date_modified", sa.DateTime(), nullable=True),
sa.Column(
"descriptor_json", postgresql.JSONB(astext_type=sa.Text()), nullable=True
),
sa.PrimaryKeyConstraint("data_resource"),
)
op.create_table(
"logs",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("logger", sa.String(), nullable=True),
sa.Column("level", sa.String(), nullable=True),
sa.Column("trace", sa.String(), nullable=True),
sa.Column("msg", sa.String(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint("id"),
)
op.create_table(
"migrations",
sa.Column("file_name", sa.String(), nullable=False),
sa.Column("file_blob", sa.LargeBinary(), nullable=False),
sa.PrimaryKeyConstraint("file_name"),
)
| true | true |
f7f73831b920f239d1f4fcf6d18367f2ef00498c | 908 | py | Python | dnafrag/tests/test_vplot_end_to_end.py | kundajelab/dnafrag | 3c6cb2c585fc35aa1882dcff2f171cbc9020c091 | [
"BSD-3-Clause"
] | 1 | 2021-03-11T07:57:10.000Z | 2021-03-11T07:57:10.000Z | dnafrag/tests/test_vplot_end_to_end.py | DebadityaPal/dnafrag | f9703ac84c740e122cb07c5e4c6f7b871ac1b0ee | [
"BSD-3-Clause"
] | null | null | null | dnafrag/tests/test_vplot_end_to_end.py | DebadityaPal/dnafrag | f9703ac84c740e122cb07c5e4c6f7b871ac1b0ee | [
"BSD-3-Clause"
] | null | null | null | import os
import numpy as np
import dnafrag
MODULE_BASE_PATH = os.path.abspath(os.path.dirname(dnafrag.__file__))
FRAGBED_PATH = os.path.join(MODULE_BASE_PATH, "tests/test_fragbed_100k.fragbed.gz")
CHRSZ_PATH = os.path.join(MODULE_BASE_PATH, "tests/test_fragbed_hg19.chrom.sizes")
def test_vplot_end_to_end(tmpdir):
dest = os.path.join(tmpdir, "100kfragbed_array")
assert not os.path.exists(dest)
run_extract = "dnafrag-from-fragbed {} {} {}".format(FRAGBED_PATH, dest, CHRSZ_PATH)
os.system(run_extract)
assert os.path.isdir(dest)
data = dnafrag.load(dest)
assert len(data.keys()) == 1
assert "chr1" in data.keys()
data = data["chr1"]
assert data[0, 0]["v"].shape[0] == 0
assert data[:1000, :1000]["v"].shape[0] == 0
assert data[:, :]["v"].sum() == 100000
assert data[0, 0]["v"].shape[0] == 0
assert data[:1000, :1000]["v"].shape[0] == 0
| 25.942857 | 88 | 0.665198 | import os
import numpy as np
import dnafrag
MODULE_BASE_PATH = os.path.abspath(os.path.dirname(dnafrag.__file__))
FRAGBED_PATH = os.path.join(MODULE_BASE_PATH, "tests/test_fragbed_100k.fragbed.gz")
CHRSZ_PATH = os.path.join(MODULE_BASE_PATH, "tests/test_fragbed_hg19.chrom.sizes")
def test_vplot_end_to_end(tmpdir):
dest = os.path.join(tmpdir, "100kfragbed_array")
assert not os.path.exists(dest)
run_extract = "dnafrag-from-fragbed {} {} {}".format(FRAGBED_PATH, dest, CHRSZ_PATH)
os.system(run_extract)
assert os.path.isdir(dest)
data = dnafrag.load(dest)
assert len(data.keys()) == 1
assert "chr1" in data.keys()
data = data["chr1"]
assert data[0, 0]["v"].shape[0] == 0
assert data[:1000, :1000]["v"].shape[0] == 0
assert data[:, :]["v"].sum() == 100000
assert data[0, 0]["v"].shape[0] == 0
assert data[:1000, :1000]["v"].shape[0] == 0
| true | true |
f7f738a5e023eec6d4eec09d9dfdcba6df63c765 | 1,141 | py | Python | hard-gists/777789/snippet.py | jjhenkel/dockerizeme | eaa4fe5366f6b9adf74399eab01c712cacaeb279 | [
"Apache-2.0"
] | 21 | 2019-07-08T08:26:45.000Z | 2022-01-24T23:53:25.000Z | hard-gists/777789/snippet.py | jjhenkel/dockerizeme | eaa4fe5366f6b9adf74399eab01c712cacaeb279 | [
"Apache-2.0"
] | 5 | 2019-06-15T14:47:47.000Z | 2022-02-26T05:02:56.000Z | hard-gists/777789/snippet.py | jjhenkel/dockerizeme | eaa4fe5366f6b9adf74399eab01c712cacaeb279 | [
"Apache-2.0"
] | 17 | 2019-05-16T03:50:34.000Z | 2021-01-14T14:35:12.000Z | # -*- coding:utf-8 -*-
import re
import urllib2
from lib.BeautifulSoup import BeautifulSoup
agent="""Sosospider+(+http://help.soso.com/webspider.htm)"""
blog_url = 'http://blog.sina.com.cn/s/articlelist_1517582220_0_1.html'
spider_handle = urllib2.urlopen(blog_url)
blog_content = spider_handle.read()
soup = BeautifulSoup(blog_content, fromEncoding='utf-8')
item_list = soup.findAll('span', {'class':'atc_title'})
urls = ['http://blog.csdn.net/heiyeshuwu/archive/2010/12/19/6085876.aspx']
#for item in item_list:
# urls.append(item.a['href'])
for url in urls:
request = urllib2.Request(url)
request.add_header('User-Agent', agent)
handle = urllib2.urlopen(request).read()
article_soup = BeautifulSoup(handle, fromEncoding='utf-8')
title = article_soup.find('h1',{'class':'title_txt'})
content = article_soup.find('div',{'id':'sina_keyword_ad_area2'})
# tmp = []
# for c in content.contents:
# print type(c)
# tmp.append(c.__str__('utf-8'))
print url
print title.contents
print title.contents[2].replace('\t', '').replace('\r\n', '')
# print ''.join(tmp)
exit()
| 33.558824 | 74 | 0.675723 |
import re
import urllib2
from lib.BeautifulSoup import BeautifulSoup
agent="""Sosospider+(+http://help.soso.com/webspider.htm)"""
blog_url = 'http://blog.sina.com.cn/s/articlelist_1517582220_0_1.html'
spider_handle = urllib2.urlopen(blog_url)
blog_content = spider_handle.read()
soup = BeautifulSoup(blog_content, fromEncoding='utf-8')
item_list = soup.findAll('span', {'class':'atc_title'})
urls = ['http://blog.csdn.net/heiyeshuwu/archive/2010/12/19/6085876.aspx']
for url in urls:
request = urllib2.Request(url)
request.add_header('User-Agent', agent)
handle = urllib2.urlopen(request).read()
article_soup = BeautifulSoup(handle, fromEncoding='utf-8')
title = article_soup.find('h1',{'class':'title_txt'})
content = article_soup.find('div',{'id':'sina_keyword_ad_area2'})
print url
print title.contents
print title.contents[2].replace('\t', '').replace('\r\n', '')
exit()
| false | true |
f7f738e8584f0ec5c8b3d8c314118027dfd488de | 2,215 | bzl | Python | deps/core/repository.bzl | y0psolo/YAD | 0f1f9c5140687345dee591667793d6f8ed6e29e5 | [
"Apache-2.0"
] | 1 | 2021-11-05T09:13:57.000Z | 2021-11-05T09:13:57.000Z | deps/core/repository.bzl | y0psolo/YAD | 0f1f9c5140687345dee591667793d6f8ed6e29e5 | [
"Apache-2.0"
] | 9 | 2021-12-02T13:25:52.000Z | 2022-01-26T14:24:05.000Z | deps/core/repository.bzl | y0psolo/YAD | 0f1f9c5140687345dee591667793d6f8ed6e29e5 | [
"Apache-2.0"
] | null | null | null | load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file")
load(":ubuntu_focal_amd64.bzl", "ubuntu_focal_amd64")
load(":ubuntu_focal_arm64.bzl", "ubuntu_focal_arm64")
load(":ubuntu_bionic_amd64.bzl", "ubuntu_bionic_amd64")
load(":ubuntu_bionic_arm64.bzl", "ubuntu_bionic_arm64")
def core_repository():
# Ubuntu key
http_file(
name = "ubuntu_focal_key",
sha256 = "10d6c8ab5ea4ef4f5fc7b9ff7aaf2d61d825cea57ac0124b76eb908ca6acd712",
urls = ["https://keyserver.ubuntu.com/pks/lookup?op=get&search=0xf6ecb3762474eda9d21b7022871920d1991bc93c"],
)
# Ubuntu key
http_file(
name = "ubuntu_bionic_key",
sha256 = "0a81ec85f5abd4ff15a51565382e5ca3e0d7dca7fbf853eb2de9519429945e1b",
urls = ["https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x790bc7277767219c42c86f933b4fe6acc0b21f32"],
)
ubuntu_focal_amd64()
ubuntu_focal_arm64()
ubuntu_bionic_amd64()
ubuntu_bionic_arm64()
# Tini executable
http_file(
name = "tini_amd64",
downloaded_file_path = "tini",
executable = True,
sha256 = "93dcc18adc78c65a028a84799ecf8ad40c936fdfc5f2a57b1acda5a8117fa82c",
urls = ["https://github.com/krallin/tini/releases/download/v0.19.0/tini-amd64"],
)
http_file(
name = "tini_arm64",
downloaded_file_path = "tini",
executable = True,
sha256 = "07952557df20bfd2a95f9bef198b445e006171969499a1d361bd9e6f8e5e0e81",
urls = ["https://github.com/krallin/tini/releases/download/v0.19.0/tini-arm64"],
)
# Get Busybox
http_file(
name = "busybox_amd64",
downloaded_file_path = "busybox",
executable = True,
sha256 = "51fcb60efbdf3e579550e9ab893730df56b33d0cc928a2a6467bd846cdfef7d8",
urls = ["https://busybox.net/downloads/binaries/1.31.0-defconfig-multiarch-musl/busybox-x86_64"],
)
http_file(
name = "busybox_arm64",
downloaded_file_path = "busybox",
executable = True,
sha256 = "141adb1b625a6f44c4b114f76b4387b4ea4f7ab802b88eb40e0d2f6adcccb1c3",
urls = ["https://busybox.net/downloads/binaries/1.31.0-defconfig-multiarch-musl/busybox-armv8l"],
)
| 36.916667 | 116 | 0.695711 | load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file")
load(":ubuntu_focal_amd64.bzl", "ubuntu_focal_amd64")
load(":ubuntu_focal_arm64.bzl", "ubuntu_focal_arm64")
load(":ubuntu_bionic_amd64.bzl", "ubuntu_bionic_amd64")
load(":ubuntu_bionic_arm64.bzl", "ubuntu_bionic_arm64")
def core_repository():
http_file(
name = "ubuntu_focal_key",
sha256 = "10d6c8ab5ea4ef4f5fc7b9ff7aaf2d61d825cea57ac0124b76eb908ca6acd712",
urls = ["https://keyserver.ubuntu.com/pks/lookup?op=get&search=0xf6ecb3762474eda9d21b7022871920d1991bc93c"],
)
http_file(
name = "ubuntu_bionic_key",
sha256 = "0a81ec85f5abd4ff15a51565382e5ca3e0d7dca7fbf853eb2de9519429945e1b",
urls = ["https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x790bc7277767219c42c86f933b4fe6acc0b21f32"],
)
ubuntu_focal_amd64()
ubuntu_focal_arm64()
ubuntu_bionic_amd64()
ubuntu_bionic_arm64()
http_file(
name = "tini_amd64",
downloaded_file_path = "tini",
executable = True,
sha256 = "93dcc18adc78c65a028a84799ecf8ad40c936fdfc5f2a57b1acda5a8117fa82c",
urls = ["https://github.com/krallin/tini/releases/download/v0.19.0/tini-amd64"],
)
http_file(
name = "tini_arm64",
downloaded_file_path = "tini",
executable = True,
sha256 = "07952557df20bfd2a95f9bef198b445e006171969499a1d361bd9e6f8e5e0e81",
urls = ["https://github.com/krallin/tini/releases/download/v0.19.0/tini-arm64"],
)
http_file(
name = "busybox_amd64",
downloaded_file_path = "busybox",
executable = True,
sha256 = "51fcb60efbdf3e579550e9ab893730df56b33d0cc928a2a6467bd846cdfef7d8",
urls = ["https://busybox.net/downloads/binaries/1.31.0-defconfig-multiarch-musl/busybox-x86_64"],
)
http_file(
name = "busybox_arm64",
downloaded_file_path = "busybox",
executable = True,
sha256 = "141adb1b625a6f44c4b114f76b4387b4ea4f7ab802b88eb40e0d2f6adcccb1c3",
urls = ["https://busybox.net/downloads/binaries/1.31.0-defconfig-multiarch-musl/busybox-armv8l"],
)
| true | true |
f7f7390e07b6cc7e6cd311651787c896d95584ec | 5,544 | py | Python | oauth_dropins/medium.py | ravenscroftj/oauth-dropins | 59cc4bfc8157142249c5eb561b1f665da560e6c1 | [
"Unlicense"
] | null | null | null | oauth_dropins/medium.py | ravenscroftj/oauth-dropins | 59cc4bfc8157142249c5eb561b1f665da560e6c1 | [
"Unlicense"
] | null | null | null | oauth_dropins/medium.py | ravenscroftj/oauth-dropins | 59cc4bfc8157142249c5eb561b1f665da560e6c1 | [
"Unlicense"
] | null | null | null | """Medium OAuth drop-in.
API docs:
https://github.com/Medium/medium-api-docs#contents
https://medium.com/developers/welcome-to-the-medium-api-3418f956552
Medium doesn't let you use a localhost redirect URL. :/ A common workaround is
to map an arbitrary host to localhost in your /etc/hosts, e.g.:
127.0.0.1 my.dev.com
You can then test on your local machine by running dev_appserver and opening
http://my.dev.com:8080/ instead of http://localhost:8080/ .
"""
import logging
import urllib.parse
from flask import request
from google.cloud import ndb
from . import views
from .models import BaseAuth
from .webutil import flask_util, util
from .webutil.util import json_dumps, json_loads
MEDIUM_CLIENT_ID = util.read('medium_client_id')
MEDIUM_CLIENT_SECRET = util.read('medium_client_secret')
# medium is behind cloudflare, which often blocks requests's user agent, so set
# our own.
USER_AGENT = 'oauth-dropins (https://oauth-dropins.appspot.com/)'
# URL templates. Can't (easily) use urlencode() because I want to keep the
# %(...)s placeholders as is and fill them in later in code.
GET_AUTH_CODE_URL = '&'.join((
'https://medium.com/m/oauth/authorize?'
'client_id=%(client_id)s',
# https://github.com/Medium/medium-api-docs#user-content-21-browser-based-authentication
# basicProfile, listPublications, publishPost, uploadImage
'scope=%(scope)s',
# redirect_uri here must be the same in the access token request!
'redirect_uri=%(redirect_uri)s',
'state=%(state)s',
'response_type=code',
))
API_BASE = 'https://api.medium.com/v1/'
GET_ACCESS_TOKEN_URL = API_BASE + 'tokens'
API_USER_URL = API_BASE + 'me'
class MediumAuth(BaseAuth):
"""An authenticated Medium user.
Provides methods that return information about this user and make OAuth-signed
requests to the Medium REST API. Stores OAuth credentials in the datastore.
See models.BaseAuth for usage details.
Medium-specific details: implements get() but not urlopen() or api().
The key name is the user id (*not* username).
"""
access_token_str = ndb.StringProperty(required=True)
user_json = ndb.TextProperty()
# used by bridgy in
# https://github.com/snarfed/bridgy/commit/58cce60790e746d300e7e5dac331543c56bd9108
# background: https://github.com/snarfed/bridgy/issues/506
publications_json = ndb.TextProperty()
def site_name(self):
return 'Medium'
def user_display_name(self):
"""Returns the user's full name or username.
"""
if self.user_json:
data = json_loads(self.user_json).get('data')
if data:
return data.get('name') or data.get('username')
return self.key_id()
def access_token(self):
"""Returns the OAuth access token string.
"""
return self.access_token_str
def get(self, *args, **kwargs):
"""Wraps requests.get() and adds the Bearer token header.
"""
headers = kwargs.setdefault('headers', {})
headers['Authorization'] = 'Bearer ' + self.access_token_str
headers.setdefault('User-Agent', USER_AGENT)
resp = util.requests_get(*args, **kwargs)
try:
resp.raise_for_status()
except BaseException as e:
util.interpret_http_exception(e)
raise
return resp
class Start(views.Start):
"""Starts Medium auth. Requests an auth code and expects a redirect back.
"""
NAME = 'medium'
LABEL = 'Medium'
DEFAULT_SCOPE = 'basicProfile'
def redirect_url(self, state=None):
assert MEDIUM_CLIENT_ID and MEDIUM_CLIENT_SECRET, \
"Please fill in the medium_client_id and medium_client_secret files in your app's root directory."
return GET_AUTH_CODE_URL % {
'client_id': MEDIUM_CLIENT_ID,
'redirect_uri': urllib.parse.quote_plus(self.to_url()),
# Medium requires non-empty state
'state': urllib.parse.quote_plus(state or 'unused'),
'scope': self.scope,
}
class Callback(views.Callback):
"""The OAuth callback. Fetches an access token and stores it.
"""
def dispatch_request(self):
# handle errors
error = request.values.get('error')
if error:
if error == 'access_denied':
logging.info('User declined')
return self.finish(None, state=request.values.get('state'))
else:
flask_util.error(error)
# extract auth code and request access token
auth_code = request.values['code']
data = {
'code': auth_code,
'client_id': MEDIUM_CLIENT_ID,
'client_secret': MEDIUM_CLIENT_SECRET,
# redirect_uri here must be the same in the oauth code request!
# (the value here doesn't actually matter since it's requested server side.)
'redirect_uri': request.base_url,
'grant_type': 'authorization_code',
}
resp = util.requests_post(GET_ACCESS_TOKEN_URL, data=data,
headers={'User-Agent': USER_AGENT})
resp.raise_for_status()
logging.debug(f'Access token response: {resp.text}')
try:
resp = json_loads(resp.text)
except:
logging.error('Could not decode JSON', exc_info=True)
raise
errors = resp.get('errors') or resp.get('error')
if errors:
logging.info(f'Errors: {errors}')
flask_util.error(errors[0].get('message'))
# TODO: handle refresh token
access_token = resp['access_token']
user_json = MediumAuth(access_token_str=access_token).get(API_USER_URL).text
id = json_loads(user_json)['data']['id']
auth = MediumAuth(id=id, access_token_str=access_token, user_json=user_json)
auth.put()
return self.finish(auth, state=request.values.get('state'))
| 32.421053 | 104 | 0.701659 | import logging
import urllib.parse
from flask import request
from google.cloud import ndb
from . import views
from .models import BaseAuth
from .webutil import flask_util, util
from .webutil.util import json_dumps, json_loads
MEDIUM_CLIENT_ID = util.read('medium_client_id')
MEDIUM_CLIENT_SECRET = util.read('medium_client_secret')
# our own.
USER_AGENT = 'oauth-dropins (https://oauth-dropins.appspot.com/)'
# URL templates. Can't (easily) use urlencode() because I want to keep the
GET_AUTH_CODE_URL = '&'.join((
'https://medium.com/m/oauth/authorize?'
'client_id=%(client_id)s',
(redirect_uri)s',
'state=%(state)s',
'response_type=code',
))
API_BASE = 'https://api.medium.com/v1/'
GET_ACCESS_TOKEN_URL = API_BASE + 'tokens'
API_USER_URL = API_BASE + 'me'
class MediumAuth(BaseAuth):
access_token_str = ndb.StringProperty(required=True)
user_json = ndb.TextProperty()
publications_json = ndb.TextProperty()
def site_name(self):
return 'Medium'
def user_display_name(self):
if self.user_json:
data = json_loads(self.user_json).get('data')
if data:
return data.get('name') or data.get('username')
return self.key_id()
def access_token(self):
return self.access_token_str
def get(self, *args, **kwargs):
headers = kwargs.setdefault('headers', {})
headers['Authorization'] = 'Bearer ' + self.access_token_str
headers.setdefault('User-Agent', USER_AGENT)
resp = util.requests_get(*args, **kwargs)
try:
resp.raise_for_status()
except BaseException as e:
util.interpret_http_exception(e)
raise
return resp
class Start(views.Start):
NAME = 'medium'
LABEL = 'Medium'
DEFAULT_SCOPE = 'basicProfile'
def redirect_url(self, state=None):
assert MEDIUM_CLIENT_ID and MEDIUM_CLIENT_SECRET, \
"Please fill in the medium_client_id and medium_client_secret files in your app's root directory."
return GET_AUTH_CODE_URL % {
'client_id': MEDIUM_CLIENT_ID,
'redirect_uri': urllib.parse.quote_plus(self.to_url()),
# Medium requires non-empty state
'state': urllib.parse.quote_plus(state or 'unused'),
'scope': self.scope,
}
class Callback(views.Callback):
def dispatch_request(self):
# handle errors
error = request.values.get('error')
if error:
if error == 'access_denied':
logging.info('User declined')
return self.finish(None, state=request.values.get('state'))
else:
flask_util.error(error)
# extract auth code and request access token
auth_code = request.values['code']
data = {
'code': auth_code,
'client_id': MEDIUM_CLIENT_ID,
'client_secret': MEDIUM_CLIENT_SECRET,
# redirect_uri here must be the same in the oauth code request!
# (the value here doesn't actually matter since it's requested server side.)
'redirect_uri': request.base_url,
'grant_type': 'authorization_code',
}
resp = util.requests_post(GET_ACCESS_TOKEN_URL, data=data,
headers={'User-Agent': USER_AGENT})
resp.raise_for_status()
logging.debug(f'Access token response: {resp.text}')
try:
resp = json_loads(resp.text)
except:
logging.error('Could not decode JSON', exc_info=True)
raise
errors = resp.get('errors') or resp.get('error')
if errors:
logging.info(f'Errors: {errors}')
flask_util.error(errors[0].get('message'))
# TODO: handle refresh token
access_token = resp['access_token']
user_json = MediumAuth(access_token_str=access_token).get(API_USER_URL).text
id = json_loads(user_json)['data']['id']
auth = MediumAuth(id=id, access_token_str=access_token, user_json=user_json)
auth.put()
return self.finish(auth, state=request.values.get('state'))
| true | true |
f7f7394e504d7d329c52bef00fe2a3781ebcba3a | 7,265 | py | Python | bigbench/models/json_rpc_model.py | dimmollo/BIG-bench | f0dffeb4f16ef5489686a81e2d63362d251cda3e | [
"Apache-2.0"
] | null | null | null | bigbench/models/json_rpc_model.py | dimmollo/BIG-bench | f0dffeb4f16ef5489686a81e2d63362d251cda3e | [
"Apache-2.0"
] | null | null | null | bigbench/models/json_rpc_model.py | dimmollo/BIG-bench | f0dffeb4f16ef5489686a81e2d63362d251cda3e | [
"Apache-2.0"
] | null | null | null | """JSON-rpc proxy model for BIG-Bench."""
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from typing import Optional, Any, Dict, Union, List
import urllib.parse
import uuid
import bigbench.api.model as model
import requests
import requests_unixsocket
import time
_RPC_VERSION = '2.0'
_INET_URL_PREFIX = 'http://'
_UNIX_URL_PREFIX = 'http+unix://'
_MAX_RETRIES = 8
_RETRY_DELAY_SEC = 10
class JsonRpcModel(model.Model):
"""A BIGBench api-compatible json-rpc interface.
Attributes:
model_name: name of model
url: json rpc url
"""
def __init__(
self,
model_name: str,
host: Optional[str] = None,
port: Optional[int] = None,
socket_path: Optional[str] = None,
):
"""Initializes instance.
Either host+port or socket_path must be specified.
Args:
model_name: name of model
host: hostname for inet connections
port: port number for inet connections
socket_path: path to socket for unix-domain socket connections
Raises:
ValueError if host+port or socket_path is not set
"""
if socket_path is None:
if host is None or port is None:
raise ValueError('either host+port or socket_path must be specified')
self.url = f'{_INET_URL_PREFIX}{host}:{port}/jsonrpc'
else:
abs_socket_path = os.path.abspath(os.path.expanduser(socket_path))
encoded_path = urllib.parse.quote_plus(abs_socket_path)
self.url = f'{_UNIX_URL_PREFIX}{encoded_path}/jsonrpc'
self.model_name = model_name
def _post(self, payload: Dict[str, Any]) -> Optional[Any]:
"""Posts request to server.
Args:
payload: dictionary containing rpc params
Returns:
result from rpc call
Raises:
RuntimeError: An error from the server.
HTTPError: An error communicating with server.
"""
for i in range(_MAX_RETRIES):
if self.url.startswith(_UNIX_URL_PREFIX):
with requests_unixsocket.monkeypatch():
response = requests.post(self.url, json=payload)
else:
response = requests.post(self.url, json=payload)
if response.status_code != requests.codes.ok:
#response.raise_for_status()
print(f'error from server: {response}')
time.sleep(_RETRY_DELAY_SEC)
continue
json_response = response.json()
if 'result' not in json_response:
#raise RuntimeError(f'response from server: {json_response}')
print(f'error: bad response from server: {json_response}')
time.sleep(_RETRY_DELAY_SEC)
continue
#print(f'response:\n{json_response["result"]}')
return json_response['result']
raise RuntimeError(f'error: retry count exceeded')
def _payload(self, method: str, params: Dict[str, Any]) -> Dict[str, Any]:
"""Generates payload dictionary for rpc call.
Args:
method: rpc method name
params: parameter dictonary for rpc call
Returns:
json-serializable payload dictionary
"""
return {
'method': method,
'params': {**params, 'model_name': self.model_name},
'jsonrpc': _RPC_VERSION,
'id': uuid.uuid1().int,
}
def generate_text(
self,
inputs: Union[str, List[str]],
max_length: Optional[int] = None,
stop_string: Optional[str] = None,
output_regex: Optional[str] = None,
) -> Union[str, List[str]]:
"""Generates and returns outputs from language model.
Args:
inputs: String or list of input strings.
max_length: Maximum output length, if None, limited only by model max
output length
stop_string: If specified, model output will be truncated to the shortest
string which includes stop_string.
output_regex: If specified, the first match to the python regular
expression output_regex in the model output will be returned. If there
is no match, an empty string will be returned.
Returns:
list of lists (of length=num_outputs) with generated responses
Raises:
RuntimeError: An error from the server.
HTTPError: An error communicating with the server.
"""
return self._post(
self._payload(
method='generate_text',
params={
'inputs': inputs,
'max_length': max_length,
'stop_string': stop_string,
'output_regex': output_regex,
}))
def cond_log_prob(
self,
inputs: Union[str, List[str]],
targets: Union[List[str], List[List[str]]],
absolute_normalization: Optional[bool] = False,
) -> Union[List[float], List[List[float]]]:
"""Computes conditional log probabilities of targets given inputs.
Args:
inputs: A single string input or a list of string inputs.
targets: Possible string outputs for each input. If input is a string,
this is a list `[t_1, t_2, ..., t_n]` of possible string outputs. If
input is a list of strings, then this is a nested list `[[t_1, t_2, ...,
t_n], ...]` with length equal to `len(inputs)`.
absolute_normalization: When True, the function returns the log
probability of unconstrained generation or the target sequence. When
False (default), log probabilities are normalized so that the
probabilities of generating `targets` sum to 1. Note that setting
`absolute_normalization` to True restricts the class of models that can
be evaluated to those that can assign absolute probabilities to
sequences.
Returns:
If a single string input is provided, returns a list of
log-probabilities `[lp_1, lp_2, ..., lp_n]` predicted by the model,
where `lp_i = log(prob(t_i | input)` is the conditional log-prob
to generate target `t_i` given input. If a list of string inputs
was provided, returns a list of such elements of the form
`[[lp_1, lp_2, ..., lp_n], ...]`, where each element contains the
log-probabilities for the corresponding input and targets.
In this case, the length of the returned list is `len(input)`.
If conditional probabilities are not supported by the model, the
model returns None.
Raises:
RuntimeError: An error from the server.
HTTPError: An error communicating with the server.
"""
return self._post(
self._payload(
method='cond_log_prob',
params={
'inputs': inputs,
'targets': targets,
'absolute_normalization': absolute_normalization,
}))
def shutdown_server(self) -> None:
"""Shuts down remote proxy server gracefully."""
self._post(self._payload(method='shutdown', params={}))
| 33.634259 | 80 | 0.662354 |
import os
from typing import Optional, Any, Dict, Union, List
import urllib.parse
import uuid
import bigbench.api.model as model
import requests
import requests_unixsocket
import time
_RPC_VERSION = '2.0'
_INET_URL_PREFIX = 'http://'
_UNIX_URL_PREFIX = 'http+unix://'
_MAX_RETRIES = 8
_RETRY_DELAY_SEC = 10
class JsonRpcModel(model.Model):
def __init__(
self,
model_name: str,
host: Optional[str] = None,
port: Optional[int] = None,
socket_path: Optional[str] = None,
):
if socket_path is None:
if host is None or port is None:
raise ValueError('either host+port or socket_path must be specified')
self.url = f'{_INET_URL_PREFIX}{host}:{port}/jsonrpc'
else:
abs_socket_path = os.path.abspath(os.path.expanduser(socket_path))
encoded_path = urllib.parse.quote_plus(abs_socket_path)
self.url = f'{_UNIX_URL_PREFIX}{encoded_path}/jsonrpc'
self.model_name = model_name
def _post(self, payload: Dict[str, Any]) -> Optional[Any]:
for i in range(_MAX_RETRIES):
if self.url.startswith(_UNIX_URL_PREFIX):
with requests_unixsocket.monkeypatch():
response = requests.post(self.url, json=payload)
else:
response = requests.post(self.url, json=payload)
if response.status_code != requests.codes.ok:
print(f'error from server: {response}')
time.sleep(_RETRY_DELAY_SEC)
continue
json_response = response.json()
if 'result' not in json_response:
print(f'error: bad response from server: {json_response}')
time.sleep(_RETRY_DELAY_SEC)
continue
return json_response['result']
raise RuntimeError(f'error: retry count exceeded')
def _payload(self, method: str, params: Dict[str, Any]) -> Dict[str, Any]:
return {
'method': method,
'params': {**params, 'model_name': self.model_name},
'jsonrpc': _RPC_VERSION,
'id': uuid.uuid1().int,
}
def generate_text(
self,
inputs: Union[str, List[str]],
max_length: Optional[int] = None,
stop_string: Optional[str] = None,
output_regex: Optional[str] = None,
) -> Union[str, List[str]]:
return self._post(
self._payload(
method='generate_text',
params={
'inputs': inputs,
'max_length': max_length,
'stop_string': stop_string,
'output_regex': output_regex,
}))
def cond_log_prob(
self,
inputs: Union[str, List[str]],
targets: Union[List[str], List[List[str]]],
absolute_normalization: Optional[bool] = False,
) -> Union[List[float], List[List[float]]]:
return self._post(
self._payload(
method='cond_log_prob',
params={
'inputs': inputs,
'targets': targets,
'absolute_normalization': absolute_normalization,
}))
def shutdown_server(self) -> None:
self._post(self._payload(method='shutdown', params={}))
| true | true |
f7f73a40647537ff77146cae81c85a1e916c601b | 627 | py | Python | home/migrations/0001_initial.py | VSevagen/ProctOS | a34124b0a5d152e30c064c8ed801e7af894eb04a | [
"MIT"
] | null | null | null | home/migrations/0001_initial.py | VSevagen/ProctOS | a34124b0a5d152e30c064c8ed801e7af894eb04a | [
"MIT"
] | null | null | null | home/migrations/0001_initial.py | VSevagen/ProctOS | a34124b0a5d152e30c064c8ed801e7af894eb04a | [
"MIT"
] | null | null | null | # Generated by Django 2.1.7 on 2019-04-06 16:47
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='UserProfile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('email', models.EmailField(max_length=30, unique=True)),
('password', models.CharField(max_length=15)),
('name', models.CharField(max_length=30)),
],
),
]
| 26.125 | 114 | 0.575758 |
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='UserProfile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('email', models.EmailField(max_length=30, unique=True)),
('password', models.CharField(max_length=15)),
('name', models.CharField(max_length=30)),
],
),
]
| true | true |
f7f73b2e0b65aaa27677c44b8ec7c97509604f5f | 8,595 | py | Python | experiments/experiment_base_original.py | Emmyphung/flexible-input-slu | a2c7fff640b2b4aec830f3ca1b447c28dc506bb4 | [
"Apache-2.0"
] | null | null | null | experiments/experiment_base_original.py | Emmyphung/flexible-input-slu | a2c7fff640b2b4aec830f3ca1b447c28dc506bb4 | [
"Apache-2.0"
] | null | null | null | experiments/experiment_base_original.py | Emmyphung/flexible-input-slu | a2c7fff640b2b4aec830f3ca1b447c28dc506bb4 | [
"Apache-2.0"
] | null | null | null | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import torch
import numpy as np
from utils.utils import AverageMeter
from tqdm import tqdm
# from utils.visualize import plot_confusion_matrix
from sklearn.metrics import confusion_matrix
class ExperimentRunnerBase:
def __init__(self, args):
# Set the LR Scheduler and Loss Parameters
if args.scheduler == 'plateau':
self.scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(self.optimizer,
factor=0.5,
patience=3,
mode='max',
verbose=True)
elif args.scheduler == 'cycle':
self.scheduler = torch.optim.lr_scheduler.OneCycleLR(self.optimizer,
max_lr=args.learning_rate,
steps_per_epoch=len(self.train_loader),
epochs=args.num_epochs)
self.criterion = torch.nn.CrossEntropyLoss()
self.visualize = args.visualize
if self.visualize:
print("if visualize is true this line will run")
from torch.utils.tensorboard import SummaryWriter
self.writer = SummaryWriter()
# Training specific params
self.args = args
self.num_epochs = args.num_epochs
self.print_every = args.print_every
self.val_every = args.val_every
self.model_dir = args.model_dir
self.save_every = args.save_every
def train(self):
# Setting the variables before starting the training
avg_train_loss = AverageMeter()
avg_train_acc = AverageMeter()
best_val_acc = -np.inf
for epoch in range(self.num_epochs):
avg_train_loss.reset()
avg_train_acc.reset()
# Mini batch loop
for batch_idx, batch in enumerate(tqdm(self.train_loader)):
step = epoch * len(self.train_loader) + batch_idx
# Get the model output for the batch and update the loss and accuracy meters
train_loss, train_acc = self.train_step(batch)
if self.args.scheduler == 'cycle':
self.scheduler.step()
avg_train_loss.update([train_loss.item()])
avg_train_acc.update([train_acc])
# Save the step checkpoint if needed
# if step % self.save_every == 0:
# step_chkpt_path = os.path.join(self.model_dir,
# 'step_chkpt_{}_{}.pth'.format(epoch, step))
# print("Saving the model checkpoint for epoch {} at step {}".format(epoch, step))
# torch.save(self.model.state_dict(), step_chkpt_path)
# Logging and validation check
if step % self.print_every == 0:
print('Epoch {}, batch {}, step {}, '
'loss = {:.4f}, acc = {:.4f}, '
'running averages: loss = {:.4f}, acc = {:.4f}'.format(epoch,
batch_idx,
step,
train_loss.item(),
train_acc,
avg_train_loss.get(),
avg_train_acc.get()))
if step % self.val_every == 0:
val_loss, val_acc = self.val()
print('Val acc = {:.4f}, Val loss = {:.4f}'.format(val_acc, val_loss))
if self.visualize:
self.writer.add_scalar('Val/loss', val_loss, step)
self.writer.add_scalar('Val/acc', val_acc, step)
# Update the save the best validation checkpoint if needed
if val_acc > best_val_acc:
best_val_acc = val_acc
best_chkpt_path = os.path.join(self.model_dir,
'best_ckpt.pth')
torch.save(self.model.state_dict(), best_chkpt_path)
if self.args.scheduler == 'plateau':
self.scheduler.step(val_acc)
if self.visualize:
# Log data to
self.writer.add_scalar('Train/loss', train_loss.item(), step)
self.writer.add_scalar('Train/acc', train_acc, step)
def compute_loss(self, batch):
""" This function is specific to the kind of model we are training and must be implemented """
raise NotImplementedError
def train_step(self, batch):
self.model.train()
self.optimizer.zero_grad()
metrics = self.compute_loss(batch)
metrics['loss'].backward()
self.optimizer.step()
return metrics['loss'], metrics['accuracy']
def load_model_for_eval(self):
chkpt_path = os.path.join(self.model_dir, 'best_ckpt.pth') \
if self.args.eval_checkpoint_path is None else self.args.eval_checkpoint_path
self.model.load_state_dict(torch.load(chkpt_path))
self.model.eval()
@torch.no_grad()
def val(self):
print('VALIDATING:')
avg_val_loss = AverageMeter()
avg_val_acc = AverageMeter()
self.model.eval()
for batch_idx, batch in enumerate(tqdm(self.val_loader)):
metrics = self.compute_loss(batch)
avg_val_acc.update(metrics['correct'].cpu().numpy())
avg_val_loss.update([metrics['loss']])
return avg_val_loss.get(), avg_val_acc.get()
@torch.no_grad()
def infer(self):
self.load_model_for_eval()
avg_test_loss = AverageMeter()
avg_test_acc = AverageMeter()
all_true_labels = []
all_pred_labels = []
all_audio_embeddings = []
all_text_embeddings = []
for batch_idx, batch in enumerate(tqdm(self.test_loader)):
# Get the model output and update the meters
output = self.compute_loss(batch)
avg_test_acc.update(output['correct'].cpu().numpy())
avg_test_loss.update([output['loss']])
# Store the Predictions
all_true_labels.append(batch['label'].cpu())
all_pred_labels.append(output['predicted'].cpu())
all_audio_embeddings.append(output['model_output']['audio_embed'].cpu())
all_text_embeddings.append(output['model_output']['text_embed'].cpu())
# Collect the predictions and embeddings for the full set
all_true_labels = torch.cat(all_true_labels).numpy()
all_pred_labels = torch.cat(all_pred_labels).numpy()
all_audio_embeddings = torch.cat(all_audio_embeddings).numpy()
all_text_embeddings = torch.cat(all_text_embeddings).numpy()
# Save the embeddings and plot the confusion matrix
np.savez_compressed('embeddings.npz',
audio=all_audio_embeddings,
text=all_text_embeddings,
labels=all_true_labels)
# cm = confusion_matrix(all_true_labels, all_pred_labels)
# plot_confusion_matrix(cm, self.test_loader.dataset.labels_list(), normalize=True)
print('Final test acc = {:.4f}, test loss = {:.4f}'.format(avg_test_acc.get(), avg_test_loss.get()))
return avg_test_loss.get(), avg_test_acc.get()
| 46.967213 | 108 | 0.54078 |
import os
import torch
import numpy as np
from utils.utils import AverageMeter
from tqdm import tqdm
from sklearn.metrics import confusion_matrix
class ExperimentRunnerBase:
def __init__(self, args):
if args.scheduler == 'plateau':
self.scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(self.optimizer,
factor=0.5,
patience=3,
mode='max',
verbose=True)
elif args.scheduler == 'cycle':
self.scheduler = torch.optim.lr_scheduler.OneCycleLR(self.optimizer,
max_lr=args.learning_rate,
steps_per_epoch=len(self.train_loader),
epochs=args.num_epochs)
self.criterion = torch.nn.CrossEntropyLoss()
self.visualize = args.visualize
if self.visualize:
print("if visualize is true this line will run")
from torch.utils.tensorboard import SummaryWriter
self.writer = SummaryWriter()
self.args = args
self.num_epochs = args.num_epochs
self.print_every = args.print_every
self.val_every = args.val_every
self.model_dir = args.model_dir
self.save_every = args.save_every
def train(self):
avg_train_loss = AverageMeter()
avg_train_acc = AverageMeter()
best_val_acc = -np.inf
for epoch in range(self.num_epochs):
avg_train_loss.reset()
avg_train_acc.reset()
for batch_idx, batch in enumerate(tqdm(self.train_loader)):
step = epoch * len(self.train_loader) + batch_idx
train_loss, train_acc = self.train_step(batch)
if self.args.scheduler == 'cycle':
self.scheduler.step()
avg_train_loss.update([train_loss.item()])
avg_train_acc.update([train_acc])
if step % self.print_every == 0:
print('Epoch {}, batch {}, step {}, '
'loss = {:.4f}, acc = {:.4f}, '
'running averages: loss = {:.4f}, acc = {:.4f}'.format(epoch,
batch_idx,
step,
train_loss.item(),
train_acc,
avg_train_loss.get(),
avg_train_acc.get()))
if step % self.val_every == 0:
val_loss, val_acc = self.val()
print('Val acc = {:.4f}, Val loss = {:.4f}'.format(val_acc, val_loss))
if self.visualize:
self.writer.add_scalar('Val/loss', val_loss, step)
self.writer.add_scalar('Val/acc', val_acc, step)
if val_acc > best_val_acc:
best_val_acc = val_acc
best_chkpt_path = os.path.join(self.model_dir,
'best_ckpt.pth')
torch.save(self.model.state_dict(), best_chkpt_path)
if self.args.scheduler == 'plateau':
self.scheduler.step(val_acc)
if self.visualize:
self.writer.add_scalar('Train/loss', train_loss.item(), step)
self.writer.add_scalar('Train/acc', train_acc, step)
def compute_loss(self, batch):
raise NotImplementedError
def train_step(self, batch):
self.model.train()
self.optimizer.zero_grad()
metrics = self.compute_loss(batch)
metrics['loss'].backward()
self.optimizer.step()
return metrics['loss'], metrics['accuracy']
def load_model_for_eval(self):
chkpt_path = os.path.join(self.model_dir, 'best_ckpt.pth') \
if self.args.eval_checkpoint_path is None else self.args.eval_checkpoint_path
self.model.load_state_dict(torch.load(chkpt_path))
self.model.eval()
@torch.no_grad()
def val(self):
print('VALIDATING:')
avg_val_loss = AverageMeter()
avg_val_acc = AverageMeter()
self.model.eval()
for batch_idx, batch in enumerate(tqdm(self.val_loader)):
metrics = self.compute_loss(batch)
avg_val_acc.update(metrics['correct'].cpu().numpy())
avg_val_loss.update([metrics['loss']])
return avg_val_loss.get(), avg_val_acc.get()
@torch.no_grad()
def infer(self):
self.load_model_for_eval()
avg_test_loss = AverageMeter()
avg_test_acc = AverageMeter()
all_true_labels = []
all_pred_labels = []
all_audio_embeddings = []
all_text_embeddings = []
for batch_idx, batch in enumerate(tqdm(self.test_loader)):
output = self.compute_loss(batch)
avg_test_acc.update(output['correct'].cpu().numpy())
avg_test_loss.update([output['loss']])
all_true_labels.append(batch['label'].cpu())
all_pred_labels.append(output['predicted'].cpu())
all_audio_embeddings.append(output['model_output']['audio_embed'].cpu())
all_text_embeddings.append(output['model_output']['text_embed'].cpu())
all_true_labels = torch.cat(all_true_labels).numpy()
all_pred_labels = torch.cat(all_pred_labels).numpy()
all_audio_embeddings = torch.cat(all_audio_embeddings).numpy()
all_text_embeddings = torch.cat(all_text_embeddings).numpy()
np.savez_compressed('embeddings.npz',
audio=all_audio_embeddings,
text=all_text_embeddings,
labels=all_true_labels)
print('Final test acc = {:.4f}, test loss = {:.4f}'.format(avg_test_acc.get(), avg_test_loss.get()))
return avg_test_loss.get(), avg_test_acc.get()
| true | true |
f7f73cc1c33a82a6602a7eae3653a3ab0b58758b | 2,287 | py | Python | load_cifar10.py | Monster880/pytorch_py | 9c5ac5974f48edb5ea3d897a1100a63d488c61d9 | [
"MIT"
] | null | null | null | load_cifar10.py | Monster880/pytorch_py | 9c5ac5974f48edb5ea3d897a1100a63d488c61d9 | [
"MIT"
] | null | null | null | load_cifar10.py | Monster880/pytorch_py | 9c5ac5974f48edb5ea3d897a1100a63d488c61d9 | [
"MIT"
] | null | null | null | import glob
from torchvision import transforms
from torch.utils.data import DataLoader, Dataset
import os
from PIL import Image
import numpy as np
label_name = [
"airplane",
"automobile",
"bird",
"cat",
"deer",
"dog",
"frog",
"horse",
"ship",
"truck"
]
label_dict = {}
for idx, name in enumerate(label_name):
label_dict[name] = idx
def default_loader(path):
return Image.open(path).convert("RGB")
# train_transform = transforms.Compose([
# transforms.RandomResizedCrop((28 , 28)),
# transforms.RandomHorizontalFlip(),
# transforms.RandomVerticalFlip(),
# transforms.RandomRotation(90),
# transforms.RandomGrayscale(0.1),
# transforms.ColorJitter(0.3, 0.3, 0.3, 0.3),
# transforms.ToTensor()
# ])
train_transform = transforms.Compose([
transforms.RandomCrop(28),
transforms.RandomHorizontalFlip(),
transforms.ToTensor()
])
test_transform = transforms.Compose([
transforms.Resize((28 , 28)),
transforms.ToTensor()
])
class MyDataSet(Dataset):
def __init__(self, im_list, transform=None, loader = default_loader):
super(MyDataSet, self).__init__()
imgs = []
for im_item in im_list:
im_label_name = im_item.split("/")[-2]
imgs.append([im_item, label_dict[im_label_name]])
self.imgs = imgs
self.transfrom = transform
self.loader = loader
def __getitem__(self, index):
im_path, im_label = self.imgs[index]
im_data = self.loader(im_path)
if self.transfrom is not None:
im_data = self.transfrom(im_data)
return im_data,im_label
def __len__(self):
return len(self.imgs)
im_train_list = glob.glob("/Users/liding/Documents/pytorch_py/train/*/*.png")
im_test_list = glob.glob("/Users/liding/Documents/pytorch_py/test/*/*.png")
train_dataset = MyDataSet(im_train_list, transform= train_transform)
test_dataset = MyDataSet(im_test_list, transform= transforms.ToTensor())
train_data_loader = DataLoader(dataset = train_dataset, batch_size=6, shuffle=True, num_workers=4)
test_data_loader = DataLoader(dataset = test_dataset, batch_size=6, shuffle=False, num_workers=4)
print("num_of_train", len(train_dataset))
print("num_of_test", len(test_dataset)) | 26.287356 | 98 | 0.682991 | import glob
from torchvision import transforms
from torch.utils.data import DataLoader, Dataset
import os
from PIL import Image
import numpy as np
label_name = [
"airplane",
"automobile",
"bird",
"cat",
"deer",
"dog",
"frog",
"horse",
"ship",
"truck"
]
label_dict = {}
for idx, name in enumerate(label_name):
label_dict[name] = idx
def default_loader(path):
return Image.open(path).convert("RGB")
train_transform = transforms.Compose([
transforms.RandomCrop(28),
transforms.RandomHorizontalFlip(),
transforms.ToTensor()
])
test_transform = transforms.Compose([
transforms.Resize((28 , 28)),
transforms.ToTensor()
])
class MyDataSet(Dataset):
def __init__(self, im_list, transform=None, loader = default_loader):
super(MyDataSet, self).__init__()
imgs = []
for im_item in im_list:
im_label_name = im_item.split("/")[-2]
imgs.append([im_item, label_dict[im_label_name]])
self.imgs = imgs
self.transfrom = transform
self.loader = loader
def __getitem__(self, index):
im_path, im_label = self.imgs[index]
im_data = self.loader(im_path)
if self.transfrom is not None:
im_data = self.transfrom(im_data)
return im_data,im_label
def __len__(self):
return len(self.imgs)
im_train_list = glob.glob("/Users/liding/Documents/pytorch_py/train/*/*.png")
im_test_list = glob.glob("/Users/liding/Documents/pytorch_py/test/*/*.png")
train_dataset = MyDataSet(im_train_list, transform= train_transform)
test_dataset = MyDataSet(im_test_list, transform= transforms.ToTensor())
train_data_loader = DataLoader(dataset = train_dataset, batch_size=6, shuffle=True, num_workers=4)
test_data_loader = DataLoader(dataset = test_dataset, batch_size=6, shuffle=False, num_workers=4)
print("num_of_train", len(train_dataset))
print("num_of_test", len(test_dataset)) | true | true |
f7f73d19ef67a6a11368996051e1a1a402f71bfa | 3,828 | py | Python | qwirk/deck.py | jensenak/qwirk | 7ddfa010d12770827ed1778dff4eabd2c2f8b462 | [
"MIT"
] | null | null | null | qwirk/deck.py | jensenak/qwirk | 7ddfa010d12770827ed1778dff4eabd2c2f8b462 | [
"MIT"
] | null | null | null | qwirk/deck.py | jensenak/qwirk | 7ddfa010d12770827ed1778dff4eabd2c2f8b462 | [
"MIT"
] | null | null | null | import random
from queue import Queue
from threading import Thread, Timer
from qwirk.game import GameObj
class BadOptions(Exception):
pass
class BadDeck(Exception):
pass
class Deck():
def __init__(self, settings):
self.game = GameObj.game
self.deck = []
self.settings = settings
if settings.handSize < 5:
raise BadOptions("Not enough cards to play")
if settings.handSize > 10:
raise BadOptions("Too many cards in hand size")
try:
for card in settings.rawDeck()['cards']:
for c in range(0, card['count']):
r = random.randint(0, 100)
k = card.copy()
k['priority'] += r
del k['count']
self.deck.append(k)
random.shuffle(self.deck)
except Exception as e:
raise BadDeck(str(e))
def coerceRegisters(self, player, opcodes):
"""
We're enforcing 3 things:
1) Player has only changed unlocked cards
2) Player has only used cards dealt to him
3) Cards dealt have only been used once
:param player: player object
:param opcodes: list of opcodes to be assigned to player
:return: valid list of opcodes
"""
slicelen = min((self.settings.maxDamage-player.damage), len(player.opcodes))
avail = player.opcodes[:slicelen] # copy unlocked opcodes
newops = []
for i in opcodes:
try:
# Remove the opcode from the available list and append it to the valid one
avail.remove(i)
newops.append(i)
except ValueError:
# Value error raised when opcode not in available list
newops.append(avail.pop()) # Player shouldn't have cheated... now everything's messed up
# Set player's opcodes to the new ones + whatever was already there.
player.opcodes = newops + avail + player.opcodes[slicelen:]
def deal(self):
'''
give cards to each player based on how many damage points he/she has
receive card order from each player within a time limit
:return:
'''
async = {}
q = Queue(maxsize=0)
for i in range(0, len(self.game.players)):
for j in range(0, min(self.settings.handSize, self.settings.maxDamage - self.game.players[i].damage)):
#As player sustains more and more damage, opcodes get locked
op = self.deck.pop()
self.game.players[i].opcodes[j] = op
#After assigning cards, start a thread to receive input from player
#This thread is meant to run longer than allowed just to make sure we never cut the player short
t = Thread(target=self.game.io.receive, args=(q, self.game.players[i]))
async[self.game.players[i].name] = {"q":q, "t":t, "recv": False}
t.start()
expire = Timer(60, q.put, {"src":"qtimer", "data":"expired"})
expire.start()
while False in [v['recv'] for k, v in async.items()]:
resp = q.get(block=True)
if resp['src'] == "qtimer":
break #Out of time, all unrecv'd players will retain card order as dealt
self.coerceRegisters(resp['src'], resp['data'])
async[resp['src'].name]['recv'] = True
# Note that dealing puts opcodes in a player's opcode list. If they didn't respond
# during the window above, they'll just retain the opcodes as dealt
expire.cancel()
print("All cards dealt")
for i in range(0, len(self.game.players)):
print("----===={}====----".format(self.game.players[i].name))
print(self.game.players[i].opcodes)
| 40.723404 | 114 | 0.576019 | import random
from queue import Queue
from threading import Thread, Timer
from qwirk.game import GameObj
class BadOptions(Exception):
pass
class BadDeck(Exception):
pass
class Deck():
def __init__(self, settings):
self.game = GameObj.game
self.deck = []
self.settings = settings
if settings.handSize < 5:
raise BadOptions("Not enough cards to play")
if settings.handSize > 10:
raise BadOptions("Too many cards in hand size")
try:
for card in settings.rawDeck()['cards']:
for c in range(0, card['count']):
r = random.randint(0, 100)
k = card.copy()
k['priority'] += r
del k['count']
self.deck.append(k)
random.shuffle(self.deck)
except Exception as e:
raise BadDeck(str(e))
def coerceRegisters(self, player, opcodes):
"""
We're enforcing 3 things:
1) Player has only changed unlocked cards
2) Player has only used cards dealt to him
3) Cards dealt have only been used once
:param player: player object
:param opcodes: list of opcodes to be assigned to player
:return: valid list of opcodes
"""
slicelen = min((self.settings.maxDamage-player.damage), len(player.opcodes))
avail = player.opcodes[:slicelen] # copy unlocked opcodes
newops = []
for i in opcodes:
try:
# Remove the opcode from the available list and append it to the valid one
avail.remove(i)
newops.append(i)
except ValueError:
# Value error raised when opcode not in available list
newops.append(avail.pop()) # Player shouldn't have cheated... now everything's messed up
# Set player's opcodes to the new ones + whatever was already there.
player.opcodes = newops + avail + player.opcodes[slicelen:]
def deal(self):
'''
give cards to each player based on how many damage points he/she has
receive card order from each player within a time limit
:return:
'''
async = {}
q = Queue(maxsize=0)
for i in range(0, len(self.game.players)):
for j in range(0, min(self.settings.handSize, self.settings.maxDamage - self.game.players[i].damage)):
op = self.deck.pop()
self.game.players[i].opcodes[j] = op
t = Thread(target=self.game.io.receive, args=(q, self.game.players[i]))
async[self.game.players[i].name] = {"q":q, "t":t, "recv": False}
t.start()
expire = Timer(60, q.put, {"src":"qtimer", "data":"expired"})
expire.start()
while False in [v['recv'] for k, v in async.items()]:
resp = q.get(block=True)
if resp['src'] == "qtimer":
break
self.coerceRegisters(resp['src'], resp['data'])
async[resp['src'].name]['recv'] = True
# Note that dealing puts opcodes in a player's opcode list. If they didn't respond
# during the window above, they'll just retain the opcodes as dealt
expire.cancel()
print("All cards dealt")
for i in range(0, len(self.game.players)):
print("----===={}====----".format(self.game.players[i].name))
print(self.game.players[i].opcodes)
| false | true |
f7f73d90929fc8e469ecd85269d19748280b98ba | 6,704 | py | Python | scripts/DL_final_Encoder_regressor.py | svenvanderburg/EEG_age_prediction | 6ce32d0776f4f0cf6287d8b7b215c20cef5d9926 | [
"Apache-2.0"
] | 2 | 2021-09-23T07:45:29.000Z | 2022-03-18T13:21:57.000Z | scripts/DL_final_Encoder_regressor.py | NadineUU/EEG_age_prediction | 958e8d6445bf277a445608e05d779315dbd9b376 | [
"Apache-2.0"
] | 8 | 2021-09-21T08:08:53.000Z | 2022-03-16T18:19:55.000Z | scripts/DL_final_Encoder_regressor.py | NadineUU/EEG_age_prediction | 958e8d6445bf277a445608e05d779315dbd9b376 | [
"Apache-2.0"
] | 2 | 2022-03-16T10:50:52.000Z | 2022-03-17T15:41:53.000Z | #!/usr/bin/env python
# ================ IMPORT LIBRARIES ================ #
import sys, os, fnmatch, time
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
sys.path.insert(0, os.path.dirname(os.getcwd()))
from dataset_generator import DataGenerator
import tensorflow as tf
import tensorflow_addons as tfa
from tensorflow import keras
from tensorflow.keras import layers, Input, Sequential
from tensorflow.keras.layers import Bidirectional, LSTM, Dropout, BatchNormalization, Dense, Conv1D, LeakyReLU, AveragePooling1D, Flatten, Reshape, MaxPooling1D
from tensorflow.keras.optimizers import Adam, Adadelta, SGD
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau
from tensorflow.keras.metrics import RootMeanSquaredError, MeanAbsoluteError
n_timesteps = 501
n_features = 30
n_outputs = 1
COUNT_MODEL = "FINAL" # This will be appended to the saved model's name. To make sure to not overwrite models, increase this.
MAX_QUEUE_SIZE = 5000
WORKERS = 6
input_shape = (n_timesteps, n_features)
# Input and output folders
PATH_DATA_PROCESSED_DL = sys.argv[1]
PATH_OUTPUT = sys.argv[2]
# ================ INITIAL LOGS ================ #
print("LOGGING: Imported all modules")
# ================ LOAD PREPROCESSED DATA ================ #
# Step 1: Get all the files in the output folder
file_names = os.listdir(PATH_DATA_PROCESSED_DL)
# Step 2: Get the full paths of the files (without extensions)
files = [os.path.splitext(os.path.join(PATH_DATA_PROCESSED_DL, file_name))[0] for file_name in fnmatch.filter(file_names, "*.zarr")]
# Step 3: Load all the metadata
frames = []
for idx, feature_file in enumerate(files):
df_metadata = pd.read_csv(feature_file.replace("processed_raw_", "processed_metadata_") + ".csv")
frames.append(df_metadata)
df_metadata = pd.concat(frames)
# Step 4: Add missing age information based on the age group the subject is in
df_metadata['age_months'].fillna(df_metadata['age_group'], inplace=True)
df_metadata['age_days'].fillna(df_metadata['age_group']*30, inplace=True)
df_metadata['age_years'].fillna(df_metadata['age_group']/12, inplace=True)
# Step 5: List all the unique subject IDs
subject_ids = sorted(list(set(df_metadata["code"].tolist())))
# Step 6: Split the subjects into train, val and test
IDs_train, IDs_temp = train_test_split(subject_ids, test_size=0.3, random_state=42)
IDs_test, IDs_val = train_test_split(IDs_temp, test_size=0.5, random_state=42)
# Step 7: Initialize DataGenerators
train_generator_noise = DataGenerator(list_IDs = IDs_train,
BASE_PATH = PATH_DATA_PROCESSED_DL,
metadata = df_metadata,
n_average = 30,
batch_size = 10,
gaussian_noise=0.01,
iter_per_epoch = 30,
n_timepoints = 501,
n_channels=30,
shuffle=True)
val_generator = DataGenerator(list_IDs = IDs_val,
BASE_PATH = PATH_DATA_PROCESSED_DL,
metadata = df_metadata,
n_average = 30,
batch_size = 10,
iter_per_epoch = 100,
n_timepoints = 501,
n_channels=30,
shuffle=True)
print("LOGGING: Loaded all data and created generators")
# ================ Encoder model ================ #
try:
def encoder_model():
""" Returns the Encoder model from Ismail Fawaz et al. (2019). """
input_layer = keras.layers.Input(input_shape)
# conv block -1
conv1 = keras.layers.Conv1D(filters=128,kernel_size=5,strides=1,padding='same')(input_layer)
conv1 = tfa.layers.InstanceNormalization()(conv1)
conv1 = keras.layers.PReLU(shared_axes=[1])(conv1)
conv1 = keras.layers.Dropout(rate=0.2)(conv1)
conv1 = keras.layers.MaxPooling1D(pool_size=2)(conv1)
# conv block -2
conv2 = keras.layers.Conv1D(filters=256,kernel_size=11,strides=1,padding='same')(conv1)
conv2 = tfa.layers.InstanceNormalization()(conv2)
conv2 = keras.layers.PReLU(shared_axes=[1])(conv2)
conv2 = keras.layers.Dropout(rate=0.2)(conv2)
conv2 = keras.layers.MaxPooling1D(pool_size=2)(conv2)
# conv block -3
conv3 = keras.layers.Conv1D(filters=512,kernel_size=21,strides=1,padding='same')(conv2)
conv3 = tfa.layers.InstanceNormalization()(conv3)
conv3 = keras.layers.PReLU(shared_axes=[1])(conv3)
conv3 = keras.layers.Dropout(rate=0.2)(conv3)
# split for attention
attention_data = keras.layers.Lambda(lambda x: x[:,:,:256])(conv3)
attention_softmax = keras.layers.Lambda(lambda x: x[:,:,256:])(conv3)
# attention mechanism
attention_softmax = keras.layers.Softmax()(attention_softmax)
multiply_layer = keras.layers.Multiply()([attention_softmax,attention_data])
# last layer
dense_layer = keras.layers.Dense(units=256,activation='sigmoid')(multiply_layer)
dense_layer = tfa.layers.InstanceNormalization()(dense_layer)
# output layer
flatten_layer = keras.layers.Flatten()(dense_layer)
output_layer = keras.layers.Dense(1)(flatten_layer)
model = keras.models.Model(inputs=input_layer, outputs=output_layer)
return model
model = encoder_model()
optimizer = Adam(learning_rate=0.00001)
model.compile(loss='mean_squared_error',
optimizer=optimizer,
metrics=[RootMeanSquaredError(), MeanAbsoluteError()])
output_filename = f'Encoder_regressor_{COUNT_MODEL}'
output_file = os.path.join(PATH_OUTPUT, output_filename)
checkpointer = ModelCheckpoint(filepath = output_file + ".hdf5", monitor='val_loss', verbose=1, save_best_only=True)
epochs = 500
print("LOGGING: Starting Encoder model training")
# fit network
history = model.fit(x=train_generator_noise,
validation_data=val_generator,
epochs=epochs,
verbose=2,
max_queue_size=MAX_QUEUE_SIZE,
workers=WORKERS,
callbacks=[checkpointer])
print("LOGGING: Finished Encoder model training")
except Exception as e:
print("LOGGING: Failed Encoder model training:")
print(e)
pass
| 40.878049 | 160 | 0.637381 |
import sys, os, fnmatch, time
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
sys.path.insert(0, os.path.dirname(os.getcwd()))
from dataset_generator import DataGenerator
import tensorflow as tf
import tensorflow_addons as tfa
from tensorflow import keras
from tensorflow.keras import layers, Input, Sequential
from tensorflow.keras.layers import Bidirectional, LSTM, Dropout, BatchNormalization, Dense, Conv1D, LeakyReLU, AveragePooling1D, Flatten, Reshape, MaxPooling1D
from tensorflow.keras.optimizers import Adam, Adadelta, SGD
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau
from tensorflow.keras.metrics import RootMeanSquaredError, MeanAbsoluteError
n_timesteps = 501
n_features = 30
n_outputs = 1
COUNT_MODEL = "FINAL"
MAX_QUEUE_SIZE = 5000
WORKERS = 6
input_shape = (n_timesteps, n_features)
# Input and output folders
PATH_DATA_PROCESSED_DL = sys.argv[1]
PATH_OUTPUT = sys.argv[2]
# ================ INITIAL LOGS ================ #
print("LOGGING: Imported all modules")
# ================ LOAD PREPROCESSED DATA ================ #
# Step 1: Get all the files in the output folder
file_names = os.listdir(PATH_DATA_PROCESSED_DL)
# Step 2: Get the full paths of the files (without extensions)
files = [os.path.splitext(os.path.join(PATH_DATA_PROCESSED_DL, file_name))[0] for file_name in fnmatch.filter(file_names, "*.zarr")]
# Step 3: Load all the metadata
frames = []
for idx, feature_file in enumerate(files):
df_metadata = pd.read_csv(feature_file.replace("processed_raw_", "processed_metadata_") + ".csv")
frames.append(df_metadata)
df_metadata = pd.concat(frames)
# Step 4: Add missing age information based on the age group the subject is in
df_metadata['age_months'].fillna(df_metadata['age_group'], inplace=True)
df_metadata['age_days'].fillna(df_metadata['age_group']*30, inplace=True)
df_metadata['age_years'].fillna(df_metadata['age_group']/12, inplace=True)
# Step 5: List all the unique subject IDs
subject_ids = sorted(list(set(df_metadata["code"].tolist())))
# Step 6: Split the subjects into train, val and test
IDs_train, IDs_temp = train_test_split(subject_ids, test_size=0.3, random_state=42)
IDs_test, IDs_val = train_test_split(IDs_temp, test_size=0.5, random_state=42)
# Step 7: Initialize DataGenerators
train_generator_noise = DataGenerator(list_IDs = IDs_train,
BASE_PATH = PATH_DATA_PROCESSED_DL,
metadata = df_metadata,
n_average = 30,
batch_size = 10,
gaussian_noise=0.01,
iter_per_epoch = 30,
n_timepoints = 501,
n_channels=30,
shuffle=True)
val_generator = DataGenerator(list_IDs = IDs_val,
BASE_PATH = PATH_DATA_PROCESSED_DL,
metadata = df_metadata,
n_average = 30,
batch_size = 10,
iter_per_epoch = 100,
n_timepoints = 501,
n_channels=30,
shuffle=True)
print("LOGGING: Loaded all data and created generators")
# ================ Encoder model ================ #
try:
def encoder_model():
input_layer = keras.layers.Input(input_shape)
# conv block -1
conv1 = keras.layers.Conv1D(filters=128,kernel_size=5,strides=1,padding='same')(input_layer)
conv1 = tfa.layers.InstanceNormalization()(conv1)
conv1 = keras.layers.PReLU(shared_axes=[1])(conv1)
conv1 = keras.layers.Dropout(rate=0.2)(conv1)
conv1 = keras.layers.MaxPooling1D(pool_size=2)(conv1)
# conv block -2
conv2 = keras.layers.Conv1D(filters=256,kernel_size=11,strides=1,padding='same')(conv1)
conv2 = tfa.layers.InstanceNormalization()(conv2)
conv2 = keras.layers.PReLU(shared_axes=[1])(conv2)
conv2 = keras.layers.Dropout(rate=0.2)(conv2)
conv2 = keras.layers.MaxPooling1D(pool_size=2)(conv2)
# conv block -3
conv3 = keras.layers.Conv1D(filters=512,kernel_size=21,strides=1,padding='same')(conv2)
conv3 = tfa.layers.InstanceNormalization()(conv3)
conv3 = keras.layers.PReLU(shared_axes=[1])(conv3)
conv3 = keras.layers.Dropout(rate=0.2)(conv3)
# split for attention
attention_data = keras.layers.Lambda(lambda x: x[:,:,:256])(conv3)
attention_softmax = keras.layers.Lambda(lambda x: x[:,:,256:])(conv3)
# attention mechanism
attention_softmax = keras.layers.Softmax()(attention_softmax)
multiply_layer = keras.layers.Multiply()([attention_softmax,attention_data])
# last layer
dense_layer = keras.layers.Dense(units=256,activation='sigmoid')(multiply_layer)
dense_layer = tfa.layers.InstanceNormalization()(dense_layer)
# output layer
flatten_layer = keras.layers.Flatten()(dense_layer)
output_layer = keras.layers.Dense(1)(flatten_layer)
model = keras.models.Model(inputs=input_layer, outputs=output_layer)
return model
model = encoder_model()
optimizer = Adam(learning_rate=0.00001)
model.compile(loss='mean_squared_error',
optimizer=optimizer,
metrics=[RootMeanSquaredError(), MeanAbsoluteError()])
output_filename = f'Encoder_regressor_{COUNT_MODEL}'
output_file = os.path.join(PATH_OUTPUT, output_filename)
checkpointer = ModelCheckpoint(filepath = output_file + ".hdf5", monitor='val_loss', verbose=1, save_best_only=True)
epochs = 500
print("LOGGING: Starting Encoder model training")
# fit network
history = model.fit(x=train_generator_noise,
validation_data=val_generator,
epochs=epochs,
verbose=2,
max_queue_size=MAX_QUEUE_SIZE,
workers=WORKERS,
callbacks=[checkpointer])
print("LOGGING: Finished Encoder model training")
except Exception as e:
print("LOGGING: Failed Encoder model training:")
print(e)
pass
| true | true |
f7f73e3fa0545b771ffcadd2a3b29e9ec40e8abf | 1,285 | py | Python | aoc_01.py | ForestRupicolous/advent_of_code | 1335e695e79842ae68c4b492ac2ad89c87a6ea29 | [
"MIT"
] | null | null | null | aoc_01.py | ForestRupicolous/advent_of_code | 1335e695e79842ae68c4b492ac2ad89c87a6ea29 | [
"MIT"
] | null | null | null | aoc_01.py | ForestRupicolous/advent_of_code | 1335e695e79842ae68c4b492ac2ad89c87a6ea29 | [
"MIT"
] | null | null | null | #! python3
# aoc_01.py
# Advent of code:
# https://adventofcode.com/2021/day/1
# https://adventofcode.com/2021/day/1#part2
# download input data (optional, for future use)
# Count depth increase (if current num is > last: ++)
# return number of depth increases
def aoc_count_depth_increase(aoc_input):
prev_depth = 0
cnt = -1
with open(aoc_input, 'r') as input:
for depth in input.readlines():
if int(depth) > prev_depth:
cnt+=1
prev_depth = int(depth)
return cnt
#2nd challenge - better code as integers are converted in the beginning
def aoc_count_depth_sum_increase(aoc_input, winsize=3):
prev_depth_sum = 0
cnt = -1
with open(aoc_input, 'r') as input:
depths = list(map(int,input.readlines()))
print(depths)
for i in range(len(depths) - winsize + 1):
window = depths[i: i + winsize]
depth_sum = sum(window)
print(window, sum(window))
if depth_sum > prev_depth_sum:
cnt+=1
prev_depth_sum = depth_sum
return cnt
print("Hello World!")
print(aoc_count_depth_increase('aoc_01_example.txt'))
print(aoc_count_depth_increase('aoc_01_input.txt'))
print(aoc_count_depth_sum_increase('aoc_01_input.txt'))
| 29.204545 | 71 | 0.647471 |
def aoc_count_depth_increase(aoc_input):
prev_depth = 0
cnt = -1
with open(aoc_input, 'r') as input:
for depth in input.readlines():
if int(depth) > prev_depth:
cnt+=1
prev_depth = int(depth)
return cnt
def aoc_count_depth_sum_increase(aoc_input, winsize=3):
prev_depth_sum = 0
cnt = -1
with open(aoc_input, 'r') as input:
depths = list(map(int,input.readlines()))
print(depths)
for i in range(len(depths) - winsize + 1):
window = depths[i: i + winsize]
depth_sum = sum(window)
print(window, sum(window))
if depth_sum > prev_depth_sum:
cnt+=1
prev_depth_sum = depth_sum
return cnt
print("Hello World!")
print(aoc_count_depth_increase('aoc_01_example.txt'))
print(aoc_count_depth_increase('aoc_01_input.txt'))
print(aoc_count_depth_sum_increase('aoc_01_input.txt'))
| true | true |
f7f7402df691933fa0171ff77a9abbad10862589 | 8,904 | py | Python | pyevr/openapi_client/models/consolidated_act_all_of.py | thorgate/pyevr | 168f2e9459020212213ed0291882a285ebb53839 | [
"MIT"
] | 3 | 2020-04-18T19:45:51.000Z | 2022-03-01T19:48:11.000Z | pyevr/openapi_client/models/consolidated_act_all_of.py | thorgate/pyevr | 168f2e9459020212213ed0291882a285ebb53839 | [
"MIT"
] | 39 | 2019-11-16T01:35:35.000Z | 2021-11-18T12:58:41.000Z | pyevr/openapi_client/models/consolidated_act_all_of.py | thorgate/pyevr | 168f2e9459020212213ed0291882a285ebb53839 | [
"MIT"
] | null | null | null | # coding: utf-8
"""
EVR API
OpenAPI Generator'i jaoks kohandatud EVR API kirjeldus. Kasuta seda juhul, kui spetsifikatsioonile vastava EVR API kirjeldusega ei õnnestu klienti genereerida. # noqa: E501
The version of the OpenAPI document: 1.8.0
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from pyevr.openapi_client.configuration import Configuration
class ConsolidatedActAllOf(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_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.
"""
openapi_types = {
'contract_number': 'str',
'contract_date': 'datetime',
'cadaster': 'str',
'compartment': 'str',
'forest_allocation_number': 'str'
}
attribute_map = {
'contract_number': 'contractNumber',
'contract_date': 'contractDate',
'cadaster': 'cadaster',
'compartment': 'compartment',
'forest_allocation_number': 'forestAllocationNumber'
}
def __init__(self, contract_number=None, contract_date=None, cadaster=None, compartment=None, forest_allocation_number=None, local_vars_configuration=None): # noqa: E501
"""ConsolidatedActAllOf - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._contract_number = None
self._contract_date = None
self._cadaster = None
self._compartment = None
self._forest_allocation_number = None
self.discriminator = None
self.contract_number = contract_number
self.contract_date = contract_date
self.cadaster = cadaster
self.compartment = compartment
self.forest_allocation_number = forest_allocation_number
@property
def contract_number(self):
"""Gets the contract_number of this ConsolidatedActAllOf. # noqa: E501
Dokumendi number # noqa: E501
:return: The contract_number of this ConsolidatedActAllOf. # noqa: E501
:rtype: str
"""
return self._contract_number
@contract_number.setter
def contract_number(self, contract_number):
"""Sets the contract_number of this ConsolidatedActAllOf.
Dokumendi number # noqa: E501
:param contract_number: The contract_number of this ConsolidatedActAllOf. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and contract_number is None: # noqa: E501
raise ValueError("Invalid value for `contract_number`, must not be `None`") # noqa: E501
if (self.local_vars_configuration.client_side_validation and
contract_number is not None and len(contract_number) > 500):
raise ValueError("Invalid value for `contract_number`, length must be less than or equal to `500`") # noqa: E501
if (self.local_vars_configuration.client_side_validation and
contract_number is not None and len(contract_number) < 0):
raise ValueError("Invalid value for `contract_number`, length must be greater than or equal to `0`") # noqa: E501
self._contract_number = contract_number
@property
def contract_date(self):
"""Gets the contract_date of this ConsolidatedActAllOf. # noqa: E501
Dokumendi kuupäev # noqa: E501
:return: The contract_date of this ConsolidatedActAllOf. # noqa: E501
:rtype: datetime
"""
return self._contract_date
@contract_date.setter
def contract_date(self, contract_date):
"""Sets the contract_date of this ConsolidatedActAllOf.
Dokumendi kuupäev # noqa: E501
:param contract_date: The contract_date of this ConsolidatedActAllOf. # noqa: E501
:type: datetime
"""
if self.local_vars_configuration.client_side_validation and contract_date is None: # noqa: E501
raise ValueError("Invalid value for `contract_date`, must not be `None`") # noqa: E501
self._contract_date = contract_date
@property
def cadaster(self):
"""Gets the cadaster of this ConsolidatedActAllOf. # noqa: E501
Katastritunnus # noqa: E501
:return: The cadaster of this ConsolidatedActAllOf. # noqa: E501
:rtype: str
"""
return self._cadaster
@cadaster.setter
def cadaster(self, cadaster):
"""Sets the cadaster of this ConsolidatedActAllOf.
Katastritunnus # noqa: E501
:param cadaster: The cadaster of this ConsolidatedActAllOf. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and cadaster is None: # noqa: E501
raise ValueError("Invalid value for `cadaster`, must not be `None`") # noqa: E501
if (self.local_vars_configuration.client_side_validation and
cadaster is not None and len(cadaster) > 500):
raise ValueError("Invalid value for `cadaster`, length must be less than or equal to `500`") # noqa: E501
if (self.local_vars_configuration.client_side_validation and
cadaster is not None and len(cadaster) < 0):
raise ValueError("Invalid value for `cadaster`, length must be greater than or equal to `0`") # noqa: E501
self._cadaster = cadaster
@property
def compartment(self):
"""Gets the compartment of this ConsolidatedActAllOf. # noqa: E501
Kvartal # noqa: E501
:return: The compartment of this ConsolidatedActAllOf. # noqa: E501
:rtype: str
"""
return self._compartment
@compartment.setter
def compartment(self, compartment):
"""Sets the compartment of this ConsolidatedActAllOf.
Kvartal # noqa: E501
:param compartment: The compartment of this ConsolidatedActAllOf. # noqa: E501
:type: str
"""
if (self.local_vars_configuration.client_side_validation and
compartment is not None and len(compartment) > 200):
raise ValueError("Invalid value for `compartment`, length must be less than or equal to `200`") # noqa: E501
self._compartment = compartment
@property
def forest_allocation_number(self):
"""Gets the forest_allocation_number of this ConsolidatedActAllOf. # noqa: E501
Metsaeraldis # noqa: E501
:return: The forest_allocation_number of this ConsolidatedActAllOf. # noqa: E501
:rtype: str
"""
return self._forest_allocation_number
@forest_allocation_number.setter
def forest_allocation_number(self, forest_allocation_number):
"""Sets the forest_allocation_number of this ConsolidatedActAllOf.
Metsaeraldis # noqa: E501
:param forest_allocation_number: The forest_allocation_number of this ConsolidatedActAllOf. # noqa: E501
:type: str
"""
self._forest_allocation_number = forest_allocation_number
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_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
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, ConsolidatedActAllOf):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, ConsolidatedActAllOf):
return True
return self.to_dict() != other.to_dict()
| 35.474104 | 177 | 0.640611 |
import pprint
import re
import six
from pyevr.openapi_client.configuration import Configuration
class ConsolidatedActAllOf(object):
openapi_types = {
'contract_number': 'str',
'contract_date': 'datetime',
'cadaster': 'str',
'compartment': 'str',
'forest_allocation_number': 'str'
}
attribute_map = {
'contract_number': 'contractNumber',
'contract_date': 'contractDate',
'cadaster': 'cadaster',
'compartment': 'compartment',
'forest_allocation_number': 'forestAllocationNumber'
}
def __init__(self, contract_number=None, contract_date=None, cadaster=None, compartment=None, forest_allocation_number=None, local_vars_configuration=None):
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._contract_number = None
self._contract_date = None
self._cadaster = None
self._compartment = None
self._forest_allocation_number = None
self.discriminator = None
self.contract_number = contract_number
self.contract_date = contract_date
self.cadaster = cadaster
self.compartment = compartment
self.forest_allocation_number = forest_allocation_number
@property
def contract_number(self):
return self._contract_number
@contract_number.setter
def contract_number(self, contract_number):
if self.local_vars_configuration.client_side_validation and contract_number is None:
raise ValueError("Invalid value for `contract_number`, must not be `None`")
if (self.local_vars_configuration.client_side_validation and
contract_number is not None and len(contract_number) > 500):
raise ValueError("Invalid value for `contract_number`, length must be less than or equal to `500`")
if (self.local_vars_configuration.client_side_validation and
contract_number is not None and len(contract_number) < 0):
raise ValueError("Invalid value for `contract_number`, length must be greater than or equal to `0`")
self._contract_number = contract_number
@property
def contract_date(self):
return self._contract_date
@contract_date.setter
def contract_date(self, contract_date):
if self.local_vars_configuration.client_side_validation and contract_date is None:
raise ValueError("Invalid value for `contract_date`, must not be `None`")
self._contract_date = contract_date
@property
def cadaster(self):
return self._cadaster
@cadaster.setter
def cadaster(self, cadaster):
if self.local_vars_configuration.client_side_validation and cadaster is None:
raise ValueError("Invalid value for `cadaster`, must not be `None`")
if (self.local_vars_configuration.client_side_validation and
cadaster is not None and len(cadaster) > 500):
raise ValueError("Invalid value for `cadaster`, length must be less than or equal to `500`")
if (self.local_vars_configuration.client_side_validation and
cadaster is not None and len(cadaster) < 0):
raise ValueError("Invalid value for `cadaster`, length must be greater than or equal to `0`")
self._cadaster = cadaster
@property
def compartment(self):
return self._compartment
@compartment.setter
def compartment(self, compartment):
if (self.local_vars_configuration.client_side_validation and
compartment is not None and len(compartment) > 200):
raise ValueError("Invalid value for `compartment`, length must be less than or equal to `200`")
self._compartment = compartment
@property
def forest_allocation_number(self):
return self._forest_allocation_number
@forest_allocation_number.setter
def forest_allocation_number(self, forest_allocation_number):
self._forest_allocation_number = forest_allocation_number
def to_dict(self):
result = {}
for attr, _ in six.iteritems(self.openapi_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
return result
def to_str(self):
return pprint.pformat(self.to_dict())
def __repr__(self):
return self.to_str()
def __eq__(self, other):
if not isinstance(other, ConsolidatedActAllOf):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
if not isinstance(other, ConsolidatedActAllOf):
return True
return self.to_dict() != other.to_dict()
| true | true |
f7f74173e04fb3a67359a4386b15eb25ac3757e4 | 1,815 | py | Python | IPL_Match_Simulation/Step3/Step3_4_Program6_Player_vs_Player_Calculate_wickets.py | KavyaThani/Cls_IPL_01FB15ECS326 | ba8642596d559a9d0af0bfff2bf2afcfdc937332 | [
"MIT"
] | null | null | null | IPL_Match_Simulation/Step3/Step3_4_Program6_Player_vs_Player_Calculate_wickets.py | KavyaThani/Cls_IPL_01FB15ECS326 | ba8642596d559a9d0af0bfff2bf2afcfdc937332 | [
"MIT"
] | null | null | null | IPL_Match_Simulation/Step3/Step3_4_Program6_Player_vs_Player_Calculate_wickets.py | KavyaThani/Cls_IPL_01FB15ECS326 | ba8642596d559a9d0af0bfff2bf2afcfdc937332 | [
"MIT"
] | null | null | null | f = open('player_vs_player_Probability_wickets3.txt', 'w')
inF = open('player_vs_player_Probability_wickets2.txt', 'r')
lines = inF.readlines()
w=0
counter=0
for i in range(len(lines)):
line1=lines[i]
if i+1 <= len(lines)-1:
line2=lines[i+1]
else :
break
list1=[]
list2=[]
list1=line1.split(',')
list2=line2.split(',')
list1[2]=float(list1[2])
list2[2]=float(list2[2])
if list1[0]==list2[0]:
if list1[1]==list2[1]:
w=w+float(list2[2]) #0
counter=counter+1
else :
w=w+float(list2[2]) #0
counter=counter+1
#f.write(str(list1[0])+","+str(list1[1])+","+str(list4)+"\n")
w=float(w)/counter
f.write(str(list1[0])+","+str(list1[1])+","+str(w)+"\n")
w=0
counter=0
else :
w=w+float(list2[2]) #0
counter=counter+1
#f.write(str(list1[0])+","+str(list1[1])+","+str(list4)+"\n")
w=float(w)/counter
f.write(str(list1[0])+","+str(list1[1])+","+str(w)+"\n")
w=0
counter=0
list3=[]
line3=lines[len(lines)-1]
list3=line3.split(',')
list3[2]=float(list3[2])
#print(list4)
if list3[0]==list2[0]:
if list3[1]==list2[1]:
w=w+float(list2[2]) #0
counter=counter+1
else :
w=w+list2[2] #0
counter=counter+1
#f.write(str(list1[0])+","+str(list1[1])+","+str(list4)+"\n")
w=float(w)/counter
f.write(str(list1[0])+","+str(list1[1])+","+str(w)+"\n")
w=0
counter=0
else :
w=w+float(list2[2]) #0
counter=counter+1
#f.write(str(list1[0])+","+str(list1[1])+","+str(list4)+"\n")
w=float(w)/counter
f.write(str(list1[0])+","+str(list1[1])+","+str(w)+"\n")
w=0
counter=0
f.write(str(list1[0])+","+str(list1[1])+","+str(w)+"\n")
f.close()
inF.close()
| 20.166667 | 64 | 0.525069 | f = open('player_vs_player_Probability_wickets3.txt', 'w')
inF = open('player_vs_player_Probability_wickets2.txt', 'r')
lines = inF.readlines()
w=0
counter=0
for i in range(len(lines)):
line1=lines[i]
if i+1 <= len(lines)-1:
line2=lines[i+1]
else :
break
list1=[]
list2=[]
list1=line1.split(',')
list2=line2.split(',')
list1[2]=float(list1[2])
list2[2]=float(list2[2])
if list1[0]==list2[0]:
if list1[1]==list2[1]:
w=w+float(list2[2])
counter=counter+1
else :
w=w+float(list2[2])
counter=counter+1
w=float(w)/counter
f.write(str(list1[0])+","+str(list1[1])+","+str(w)+"\n")
w=0
counter=0
else :
w=w+float(list2[2])
counter=counter+1
w=float(w)/counter
f.write(str(list1[0])+","+str(list1[1])+","+str(w)+"\n")
w=0
counter=0
list3=[]
line3=lines[len(lines)-1]
list3=line3.split(',')
list3[2]=float(list3[2])
if list3[0]==list2[0]:
if list3[1]==list2[1]:
w=w+float(list2[2])
counter=counter+1
else :
w=w+list2[2]
counter=counter+1
w=float(w)/counter
f.write(str(list1[0])+","+str(list1[1])+","+str(w)+"\n")
w=0
counter=0
else :
w=w+float(list2[2])
counter=counter+1
w=float(w)/counter
f.write(str(list1[0])+","+str(list1[1])+","+str(w)+"\n")
w=0
counter=0
f.write(str(list1[0])+","+str(list1[1])+","+str(w)+"\n")
f.close()
inF.close()
| true | true |
f7f741ac22ba841535c7e0857f0335593ff5f99e | 566 | py | Python | pythonProject2/exercicios/exercicio02.py | DeyvidMonteiro/PycharmProjects | c8fb45f05bbbaab41a20ff22f0e60fdde87210af | [
"MIT"
] | null | null | null | pythonProject2/exercicios/exercicio02.py | DeyvidMonteiro/PycharmProjects | c8fb45f05bbbaab41a20ff22f0e60fdde87210af | [
"MIT"
] | null | null | null | pythonProject2/exercicios/exercicio02.py | DeyvidMonteiro/PycharmProjects | c8fb45f05bbbaab41a20ff22f0e60fdde87210af | [
"MIT"
] | null | null | null | num = int(input('digite um numero inteiro: '))
print('''escolha umas das bases para conversão:
[ 1 ] converter para BINARIO
[ 2 ] converter para OCTAL
[ 3 ] converter para EXADECIMAL ''')
opcao = int(input('sua opção: '))
if opcao == 1:
print('{} convertido para binario é igual a {} '.format(num, bin(num)[2:]))
elif opcao == 2:
print('{} convertido para OCTAL e igaul a {} '.format(num, oct(num[2:])))
elif opcao == 3:
print('{} convertido para EXADECIMAL é igaul a {} '.format(num, hex(num)[2:]))
else:
print('opção invalida. tente novamente!') | 40.428571 | 82 | 0.646643 | num = int(input('digite um numero inteiro: '))
print('''escolha umas das bases para conversão:
[ 1 ] converter para BINARIO
[ 2 ] converter para OCTAL
[ 3 ] converter para EXADECIMAL ''')
opcao = int(input('sua opção: '))
if opcao == 1:
print('{} convertido para binario é igual a {} '.format(num, bin(num)[2:]))
elif opcao == 2:
print('{} convertido para OCTAL e igaul a {} '.format(num, oct(num[2:])))
elif opcao == 3:
print('{} convertido para EXADECIMAL é igaul a {} '.format(num, hex(num)[2:]))
else:
print('opção invalida. tente novamente!') | true | true |
f7f743aafe5ab0506d150de4f2d0d80c7e9d962c | 3,710 | py | Python | tests/core/test_format_validators.py | maroux/flex | dfd7c6d79d065d7ce1b0c799e51e9bb5292612b2 | [
"MIT"
] | 160 | 2015-01-15T05:36:44.000Z | 2021-08-04T00:43:54.000Z | tests/core/test_format_validators.py | maroux/flex | dfd7c6d79d065d7ce1b0c799e51e9bb5292612b2 | [
"MIT"
] | 151 | 2015-01-20T16:45:36.000Z | 2022-02-23T21:07:58.000Z | tests/core/test_format_validators.py | maroux/flex | dfd7c6d79d065d7ce1b0c799e51e9bb5292612b2 | [
"MIT"
] | 90 | 2015-01-20T11:19:36.000Z | 2021-08-03T08:58:18.000Z | import pytest
import uuid
from flex.exceptions import ValidationError
from flex.formats import (
date_time_format_validator,
uuid_format_validator,
int32_validator,
int64_validator,
email_validator,
)
#
# date_time_format_validator tests
#
@pytest.mark.parametrize(
'value',
(1, True, None, 2.0, [], {}),
)
def test_date_time_format_validator_skips_non_string_types(value):
date_time_format_validator(value)
@pytest.mark.parametrize(
'value',
(
'2017', # Not a full date
'2017-01-02T12:34:56', # No TZ part
'2011-13-18T10:29:47+03:00', # Invalid month 13
'2011-08-32T10:29:47+03:00', # Invalid day 32
'2011-08-18T25:29:47+03:00', # Invalid hour 25
'2011-08-18T10:65:47+03:00', # Invalid minute 65
'2011-08-18T10:29:65+03:00', # Invalid second 65
'2011-08-18T10:29:65+25:00', # Invalid offset 25 hours
)
)
def test_date_time_format_validator_detects_invalid_values(value):
with pytest.raises(ValidationError):
date_time_format_validator(value)
@pytest.mark.parametrize(
'value',
(
'2011-08-18T10:29:47+03:00',
'1985-04-12T23:20:50.52Z',
'1996-12-19T16:39:57-08:00',
# Leap second should be valid but strict_rfc339 doesn't correctly parse.
pytest.param('1990-12-31T23:59:60Z', marks=pytest.mark.xfail),
# Leap second should be valid but strict_rfc339 doesn't correctly parse.
pytest.param('1990-12-31T15:59:60-08:00', marks=pytest.mark.xfail),
# Weird netherlands time from strange 1909 law.
'1937-01-01T12:00:27.87+00:20',
)
)
def test_date_time_format_validator_with_valid_dateties(value):
date_time_format_validator(value)
#
# uuid format tests
#
def test_uuid1_matches():
for _ in range(100):
uuid_format_validator(str(uuid.uuid1()))
def test_uuid3_matches():
for _ in range(100):
uuid_format_validator(str(uuid.uuid3(uuid.uuid4(), 'test-4')))
uuid_format_validator(str(uuid.uuid3(uuid.uuid1(), 'test-1')))
def test_uuid4_matches():
for _ in range(100):
uuid_format_validator(str(uuid.uuid4()))
def test_uuid5_matches():
for _ in range(100):
uuid_format_validator(str(uuid.uuid5(uuid.uuid4(), 'test-4')))
uuid_format_validator(str(uuid.uuid5(uuid.uuid1(), 'test-1')))
MAX_INT32 = 2 ** 31 - 1
MIN_INT32 = -1 * 2 ** 31
MAX_INT64 = 2 ** 63 - 1
MIN_INT64 = -1 * 2 ** 63
#
# int32 and int64 format tests.
#
@pytest.mark.parametrize(
'n',
(MIN_INT32, -1, 0, 1, MAX_INT32),
)
def test_int32_with_in_range_number(n):
int32_validator(n)
@pytest.mark.parametrize(
'n',
(MIN_INT32 - 1, MAX_INT32 + 1),
)
def test_int32_with_out_of_range_number(n):
with pytest.raises(ValidationError):
int32_validator(n)
@pytest.mark.parametrize(
'n',
(MIN_INT64, -1, 0, 1, MAX_INT64),
)
def test_int64_with_in_range_number(n):
int64_validator(n)
@pytest.mark.parametrize(
'n',
(MIN_INT64 - 1, MAX_INT64 + 1),
)
def test_int64_with_out_of_range_number(n):
with pytest.raises(ValidationError):
int64_validator(n)
#
# email validators
#
@pytest.mark.parametrize(
'email_address',
(
'test@example.com',
'test+extra@example.com',
),
)
def test_email_validation_with_valid_email_addresses(email_address):
email_validator(email_address)
@pytest.mark.parametrize(
'email_address',
(
'example.com',
'www.example.com',
'not-an-email-address-at-all',
),
)
def test_email_validation_with_invalid_email_addresses(email_address):
with pytest.raises(ValidationError):
email_validator(email_address)
| 24.569536 | 80 | 0.668464 | import pytest
import uuid
from flex.exceptions import ValidationError
from flex.formats import (
date_time_format_validator,
uuid_format_validator,
int32_validator,
int64_validator,
email_validator,
)
@pytest.mark.parametrize(
'value',
(1, True, None, 2.0, [], {}),
)
def test_date_time_format_validator_skips_non_string_types(value):
date_time_format_validator(value)
@pytest.mark.parametrize(
'value',
(
'2017',
'2017-01-02T12:34:56',
'2011-13-18T10:29:47+03:00',
'2011-08-32T10:29:47+03:00',
'2011-08-18T25:29:47+03:00',
'2011-08-18T10:65:47+03:00',
'2011-08-18T10:29:65+03:00',
'2011-08-18T10:29:65+25:00',
)
)
def test_date_time_format_validator_detects_invalid_values(value):
with pytest.raises(ValidationError):
date_time_format_validator(value)
@pytest.mark.parametrize(
'value',
(
'2011-08-18T10:29:47+03:00',
'1985-04-12T23:20:50.52Z',
'1996-12-19T16:39:57-08:00',
pytest.param('1990-12-31T23:59:60Z', marks=pytest.mark.xfail),
# Leap second should be valid but strict_rfc339 doesn't correctly parse.
pytest.param('1990-12-31T15:59:60-08:00', marks=pytest.mark.xfail),
'1937-01-01T12:00:27.87+00:20',
)
)
def test_date_time_format_validator_with_valid_dateties(value):
date_time_format_validator(value)
def test_uuid1_matches():
for _ in range(100):
uuid_format_validator(str(uuid.uuid1()))
def test_uuid3_matches():
for _ in range(100):
uuid_format_validator(str(uuid.uuid3(uuid.uuid4(), 'test-4')))
uuid_format_validator(str(uuid.uuid3(uuid.uuid1(), 'test-1')))
def test_uuid4_matches():
for _ in range(100):
uuid_format_validator(str(uuid.uuid4()))
def test_uuid5_matches():
for _ in range(100):
uuid_format_validator(str(uuid.uuid5(uuid.uuid4(), 'test-4')))
uuid_format_validator(str(uuid.uuid5(uuid.uuid1(), 'test-1')))
MAX_INT32 = 2 ** 31 - 1
MIN_INT32 = -1 * 2 ** 31
MAX_INT64 = 2 ** 63 - 1
MIN_INT64 = -1 * 2 ** 63
@pytest.mark.parametrize(
'n',
(MIN_INT32, -1, 0, 1, MAX_INT32),
)
def test_int32_with_in_range_number(n):
int32_validator(n)
@pytest.mark.parametrize(
'n',
(MIN_INT32 - 1, MAX_INT32 + 1),
)
def test_int32_with_out_of_range_number(n):
with pytest.raises(ValidationError):
int32_validator(n)
@pytest.mark.parametrize(
'n',
(MIN_INT64, -1, 0, 1, MAX_INT64),
)
def test_int64_with_in_range_number(n):
int64_validator(n)
@pytest.mark.parametrize(
'n',
(MIN_INT64 - 1, MAX_INT64 + 1),
)
def test_int64_with_out_of_range_number(n):
with pytest.raises(ValidationError):
int64_validator(n)
@pytest.mark.parametrize(
'email_address',
(
'test@example.com',
'test+extra@example.com',
),
)
def test_email_validation_with_valid_email_addresses(email_address):
email_validator(email_address)
@pytest.mark.parametrize(
'email_address',
(
'example.com',
'www.example.com',
'not-an-email-address-at-all',
),
)
def test_email_validation_with_invalid_email_addresses(email_address):
with pytest.raises(ValidationError):
email_validator(email_address)
| true | true |
f7f745691a17c855759eaa6d1a27b92ce0957319 | 2,235 | py | Python | server/www/packages/packages-windows/x86/ldap3/protocol/sasl/plain.py | tinygg/teleport | 5ac759c707d355767a209e29becaadf250b0e366 | [
"Apache-2.0"
] | 640 | 2018-09-12T03:14:13.000Z | 2022-03-30T04:38:09.000Z | server/www/packages/packages-windows/x86/ldap3/protocol/sasl/plain.py | tinygg/teleport | 5ac759c707d355767a209e29becaadf250b0e366 | [
"Apache-2.0"
] | 175 | 2018-09-10T19:52:20.000Z | 2022-03-30T04:37:30.000Z | server/www/packages/packages-windows/x86/ldap3/protocol/sasl/plain.py | tinygg/teleport | 5ac759c707d355767a209e29becaadf250b0e366 | [
"Apache-2.0"
] | 230 | 2018-09-13T02:40:49.000Z | 2022-03-29T11:53:58.000Z | """
"""
# Created on 2014.01.04
#
# Author: Giovanni Cannata
#
# Copyright 2014 - 2020 Giovanni Cannata
#
# This file is part of ldap3.
#
# ldap3 is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ldap3 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with ldap3 in the COPYING and COPYING.LESSER files.
# If not, see <http://www.gnu.org/licenses/>.
# payload for PLAIN mechanism
# message = [authzid] UTF8NUL authcid UTF8NUL passwd
# authcid = 1*SAFE ; MUST accept up to 255 octets
# authzid = 1*SAFE ; MUST accept up to 255 octets
# passwd = 1*SAFE ; MUST accept up to 255 octets
# UTF8NUL = %x00 ; UTF-8 encoded NUL character
#
# SAFE = UTF1 / UTF2 / UTF3 / UTF4
# ;; any UTF-8 encoded Unicode character except NUL
#
# UTF1 = %x01-7F ;; except NUL
# UTF2 = %xC2-DF UTF0
# UTF3 = %xE0 %xA0-BF UTF0 / %xE1-EC 2(UTF0) /
# %xED %x80-9F UTF0 / %xEE-EF 2(UTF0)
# UTF4 = %xF0 %x90-BF 2(UTF0) / %xF1-F3 3(UTF0) /
# %xF4 %x80-8F 2(UTF0)
# UTF0 = %x80-BF
from ...protocol.sasl.sasl import send_sasl_negotiation
from .sasl import sasl_prep
from ...utils.conv import to_raw, to_unicode
def sasl_plain(connection, controls):
authzid = connection.sasl_credentials[0]
authcid = connection.sasl_credentials[1]
passwd = connection.sasl_credentials[2]
payload = b''
if authzid:
payload += to_raw(sasl_prep(to_unicode(authzid)))
payload += b'\0'
if authcid:
payload += to_raw(sasl_prep(to_unicode(authcid)))
payload += b'\0'
if passwd:
payload += to_raw(sasl_prep(to_unicode(passwd)))
result = send_sasl_negotiation(connection, controls, payload)
return result
| 31.478873 | 75 | 0.656823 |
from ...protocol.sasl.sasl import send_sasl_negotiation
from .sasl import sasl_prep
from ...utils.conv import to_raw, to_unicode
def sasl_plain(connection, controls):
authzid = connection.sasl_credentials[0]
authcid = connection.sasl_credentials[1]
passwd = connection.sasl_credentials[2]
payload = b''
if authzid:
payload += to_raw(sasl_prep(to_unicode(authzid)))
payload += b'\0'
if authcid:
payload += to_raw(sasl_prep(to_unicode(authcid)))
payload += b'\0'
if passwd:
payload += to_raw(sasl_prep(to_unicode(passwd)))
result = send_sasl_negotiation(connection, controls, payload)
return result
| true | true |
f7f74639fb5a2a886b8020a3fba3b1af8656fbe3 | 4,700 | py | Python | tree.py | arash2060/WeSHClass | 5251689f1d064e41f8d8aa8c48baf7052ad74a9a | [
"Apache-2.0"
] | null | null | null | tree.py | arash2060/WeSHClass | 5251689f1d064e41f8d8aa8c48baf7052ad74a9a | [
"Apache-2.0"
] | null | null | null | tree.py | arash2060/WeSHClass | 5251689f1d064e41f8d8aa8c48baf7052ad74a9a | [
"Apache-2.0"
] | null | null | null |
class ClassNode(object):
def __init__(self, name, parent, label=None):
self.name = name
self.parent = parent
self.label = label
self.children = []
self.keywords = []
self.expanded = []
self.doc_idx = []
self.model = None
self.embedding = None
self.sup_idx = []
def add_child(self, node):
self.children.append(node)
def add_keywords(self, keywords):
self.keywords += keywords
def find_descendants(self):
if self.children == []:
return []
else:
descendants = self.children
for child in self.children:
descendants += child.find_descendants()
return descendants
def find_leaves(self):
leaves = []
if self.children == []:
leaves += [self]
else:
for child in self.children:
leaves += child.find_leaves()
return leaves
def find_ancestors(self):
if self.label == -1 or self.parent.label == -1 : # self or parent is ROOT
return []
return [self.parent] + self.parent.find_ancestors()
def get_full_label(self):
full_label = [self.label]
ancestors = self.find_ancestors()
for ancestor in ancestors:
full_label.append(ancestor.label)
return full_label
def get_size(self):
sz = 1
for child in self.children:
sz += child.get_size()
return sz
def get_height(self):
if self.children == []:
return 0
else:
heights = [child.get_height() for child in self.children]
return max(heights) + 1
def find(self, name):
if type(name) == str:
if name == self.name:
return self
elif type(name) == int:
if name == self.label:
return self
if self.children == []:
return None
for child in self.children:
if child.find(name):
return child.find(name)
return None
def find_add_child(self, name, node):
target = self.find(name)
assert target
target.add_child(node)
def find_add_keywords(self, name, keywords):
target = self.find(name)
assert target, f'Class {name} not found!'
target.add_keywords(keywords)
def aggregate_keywords(self):
if self.children == []:
assert self.keywords
else:
if self.keywords == []:
for child in self.children:
self.add_keywords(child.aggregate_keywords())
return self.keywords
def name2label(self, name):
target = self.find(name)
assert target
return target.get_full_label()
def find_at_level(self, level):
targets = []
if level == 0:
targets.append(self)
else:
for child in self.children:
targets += child.find_at_level(level-1)
return targets
def siblings_at_level(self, level):
siblings_map = {}
parent_nodes = self.find_at_level(level)
offset = 0
for node in parent_nodes:
num_children = len(node.children)
siblings = range(offset, offset+num_children)
for i in range(offset, offset+num_children):
siblings_map[i] = siblings
offset += num_children
return siblings_map
def visualize_tree(self):
print_string = self.name + ' (' + str(self.label) + ') ' + '\t'
print_string += ','.join(child.name for child in self.children) + '\n'
for child in self.children:
print_string += child.visualize_tree()
return print_string
def visualize_node(self):
print_string = self.name + ' (' + str(self.label) + ') ' + '\n'
if self.parent:
print_string += "Parent: " + self.parent.name + '\n'
else:
print_string += "Parent: None \n"
if self.children:
print_string += "Children: " + ','.join(child.name for child in self.children) + '\n'
else:
print_string += "Children: None \n"
if self.keywords:
print_string += "Keywords: " + ','.join(keyword for keyword in self.keywords) + '\n'
else:
print_string += "Keywords: None \n"
print_string += '\n'
return print_string
def visualize_nodes(self):
print_string = self.visualize_node()
for child in self.children:
print_string += child.visualize_nodes()
return print_string
| 30.718954 | 97 | 0.548085 |
class ClassNode(object):
def __init__(self, name, parent, label=None):
self.name = name
self.parent = parent
self.label = label
self.children = []
self.keywords = []
self.expanded = []
self.doc_idx = []
self.model = None
self.embedding = None
self.sup_idx = []
def add_child(self, node):
self.children.append(node)
def add_keywords(self, keywords):
self.keywords += keywords
def find_descendants(self):
if self.children == []:
return []
else:
descendants = self.children
for child in self.children:
descendants += child.find_descendants()
return descendants
def find_leaves(self):
leaves = []
if self.children == []:
leaves += [self]
else:
for child in self.children:
leaves += child.find_leaves()
return leaves
def find_ancestors(self):
if self.label == -1 or self.parent.label == -1 :
return []
return [self.parent] + self.parent.find_ancestors()
def get_full_label(self):
full_label = [self.label]
ancestors = self.find_ancestors()
for ancestor in ancestors:
full_label.append(ancestor.label)
return full_label
def get_size(self):
sz = 1
for child in self.children:
sz += child.get_size()
return sz
def get_height(self):
if self.children == []:
return 0
else:
heights = [child.get_height() for child in self.children]
return max(heights) + 1
def find(self, name):
if type(name) == str:
if name == self.name:
return self
elif type(name) == int:
if name == self.label:
return self
if self.children == []:
return None
for child in self.children:
if child.find(name):
return child.find(name)
return None
def find_add_child(self, name, node):
target = self.find(name)
assert target
target.add_child(node)
def find_add_keywords(self, name, keywords):
target = self.find(name)
assert target, f'Class {name} not found!'
target.add_keywords(keywords)
def aggregate_keywords(self):
if self.children == []:
assert self.keywords
else:
if self.keywords == []:
for child in self.children:
self.add_keywords(child.aggregate_keywords())
return self.keywords
def name2label(self, name):
target = self.find(name)
assert target
return target.get_full_label()
def find_at_level(self, level):
targets = []
if level == 0:
targets.append(self)
else:
for child in self.children:
targets += child.find_at_level(level-1)
return targets
def siblings_at_level(self, level):
siblings_map = {}
parent_nodes = self.find_at_level(level)
offset = 0
for node in parent_nodes:
num_children = len(node.children)
siblings = range(offset, offset+num_children)
for i in range(offset, offset+num_children):
siblings_map[i] = siblings
offset += num_children
return siblings_map
def visualize_tree(self):
print_string = self.name + ' (' + str(self.label) + ') ' + '\t'
print_string += ','.join(child.name for child in self.children) + '\n'
for child in self.children:
print_string += child.visualize_tree()
return print_string
def visualize_node(self):
print_string = self.name + ' (' + str(self.label) + ') ' + '\n'
if self.parent:
print_string += "Parent: " + self.parent.name + '\n'
else:
print_string += "Parent: None \n"
if self.children:
print_string += "Children: " + ','.join(child.name for child in self.children) + '\n'
else:
print_string += "Children: None \n"
if self.keywords:
print_string += "Keywords: " + ','.join(keyword for keyword in self.keywords) + '\n'
else:
print_string += "Keywords: None \n"
print_string += '\n'
return print_string
def visualize_nodes(self):
print_string = self.visualize_node()
for child in self.children:
print_string += child.visualize_nodes()
return print_string
| true | true |
f7f746654d3d209cfadfd94cc49e682df5e712a0 | 555 | py | Python | Backend/equation test/venv/Lib/site-packages/kwargs/__init__.py | chehansivaruban/Cyber---SDGP | 6676c284c34c4c15279bf3e5cfb73fd4e5b7391a | [
"CC0-1.0"
] | 1 | 2021-05-18T10:55:32.000Z | 2021-05-18T10:55:32.000Z | Backend/equation test/venv/Lib/site-packages/kwargs/__init__.py | chehansivaruban/Cyber---SDGP | 6676c284c34c4c15279bf3e5cfb73fd4e5b7391a | [
"CC0-1.0"
] | null | null | null | Backend/equation test/venv/Lib/site-packages/kwargs/__init__.py | chehansivaruban/Cyber---SDGP | 6676c284c34c4c15279bf3e5cfb73fd4e5b7391a | [
"CC0-1.0"
] | 2 | 2021-03-29T19:00:55.000Z | 2021-04-02T13:18:07.000Z | #pylint: disable=too-few-public-methods
""" Kwargs is the only True python micro-framework that doesn't limit your creativity™. """
def run(callback, *args, **kwargs):
""" Alias for App.run """
return callback(*args, **kwargs)
class App(object):
""" App represents Kwargs application instance. """
def __init__(self, callback):
self.callback = callback
def run(self, *args, **kwargs):
""" Exexutes callback function provided in __init__ with given parameters """
return run(self.callback, *args, **kwargs)
| 30.833333 | 91 | 0.664865 |
def run(callback, *args, **kwargs):
return callback(*args, **kwargs)
class App(object):
def __init__(self, callback):
self.callback = callback
def run(self, *args, **kwargs):
return run(self.callback, *args, **kwargs)
| true | true |
f7f747bd1f403cd6bba10abbd1809c53f6884a40 | 2,198 | py | Python | merge.py | Junot974/Excel-Merge-Script | 6c2216043f665affa8db70bf353c40a0deed82d5 | [
"MIT"
] | 1 | 2022-02-02T14:47:39.000Z | 2022-02-02T14:47:39.000Z | merge.py | Junot974/Excel-Merge-Script | 6c2216043f665affa8db70bf353c40a0deed82d5 | [
"MIT"
] | null | null | null | merge.py | Junot974/Excel-Merge-Script | 6c2216043f665affa8db70bf353c40a0deed82d5 | [
"MIT"
] | null | null | null | # importing openpyxl module
import openpyxl as xl;
from openpyxl import load_workbook
from openpyxl import Workbook
##
#Create Workbook
##
wb = Workbook()
ws = wb.active
ws.title = "worksheet"
wb.save(filename = '/path/file.xlsx')
##
# opening the source excel file
##
wb1 = xl.load_workbook("/path/file1.xlsx")
ws1 = wb1.worksheets[0]
wb2 = xl.load_workbook("/path/file2.xlsx")
ws2 = wb2.worksheets[0]
wb3 = xl.load_workbook("/path/file3.xlsx")
ws3 = wb3.worksheets[0]
# opening the destination excel file
filename1 ="/path/file.xlsx"
wb4 = xl.load_workbook(filename1)
wb4.create_sheet('Worksheet2')
wb4.create_sheet('Worksheet3')
ws4 = wb4.worksheets[0]
ws5 = wb4.worksheets[1]
ws6 = wb4.worksheets[2]
wb4.save('/path/sortieFinale.xlsx')
# calculate total number of rows and
# columns in source excel file
mr = ws1.max_row
mc = ws1.max_column
# copying the cell values from source
# excel file to destination excel file
for i in range (1, mr + 1):
for j in range (1, mc + 1):
# reading cell value from source excel file
c = ws1.cell(row = i, column = j)
# writing the read value to destination excel file
ws4.cell(row = i, column = j).value = c.value
# calculate total number of rows and
# columns in source excel file
mr = ws2.max_row
mc = ws2.max_column
# copying the cell values from source
# excel file to destination excel file
for i in range (1, mr + 1):
for j in range (1, mc + 1):
# reading cell value from source excel file
c = ws2.cell(row = i, column = j)
# writing the read value to destination excel file
ws5.cell(row = i, column = j).value = c.value
# calculate total number of rows and
# columns in source excel file
mr = ws3.max_row
mc = ws3.max_column
# copying the cell values from source
# excel file to destination excel file
for i in range (1, mr + 1):
for j in range (1, mc + 1):
# reading cell value from source excel file
c = ws3.cell(row = i, column = j)
# writing the read value to destination excel file
ws6.cell(row = i, column = j).value = c.value
# saving the destination excel file
wb4.save(str(filename1))
| 23.382979 | 58 | 0.674249 |
import openpyxl as xl;
from openpyxl import load_workbook
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.title = "worksheet"
wb.save(filename = '/path/file.xlsx')
wb1 = xl.load_workbook("/path/file1.xlsx")
ws1 = wb1.worksheets[0]
wb2 = xl.load_workbook("/path/file2.xlsx")
ws2 = wb2.worksheets[0]
wb3 = xl.load_workbook("/path/file3.xlsx")
ws3 = wb3.worksheets[0]
filename1 ="/path/file.xlsx"
wb4 = xl.load_workbook(filename1)
wb4.create_sheet('Worksheet2')
wb4.create_sheet('Worksheet3')
ws4 = wb4.worksheets[0]
ws5 = wb4.worksheets[1]
ws6 = wb4.worksheets[2]
wb4.save('/path/sortieFinale.xlsx')
mr = ws1.max_row
mc = ws1.max_column
for i in range (1, mr + 1):
for j in range (1, mc + 1):
c = ws1.cell(row = i, column = j)
ws4.cell(row = i, column = j).value = c.value
mr = ws2.max_row
mc = ws2.max_column
for i in range (1, mr + 1):
for j in range (1, mc + 1):
c = ws2.cell(row = i, column = j)
ws5.cell(row = i, column = j).value = c.value
mr = ws3.max_row
mc = ws3.max_column
for i in range (1, mr + 1):
for j in range (1, mc + 1):
c = ws3.cell(row = i, column = j)
ws6.cell(row = i, column = j).value = c.value
wb4.save(str(filename1))
| true | true |
f7f7485c61c709ca15618f4cdb3c6f17289f7bfd | 3,535 | py | Python | kaori/plugins/gacha/engine/core/battle.py | austinpray/kaori | b21c4146b9d0d27b87015cff0768138568a12e9c | [
"MIT"
] | 3 | 2020-05-04T03:43:20.000Z | 2020-12-03T22:34:47.000Z | kaori/plugins/gacha/engine/core/battle.py | austinpray/kaori | b21c4146b9d0d27b87015cff0768138568a12e9c | [
"MIT"
] | 287 | 2020-04-21T02:39:47.000Z | 2022-03-28T13:11:59.000Z | kaori/plugins/gacha/engine/core/battle.py | austinpray/kaori | b21c4146b9d0d27b87015cff0768138568a12e9c | [
"MIT"
] | 1 | 2020-10-22T00:20:43.000Z | 2020-10-22T00:20:43.000Z | from __future__ import annotations
import re
from enum import Enum, unique
from random import sample, random
from typing import List
from .card import Card
from .. import CRIT_MULTIPLIER
@unique
class TurnResult(Enum):
standoff = 'S'
evade = 'E'
hit = 'H'
kill = 'K'
def __str__(self):
return self.value
_standoff = TurnResult.standoff
_evade = TurnResult.evade
_hit = TurnResult.hit
_kill = TurnResult.kill
class Turn:
_serialize_version = 1
def __init__(self,
attacker: Card,
defender: Card,
result: TurnResult) -> None:
self.result = result
self.defender = defender
self.attacker = attacker
self.dmg = 0
self.crit = False
notation_regex = re.compile(r'(?P<prefix>v(?P<version>\d+)\.(?P<attacker>\d+)x(?P<defender>\d+))'
r'(?P<payload>(?P<result>[A-Z])(?P<dmg>\d+)?(?P<crit>C)?)')
def __str__(self) -> str:
result = str(self.result)
if self.result in [_hit, _kill]:
crit = 'C' if self.crit else ''
result += f'{self.dmg}{crit}'
return f"v{self._serialize_version}.{self.attacker.id}x{self.defender.id}{result}"
class Battle:
turns: List[Turn]
winner: Card
loser: Card
def __init__(self,
card_a: Card,
card_b: Card) -> None:
self.card_a = card_a
self.card_b = card_b
self.winner = None
self.loser = None
self.turns = []
self.debug = False
def run(self) -> Battle:
a = self.card_a
b = self.card_b
if a.speed != b.speed:
cards = sorted([a, b], key=lambda card: -card.speed)
else:
cards = sample([a, b], 2)
first, second = cards
if Card.detect_standoff(a, b, debug=self.debug):
self.turns.append(Turn(attacker=first, defender=second, result=_standoff))
return self
while a.current_hp > 0 and b.current_hp > 0:
turn = len(self.turns)
if turn > 100:
raise RuntimeError('This battle is taking too long...')
attacker = cards[turn % len(cards)]
defender = cards[(turn + 1) % len(cards)]
turn = Turn(attacker=attacker, defender=defender, result=_hit)
# evasion check
if random() < defender.evasion:
turn.result = _evade
self.turns.append(turn)
continue
crit_multiplier = 1
if random() < attacker.crit:
crit_multiplier = CRIT_MULTIPLIER
turn.crit = True
turn.dmg = attacker.attack_damage(defender, crit_multiplier=crit_multiplier, debug=self.debug)
defender.accept_damage(turn.dmg)
if defender.current_hp < 1:
turn.result = _kill
self.turns.append(turn)
self.winner = attacker
self.loser = defender
break
self.turns.append(turn)
return self
def serialize_min(self):
turns_prefix = Turn.notation_regex.match(str(self.turns[0])).group('prefix')
turns = [
Turn.notation_regex.match(str(t)).group('payload')
for t in self.turns
]
return {
'a': self.card_a.serialize_min(),
'b': self.card_b.serialize_min(),
'turns': turns_prefix + '~'.join(turns)
}
| 26.380597 | 106 | 0.546252 | from __future__ import annotations
import re
from enum import Enum, unique
from random import sample, random
from typing import List
from .card import Card
from .. import CRIT_MULTIPLIER
@unique
class TurnResult(Enum):
standoff = 'S'
evade = 'E'
hit = 'H'
kill = 'K'
def __str__(self):
return self.value
_standoff = TurnResult.standoff
_evade = TurnResult.evade
_hit = TurnResult.hit
_kill = TurnResult.kill
class Turn:
_serialize_version = 1
def __init__(self,
attacker: Card,
defender: Card,
result: TurnResult) -> None:
self.result = result
self.defender = defender
self.attacker = attacker
self.dmg = 0
self.crit = False
notation_regex = re.compile(r'(?P<prefix>v(?P<version>\d+)\.(?P<attacker>\d+)x(?P<defender>\d+))'
r'(?P<payload>(?P<result>[A-Z])(?P<dmg>\d+)?(?P<crit>C)?)')
def __str__(self) -> str:
result = str(self.result)
if self.result in [_hit, _kill]:
crit = 'C' if self.crit else ''
result += f'{self.dmg}{crit}'
return f"v{self._serialize_version}.{self.attacker.id}x{self.defender.id}{result}"
class Battle:
turns: List[Turn]
winner: Card
loser: Card
def __init__(self,
card_a: Card,
card_b: Card) -> None:
self.card_a = card_a
self.card_b = card_b
self.winner = None
self.loser = None
self.turns = []
self.debug = False
def run(self) -> Battle:
a = self.card_a
b = self.card_b
if a.speed != b.speed:
cards = sorted([a, b], key=lambda card: -card.speed)
else:
cards = sample([a, b], 2)
first, second = cards
if Card.detect_standoff(a, b, debug=self.debug):
self.turns.append(Turn(attacker=first, defender=second, result=_standoff))
return self
while a.current_hp > 0 and b.current_hp > 0:
turn = len(self.turns)
if turn > 100:
raise RuntimeError('This battle is taking too long...')
attacker = cards[turn % len(cards)]
defender = cards[(turn + 1) % len(cards)]
turn = Turn(attacker=attacker, defender=defender, result=_hit)
if random() < defender.evasion:
turn.result = _evade
self.turns.append(turn)
continue
crit_multiplier = 1
if random() < attacker.crit:
crit_multiplier = CRIT_MULTIPLIER
turn.crit = True
turn.dmg = attacker.attack_damage(defender, crit_multiplier=crit_multiplier, debug=self.debug)
defender.accept_damage(turn.dmg)
if defender.current_hp < 1:
turn.result = _kill
self.turns.append(turn)
self.winner = attacker
self.loser = defender
break
self.turns.append(turn)
return self
def serialize_min(self):
turns_prefix = Turn.notation_regex.match(str(self.turns[0])).group('prefix')
turns = [
Turn.notation_regex.match(str(t)).group('payload')
for t in self.turns
]
return {
'a': self.card_a.serialize_min(),
'b': self.card_b.serialize_min(),
'turns': turns_prefix + '~'.join(turns)
}
| true | true |
f7f748efe0013552a936e9073a8acffd56620df4 | 4,626 | py | Python | torchreid/data/datasets/video/mars.py | qw85639229/hardest | ef86536dbbe1089248e34afbbb7bb513f97f58f1 | [
"MIT"
] | 23 | 2021-08-06T01:08:34.000Z | 2022-03-30T02:54:57.000Z | torchreid/data/datasets/video/mars.py | qw85639229/hardest | ef86536dbbe1089248e34afbbb7bb513f97f58f1 | [
"MIT"
] | 10 | 2020-11-18T07:40:22.000Z | 2021-10-05T07:58:25.000Z | torchreid/data/datasets/video/mars.py | qw85639229/hardest | ef86536dbbe1089248e34afbbb7bb513f97f58f1 | [
"MIT"
] | 7 | 2020-11-19T08:40:27.000Z | 2022-02-05T06:24:08.000Z | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import sys
import os
import os.path as osp
from scipy.io import loadmat
import warnings
from torchreid.data.datasets import VideoDataset
class Mars(VideoDataset):
"""MARS.
Reference:
Zheng et al. MARS: A Video Benchmark for Large-Scale Person Re-identification. ECCV 2016.
URL: `<http://www.liangzheng.com.cn/Project/project_mars.html>`_
Dataset statistics:
- identities: 1261.
- tracklets: 8298 (train) + 1980 (query) + 9330 (gallery).
- cameras: 6.
"""
dataset_dir = 'mars'
dataset_url = None
def __init__(self, root='', **kwargs):
self.root = osp.abspath(osp.expanduser(root))
self.dataset_dir = osp.join(self.root, self.dataset_dir)
self.download_dataset(self.dataset_dir, self.dataset_url)
self.train_name_path = osp.join(self.dataset_dir, 'info/train_name.txt')
self.test_name_path = osp.join(self.dataset_dir, 'info/test_name.txt')
self.track_train_info_path = osp.join(self.dataset_dir, 'info/tracks_train_info.mat')
self.track_test_info_path = osp.join(self.dataset_dir, 'info/tracks_test_info.mat')
self.query_IDX_path = osp.join(self.dataset_dir, 'info/query_IDX.mat')
required_files = [
self.dataset_dir,
self.train_name_path,
self.test_name_path,
self.track_train_info_path,
self.track_test_info_path,
self.query_IDX_path
]
self.check_before_run(required_files)
train_names = self.get_names(self.train_name_path)
test_names = self.get_names(self.test_name_path)
track_train = loadmat(self.track_train_info_path)['track_train_info'] # numpy.ndarray (8298, 4)
track_test = loadmat(self.track_test_info_path)['track_test_info'] # numpy.ndarray (12180, 4)
query_IDX = loadmat(self.query_IDX_path)['query_IDX'].squeeze() # numpy.ndarray (1980,)
query_IDX -= 1 # index from 0
track_query = track_test[query_IDX,:]
gallery_IDX = [i for i in range(track_test.shape[0]) if i not in query_IDX]
track_gallery = track_test[gallery_IDX,:]
train = self.process_data(train_names, track_train, home_dir='bbox_train', relabel=True)
query = self.process_data(test_names, track_query, home_dir='bbox_test', relabel=False)
gallery = self.process_data(test_names, track_gallery, home_dir='bbox_test', relabel=False)
super(Mars, self).__init__(train, query, gallery, **kwargs)
def get_names(self, fpath):
names = []
with open(fpath, 'r') as f:
for line in f:
new_line = line.rstrip()
names.append(new_line)
return names
def process_data(self, names, meta_data, home_dir=None, relabel=False, min_seq_len=0):
assert home_dir in ['bbox_train', 'bbox_test']
num_tracklets = meta_data.shape[0]
pid_list = list(set(meta_data[:,2].tolist()))
num_pids = len(pid_list)
if relabel: pid2label = {pid:label for label, pid in enumerate(pid_list)}
tracklets = []
for tracklet_idx in range(num_tracklets):
data = meta_data[tracklet_idx,...]
start_index, end_index, pid, camid = data
if pid == -1:
continue # junk images are just ignored
assert 1 <= camid <= 6
if relabel: pid = pid2label[pid]
camid -= 1 # index starts from 0
img_names = names[start_index - 1:end_index]
# make sure image names correspond to the same person
pnames = [img_name[:4] for img_name in img_names]
assert len(set(pnames)) == 1, 'Error: a single tracklet contains different person images'
# make sure all images are captured under the same camera
camnames = [img_name[5] for img_name in img_names]
assert len(set(camnames)) == 1, 'Error: images are captured under different cameras!'
# append image names with directory information
img_paths = [osp.join(self.dataset_dir, home_dir, img_name[:4], img_name) for img_name in img_names]
if len(img_paths) >= min_seq_len:
img_paths = tuple(img_paths)
tracklets.append((img_paths, pid, camid))
return tracklets
def combine_all(self):
warnings.warn('Some query IDs do not appear in gallery. Therefore, combineall '
'does not make any difference to Mars') | 41.303571 | 112 | 0.648508 | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import sys
import os
import os.path as osp
from scipy.io import loadmat
import warnings
from torchreid.data.datasets import VideoDataset
class Mars(VideoDataset):
dataset_dir = 'mars'
dataset_url = None
def __init__(self, root='', **kwargs):
self.root = osp.abspath(osp.expanduser(root))
self.dataset_dir = osp.join(self.root, self.dataset_dir)
self.download_dataset(self.dataset_dir, self.dataset_url)
self.train_name_path = osp.join(self.dataset_dir, 'info/train_name.txt')
self.test_name_path = osp.join(self.dataset_dir, 'info/test_name.txt')
self.track_train_info_path = osp.join(self.dataset_dir, 'info/tracks_train_info.mat')
self.track_test_info_path = osp.join(self.dataset_dir, 'info/tracks_test_info.mat')
self.query_IDX_path = osp.join(self.dataset_dir, 'info/query_IDX.mat')
required_files = [
self.dataset_dir,
self.train_name_path,
self.test_name_path,
self.track_train_info_path,
self.track_test_info_path,
self.query_IDX_path
]
self.check_before_run(required_files)
train_names = self.get_names(self.train_name_path)
test_names = self.get_names(self.test_name_path)
track_train = loadmat(self.track_train_info_path)['track_train_info']
track_test = loadmat(self.track_test_info_path)['track_test_info']
query_IDX = loadmat(self.query_IDX_path)['query_IDX'].squeeze()
query_IDX -= 1
track_query = track_test[query_IDX,:]
gallery_IDX = [i for i in range(track_test.shape[0]) if i not in query_IDX]
track_gallery = track_test[gallery_IDX,:]
train = self.process_data(train_names, track_train, home_dir='bbox_train', relabel=True)
query = self.process_data(test_names, track_query, home_dir='bbox_test', relabel=False)
gallery = self.process_data(test_names, track_gallery, home_dir='bbox_test', relabel=False)
super(Mars, self).__init__(train, query, gallery, **kwargs)
def get_names(self, fpath):
names = []
with open(fpath, 'r') as f:
for line in f:
new_line = line.rstrip()
names.append(new_line)
return names
def process_data(self, names, meta_data, home_dir=None, relabel=False, min_seq_len=0):
assert home_dir in ['bbox_train', 'bbox_test']
num_tracklets = meta_data.shape[0]
pid_list = list(set(meta_data[:,2].tolist()))
num_pids = len(pid_list)
if relabel: pid2label = {pid:label for label, pid in enumerate(pid_list)}
tracklets = []
for tracklet_idx in range(num_tracklets):
data = meta_data[tracklet_idx,...]
start_index, end_index, pid, camid = data
if pid == -1:
continue
assert 1 <= camid <= 6
if relabel: pid = pid2label[pid]
camid -= 1
img_names = names[start_index - 1:end_index]
pnames = [img_name[:4] for img_name in img_names]
assert len(set(pnames)) == 1, 'Error: a single tracklet contains different person images'
camnames = [img_name[5] for img_name in img_names]
assert len(set(camnames)) == 1, 'Error: images are captured under different cameras!'
img_paths = [osp.join(self.dataset_dir, home_dir, img_name[:4], img_name) for img_name in img_names]
if len(img_paths) >= min_seq_len:
img_paths = tuple(img_paths)
tracklets.append((img_paths, pid, camid))
return tracklets
def combine_all(self):
warnings.warn('Some query IDs do not appear in gallery. Therefore, combineall '
'does not make any difference to Mars') | true | true |
f7f74941e5f5f6321fad4f1337bc31f93ae45f52 | 862 | py | Python | talent/admin.py | flannerykj/urbanapplause | c9b6c0f9a2f65b869fe1e6fa921972e7236e4fe5 | [
"MIT"
] | null | null | null | talent/admin.py | flannerykj/urbanapplause | c9b6c0f9a2f65b869fe1e6fa921972e7236e4fe5 | [
"MIT"
] | null | null | null | talent/admin.py | flannerykj/urbanapplause | c9b6c0f9a2f65b869fe1e6fa921972e7236e4fe5 | [
"MIT"
] | null | null | null | from django.contrib import admin
from .models import Musician
from .models import Artist
class MusicianAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['name']}),
(None, {'fields': ['instruments']}),
]
list_display = ('name', 'author')
def save_model(self, request, obj, form, change):
obj.author = request.user
obj.save()
admin.site.register(Musician, MusicianAdmin)
class ArtistAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['name']}),
(None, {'fields': ['style']}),
(None, {'fields': ['talent_type']}),
]
list_display = ('name', 'author')
def save_model(self, request, obj, form, change):
obj.author = request.user
obj.save()
admin.site.register(Artist, ArtistAdmin) | 29.724138 | 58 | 0.562645 | from django.contrib import admin
from .models import Musician
from .models import Artist
class MusicianAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['name']}),
(None, {'fields': ['instruments']}),
]
list_display = ('name', 'author')
def save_model(self, request, obj, form, change):
obj.author = request.user
obj.save()
admin.site.register(Musician, MusicianAdmin)
class ArtistAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['name']}),
(None, {'fields': ['style']}),
(None, {'fields': ['talent_type']}),
]
list_display = ('name', 'author')
def save_model(self, request, obj, form, change):
obj.author = request.user
obj.save()
admin.site.register(Artist, ArtistAdmin) | false | true |
f7f74a63b487684635c3869ac1122ea2a0b8e2e9 | 18,906 | py | Python | FeatureServer/Server.py | AstunTechnology/featureserver | 0697730de12b7bc4c8d90bab829d95a865253e77 | [
"BSD-3-Clause-Open-MPI",
"MIT"
] | 55 | 2015-01-20T14:29:59.000Z | 2020-12-13T12:54:28.000Z | FeatureServer/Server.py | makinacorpus/featureserver | 379c1a7f51e75517ae7237751e1908f45c0c4d9a | [
"BSD-3-Clause-Open-MPI",
"MIT"
] | 3 | 2017-01-17T13:52:43.000Z | 2021-01-13T10:50:27.000Z | FeatureServer/Server.py | makinacorpus/featureserver | 379c1a7f51e75517ae7237751e1908f45c0c4d9a | [
"BSD-3-Clause-Open-MPI",
"MIT"
] | 19 | 2015-02-08T12:32:25.000Z | 2021-12-01T08:14:32.000Z | #!/usr/bin/python
__author__ = "MetaCarta"
__copyright__ = "Copyright (c) 2006-2008 MetaCarta"
__license__ = "Clear BSD"
__version__ = "$Id: Server.py 607 2009-04-27 15:53:15Z crschmidt $"
import sys
import time
import os
import traceback
import ConfigParser
from web_request.handlers import wsgi, mod_python, cgi
from lxml import etree
import cgi as cgimod
from FeatureServer.WebFeatureService.Response.TransactionResponse import TransactionResponse
from FeatureServer.WebFeatureService.Response.TransactionSummary import TransactionSummary
from FeatureServer.WebFeatureService.Response.ActionResult import ActionResult
from FeatureServer.Workspace.FileHandler import FileHandler
from FeatureServer.Exceptions.ExceptionReport import ExceptionReport
from FeatureServer.Exceptions.WebFeatureService.InvalidValueException import InvalidValueException
from FeatureServer.Exceptions.ConnectionException import ConnectionException
from FeatureServer.Exceptions.LayerNotFoundException import LayerNotFoundException
import FeatureServer.Processing
from web_request.response import Response
# First, check explicit FS_CONFIG env var
if 'FS_CONFIG' in os.environ:
cfgfiles = os.environ['FS_CONFIG'].split(",")
# Otherwise, make some guesses.
else:
# Windows doesn't always do the 'working directory' check correctly.
if sys.platform == 'win32':
workingdir = os.path.abspath(os.path.join(os.getcwd(), os.path.dirname(sys.argv[0])))
cfgfiles = (os.path.join(workingdir, "featureserver.cfg"), os.path.join(workingdir,"..","featureserver.cfg"))
else:
cfgfiles = ("featureserver.cfg", os.path.join("..", "featureserver.cfg"), "/etc/featureserver.cfg")
class Server (object):
"""The server manages the datasource list, and does the management of
request input/output. Handlers convert their specific internal
representation to the parameters that dispatchRequest is expecting,
then pass off to dispatchRequest. dispatchRequest turns the input
parameters into a (content-type, response string) tuple, which the
servers can then return to clients. It is possible to integrate
FeatureServer into another content-serving framework like Django by
simply creating your own datasources (passed to the init function)
and calling the dispatchRequest method. The Server provides a classmethod
to load datasources from a config file, which is the typical lightweight
configuration method, but does use some amount of time at script startup.
"""
def __init__ (self, datasources, metadata = {}, processes = {}):
self.datasources = datasources
self.metadata = metadata
self.processes = processes
def _loadFromSection (cls, config, section, module_type, **objargs):
type = config.get(section, "type")
module = __import__("%s.%s" % (module_type, type), globals(), locals(), type)
objclass = getattr(module, type)
for opt in config.options(section):
objargs[opt] = config.get(section, opt)
if module_type is 'DataSource':
return objclass(section, **objargs)
else:
return objclass(**objargs)
loadFromSection = classmethod(_loadFromSection)
def _load (cls, *files):
"""Class method on Service class to load datasources
and metadata from a configuration file."""
config = ConfigParser.ConfigParser()
config.read(files)
metadata = {}
if config.has_section("metadata"):
for key in config.options("metadata"):
metadata[key] = config.get("metadata", key)
processes = {}
datasources = {}
for section in config.sections():
if section == "metadata": continue
if section.startswith("process_"):
try:
processes[section[8:]] = FeatureServer.Processing.loadFromSection(config, section)
except Exception, E:
pass
else:
datasources[section] = cls.loadFromSection(config, section, 'DataSource')
return cls(datasources, metadata, processes)
load = classmethod(_load)
def dispatchRequest (self, base_path="", path_info="/", params={}, request_method = "GET", post_data = None, accepts = ""):
"""Read in request data, and return a (content-type, response string) tuple. May
raise an exception, which should be returned as a 500 error to the user."""
response_code = "200 OK"
host = base_path
request = None
content_types = {
'application/vnd.google-earth.kml+xml': 'KML',
'application/json': 'GeoJSON',
'text/javascript': 'GeoJSON',
'application/rss+xml': 'GeoRSS',
'text/html': 'HTML',
'osm': 'OSM',
'gml': 'WFS',
'wfs': 'WFS',
'kml': 'KML',
'json': 'GeoJSON',
'georss': 'GeoRSS',
'atom': 'GeoRSS',
'html': 'HTML',
'geojson':'GeoJSON',
'shp': 'SHP',
'csv': 'CSV',
'gpx': 'GPX',
'ov2': 'OV2',
'sqlite': 'SQLite',
'dxf' : 'DXF'
}
exceptionReport = ExceptionReport()
path = path_info.split("/")
found = False
format = ""
if params.has_key("format"):
format = params['format']
if format.lower() in content_types:
format = content_types[format.lower()]
found = True
if not found and len(path) > 1:
path_pieces = path[-1].split(".")
if len(path_pieces) > 1:
format = path_pieces[-1]
if format.lower() in content_types:
format = content_types[format.lower()]
found = True
if not found and not params.has_key("service") and post_data:
try:
dom = etree.XML(post_data)
params['service'] = dom.get('service')
except etree.ParseError: pass
if not found and not params.has_key("version") and post_data:
try:
dom = etree.XML(post_data)
params['version'] = dom.get('version')
except etree.ParseError: pass
if not found and not params.has_key("typename") and post_data:
try:
dom = etree.XML(post_data)
for key, value in cgimod.parse_qsl(post_data, keep_blank_values=True):
if key.lower() == 'typename':
params['typename'] = value
except etree.ParseError: pass
if not found and params.has_key("service"):
format = params['service']
if format.lower() in content_types:
format = content_types[format.lower()]
found = True
if not found and accepts:
if accepts.lower() in content_types:
format = content_types[accepts.lower()]
found = True
if not found and not format:
if self.metadata.has_key("default_service"):
format = self.metadata['default_service']
else:
format = "WFS"
#===============================================================================
# (reflection) dynamic load of format class e.g. WFS, KML, etc.
# for supported format see package 'Service'
# ----------- -------
# | Request | <|------- | WFS |
# ----------- -------
#===============================================================================
service_module = __import__("Service.%s" % format, globals(), locals(), format)
service = getattr(service_module, format)
request = service(self)
response = []
try:
request.parse(params, path_info, host, post_data, request_method)
# short circuit datasource where the first action is a metadata request.
if len(request.actions) and request.actions[0].method == "metadata":
return request.encode_metadata(request.actions[0])
# short circuit datasource where a OGC WFS request is set
# processing by service
if len(request.actions) > 0 and hasattr(request.actions[0], 'request') and request.actions[0].request is not None:
version = '1.0.0'
if hasattr(request.actions[0], 'version') and len(request.actions[0].version) > 0:
version = request.actions[0].version
if request.actions[0].request.lower() == "getcapabilities":
return getattr(request, request.actions[0].request.lower())(version)
elif request.actions[0].request.lower() == "describefeaturetype":
return getattr(request, request.actions[0].request.lower())(version)
datasource = self.datasources[request.datasources[0]]
if request_method != "GET" and hasattr(datasource, 'processes'):
raise Exception("You can't post data to a processed layer.")
try:
datasource.begin()
if len(request.actions) > 0 and hasattr(request.actions[0], 'request') and request.actions[0].request is not None:
if request.actions[0].request.lower() == "getfeature":
''' '''
try:
transactionResponse = TransactionResponse()
transactionResponse.setSummary(TransactionSummary())
for action in request.actions:
method = getattr(datasource, action.method)
try:
result = method(action)
if isinstance(result, ActionResult):
transactionResponse.addResult(result)
elif result is not None:
response += result
except InvalidValueException as e:
exceptionReport.add(e)
datasource.commit()
except:
datasource.rollback()
raise
if hasattr(datasource, 'processes'):
for process in datasource.processes.split(","):
if not self.processes.has_key(process):
raise Exception("Process %s configured incorrectly. Possible processes: \n\n%s" % (process, ",".join(self.processes.keys() )))
response = self.processes[process].dispatch(features=response, params=params)
if transactionResponse.summary.totalDeleted > 0 or transactionResponse.summary.totalInserted > 0 or transactionResponse.summary.totalUpdated > 0 or transactionResponse.summary.totalReplaced > 0:
response = transactionResponse
except ConnectionException as e:
exceptionReport.add(e)
except LayerNotFoundException as e:
exceptionReport.add(e)
if len(exceptionReport) > 0:
if self.metadata.has_key("default_exception"):
service_module = __import__("Service.%s" % self.metadata['default_exception'], globals(), locals(), self.metadata['default_exception'])
service = getattr(service_module, self.metadata['default_exception'])
default_exception = service(self)
if hasattr(default_exception, "default_exception"):
mime, data, headers, encoding = default_exception.encode_exception_report(exceptionReport)
else:
raise Exception("Defined service of key 'default_exception' does not support encoding exception reports. Please use a supported service or disable this key.")
else:
# check if service supports exception encoding
if hasattr(request, "encode_exception_report"):
mime, data, headers, encoding = request.encode_exception_report(exceptionReport)
else:
# get default service and instantiate
service_module = __import__("Service.%s" % self.metadata['default_service'], globals(), locals(), self.metadata['default_service'])
service = getattr(service_module, self.metadata['default_service'])
default_service = service(self)
if hasattr(default_service, "encode_exception_report"):
mime, data, headers, encoding = default_service.encode_exception_report(exceptionReport)
else:
# load WFS for exception handling
from FeatureServer.Service.WFS import WFS
wfs_service = WFS(self)
mime, data, headers, encoding = wfs_service.encode_exception_report(exceptionReport)
else:
mime, data, headers, encoding = request.encode(response)
return Response(data=data, content_type=mime, headers=headers, status_code=response_code, encoding=encoding)
def dispatchWorkspaceRequest (self, base_path="", path_info="/", params={}, request_method = "GET", post_data = None, accepts = ""):
handler = FileHandler('workspace.db')
handler.removeExpired()
# create workspace
if params.has_key("base"):
if params.has_key("request"):
identifier = ''
if params.has_key('id'):
identifier = params['id']
short = handler.create(params['base'], params['request'], identifier)
output = ""
if params.has_key("callback"):
output += params["callback"] + '('
output += '{"key":"' + short + '"}'
if params.has_key("callback"):
output += ');'
return Response(data=output.decode("utf-8"), content_type="application/json; charset=utf-8", status_code="200 OK")
# handle WFS request
elif params.has_key('key'):
handler.updateLastAccess(params['key'])
data = handler.getByKey(params['key'])
if len(data) > 0:
#generate workspace specific datasource
for layer in self.datasources:
if layer == data[2]:
self.datasources = {layer : self.datasources[layer]}
self.datasources[layer].abstract += " :: " + str(data[0])
break
if params.has_key('request'):
if params['request'].lower() == 'getfeature':
if params.has_key('filter') <> True:
if post_data == None:
params['filter'] = data[3]
return self.dispatchRequest(base_path, path_info, params, request_method, post_data, accepts)
# check workspace by id
elif params.has_key('skey'):
output = ""
if params.has_key("callback"):
output += params["callback"] + '('
output += '{"workspaces":['
data = handler.getByKey(params['skey'])
if len(data) > 0:
date = time.strftime("%a %b %d, %Y %I:%M:%S %p",time.localtime(float(data[4])))
output += '{"Workspace":"'+data[0]+'","LastAccess":"' + date + '"},'
output += "]}"
if params.has_key("callback"):
output += ');'
return Response(data=output.decode("utf-8"), content_type="application/json; charset=utf-8", status_code="200 OK")
# check workspace by email
elif params.has_key('sid'):
output = ""
if params.has_key("callback"):
output += params["callback"] + '('
output += '{"workspaces":['
workspaces = handler.getByIdentifier(params['sid'])
for data in workspaces:
date = time.strftime("%a %b %d, %Y %I:%M:%S %p",time.localtime(float(data[4])))
output += '{"Workspace":"'+data[0]+'","LastAccess":"' + date + '"},'
if len(data) > 0:
output = output[:-1]
output += "]}"
if params.has_key("callback"):
output += ');'
return Response(data=output.decode("utf-8"), content_type="application/json; charset=utf-8", status_code="200 OK")
#TODO: not available
return None
theServer = None
lastRead = 0
#def handler (apacheReq):
# global theServer
# if not theServer:
# options = apacheReq.get_options()
# cfgs = cfgfiles
# if options.has_key("FeatureServerConfig"):
# cfgs = (options["FeatureServerConfig"],) + cfgs
# theServer = Server.load(*cfgs)
# return mod_python(theServer.dispatchRequest, apacheReq)
def wsgi_app (environ, start_response):
global theServer, lastRead
last = 0
for cfg in cfgfiles:
try:
cfgTime = os.stat(cfg)[8]
if cfgTime > last:
last = cfgTime
except:
pass
if not theServer or last > lastRead:
cfgs = cfgfiles
theServer = Server.load(*cfgs)
lastRead = time.time()
return wsgi(theServer.dispatchRequest, environ, start_response)
def wsgi_app_workspace(environ, start_response):
global theServer, lastRead
last = 0
for cfg in cfgfiles:
try:
cfgTime = os.stat(cfg)[8]
if cfgTime > last:
last = cfgTime
except:
pass
if not theServer or last > lastRead:
cfgs = cfgfiles
theServer = Server.load(*cfgs)
lastRead = time.time()
return wsgi(theServer.dispatchWorkspaceRequest, environ, start_response)
if __name__ == '__main__':
service = Server.load(*cfgfiles)
cgi(service)
| 42.200893 | 210 | 0.54972 |
__author__ = "MetaCarta"
__copyright__ = "Copyright (c) 2006-2008 MetaCarta"
__license__ = "Clear BSD"
__version__ = "$Id: Server.py 607 2009-04-27 15:53:15Z crschmidt $"
import sys
import time
import os
import traceback
import ConfigParser
from web_request.handlers import wsgi, mod_python, cgi
from lxml import etree
import cgi as cgimod
from FeatureServer.WebFeatureService.Response.TransactionResponse import TransactionResponse
from FeatureServer.WebFeatureService.Response.TransactionSummary import TransactionSummary
from FeatureServer.WebFeatureService.Response.ActionResult import ActionResult
from FeatureServer.Workspace.FileHandler import FileHandler
from FeatureServer.Exceptions.ExceptionReport import ExceptionReport
from FeatureServer.Exceptions.WebFeatureService.InvalidValueException import InvalidValueException
from FeatureServer.Exceptions.ConnectionException import ConnectionException
from FeatureServer.Exceptions.LayerNotFoundException import LayerNotFoundException
import FeatureServer.Processing
from web_request.response import Response
if 'FS_CONFIG' in os.environ:
cfgfiles = os.environ['FS_CONFIG'].split(",")
else:
if sys.platform == 'win32':
workingdir = os.path.abspath(os.path.join(os.getcwd(), os.path.dirname(sys.argv[0])))
cfgfiles = (os.path.join(workingdir, "featureserver.cfg"), os.path.join(workingdir,"..","featureserver.cfg"))
else:
cfgfiles = ("featureserver.cfg", os.path.join("..", "featureserver.cfg"), "/etc/featureserver.cfg")
class Server (object):
"""The server manages the datasource list, and does the management of
request input/output. Handlers convert their specific internal
representation to the parameters that dispatchRequest is expecting,
then pass off to dispatchRequest. dispatchRequest turns the input
parameters into a (content-type, response string) tuple, which the
servers can then return to clients. It is possible to integrate
FeatureServer into another content-serving framework like Django by
simply creating your own datasources (passed to the init function)
and calling the dispatchRequest method. The Server provides a classmethod
to load datasources from a config file, which is the typical lightweight
configuration method, but does use some amount of time at script startup.
"""
def __init__ (self, datasources, metadata = {}, processes = {}):
self.datasources = datasources
self.metadata = metadata
self.processes = processes
def _loadFromSection (cls, config, section, module_type, **objargs):
type = config.get(section, "type")
module = __import__("%s.%s" % (module_type, type), globals(), locals(), type)
objclass = getattr(module, type)
for opt in config.options(section):
objargs[opt] = config.get(section, opt)
if module_type is 'DataSource':
return objclass(section, **objargs)
else:
return objclass(**objargs)
loadFromSection = classmethod(_loadFromSection)
def _load (cls, *files):
"""Class method on Service class to load datasources
and metadata from a configuration file."""
config = ConfigParser.ConfigParser()
config.read(files)
metadata = {}
if config.has_section("metadata"):
for key in config.options("metadata"):
metadata[key] = config.get("metadata", key)
processes = {}
datasources = {}
for section in config.sections():
if section == "metadata": continue
if section.startswith("process_"):
try:
processes[section[8:]] = FeatureServer.Processing.loadFromSection(config, section)
except Exception, E:
pass
else:
datasources[section] = cls.loadFromSection(config, section, 'DataSource')
return cls(datasources, metadata, processes)
load = classmethod(_load)
def dispatchRequest (self, base_path="", path_info="/", params={}, request_method = "GET", post_data = None, accepts = ""):
"""Read in request data, and return a (content-type, response string) tuple. May
raise an exception, which should be returned as a 500 error to the user."""
response_code = "200 OK"
host = base_path
request = None
content_types = {
'application/vnd.google-earth.kml+xml': 'KML',
'application/json': 'GeoJSON',
'text/javascript': 'GeoJSON',
'application/rss+xml': 'GeoRSS',
'text/html': 'HTML',
'osm': 'OSM',
'gml': 'WFS',
'wfs': 'WFS',
'kml': 'KML',
'json': 'GeoJSON',
'georss': 'GeoRSS',
'atom': 'GeoRSS',
'html': 'HTML',
'geojson':'GeoJSON',
'shp': 'SHP',
'csv': 'CSV',
'gpx': 'GPX',
'ov2': 'OV2',
'sqlite': 'SQLite',
'dxf' : 'DXF'
}
exceptionReport = ExceptionReport()
path = path_info.split("/")
found = False
format = ""
if params.has_key("format"):
format = params['format']
if format.lower() in content_types:
format = content_types[format.lower()]
found = True
if not found and len(path) > 1:
path_pieces = path[-1].split(".")
if len(path_pieces) > 1:
format = path_pieces[-1]
if format.lower() in content_types:
format = content_types[format.lower()]
found = True
if not found and not params.has_key("service") and post_data:
try:
dom = etree.XML(post_data)
params['service'] = dom.get('service')
except etree.ParseError: pass
if not found and not params.has_key("version") and post_data:
try:
dom = etree.XML(post_data)
params['version'] = dom.get('version')
except etree.ParseError: pass
if not found and not params.has_key("typename") and post_data:
try:
dom = etree.XML(post_data)
for key, value in cgimod.parse_qsl(post_data, keep_blank_values=True):
if key.lower() == 'typename':
params['typename'] = value
except etree.ParseError: pass
if not found and params.has_key("service"):
format = params['service']
if format.lower() in content_types:
format = content_types[format.lower()]
found = True
if not found and accepts:
if accepts.lower() in content_types:
format = content_types[accepts.lower()]
found = True
if not found and not format:
if self.metadata.has_key("default_service"):
format = self.metadata['default_service']
else:
format = "WFS"
#===============================================================================
# (reflection) dynamic load of format class e.g. WFS, KML, etc.
# for supported format see package 'Service'
# ----------- -------
# | Request | <|------- | WFS |
# ----------- -------
#===============================================================================
service_module = __import__("Service.%s" % format, globals(), locals(), format)
service = getattr(service_module, format)
request = service(self)
response = []
try:
request.parse(params, path_info, host, post_data, request_method)
# short circuit datasource where the first action is a metadata request.
if len(request.actions) and request.actions[0].method == "metadata":
return request.encode_metadata(request.actions[0])
# short circuit datasource where a OGC WFS request is set
# processing by service
if len(request.actions) > 0 and hasattr(request.actions[0], 'request') and request.actions[0].request is not None:
version = '1.0.0'
if hasattr(request.actions[0], 'version') and len(request.actions[0].version) > 0:
version = request.actions[0].version
if request.actions[0].request.lower() == "getcapabilities":
return getattr(request, request.actions[0].request.lower())(version)
elif request.actions[0].request.lower() == "describefeaturetype":
return getattr(request, request.actions[0].request.lower())(version)
datasource = self.datasources[request.datasources[0]]
if request_method != "GET" and hasattr(datasource, 'processes'):
raise Exception("You can't post data to a processed layer.")
try:
datasource.begin()
if len(request.actions) > 0 and hasattr(request.actions[0], 'request') and request.actions[0].request is not None:
if request.actions[0].request.lower() == "getfeature":
''' '''
try:
transactionResponse = TransactionResponse()
transactionResponse.setSummary(TransactionSummary())
for action in request.actions:
method = getattr(datasource, action.method)
try:
result = method(action)
if isinstance(result, ActionResult):
transactionResponse.addResult(result)
elif result is not None:
response += result
except InvalidValueException as e:
exceptionReport.add(e)
datasource.commit()
except:
datasource.rollback()
raise
if hasattr(datasource, 'processes'):
for process in datasource.processes.split(","):
if not self.processes.has_key(process):
raise Exception("Process %s configured incorrectly. Possible processes: \n\n%s" % (process, ",".join(self.processes.keys() )))
response = self.processes[process].dispatch(features=response, params=params)
if transactionResponse.summary.totalDeleted > 0 or transactionResponse.summary.totalInserted > 0 or transactionResponse.summary.totalUpdated > 0 or transactionResponse.summary.totalReplaced > 0:
response = transactionResponse
except ConnectionException as e:
exceptionReport.add(e)
except LayerNotFoundException as e:
exceptionReport.add(e)
if len(exceptionReport) > 0:
if self.metadata.has_key("default_exception"):
service_module = __import__("Service.%s" % self.metadata['default_exception'], globals(), locals(), self.metadata['default_exception'])
service = getattr(service_module, self.metadata['default_exception'])
default_exception = service(self)
if hasattr(default_exception, "default_exception"):
mime, data, headers, encoding = default_exception.encode_exception_report(exceptionReport)
else:
raise Exception("Defined service of key 'default_exception' does not support encoding exception reports. Please use a supported service or disable this key.")
else:
if hasattr(request, "encode_exception_report"):
mime, data, headers, encoding = request.encode_exception_report(exceptionReport)
else:
service_module = __import__("Service.%s" % self.metadata['default_service'], globals(), locals(), self.metadata['default_service'])
service = getattr(service_module, self.metadata['default_service'])
default_service = service(self)
if hasattr(default_service, "encode_exception_report"):
mime, data, headers, encoding = default_service.encode_exception_report(exceptionReport)
else:
from FeatureServer.Service.WFS import WFS
wfs_service = WFS(self)
mime, data, headers, encoding = wfs_service.encode_exception_report(exceptionReport)
else:
mime, data, headers, encoding = request.encode(response)
return Response(data=data, content_type=mime, headers=headers, status_code=response_code, encoding=encoding)
def dispatchWorkspaceRequest (self, base_path="", path_info="/", params={}, request_method = "GET", post_data = None, accepts = ""):
handler = FileHandler('workspace.db')
handler.removeExpired()
if params.has_key("base"):
if params.has_key("request"):
identifier = ''
if params.has_key('id'):
identifier = params['id']
short = handler.create(params['base'], params['request'], identifier)
output = ""
if params.has_key("callback"):
output += params["callback"] + '('
output += '{"key":"' + short + '"}'
if params.has_key("callback"):
output += ');'
return Response(data=output.decode("utf-8"), content_type="application/json; charset=utf-8", status_code="200 OK")
elif params.has_key('key'):
handler.updateLastAccess(params['key'])
data = handler.getByKey(params['key'])
if len(data) > 0:
for layer in self.datasources:
if layer == data[2]:
self.datasources = {layer : self.datasources[layer]}
self.datasources[layer].abstract += " :: " + str(data[0])
break
if params.has_key('request'):
if params['request'].lower() == 'getfeature':
if params.has_key('filter') <> True:
if post_data == None:
params['filter'] = data[3]
return self.dispatchRequest(base_path, path_info, params, request_method, post_data, accepts)
elif params.has_key('skey'):
output = ""
if params.has_key("callback"):
output += params["callback"] + '('
output += '{"workspaces":['
data = handler.getByKey(params['skey'])
if len(data) > 0:
date = time.strftime("%a %b %d, %Y %I:%M:%S %p",time.localtime(float(data[4])))
output += '{"Workspace":"'+data[0]+'","LastAccess":"' + date + '"},'
output += "]}"
if params.has_key("callback"):
output += ');'
return Response(data=output.decode("utf-8"), content_type="application/json; charset=utf-8", status_code="200 OK")
elif params.has_key('sid'):
output = ""
if params.has_key("callback"):
output += params["callback"] + '('
output += '{"workspaces":['
workspaces = handler.getByIdentifier(params['sid'])
for data in workspaces:
date = time.strftime("%a %b %d, %Y %I:%M:%S %p",time.localtime(float(data[4])))
output += '{"Workspace":"'+data[0]+'","LastAccess":"' + date + '"},'
if len(data) > 0:
output = output[:-1]
output += "]}"
if params.has_key("callback"):
output += ');'
return Response(data=output.decode("utf-8"), content_type="application/json; charset=utf-8", status_code="200 OK")
return None
theServer = None
lastRead = 0
def wsgi_app (environ, start_response):
global theServer, lastRead
last = 0
for cfg in cfgfiles:
try:
cfgTime = os.stat(cfg)[8]
if cfgTime > last:
last = cfgTime
except:
pass
if not theServer or last > lastRead:
cfgs = cfgfiles
theServer = Server.load(*cfgs)
lastRead = time.time()
return wsgi(theServer.dispatchRequest, environ, start_response)
def wsgi_app_workspace(environ, start_response):
global theServer, lastRead
last = 0
for cfg in cfgfiles:
try:
cfgTime = os.stat(cfg)[8]
if cfgTime > last:
last = cfgTime
except:
pass
if not theServer or last > lastRead:
cfgs = cfgfiles
theServer = Server.load(*cfgs)
lastRead = time.time()
return wsgi(theServer.dispatchWorkspaceRequest, environ, start_response)
if __name__ == '__main__':
service = Server.load(*cfgfiles)
cgi(service)
| false | true |
f7f74b1c3145d6c93b73607c24604efc144ca890 | 1,951 | py | Python | examples/custom_context.py | Ryomen-Sukuna/discord.py | 0bcb0d0e3ce395d42a5b1dae61b0090791ee018d | [
"MIT"
] | 1 | 2021-09-11T09:24:38.000Z | 2021-09-11T09:24:38.000Z | examples/custom_context.py | Ryomen-Sukuna/discord.py | 0bcb0d0e3ce395d42a5b1dae61b0090791ee018d | [
"MIT"
] | 1 | 2022-02-19T18:25:19.000Z | 2022-02-19T18:25:19.000Z | examples/custom_context.py | Ryomen-Sukuna/discord.py | 0bcb0d0e3ce395d42a5b1dae61b0090791ee018d | [
"MIT"
] | null | null | null | # This example requires the 'message_content' privileged intent to function.
import random
import discord
from discord.ext import commands
class MyContext(commands.Context):
async def tick(self, value):
# reacts to the message with an emoji
# depending on whether value is True or False
# if its True, it'll add a green check mark
# otherwise, it'll add a red cross mark
emoji = '\N{WHITE HEAVY CHECK MARK}' if value else '\N{CROSS MARK}'
try:
# this will react to the command author's message
await self.message.add_reaction(emoji)
except discord.HTTPException:
# sometimes errors occur during this, for example
# maybe you don't have permission to do that
# we don't mind, so we can just ignore them
pass
class MyBot(commands.Bot):
async def get_context(self, message, *, cls=MyContext):
# when you override this method, you pass your new Context
# subclass to the super() method, which tells the bot to
# use the new MyContext class
return await super().get_context(message, cls=cls)
intents = discord.Intents.default()
intents.message_content = True
bot = MyBot(command_prefix='!', intents=intents)
@bot.command()
async def guess(ctx, number: int):
"""Guess a random number from 1 to 6."""
# explained in a previous example, this gives you
# a random number from 1-6
value = random.randint(1, 6)
# with your new helper function, you can add a
# green check mark if the guess was correct,
# or a red cross mark if it wasn't
await ctx.tick(number == value)
# IMPORTANT: You shouldn't hard code your token
# these are very important, and leaking them can
# let people do very malicious things with your
# bot. Try to use a file or something to keep
# them private, and don't commit it to GitHub
token = "your token here"
bot.run(token)
| 32.516667 | 76 | 0.674013 |
import random
import discord
from discord.ext import commands
class MyContext(commands.Context):
async def tick(self, value):
# otherwise, it'll add a red cross mark
emoji = '\N{WHITE HEAVY CHECK MARK}' if value else '\N{CROSS MARK}'
try:
await self.message.add_reaction(emoji)
except discord.HTTPException:
# sometimes errors occur during this, for example
# maybe you don't have permission to do that
pass
class MyBot(commands.Bot):
async def get_context(self, message, *, cls=MyContext):
# when you override this method, you pass your new Context
# subclass to the super() method, which tells the bot to
# use the new MyContext class
return await super().get_context(message, cls=cls)
intents = discord.Intents.default()
intents.message_content = True
bot = MyBot(command_prefix='!', intents=intents)
@bot.command()
async def guess(ctx, number: int):
# explained in a previous example, this gives you
# a random number from 1-6
value = random.randint(1, 6)
# with your new helper function, you can add a
# green check mark if the guess was correct,
# or a red cross mark if it wasn't
await ctx.tick(number == value)
# these are very important, and leaking them can
# let people do very malicious things with your
# bot. Try to use a file or something to keep
# them private, and don't commit it to GitHub
token = "your token here"
bot.run(token)
| true | true |
f7f74b41bc438a17f0cd16a5250d1822798dfb2b | 1,571 | py | Python | oxe-api/resource/user/update_user_group_assignment.py | CybersecurityLuxembourg/openxeco | 8d4e5578bde6a07f5d6d569b16b4de224abf7bf0 | [
"BSD-2-Clause"
] | null | null | null | oxe-api/resource/user/update_user_group_assignment.py | CybersecurityLuxembourg/openxeco | 8d4e5578bde6a07f5d6d569b16b4de224abf7bf0 | [
"BSD-2-Clause"
] | null | null | null | oxe-api/resource/user/update_user_group_assignment.py | CybersecurityLuxembourg/openxeco | 8d4e5578bde6a07f5d6d569b16b4de224abf7bf0 | [
"BSD-2-Clause"
] | null | null | null | from flask_apispec import MethodResource
from flask_apispec import use_kwargs, doc
from flask_jwt_extended import jwt_required
from flask_restful import Resource
from webargs import fields
from decorator.catch_exception import catch_exception
from decorator.log_request import log_request
from decorator.verify_admin_access import verify_admin_access
from exception.object_not_found import ObjectNotFound
class UpdateUserGroupAssignment(MethodResource, Resource):
db = None
def __init__(self, db):
self.db = db
@log_request
@doc(tags=['user'],
description='Update user group assignment',
responses={
"200": {},
"422.a": {"description": "Object not found: group"},
"422.b": {"description": "Object not found: user"}
})
@use_kwargs({
'user': fields.Int(),
'group': fields.Int(),
})
@jwt_required
@verify_admin_access
@catch_exception
def post(self, **kwargs):
users = self.db.get(self.db.tables["User"], {"id": kwargs["user"]})
if len(users) == 0:
raise ObjectNotFound("user")
groups = self.db.get(self.db.tables["UserGroup"], {"id": kwargs["group"]})
if len(groups) == 0:
raise ObjectNotFound("group")
self.db.delete(self.db.tables["UserGroupAssignment"], {"user_id": kwargs["user"]})
self.db.insert({
"user_id": kwargs["user"],
"group_id": kwargs["group"]
}, self.db.tables["UserGroupAssignment"])
return "", "200 "
| 28.563636 | 90 | 0.631445 | from flask_apispec import MethodResource
from flask_apispec import use_kwargs, doc
from flask_jwt_extended import jwt_required
from flask_restful import Resource
from webargs import fields
from decorator.catch_exception import catch_exception
from decorator.log_request import log_request
from decorator.verify_admin_access import verify_admin_access
from exception.object_not_found import ObjectNotFound
class UpdateUserGroupAssignment(MethodResource, Resource):
db = None
def __init__(self, db):
self.db = db
@log_request
@doc(tags=['user'],
description='Update user group assignment',
responses={
"200": {},
"422.a": {"description": "Object not found: group"},
"422.b": {"description": "Object not found: user"}
})
@use_kwargs({
'user': fields.Int(),
'group': fields.Int(),
})
@jwt_required
@verify_admin_access
@catch_exception
def post(self, **kwargs):
users = self.db.get(self.db.tables["User"], {"id": kwargs["user"]})
if len(users) == 0:
raise ObjectNotFound("user")
groups = self.db.get(self.db.tables["UserGroup"], {"id": kwargs["group"]})
if len(groups) == 0:
raise ObjectNotFound("group")
self.db.delete(self.db.tables["UserGroupAssignment"], {"user_id": kwargs["user"]})
self.db.insert({
"user_id": kwargs["user"],
"group_id": kwargs["group"]
}, self.db.tables["UserGroupAssignment"])
return "", "200 "
| true | true |
f7f74b630d636082a2cbce49328a0e6143b855f2 | 324 | py | Python | setup.py | ap193uee/common | 9fd1674260a6188b1cefebad46f9fafd542554c1 | [
"MIT"
] | 3 | 2019-02-04T06:42:58.000Z | 2019-08-21T09:40:44.000Z | setup.py | ap193uee/cvutils | 9fd1674260a6188b1cefebad46f9fafd542554c1 | [
"MIT"
] | 1 | 2020-03-23T15:56:20.000Z | 2020-03-23T15:56:20.000Z | setup.py | ap193uee/cvutils | 9fd1674260a6188b1cefebad46f9fafd542554c1 | [
"MIT"
] | 1 | 2019-03-20T08:31:20.000Z | 2019-03-20T08:31:20.000Z | from setuptools import setup
setup(
name='common',
version='1.1.0',
description='Common utlity functions',
url='http://demo.vedalabs.in/',
# Author details
author='Atinderpal Singh',
author_email='atinderpalap@gmail.com',
license='MIT',
packages=['common'],
zip_safe=False
)
| 17.052632 | 42 | 0.635802 | from setuptools import setup
setup(
name='common',
version='1.1.0',
description='Common utlity functions',
url='http://demo.vedalabs.in/',
author='Atinderpal Singh',
author_email='atinderpalap@gmail.com',
license='MIT',
packages=['common'],
zip_safe=False
)
| true | true |
f7f74ce8643d997aee4cc71cad42ca18ae6f6280 | 81,660 | py | Python | nova/compute/resource_tracker.py | rolaya/nova | 5434e4c401cc7968ddd516537971b687631b3147 | [
"Apache-2.0"
] | null | null | null | nova/compute/resource_tracker.py | rolaya/nova | 5434e4c401cc7968ddd516537971b687631b3147 | [
"Apache-2.0"
] | null | null | null | nova/compute/resource_tracker.py | rolaya/nova | 5434e4c401cc7968ddd516537971b687631b3147 | [
"Apache-2.0"
] | null | null | null | # Copyright (c) 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Track resources like memory and disk for a compute host. Provides the
scheduler with useful information about availability through the ComputeNode
model.
"""
import collections
import copy
from keystoneauth1 import exceptions as ks_exc
import os_traits
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import excutils
import retrying
from nova.compute import claims
from nova.compute import monitors
from nova.compute import stats as compute_stats
from nova.compute import task_states
from nova.compute import utils as compute_utils
from nova.compute import vm_states
import nova.conf
from nova import exception
from nova.i18n import _
from nova import objects
from nova.objects import base as obj_base
from nova.objects import migration as migration_obj
from nova.pci import manager as pci_manager
from nova.pci import request as pci_request
from nova import rpc
from nova.scheduler.client import report
from nova import utils
from nova.virt import hardware
CONF = nova.conf.CONF
LOG = logging.getLogger(__name__)
COMPUTE_RESOURCE_SEMAPHORE = "compute_resources"
def _instance_in_resize_state(instance):
"""Returns True if the instance is in one of the resizing states.
:param instance: `nova.objects.Instance` object
"""
vm = instance.vm_state
task = instance.task_state
if vm == vm_states.RESIZED:
return True
if vm in [vm_states.ACTIVE, vm_states.STOPPED] and task in (
task_states.resizing_states + task_states.rebuild_states):
return True
return False
def _instance_is_live_migrating(instance):
vm = instance.vm_state
task = instance.task_state
if task == task_states.MIGRATING and vm in [vm_states.ACTIVE,
vm_states.PAUSED]:
return True
return False
class ResourceTracker(object):
"""Compute helper class for keeping track of resource usage as instances
are built and destroyed.
"""
def __init__(self, host, driver, reportclient=None):
self.host = host
self.driver = driver
self.pci_tracker = None
# Dict of objects.ComputeNode objects, keyed by nodename
self.compute_nodes = {}
# Dict of Stats objects, keyed by nodename
self.stats = collections.defaultdict(compute_stats.Stats)
# Set of UUIDs of instances tracked on this host.
self.tracked_instances = set()
self.tracked_migrations = {}
self.is_bfv = {} # dict, keyed by instance uuid, to is_bfv boolean
monitor_handler = monitors.MonitorHandler(self)
self.monitors = monitor_handler.monitors
self.old_resources = collections.defaultdict(objects.ComputeNode)
self.reportclient = reportclient or report.SchedulerReportClient()
self.ram_allocation_ratio = CONF.ram_allocation_ratio
self.cpu_allocation_ratio = CONF.cpu_allocation_ratio
self.disk_allocation_ratio = CONF.disk_allocation_ratio
self.provider_tree = None
# Dict of assigned_resources, keyed by resource provider uuid
# the value is a dict again, keyed by resource class
# and value of this sub-dict is a set of Resource obj
self.assigned_resources = collections.defaultdict(
lambda: collections.defaultdict(set))
@utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE)
def instance_claim(self, context, instance, nodename, allocations,
limits=None):
"""Indicate that some resources are needed for an upcoming compute
instance build operation.
This should be called before the compute node is about to perform
an instance build operation that will consume additional resources.
:param context: security context
:param instance: instance to reserve resources for.
:type instance: nova.objects.instance.Instance object
:param nodename: The Ironic nodename selected by the scheduler
:param allocations: The placement allocation records for the instance.
:param limits: Dict of oversubscription limits for memory, disk,
and CPUs.
:returns: A Claim ticket representing the reserved resources. It can
be used to revert the resource usage if an error occurs
during the instance build.
"""
if self.disabled(nodename):
# instance_claim() was called before update_available_resource()
# (which ensures that a compute node exists for nodename). We
# shouldn't get here but in case we do, just set the instance's
# host and nodename attribute (probably incorrect) and return a
# NoopClaim.
# TODO(jaypipes): Remove all the disabled junk from the resource
# tracker. Servicegroup API-level active-checking belongs in the
# nova-compute manager.
self._set_instance_host_and_node(instance, nodename)
return claims.NopClaim()
# sanity checks:
if instance.host:
LOG.warning("Host field should not be set on the instance "
"until resources have been claimed.",
instance=instance)
if instance.node:
LOG.warning("Node field should not be set on the instance "
"until resources have been claimed.",
instance=instance)
cn = self.compute_nodes[nodename]
pci_requests = objects.InstancePCIRequests.get_by_instance_uuid(
context, instance.uuid)
claim = claims.Claim(context, instance, nodename, self, cn,
pci_requests, limits=limits)
# self._set_instance_host_and_node() will save instance to the DB
# so set instance.numa_topology first. We need to make sure
# that numa_topology is saved while under COMPUTE_RESOURCE_SEMAPHORE
# so that the resource audit knows about any cpus we've pinned.
instance_numa_topology = claim.claimed_numa_topology
instance.numa_topology = instance_numa_topology
self._set_instance_host_and_node(instance, nodename)
if self.pci_tracker:
# NOTE(jaypipes): ComputeNode.pci_device_pools is set below
# in _update_usage_from_instance().
self.pci_tracker.claim_instance(context, pci_requests,
instance_numa_topology)
claimed_resources = self._claim_resources(allocations)
instance.resources = claimed_resources
# Mark resources in-use and update stats
self._update_usage_from_instance(context, instance, nodename)
elevated = context.elevated()
# persist changes to the compute node:
self._update(elevated, cn)
return claim
@utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE)
def rebuild_claim(self, context, instance, nodename, allocations,
limits=None, image_meta=None, migration=None):
"""Create a claim for a rebuild operation."""
instance_type = instance.flavor
return self._move_claim(context, instance, instance_type, nodename,
migration, allocations, move_type='evacuation',
limits=limits, image_meta=image_meta)
@utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE)
def resize_claim(self, context, instance, instance_type, nodename,
migration, allocations, image_meta=None, limits=None):
"""Create a claim for a resize or cold-migration move.
Note that this code assumes ``instance.new_flavor`` is set when
resizing with a new flavor.
"""
return self._move_claim(context, instance, instance_type, nodename,
migration, allocations, image_meta=image_meta,
limits=limits)
@utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE)
def live_migration_claim(self, context, instance, nodename, migration,
limits):
"""Builds a MoveClaim for a live migration.
:param context: The request context.
:param instance: The instance being live migrated.
:param nodename: The nodename of the destination host.
:param migration: The Migration object associated with this live
migration.
:param limits: A SchedulerLimits object from when the scheduler
selected the destination host.
:returns: A MoveClaim for this live migration.
"""
# Flavor and image cannot change during a live migration.
instance_type = instance.flavor
image_meta = instance.image_meta
# TODO(Luyao) will pass allocations to live_migration_claim after the
# live migration change is done, now just set it None to _move_claim
return self._move_claim(context, instance, instance_type, nodename,
migration, None, move_type='live-migration',
image_meta=image_meta, limits=limits)
def _move_claim(self, context, instance, new_instance_type, nodename,
migration, allocations, move_type=None,
image_meta=None, limits=None):
"""Indicate that resources are needed for a move to this host.
Move can be either a migrate/resize, live-migrate or an
evacuate/rebuild operation.
:param context: security context
:param instance: instance object to reserve resources for
:param new_instance_type: new instance_type being resized to
:param nodename: The Ironic nodename selected by the scheduler
:param migration: A migration object if one was already created
elsewhere for this operation (otherwise None)
:param allocations: the placement allocation records.
:param move_type: move type - can be one of 'migration', 'resize',
'live-migration', 'evacuate'
:param image_meta: instance image metadata
:param limits: Dict of oversubscription limits for memory, disk,
and CPUs
:returns: A Claim ticket representing the reserved resources. This
should be turned into finalize a resource claim or free
resources after the compute operation is finished.
"""
image_meta = image_meta or {}
if migration:
self._claim_existing_migration(migration, nodename)
else:
migration = self._create_migration(context, instance,
new_instance_type,
nodename, move_type)
if self.disabled(nodename):
# compute_driver doesn't support resource tracking, just
# generate the migration record and continue the resize:
return claims.NopClaim(migration=migration)
cn = self.compute_nodes[nodename]
# TODO(moshele): we are recreating the pci requests even if
# there was no change on resize. This will cause allocating
# the old/new pci device in the resize phase. In the future
# we would like to optimise this.
new_pci_requests = pci_request.get_pci_requests_from_flavor(
new_instance_type)
new_pci_requests.instance_uuid = instance.uuid
# On resize merge the SR-IOV ports pci_requests
# with the new instance flavor pci_requests.
if instance.pci_requests:
for request in instance.pci_requests.requests:
if request.source == objects.InstancePCIRequest.NEUTRON_PORT:
new_pci_requests.requests.append(request)
claim = claims.MoveClaim(context, instance, nodename,
new_instance_type, image_meta, self, cn,
new_pci_requests, migration, limits=limits)
claimed_pci_devices_objs = []
# TODO(artom) The second part of this condition should not be
# necessary, but since SRIOV live migration is currently handled
# elsewhere - see for example _claim_pci_for_instance_vifs() in the
# compute manager - we don't do any PCI claims if this is a live
# migration to avoid stepping on that code's toes. Ideally,
# MoveClaim/this method would be used for all live migration resource
# claims.
if self.pci_tracker and migration.migration_type != 'live-migration':
# NOTE(jaypipes): ComputeNode.pci_device_pools is set below
# in _update_usage_from_instance().
claimed_pci_devices_objs = self.pci_tracker.claim_instance(
context, new_pci_requests, claim.claimed_numa_topology)
claimed_pci_devices = objects.PciDeviceList(
objects=claimed_pci_devices_objs)
claimed_resources = self._claim_resources(allocations)
old_resources = instance.resources
# TODO(jaypipes): Move claimed_numa_topology out of the Claim's
# constructor flow so the Claim constructor only tests whether
# resources can be claimed, not consume the resources directly.
mig_context = objects.MigrationContext(
context=context, instance_uuid=instance.uuid,
migration_id=migration.id,
old_numa_topology=instance.numa_topology,
new_numa_topology=claim.claimed_numa_topology,
old_pci_devices=instance.pci_devices,
new_pci_devices=claimed_pci_devices,
old_pci_requests=instance.pci_requests,
new_pci_requests=new_pci_requests,
old_resources=old_resources,
new_resources=claimed_resources)
instance.migration_context = mig_context
instance.save()
# Mark the resources in-use for the resize landing on this
# compute host:
self._update_usage_from_migration(context, instance, migration,
nodename)
elevated = context.elevated()
self._update(elevated, cn)
return claim
def _create_migration(self, context, instance, new_instance_type,
nodename, move_type=None):
"""Create a migration record for the upcoming resize. This should
be done while the COMPUTE_RESOURCES_SEMAPHORE is held so the resource
claim will not be lost if the audit process starts.
"""
migration = objects.Migration(context=context.elevated())
migration.dest_compute = self.host
migration.dest_node = nodename
migration.dest_host = self.driver.get_host_ip_addr()
migration.old_instance_type_id = instance.flavor.id
migration.new_instance_type_id = new_instance_type.id
migration.status = 'pre-migrating'
migration.instance_uuid = instance.uuid
migration.source_compute = instance.host
migration.source_node = instance.node
if move_type:
migration.migration_type = move_type
else:
migration.migration_type = migration_obj.determine_migration_type(
migration)
migration.create()
return migration
def _claim_existing_migration(self, migration, nodename):
"""Make an existing migration record count for resource tracking.
If a migration record was created already before the request made
it to this compute host, only set up the migration so it's included in
resource tracking. This should be done while the
COMPUTE_RESOURCES_SEMAPHORE is held.
"""
migration.dest_compute = self.host
migration.dest_node = nodename
migration.dest_host = self.driver.get_host_ip_addr()
# NOTE(artom) Migration objects for live migrations are created with
# status 'accepted' by the conductor in live_migrate_instance() and do
# not have a 'pre-migrating' status.
if migration.migration_type != 'live-migration':
migration.status = 'pre-migrating'
migration.save()
def _claim_resources(self, allocations):
"""Claim resources according to assigned resources from allocations
and available resources in provider tree
"""
if not allocations:
return None
claimed_resources = []
for rp_uuid, alloc_dict in allocations.items():
try:
provider_data = self.provider_tree.data(rp_uuid)
except ValueError:
# If an instance is in evacuating, it will hold new and old
# allocations, but the provider UUIDs in old allocations won't
# exist in the current provider tree, so skip it.
LOG.debug("Skip claiming resources of provider %(rp_uuid)s, "
"since the provider UUIDs are not in provider tree.",
{'rp_uuid': rp_uuid})
continue
for rc, amount in alloc_dict['resources'].items():
if rc not in provider_data.resources:
# This means we don't use provider_data.resources to
# assign this kind of resource class, such as 'VCPU' for
# now, otherwise the provider_data.resources will be
# populated with this resource class when updating
# provider tree.
continue
assigned = self.assigned_resources[rp_uuid][rc]
free = provider_data.resources[rc] - assigned
if amount > len(free):
reason = (_("Needed %(amount)d units of resource class "
"%(rc)s, but %(avail)d are available.") %
{'amount': amount,
'rc': rc,
'avail': len(free)})
raise exception.ComputeResourcesUnavailable(reason=reason)
for i in range(amount):
claimed_resources.append(free.pop())
if claimed_resources:
self._add_assigned_resources(claimed_resources)
return objects.ResourceList(objects=claimed_resources)
def _populate_assigned_resources(self, context, instance_by_uuid):
"""Populate self.assigned_resources organized by resource class and
reource provider uuid, which is as following format:
{
$RP_UUID: {
$RESOURCE_CLASS: [objects.Resource, ...],
$RESOURCE_CLASS: [...]},
...}
"""
resources = []
# Get resources assigned to migrations
for mig in self.tracked_migrations.values():
mig_ctx = mig.instance.migration_context
# We might have a migration whose instance hasn't arrived here yet.
# Ignore it.
if not mig_ctx:
continue
if mig.source_compute == self.host and 'old_resources' in mig_ctx:
resources.extend(mig_ctx.old_resources or [])
if mig.dest_compute == self.host and 'new_resources' in mig_ctx:
resources.extend(mig_ctx.new_resources or [])
# Get resources assigned to instances
for uuid in self.tracked_instances:
resources.extend(instance_by_uuid[uuid].resources or [])
self.assigned_resources.clear()
self._add_assigned_resources(resources)
def _check_resources(self, context):
"""Check if there are assigned resources not found in provider tree"""
notfound = set()
for rp_uuid in self.assigned_resources:
provider_data = self.provider_tree.data(rp_uuid)
for rc, assigned in self.assigned_resources[rp_uuid].items():
notfound |= (assigned - provider_data.resources[rc])
if not notfound:
return
# This only happens when assigned resources are removed
# from the configuration and the compute service is SIGHUP'd
# or restarted.
resources = [(res.identifier, res.resource_class) for res in notfound]
reason = _("The following resources are assigned to instances, "
"but were not listed in the configuration: %s "
"Please check if this will influence your instances, "
"and restore your configuration if necessary") % resources
raise exception.AssignedResourceNotFound(reason=reason)
def _release_assigned_resources(self, resources):
"""Remove resources from self.assigned_resources."""
if not resources:
return
for resource in resources:
rp_uuid = resource.provider_uuid
rc = resource.resource_class
try:
self.assigned_resources[rp_uuid][rc].remove(resource)
except KeyError:
LOG.warning("Release resource %(rc)s: %(id)s of provider "
"%(rp_uuid)s, not tracked in "
"ResourceTracker.assigned_resources.",
{'rc': rc, 'id': resource.identifier,
'rp_uuid': rp_uuid})
def _add_assigned_resources(self, resources):
"""Add resources to self.assigned_resources"""
if not resources:
return
for resource in resources:
rp_uuid = resource.provider_uuid
rc = resource.resource_class
self.assigned_resources[rp_uuid][rc].add(resource)
def _set_instance_host_and_node(self, instance, nodename):
"""Tag the instance as belonging to this host. This should be done
while the COMPUTE_RESOURCES_SEMAPHORE is held so the resource claim
will not be lost if the audit process starts.
"""
# NOTE(mriedem): ComputeManager._nil_out_instance_obj_host_and_node is
# somewhat tightly coupled to the fields set in this method so if this
# method changes that method might need to be updated.
instance.host = self.host
instance.launched_on = self.host
instance.node = nodename
instance.save()
def _unset_instance_host_and_node(self, instance):
"""Untag the instance so it no longer belongs to the host.
This should be done while the COMPUTE_RESOURCES_SEMAPHORE is held so
the resource claim will not be lost if the audit process starts.
"""
instance.host = None
instance.node = None
instance.save()
@utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE)
def abort_instance_claim(self, context, instance, nodename):
"""Remove usage from the given instance."""
self._update_usage_from_instance(context, instance, nodename,
is_removed=True)
instance.clear_numa_topology()
self._unset_instance_host_and_node(instance)
self._update(context.elevated(), self.compute_nodes[nodename])
def _drop_pci_devices(self, instance, nodename, prefix):
if self.pci_tracker:
# free old/new allocated pci devices
pci_devices = self._get_migration_context_resource(
'pci_devices', instance, prefix=prefix)
if pci_devices:
for pci_device in pci_devices:
self.pci_tracker.free_device(pci_device, instance)
dev_pools_obj = self.pci_tracker.stats.to_device_pools_obj()
self.compute_nodes[nodename].pci_device_pools = dev_pools_obj
@utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE)
def drop_move_claim(self, context, instance, nodename,
instance_type=None, prefix='new_'):
"""Remove usage for an incoming/outgoing migration.
:param context: Security context.
:param instance: The instance whose usage is to be removed.
:param nodename: Host on which to remove usage. If the migration
completed successfully, this is normally the source.
If it did not complete successfully (failed or
reverted), this is normally the destination.
:param instance_type: The flavor that determines the usage to remove.
If the migration completed successfully, this is
the old flavor to be removed from the source. If
the migration did not complete successfully, this
is the new flavor to be removed from the
destination.
:param prefix: Prefix to use when accessing migration context
attributes. 'old_' or 'new_', with 'new_' being the
default.
"""
# Remove usage for an instance that is tracked in migrations, such as
# on the dest node during revert resize.
if instance['uuid'] in self.tracked_migrations:
migration = self.tracked_migrations.pop(instance['uuid'])
if not instance_type:
instance_type = self._get_instance_type(instance, prefix,
migration)
# Remove usage for an instance that is not tracked in migrations (such
# as on the source node after a migration).
# NOTE(lbeliveau): On resize on the same node, the instance is
# included in both tracked_migrations and tracked_instances.
elif instance['uuid'] in self.tracked_instances:
self.tracked_instances.remove(instance['uuid'])
if instance_type is not None:
numa_topology = self._get_migration_context_resource(
'numa_topology', instance, prefix=prefix)
usage = self._get_usage_dict(
instance_type, instance, numa_topology=numa_topology)
self._drop_pci_devices(instance, nodename, prefix)
resources = self._get_migration_context_resource(
'resources', instance, prefix=prefix)
self._release_assigned_resources(resources)
self._update_usage(usage, nodename, sign=-1)
ctxt = context.elevated()
self._update(ctxt, self.compute_nodes[nodename])
@utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE)
def update_usage(self, context, instance, nodename):
"""Update the resource usage and stats after a change in an
instance
"""
if self.disabled(nodename):
return
uuid = instance['uuid']
# don't update usage for this instance unless it submitted a resource
# claim first:
if uuid in self.tracked_instances:
self._update_usage_from_instance(context, instance, nodename)
self._update(context.elevated(), self.compute_nodes[nodename])
def disabled(self, nodename):
return (nodename not in self.compute_nodes or
not self.driver.node_is_available(nodename))
def _check_for_nodes_rebalance(self, context, resources, nodename):
"""Check if nodes rebalance has happened.
The ironic driver maintains a hash ring mapping bare metal nodes
to compute nodes. If a compute dies, the hash ring is rebuilt, and
some of its bare metal nodes (more precisely, those not in ACTIVE
state) are assigned to other computes.
This method checks for this condition and adjusts the database
accordingly.
:param context: security context
:param resources: initial values
:param nodename: node name
:returns: True if a suitable compute node record was found, else False
"""
if not self.driver.rebalances_nodes:
return False
# Its possible ironic just did a node re-balance, so let's
# check if there is a compute node that already has the correct
# hypervisor_hostname. We can re-use that rather than create a
# new one and have to move existing placement allocations
cn_candidates = objects.ComputeNodeList.get_by_hypervisor(
context, nodename)
if len(cn_candidates) == 1:
cn = cn_candidates[0]
LOG.info("ComputeNode %(name)s moving from %(old)s to %(new)s",
{"name": nodename, "old": cn.host, "new": self.host})
cn.host = self.host
self.compute_nodes[nodename] = cn
self._copy_resources(cn, resources)
self._setup_pci_tracker(context, cn, resources)
self._update(context, cn)
return True
elif len(cn_candidates) > 1:
LOG.error(
"Found more than one ComputeNode for nodename %s. "
"Please clean up the orphaned ComputeNode records in your DB.",
nodename)
return False
def _init_compute_node(self, context, resources):
"""Initialize the compute node if it does not already exist.
The resource tracker will be inoperable if compute_node
is not defined. The compute_node will remain undefined if
we fail to create it or if there is no associated service
registered.
If this method has to create a compute node it needs initial
values - these come from resources.
:param context: security context
:param resources: initial values
:returns: True if a new compute_nodes table record was created,
False otherwise
"""
nodename = resources['hypervisor_hostname']
# if there is already a compute node just use resources
# to initialize
if nodename in self.compute_nodes:
cn = self.compute_nodes[nodename]
self._copy_resources(cn, resources)
self._setup_pci_tracker(context, cn, resources)
return False
# now try to get the compute node record from the
# database. If we get one we use resources to initialize
cn = self._get_compute_node(context, nodename)
if cn:
self.compute_nodes[nodename] = cn
self._copy_resources(cn, resources)
self._setup_pci_tracker(context, cn, resources)
return False
if self._check_for_nodes_rebalance(context, resources, nodename):
return False
# there was no local copy and none in the database
# so we need to create a new compute node. This needs
# to be initialized with resource values.
cn = objects.ComputeNode(context)
cn.host = self.host
self._copy_resources(cn, resources, initial=True)
cn.create()
# Only map the ComputeNode into compute_nodes if create() was OK
# because if create() fails, on the next run through here nodename
# would be in compute_nodes and we won't try to create again (because
# of the logic above).
self.compute_nodes[nodename] = cn
LOG.info('Compute node record created for '
'%(host)s:%(node)s with uuid: %(uuid)s',
{'host': self.host, 'node': nodename, 'uuid': cn.uuid})
self._setup_pci_tracker(context, cn, resources)
return True
def _setup_pci_tracker(self, context, compute_node, resources):
if not self.pci_tracker:
n_id = compute_node.id
self.pci_tracker = pci_manager.PciDevTracker(context, node_id=n_id)
if 'pci_passthrough_devices' in resources:
dev_json = resources.pop('pci_passthrough_devices')
self.pci_tracker.update_devices_from_hypervisor_resources(
dev_json)
dev_pools_obj = self.pci_tracker.stats.to_device_pools_obj()
compute_node.pci_device_pools = dev_pools_obj
def _copy_resources(self, compute_node, resources, initial=False):
"""Copy resource values to supplied compute_node."""
nodename = resources['hypervisor_hostname']
stats = self.stats[nodename]
# purge old stats and init with anything passed in by the driver
# NOTE(danms): Preserve 'failed_builds' across the stats clearing,
# as that is not part of resources
# TODO(danms): Stop doing this when we get a column to store this
# directly
prev_failed_builds = stats.get('failed_builds', 0)
stats.clear()
stats['failed_builds'] = prev_failed_builds
stats.digest_stats(resources.get('stats'))
compute_node.stats = stats
# Update the allocation ratios for the related ComputeNode object
# but only if the configured values are not the default; the
# ComputeNode._from_db_object method takes care of providing default
# allocation ratios when the config is left at the default, so
# we'll really end up with something like a
# ComputeNode.cpu_allocation_ratio of 16.0. We want to avoid
# resetting the ComputeNode fields to None because that will make
# the _resource_change method think something changed when really it
# didn't.
# NOTE(yikun): The CONF.initial_(cpu|ram|disk)_allocation_ratio would
# be used when we initialize the compute node object, that means the
# ComputeNode.(cpu|ram|disk)_allocation_ratio will be set to
# CONF.initial_(cpu|ram|disk)_allocation_ratio when initial flag is
# True.
for res in ('cpu', 'disk', 'ram'):
attr = '%s_allocation_ratio' % res
if initial:
conf_alloc_ratio = getattr(CONF, 'initial_%s' % attr)
else:
conf_alloc_ratio = getattr(self, attr)
# NOTE(yikun): In Stein version, we change the default value of
# (cpu|ram|disk)_allocation_ratio from 0.0 to None, but we still
# should allow 0.0 to keep compatibility, and this 0.0 condition
# will be removed in the next version (T version).
if conf_alloc_ratio not in (0.0, None):
setattr(compute_node, attr, conf_alloc_ratio)
# now copy rest to compute_node
compute_node.update_from_virt_driver(resources)
def remove_node(self, nodename):
"""Handle node removal/rebalance.
Clean up any stored data about a compute node no longer
managed by this host.
"""
self.stats.pop(nodename, None)
self.compute_nodes.pop(nodename, None)
self.old_resources.pop(nodename, None)
def _get_host_metrics(self, context, nodename):
"""Get the metrics from monitors and
notify information to message bus.
"""
metrics = objects.MonitorMetricList()
metrics_info = {}
for monitor in self.monitors:
try:
monitor.populate_metrics(metrics)
except NotImplementedError:
LOG.debug("The compute driver doesn't support host "
"metrics for %(mon)s", {'mon': monitor})
except Exception as exc:
LOG.warning("Cannot get the metrics from %(mon)s; "
"error: %(exc)s",
{'mon': monitor, 'exc': exc})
# TODO(jaypipes): Remove this when compute_node.metrics doesn't need
# to be populated as a JSONified string.
metric_list = metrics.to_list()
if len(metric_list):
metrics_info['nodename'] = nodename
metrics_info['metrics'] = metric_list
metrics_info['host'] = self.host
metrics_info['host_ip'] = CONF.my_ip
notifier = rpc.get_notifier(service='compute', host=nodename)
notifier.info(context, 'compute.metrics.update', metrics_info)
compute_utils.notify_about_metrics_update(
context, self.host, CONF.my_ip, nodename, metrics)
return metric_list
def update_available_resource(self, context, nodename, startup=False):
"""Override in-memory calculations of compute node resource usage based
on data audited from the hypervisor layer.
Add in resource claims in progress to account for operations that have
declared a need for resources, but not necessarily retrieved them from
the hypervisor layer yet.
:param nodename: Temporary parameter representing the Ironic resource
node. This parameter will be removed once Ironic
baremetal resource nodes are handled like any other
resource in the system.
:param startup: Boolean indicating whether we're running this on
on startup (True) or periodic (False).
"""
LOG.debug("Auditing locally available compute resources for "
"%(host)s (node: %(node)s)",
{'node': nodename,
'host': self.host})
resources = self.driver.get_available_resource(nodename)
# NOTE(jaypipes): The resources['hypervisor_hostname'] field now
# contains a non-None value, even for non-Ironic nova-compute hosts. It
# is this value that will be populated in the compute_nodes table.
resources['host_ip'] = CONF.my_ip
# We want the 'cpu_info' to be None from the POV of the
# virt driver, but the DB requires it to be non-null so
# just force it to empty string
if "cpu_info" not in resources or resources["cpu_info"] is None:
resources["cpu_info"] = ''
self._verify_resources(resources)
self._report_hypervisor_resource_view(resources)
self._update_available_resource(context, resources, startup=startup)
def _pair_instances_to_migrations(self, migrations, instance_by_uuid):
for migration in migrations:
try:
migration.instance = instance_by_uuid[migration.instance_uuid]
except KeyError:
# NOTE(danms): If this happens, we don't set it here, and
# let the code either fail or lazy-load the instance later
# which is what happened before we added this optimization.
# NOTE(tdurakov) this situation is possible for resize/cold
# migration when migration is finished but haven't yet
# confirmed/reverted in that case instance already changed host
# to destination and no matching happens
LOG.debug('Migration for instance %(uuid)s refers to '
'another host\'s instance!',
{'uuid': migration.instance_uuid})
@utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE)
def _update_available_resource(self, context, resources, startup=False):
# initialize the compute node object, creating it
# if it does not already exist.
is_new_compute_node = self._init_compute_node(context, resources)
nodename = resources['hypervisor_hostname']
# if we could not init the compute node the tracker will be
# disabled and we should quit now
if self.disabled(nodename):
return
# Grab all instances assigned to this node:
instances = objects.InstanceList.get_by_host_and_node(
context, self.host, nodename,
expected_attrs=['system_metadata',
'numa_topology',
'flavor', 'migration_context',
'resources'])
# Now calculate usage based on instance utilization:
instance_by_uuid = self._update_usage_from_instances(
context, instances, nodename)
# Grab all in-progress migrations:
migrations = objects.MigrationList.get_in_progress_by_host_and_node(
context, self.host, nodename)
self._pair_instances_to_migrations(migrations, instance_by_uuid)
self._update_usage_from_migrations(context, migrations, nodename)
# A new compute node means there won't be a resource provider yet since
# that would be created via the _update() call below, and if there is
# no resource provider then there are no allocations against it.
if not is_new_compute_node:
self._remove_deleted_instances_allocations(
context, self.compute_nodes[nodename], migrations,
instance_by_uuid)
# Detect and account for orphaned instances that may exist on the
# hypervisor, but are not in the DB:
orphans = self._find_orphaned_instances()
self._update_usage_from_orphans(orphans, nodename)
cn = self.compute_nodes[nodename]
# NOTE(yjiang5): Because pci device tracker status is not cleared in
# this periodic task, and also because the resource tracker is not
# notified when instances are deleted, we need remove all usages
# from deleted instances.
self.pci_tracker.clean_usage(instances, migrations, orphans)
dev_pools_obj = self.pci_tracker.stats.to_device_pools_obj()
cn.pci_device_pools = dev_pools_obj
self._report_final_resource_view(nodename)
metrics = self._get_host_metrics(context, nodename)
# TODO(pmurray): metrics should not be a json string in ComputeNode,
# but it is. This should be changed in ComputeNode
cn.metrics = jsonutils.dumps(metrics)
# Update assigned resources to self.assigned_resources
self._populate_assigned_resources(context, instance_by_uuid)
# update the compute_node
self._update(context, cn, startup=startup)
LOG.debug('Compute_service record updated for %(host)s:%(node)s',
{'host': self.host, 'node': nodename})
# Check if there is any resource assigned but not found
# in provider tree
if startup:
self._check_resources(context)
def _get_compute_node(self, context, nodename):
"""Returns compute node for the host and nodename."""
try:
return objects.ComputeNode.get_by_host_and_nodename(
context, self.host, nodename)
except exception.NotFound:
LOG.warning("No compute node record for %(host)s:%(node)s",
{'host': self.host, 'node': nodename})
def _report_hypervisor_resource_view(self, resources):
"""Log the hypervisor's view of free resources.
This is just a snapshot of resource usage recorded by the
virt driver.
The following resources are logged:
- free memory
- free disk
- free CPUs
- assignable PCI devices
"""
nodename = resources['hypervisor_hostname']
free_ram_mb = resources['memory_mb'] - resources['memory_mb_used']
free_disk_gb = resources['local_gb'] - resources['local_gb_used']
vcpus = resources['vcpus']
if vcpus:
free_vcpus = vcpus - resources['vcpus_used']
else:
free_vcpus = 'unknown'
pci_devices = resources.get('pci_passthrough_devices')
LOG.debug("Hypervisor/Node resource view: "
"name=%(node)s "
"free_ram=%(free_ram)sMB "
"free_disk=%(free_disk)sGB "
"free_vcpus=%(free_vcpus)s "
"pci_devices=%(pci_devices)s",
{'node': nodename,
'free_ram': free_ram_mb,
'free_disk': free_disk_gb,
'free_vcpus': free_vcpus,
'pci_devices': pci_devices})
def _report_final_resource_view(self, nodename):
"""Report final calculate of physical memory, used virtual memory,
disk, usable vCPUs, used virtual CPUs and PCI devices,
including instance calculations and in-progress resource claims. These
values will be exposed via the compute node table to the scheduler.
"""
cn = self.compute_nodes[nodename]
vcpus = cn.vcpus
if vcpus:
tcpu = vcpus
ucpu = cn.vcpus_used
LOG.debug("Total usable vcpus: %(tcpu)s, "
"total allocated vcpus: %(ucpu)s",
{'tcpu': vcpus,
'ucpu': ucpu})
else:
tcpu = 0
ucpu = 0
pci_stats = (list(cn.pci_device_pools) if
cn.pci_device_pools else [])
LOG.debug("Final resource view: "
"name=%(node)s "
"phys_ram=%(phys_ram)sMB "
"used_ram=%(used_ram)sMB "
"phys_disk=%(phys_disk)sGB "
"used_disk=%(used_disk)sGB "
"total_vcpus=%(total_vcpus)s "
"used_vcpus=%(used_vcpus)s "
"pci_stats=%(pci_stats)s",
{'node': nodename,
'phys_ram': cn.memory_mb,
'used_ram': cn.memory_mb_used,
'phys_disk': cn.local_gb,
'used_disk': cn.local_gb_used,
'total_vcpus': tcpu,
'used_vcpus': ucpu,
'pci_stats': pci_stats})
def _resource_change(self, compute_node):
"""Check to see if any resources have changed."""
nodename = compute_node.hypervisor_hostname
old_compute = self.old_resources[nodename]
if not obj_base.obj_equal_prims(
compute_node, old_compute, ['updated_at']):
self.old_resources[nodename] = copy.deepcopy(compute_node)
return True
return False
def _sync_compute_service_disabled_trait(self, context, traits):
"""Synchronize the COMPUTE_STATUS_DISABLED trait on the node provider.
Determines if the COMPUTE_STATUS_DISABLED trait should be added to
or removed from the provider's set of traits based on the related
nova-compute service disabled status.
:param context: RequestContext for cell database access
:param traits: set of traits for the compute node resource provider;
this is modified by reference
"""
trait = os_traits.COMPUTE_STATUS_DISABLED
try:
service = objects.Service.get_by_compute_host(context, self.host)
if service.disabled:
# The service is disabled so make sure the trait is reported.
traits.add(trait)
else:
# The service is not disabled so do not report the trait.
traits.discard(trait)
except exception.NotFound:
# This should not happen but handle it gracefully. The scheduler
# should ignore this node if the compute service record is gone.
LOG.error('Unable to find services table record for nova-compute '
'host %s', self.host)
def _get_traits(self, context, nodename, provider_tree):
"""Synchronizes internal and external traits for the node provider.
This works in conjunction with the ComptueDriver.update_provider_tree
flow and is used to synchronize traits reported by the compute driver,
traits based on information in the ComputeNode record, and traits set
externally using the placement REST API.
:param context: RequestContext for cell database access
:param nodename: ComputeNode.hypervisor_hostname for the compute node
resource provider whose traits are being synchronized; the node
must be in the ProviderTree.
:param provider_tree: ProviderTree being updated
"""
# Get the traits from the ProviderTree which will be the set
# of virt-owned traits plus any externally defined traits set
# on the provider that aren't owned by the virt driver.
traits = provider_tree.data(nodename).traits
# Now get the driver's capabilities and add any supported
# traits that are missing, and remove any existing set traits
# that are not currently supported.
for trait, supported in self.driver.capabilities_as_traits().items():
if supported:
traits.add(trait)
elif trait in traits:
traits.remove(trait)
# Always mark the compute node. This lets other processes (possibly
# unrelated to nova or even OpenStack) find and distinguish these
# providers easily.
traits.add(os_traits.COMPUTE_NODE)
self._sync_compute_service_disabled_trait(context, traits)
return list(traits)
@retrying.retry(stop_max_attempt_number=4,
retry_on_exception=lambda e: isinstance(
e, exception.ResourceProviderUpdateConflict))
def _update_to_placement(self, context, compute_node, startup):
"""Send resource and inventory changes to placement."""
# NOTE(jianghuaw): Some resources(e.g. VGPU) are not saved in the
# object of compute_node; instead the inventory data for these
# resource is reported by driver's update_provider_tree(). So even if
# there is no resource change for compute_node, we need proceed
# to get inventory and use report client interfaces to update
# inventory to placement. It's report client's responsibility to
# ensure the update request to placement only happens when inventory
# is changed.
nodename = compute_node.hypervisor_hostname
# Persist the stats to the Scheduler
# Retrieve the provider tree associated with this compute node. If
# it doesn't exist yet, this will create it with a (single, root)
# provider corresponding to the compute node.
prov_tree = self.reportclient.get_provider_tree_and_ensure_root(
context, compute_node.uuid, name=compute_node.hypervisor_hostname)
# Let the virt driver rearrange the provider tree and set/update
# the inventory, traits, and aggregates throughout.
allocs = None
try:
self.driver.update_provider_tree(prov_tree, nodename)
except exception.ReshapeNeeded:
if not startup:
# This isn't supposed to happen during periodic, so raise
# it up; the compute manager will treat it specially.
raise
LOG.info("Performing resource provider inventory and "
"allocation data migration during compute service "
"startup or fast-forward upgrade.")
allocs = self.reportclient.get_allocations_for_provider_tree(
context, nodename)
self.driver.update_provider_tree(prov_tree, nodename,
allocations=allocs)
# Inject driver capabilities traits into the provider
# tree. We need to determine the traits that the virt
# driver owns - so those that come from the tree itself
# (via the virt driver) plus the compute capabilities
# traits, and then merge those with the traits set
# externally that the driver does not own - and remove any
# set on the provider externally that the virt owns but
# aren't in the current list of supported traits. For
# example, let's say we reported multiattach support as a
# trait at t1 and then at t2 it's not, so we need to
# remove it. But at both t1 and t2 there is a
# CUSTOM_VENDOR_TRAIT_X which we can't touch because it
# was set externally on the provider.
# We also want to sync the COMPUTE_STATUS_DISABLED trait based
# on the related nova-compute service's disabled status.
traits = self._get_traits(
context, nodename, provider_tree=prov_tree)
prov_tree.update_traits(nodename, traits)
self.provider_tree = prov_tree
# Flush any changes. If we processed ReshapeNeeded above, allocs is not
# None, and this will hit placement's POST /reshaper route.
self.reportclient.update_from_provider_tree(context, prov_tree,
allocations=allocs)
def _update(self, context, compute_node, startup=False):
"""Update partial stats locally and populate them to Scheduler."""
# _resource_change will update self.old_resources if it detects changes
# but we want to restore those if compute_node.save() fails.
nodename = compute_node.hypervisor_hostname
old_compute = self.old_resources[nodename]
if self._resource_change(compute_node):
# If the compute_node's resource changed, update to DB. Note that
# _update_to_placement below does not supersede the need to do this
# because there are stats-related fields in the ComputeNode object
# which could have changed and still need to be reported to the
# scheduler filters/weighers (which could be out of tree as well).
try:
compute_node.save()
except Exception:
# Restore the previous state in self.old_resources so that on
# the next trip through here _resource_change does not have
# stale data to compare.
with excutils.save_and_reraise_exception(logger=LOG):
self.old_resources[nodename] = old_compute
self._update_to_placement(context, compute_node, startup)
if self.pci_tracker:
self.pci_tracker.save(context)
def _update_usage(self, usage, nodename, sign=1):
# TODO(stephenfin): We don't use the CPU, RAM and disk fields for much
# except 'Aggregate(Core|Ram|Disk)Filter', the 'os-hypervisors' API,
# and perhaps some out-of-tree filters. Once the in-tree stuff is
# removed or updated to use information from placement, we can think
# about dropping the fields from the 'ComputeNode' object entirely
mem_usage = usage['memory_mb']
disk_usage = usage.get('root_gb', 0)
vcpus_usage = usage.get('vcpus', 0)
cn = self.compute_nodes[nodename]
cn.memory_mb_used += sign * mem_usage
cn.local_gb_used += sign * disk_usage
cn.local_gb_used += sign * usage.get('ephemeral_gb', 0)
cn.local_gb_used += sign * usage.get('swap', 0) / 1024
cn.vcpus_used += sign * vcpus_usage
# free ram and disk may be negative, depending on policy:
cn.free_ram_mb = cn.memory_mb - cn.memory_mb_used
cn.free_disk_gb = cn.local_gb - cn.local_gb_used
stats = self.stats[nodename]
cn.running_vms = stats.num_instances
# calculate the NUMA usage, assuming the instance is actually using
# NUMA, of course
if cn.numa_topology and usage.get('numa_topology'):
instance_numa_topology = usage.get('numa_topology')
# the ComputeNode.numa_topology field is a StringField, so
# deserialize
host_numa_topology = objects.NUMATopology.obj_from_db_obj(
cn.numa_topology)
free = sign == -1
# ...and reserialize once we save it back
cn.numa_topology = hardware.numa_usage_from_instance_numa(
host_numa_topology, instance_numa_topology, free)._to_json()
def _get_migration_context_resource(self, resource, instance,
prefix='new_'):
migration_context = instance.migration_context
resource = prefix + resource
if migration_context and resource in migration_context:
return getattr(migration_context, resource)
return None
def _update_usage_from_migration(self, context, instance, migration,
nodename):
"""Update usage for a single migration. The record may
represent an incoming or outbound migration.
"""
uuid = migration.instance_uuid
LOG.info("Updating resource usage from migration %s", migration.uuid,
instance_uuid=uuid)
incoming = (migration.dest_compute == self.host and
migration.dest_node == nodename)
outbound = (migration.source_compute == self.host and
migration.source_node == nodename)
same_node = (incoming and outbound)
tracked = uuid in self.tracked_instances
itype = None
numa_topology = None
sign = 0
if same_node:
# Same node resize. Record usage for the 'new_' resources. This
# is executed on resize_claim().
if (instance['instance_type_id'] ==
migration.old_instance_type_id):
itype = self._get_instance_type(instance, 'new_', migration)
numa_topology = self._get_migration_context_resource(
'numa_topology', instance)
# Allocate pci device(s) for the instance.
sign = 1
else:
# The instance is already set to the new flavor (this is done
# by the compute manager on finish_resize()), hold space for a
# possible revert to the 'old_' resources.
# NOTE(lbeliveau): When the periodic audit timer gets
# triggered, the compute usage gets reset. The usage for an
# instance that is migrated to the new flavor but not yet
# confirmed/reverted will first get accounted for by
# _update_usage_from_instances(). This method will then be
# called, and we need to account for the '_old' resources
# (just in case).
itype = self._get_instance_type(instance, 'old_', migration)
numa_topology = self._get_migration_context_resource(
'numa_topology', instance, prefix='old_')
elif incoming and not tracked:
# instance has not yet migrated here:
itype = self._get_instance_type(instance, 'new_', migration)
numa_topology = self._get_migration_context_resource(
'numa_topology', instance)
# Allocate pci device(s) for the instance.
sign = 1
LOG.debug('Starting to track incoming migration %s with flavor %s',
migration.uuid, itype.flavorid, instance=instance)
elif outbound and not tracked:
# instance migrated, but record usage for a possible revert:
itype = self._get_instance_type(instance, 'old_', migration)
numa_topology = self._get_migration_context_resource(
'numa_topology', instance, prefix='old_')
# We could be racing with confirm_resize setting the
# instance.old_flavor field to None before the migration status
# is "confirmed" so if we did not find the flavor in the outgoing
# resized instance we won't track it.
if itype:
LOG.debug('Starting to track outgoing migration %s with '
'flavor %s', migration.uuid, itype.flavorid,
instance=instance)
if itype:
cn = self.compute_nodes[nodename]
usage = self._get_usage_dict(
itype, instance, numa_topology=numa_topology)
if self.pci_tracker and sign:
self.pci_tracker.update_pci_for_instance(
context, instance, sign=sign)
self._update_usage(usage, nodename)
if self.pci_tracker:
obj = self.pci_tracker.stats.to_device_pools_obj()
cn.pci_device_pools = obj
else:
obj = objects.PciDevicePoolList()
cn.pci_device_pools = obj
self.tracked_migrations[uuid] = migration
def _update_usage_from_migrations(self, context, migrations, nodename):
filtered = {}
instances = {}
self.tracked_migrations.clear()
# do some defensive filtering against bad migrations records in the
# database:
for migration in migrations:
uuid = migration.instance_uuid
try:
if uuid not in instances:
instances[uuid] = migration.instance
except exception.InstanceNotFound as e:
# migration referencing deleted instance
LOG.debug('Migration instance not found: %s', e)
continue
# Skip migation if instance is neither in a resize state nor is
# live-migrating.
if (not _instance_in_resize_state(instances[uuid]) and not
_instance_is_live_migrating(instances[uuid])):
LOG.debug('Skipping migration as instance is neither '
'resizing nor live-migrating.', instance_uuid=uuid)
continue
# filter to most recently updated migration for each instance:
other_migration = filtered.get(uuid, None)
# NOTE(claudiub): In Python 3, you cannot compare NoneTypes.
if other_migration:
om = other_migration
other_time = om.updated_at or om.created_at
migration_time = migration.updated_at or migration.created_at
if migration_time > other_time:
filtered[uuid] = migration
else:
filtered[uuid] = migration
for migration in filtered.values():
instance = instances[migration.instance_uuid]
# Skip migration (and mark it as error) if it doesn't match the
# instance migration id.
# This can happen if we have a stale migration record.
# We want to proceed if instance.migration_context is None
if (instance.migration_context is not None and
instance.migration_context.migration_id != migration.id):
LOG.info("Current instance migration %(im)s doesn't match "
"migration %(m)s, marking migration as error. "
"This can occur if a previous migration for this "
"instance did not complete.",
{'im': instance.migration_context.migration_id,
'm': migration.id})
migration.status = "error"
migration.save()
continue
try:
self._update_usage_from_migration(context, instance, migration,
nodename)
except exception.FlavorNotFound:
LOG.warning("Flavor could not be found, skipping migration.",
instance_uuid=instance.uuid)
continue
def _update_usage_from_instance(self, context, instance, nodename,
is_removed=False):
"""Update usage for a single instance."""
uuid = instance['uuid']
is_new_instance = uuid not in self.tracked_instances
# NOTE(sfinucan): Both brand new instances as well as instances that
# are being unshelved will have is_new_instance == True
is_removed_instance = not is_new_instance and (is_removed or
instance['vm_state'] in vm_states.ALLOW_RESOURCE_REMOVAL)
if is_new_instance:
self.tracked_instances.add(uuid)
sign = 1
if is_removed_instance:
self.tracked_instances.remove(uuid)
self._release_assigned_resources(instance.resources)
sign = -1
cn = self.compute_nodes[nodename]
stats = self.stats[nodename]
stats.update_stats_for_instance(instance, is_removed_instance)
cn.stats = stats
# if it's a new or deleted instance:
if is_new_instance or is_removed_instance:
if self.pci_tracker:
self.pci_tracker.update_pci_for_instance(context,
instance,
sign=sign)
# new instance, update compute node resource usage:
self._update_usage(self._get_usage_dict(instance, instance),
nodename, sign=sign)
# Stop tracking removed instances in the is_bfv cache. This needs to
# happen *after* calling _get_usage_dict() since that relies on the
# is_bfv cache.
if is_removed_instance and uuid in self.is_bfv:
del self.is_bfv[uuid]
cn.current_workload = stats.calculate_workload()
if self.pci_tracker:
obj = self.pci_tracker.stats.to_device_pools_obj()
cn.pci_device_pools = obj
else:
cn.pci_device_pools = objects.PciDevicePoolList()
def _update_usage_from_instances(self, context, instances, nodename):
"""Calculate resource usage based on instance utilization. This is
different than the hypervisor's view as it will account for all
instances assigned to the local compute host, even if they are not
currently powered on.
"""
self.tracked_instances.clear()
cn = self.compute_nodes[nodename]
# set some initial values, reserve room for host/hypervisor:
cn.local_gb_used = CONF.reserved_host_disk_mb / 1024
cn.memory_mb_used = CONF.reserved_host_memory_mb
cn.vcpus_used = CONF.reserved_host_cpus
cn.free_ram_mb = (cn.memory_mb - cn.memory_mb_used)
cn.free_disk_gb = (cn.local_gb - cn.local_gb_used)
cn.current_workload = 0
cn.running_vms = 0
instance_by_uuid = {}
for instance in instances:
if instance.vm_state not in vm_states.ALLOW_RESOURCE_REMOVAL:
self._update_usage_from_instance(context, instance, nodename)
instance_by_uuid[instance.uuid] = instance
return instance_by_uuid
def _remove_deleted_instances_allocations(self, context, cn,
migrations, instance_by_uuid):
migration_uuids = [migration.uuid for migration in migrations
if 'uuid' in migration]
# NOTE(jaypipes): All of this code sucks. It's basically dealing with
# all the corner cases in move, local delete, unshelve and rebuild
# operations for when allocations should be deleted when things didn't
# happen according to the normal flow of events where the scheduler
# always creates allocations for an instance
try:
# pai: report.ProviderAllocInfo namedtuple
pai = self.reportclient.get_allocations_for_resource_provider(
context, cn.uuid)
except (exception.ResourceProviderAllocationRetrievalFailed,
ks_exc.ClientException) as e:
LOG.error("Skipping removal of allocations for deleted instances: "
"%s", e)
return
allocations = pai.allocations
if not allocations:
# The main loop below would short-circuit anyway, but this saves us
# the (potentially expensive) context.elevated construction below.
return
read_deleted_context = context.elevated(read_deleted='yes')
for consumer_uuid, alloc in allocations.items():
if consumer_uuid in self.tracked_instances:
LOG.debug("Instance %s actively managed on this compute host "
"and has allocations in placement: %s.",
consumer_uuid, alloc)
continue
if consumer_uuid in migration_uuids:
LOG.debug("Migration %s is active on this compute host "
"and has allocations in placement: %s.",
consumer_uuid, alloc)
continue
# We know these are instances now, so proceed
instance_uuid = consumer_uuid
instance = instance_by_uuid.get(instance_uuid)
if not instance:
try:
instance = objects.Instance.get_by_uuid(
read_deleted_context, consumer_uuid,
expected_attrs=[])
except exception.InstanceNotFound:
# The instance isn't even in the database. Either the
# scheduler _just_ created an allocation for it and we're
# racing with the creation in the cell database, or the
# instance was deleted and fully archived before we got a
# chance to run this. The former is far more likely than
# the latter. Avoid deleting allocations for a building
# instance here.
LOG.info("Instance %(uuid)s has allocations against this "
"compute host but is not found in the database.",
{'uuid': instance_uuid},
exc_info=False)
continue
if instance.deleted:
# The instance is gone, so we definitely want to remove
# allocations associated with it.
# NOTE(jaypipes): This will not be true if/when we support
# cross-cell migrations...
LOG.debug("Instance %s has been deleted (perhaps locally). "
"Deleting allocations that remained for this "
"instance against this compute host: %s.",
instance_uuid, alloc)
self.reportclient.delete_allocation_for_instance(context,
instance_uuid)
continue
if not instance.host:
# Allocations related to instances being scheduled should not
# be deleted if we already wrote the allocation previously.
LOG.debug("Instance %s has been scheduled to this compute "
"host, the scheduler has made an allocation "
"against this compute node but the instance has "
"yet to start. Skipping heal of allocation: %s.",
instance_uuid, alloc)
continue
if (instance.host == cn.host and
instance.node == cn.hypervisor_hostname):
# The instance is supposed to be on this compute host but is
# not in the list of actively managed instances. This could be
# because we are racing with an instance_claim call during
# initial build or unshelve where the instance host/node is set
# before the instance is added to tracked_instances. If the
# task_state is set, then consider things in motion and log at
# debug level instead of warning.
if instance.task_state:
LOG.debug('Instance with task_state "%s" is not being '
'actively managed by this compute host but has '
'allocations referencing this compute node '
'(%s): %s. Skipping heal of allocations during '
'the task state transition.',
instance.task_state, cn.uuid, alloc,
instance=instance)
else:
LOG.warning("Instance %s is not being actively managed by "
"this compute host but has allocations "
"referencing this compute host: %s. Skipping "
"heal of allocation because we do not know "
"what to do.", instance_uuid, alloc)
continue
if instance.host != cn.host:
# The instance has been moved to another host either via a
# migration, evacuation or unshelve in between the time when we
# ran InstanceList.get_by_host_and_node(), added those
# instances to RT.tracked_instances and the above
# Instance.get_by_uuid() call. We SHOULD attempt to remove any
# allocations that reference this compute host if the VM is in
# a stable terminal state (i.e. it isn't in a state of waiting
# for resize to confirm/revert), however if the destination
# host is an Ocata compute host, it will delete the allocation
# that contains this source compute host information anyway and
# recreate an allocation that only refers to itself. So we
# don't need to do anything in that case. Just log the
# situation here for information but don't attempt to delete or
# change the allocation.
LOG.warning("Instance %s has been moved to another host "
"%s(%s). There are allocations remaining against "
"the source host that might need to be removed: "
"%s.",
instance_uuid, instance.host, instance.node, alloc)
def delete_allocation_for_evacuated_instance(self, context, instance, node,
node_type='source'):
# Clean up the instance allocation from this node in placement
cn_uuid = self.compute_nodes[node].uuid
if not self.reportclient.remove_provider_tree_from_instance_allocation(
context, instance.uuid, cn_uuid):
LOG.error("Failed to clean allocation of evacuated "
"instance on the %s node %s",
node_type, cn_uuid, instance=instance)
def _find_orphaned_instances(self):
"""Given the set of instances and migrations already account for
by resource tracker, sanity check the hypervisor to determine
if there are any "orphaned" instances left hanging around.
Orphans could be consuming memory and should be accounted for in
usage calculations to guard against potential out of memory
errors.
"""
uuids1 = frozenset(self.tracked_instances)
uuids2 = frozenset(self.tracked_migrations.keys())
uuids = uuids1 | uuids2
usage = self.driver.get_per_instance_usage()
vuuids = frozenset(usage.keys())
orphan_uuids = vuuids - uuids
orphans = [usage[uuid] for uuid in orphan_uuids]
return orphans
def _update_usage_from_orphans(self, orphans, nodename):
"""Include orphaned instances in usage."""
for orphan in orphans:
memory_mb = orphan['memory_mb']
LOG.warning("Detected running orphan instance: %(uuid)s "
"(consuming %(memory_mb)s MB memory)",
{'uuid': orphan['uuid'], 'memory_mb': memory_mb})
# just record memory usage for the orphan
usage = {'memory_mb': memory_mb}
self._update_usage(usage, nodename)
def delete_allocation_for_shelve_offloaded_instance(self, context,
instance):
self.reportclient.delete_allocation_for_instance(context,
instance.uuid)
def _verify_resources(self, resources):
resource_keys = ["vcpus", "memory_mb", "local_gb", "cpu_info",
"vcpus_used", "memory_mb_used", "local_gb_used",
"numa_topology"]
missing_keys = [k for k in resource_keys if k not in resources]
if missing_keys:
reason = _("Missing keys: %s") % missing_keys
raise exception.InvalidInput(reason=reason)
def _get_instance_type(self, instance, prefix, migration):
"""Get the instance type from instance."""
stashed_flavors = migration.migration_type in ('resize',)
if stashed_flavors:
return getattr(instance, '%sflavor' % prefix)
else:
# NOTE(ndipanov): Certain migration types (all but resize)
# do not change flavors so there is no need to stash
# them. In that case - just get the instance flavor.
return instance.flavor
def _get_usage_dict(self, object_or_dict, instance, **updates):
"""Make a usage dict _update methods expect.
Accepts a dict or an Instance or Flavor object, and a set of updates.
Converts the object to a dict and applies the updates.
:param object_or_dict: instance or flavor as an object or just a dict
:param instance: nova.objects.Instance for the related operation; this
is needed to determine if the instance is
volume-backed
:param updates: key-value pairs to update the passed object.
Currently only considers 'numa_topology', all other
keys are ignored.
:returns: a dict with all the information from object_or_dict updated
with updates
"""
def _is_bfv():
# Check to see if we have the is_bfv value cached.
if instance.uuid in self.is_bfv:
is_bfv = self.is_bfv[instance.uuid]
else:
is_bfv = compute_utils.is_volume_backed_instance(
instance._context, instance)
self.is_bfv[instance.uuid] = is_bfv
return is_bfv
usage = {}
if isinstance(object_or_dict, objects.Instance):
is_bfv = _is_bfv()
usage = {'memory_mb': object_or_dict.flavor.memory_mb,
'swap': object_or_dict.flavor.swap,
'vcpus': object_or_dict.flavor.vcpus,
'root_gb': (0 if is_bfv else
object_or_dict.flavor.root_gb),
'ephemeral_gb': object_or_dict.flavor.ephemeral_gb,
'numa_topology': object_or_dict.numa_topology}
elif isinstance(object_or_dict, objects.Flavor):
usage = obj_base.obj_to_primitive(object_or_dict)
if _is_bfv():
usage['root_gb'] = 0
else:
usage.update(object_or_dict)
for key in ('numa_topology',):
if key in updates:
usage[key] = updates[key]
return usage
def build_failed(self, nodename):
"""Increments the failed_builds stats for the given node."""
self.stats[nodename].build_failed()
def build_succeeded(self, nodename):
"""Resets the failed_builds stats for the given node."""
self.stats[nodename].build_succeeded()
@utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE)
def claim_pci_devices(self, context, pci_requests):
"""Claim instance PCI resources
:param context: security context
:param pci_requests: a list of nova.objects.InstancePCIRequests
:returns: a list of nova.objects.PciDevice objects
"""
result = self.pci_tracker.claim_instance(
context, pci_requests, None)
self.pci_tracker.save(context)
return result
@utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE)
def allocate_pci_devices_for_instance(self, context, instance):
"""Allocate instance claimed PCI resources
:param context: security context
:param instance: instance object
"""
self.pci_tracker.allocate_instance(instance)
self.pci_tracker.save(context)
@utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE)
def free_pci_device_allocations_for_instance(self, context, instance):
"""Free instance allocated PCI resources
:param context: security context
:param instance: instance object
"""
self.pci_tracker.free_instance_allocations(context, instance)
self.pci_tracker.save(context)
@utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE)
def free_pci_device_claims_for_instance(self, context, instance):
"""Free instance claimed PCI resources
:param context: security context
:param instance: instance object
"""
self.pci_tracker.free_instance_claims(context, instance)
self.pci_tracker.save(context)
| 46.796562 | 79 | 0.620745 |
import collections
import copy
from keystoneauth1 import exceptions as ks_exc
import os_traits
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import excutils
import retrying
from nova.compute import claims
from nova.compute import monitors
from nova.compute import stats as compute_stats
from nova.compute import task_states
from nova.compute import utils as compute_utils
from nova.compute import vm_states
import nova.conf
from nova import exception
from nova.i18n import _
from nova import objects
from nova.objects import base as obj_base
from nova.objects import migration as migration_obj
from nova.pci import manager as pci_manager
from nova.pci import request as pci_request
from nova import rpc
from nova.scheduler.client import report
from nova import utils
from nova.virt import hardware
CONF = nova.conf.CONF
LOG = logging.getLogger(__name__)
COMPUTE_RESOURCE_SEMAPHORE = "compute_resources"
def _instance_in_resize_state(instance):
vm = instance.vm_state
task = instance.task_state
if vm == vm_states.RESIZED:
return True
if vm in [vm_states.ACTIVE, vm_states.STOPPED] and task in (
task_states.resizing_states + task_states.rebuild_states):
return True
return False
def _instance_is_live_migrating(instance):
vm = instance.vm_state
task = instance.task_state
if task == task_states.MIGRATING and vm in [vm_states.ACTIVE,
vm_states.PAUSED]:
return True
return False
class ResourceTracker(object):
def __init__(self, host, driver, reportclient=None):
self.host = host
self.driver = driver
self.pci_tracker = None
self.compute_nodes = {}
self.stats = collections.defaultdict(compute_stats.Stats)
self.tracked_instances = set()
self.tracked_migrations = {}
self.is_bfv = {}
monitor_handler = monitors.MonitorHandler(self)
self.monitors = monitor_handler.monitors
self.old_resources = collections.defaultdict(objects.ComputeNode)
self.reportclient = reportclient or report.SchedulerReportClient()
self.ram_allocation_ratio = CONF.ram_allocation_ratio
self.cpu_allocation_ratio = CONF.cpu_allocation_ratio
self.disk_allocation_ratio = CONF.disk_allocation_ratio
self.provider_tree = None
self.assigned_resources = collections.defaultdict(
lambda: collections.defaultdict(set))
@utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE)
def instance_claim(self, context, instance, nodename, allocations,
limits=None):
if self.disabled(nodename):
self._set_instance_host_and_node(instance, nodename)
return claims.NopClaim()
if instance.host:
LOG.warning("Host field should not be set on the instance "
"until resources have been claimed.",
instance=instance)
if instance.node:
LOG.warning("Node field should not be set on the instance "
"until resources have been claimed.",
instance=instance)
cn = self.compute_nodes[nodename]
pci_requests = objects.InstancePCIRequests.get_by_instance_uuid(
context, instance.uuid)
claim = claims.Claim(context, instance, nodename, self, cn,
pci_requests, limits=limits)
instance_numa_topology = claim.claimed_numa_topology
instance.numa_topology = instance_numa_topology
self._set_instance_host_and_node(instance, nodename)
if self.pci_tracker:
# NOTE(jaypipes): ComputeNode.pci_device_pools is set below
# in _update_usage_from_instance().
self.pci_tracker.claim_instance(context, pci_requests,
instance_numa_topology)
claimed_resources = self._claim_resources(allocations)
instance.resources = claimed_resources
# Mark resources in-use and update stats
self._update_usage_from_instance(context, instance, nodename)
elevated = context.elevated()
# persist changes to the compute node:
self._update(elevated, cn)
return claim
@utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE)
def rebuild_claim(self, context, instance, nodename, allocations,
limits=None, image_meta=None, migration=None):
instance_type = instance.flavor
return self._move_claim(context, instance, instance_type, nodename,
migration, allocations, move_type='evacuation',
limits=limits, image_meta=image_meta)
@utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE)
def resize_claim(self, context, instance, instance_type, nodename,
migration, allocations, image_meta=None, limits=None):
return self._move_claim(context, instance, instance_type, nodename,
migration, allocations, image_meta=image_meta,
limits=limits)
@utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE)
def live_migration_claim(self, context, instance, nodename, migration,
limits):
# Flavor and image cannot change during a live migration.
instance_type = instance.flavor
image_meta = instance.image_meta
# TODO(Luyao) will pass allocations to live_migration_claim after the
# live migration change is done, now just set it None to _move_claim
return self._move_claim(context, instance, instance_type, nodename,
migration, None, move_type='live-migration',
image_meta=image_meta, limits=limits)
def _move_claim(self, context, instance, new_instance_type, nodename,
migration, allocations, move_type=None,
image_meta=None, limits=None):
image_meta = image_meta or {}
if migration:
self._claim_existing_migration(migration, nodename)
else:
migration = self._create_migration(context, instance,
new_instance_type,
nodename, move_type)
if self.disabled(nodename):
# compute_driver doesn't support resource tracking, just
return claims.NopClaim(migration=migration)
cn = self.compute_nodes[nodename]
new_pci_requests = pci_request.get_pci_requests_from_flavor(
new_instance_type)
new_pci_requests.instance_uuid = instance.uuid
if instance.pci_requests:
for request in instance.pci_requests.requests:
if request.source == objects.InstancePCIRequest.NEUTRON_PORT:
new_pci_requests.requests.append(request)
claim = claims.MoveClaim(context, instance, nodename,
new_instance_type, image_meta, self, cn,
new_pci_requests, migration, limits=limits)
claimed_pci_devices_objs = []
# migration to avoid stepping on that code's toes. Ideally,
if self.pci_tracker and migration.migration_type != 'live-migration':
claimed_pci_devices_objs = self.pci_tracker.claim_instance(
context, new_pci_requests, claim.claimed_numa_topology)
claimed_pci_devices = objects.PciDeviceList(
objects=claimed_pci_devices_objs)
claimed_resources = self._claim_resources(allocations)
old_resources = instance.resources
# constructor flow so the Claim constructor only tests whether
# resources can be claimed, not consume the resources directly.
mig_context = objects.MigrationContext(
context=context, instance_uuid=instance.uuid,
migration_id=migration.id,
old_numa_topology=instance.numa_topology,
new_numa_topology=claim.claimed_numa_topology,
old_pci_devices=instance.pci_devices,
new_pci_devices=claimed_pci_devices,
old_pci_requests=instance.pci_requests,
new_pci_requests=new_pci_requests,
old_resources=old_resources,
new_resources=claimed_resources)
instance.migration_context = mig_context
instance.save()
# Mark the resources in-use for the resize landing on this
# compute host:
self._update_usage_from_migration(context, instance, migration,
nodename)
elevated = context.elevated()
self._update(elevated, cn)
return claim
def _create_migration(self, context, instance, new_instance_type,
nodename, move_type=None):
migration = objects.Migration(context=context.elevated())
migration.dest_compute = self.host
migration.dest_node = nodename
migration.dest_host = self.driver.get_host_ip_addr()
migration.old_instance_type_id = instance.flavor.id
migration.new_instance_type_id = new_instance_type.id
migration.status = 'pre-migrating'
migration.instance_uuid = instance.uuid
migration.source_compute = instance.host
migration.source_node = instance.node
if move_type:
migration.migration_type = move_type
else:
migration.migration_type = migration_obj.determine_migration_type(
migration)
migration.create()
return migration
def _claim_existing_migration(self, migration, nodename):
migration.dest_compute = self.host
migration.dest_node = nodename
migration.dest_host = self.driver.get_host_ip_addr()
# NOTE(artom) Migration objects for live migrations are created with
# status 'accepted' by the conductor in live_migrate_instance() and do
# not have a 'pre-migrating' status.
if migration.migration_type != 'live-migration':
migration.status = 'pre-migrating'
migration.save()
def _claim_resources(self, allocations):
if not allocations:
return None
claimed_resources = []
for rp_uuid, alloc_dict in allocations.items():
try:
provider_data = self.provider_tree.data(rp_uuid)
except ValueError:
# If an instance is in evacuating, it will hold new and old
# allocations, but the provider UUIDs in old allocations won't
LOG.debug("Skip claiming resources of provider %(rp_uuid)s, "
"since the provider UUIDs are not in provider tree.",
{'rp_uuid': rp_uuid})
continue
for rc, amount in alloc_dict['resources'].items():
if rc not in provider_data.resources:
# assign this kind of resource class, such as 'VCPU' for
# now, otherwise the provider_data.resources will be
# populated with this resource class when updating
# provider tree.
continue
assigned = self.assigned_resources[rp_uuid][rc]
free = provider_data.resources[rc] - assigned
if amount > len(free):
reason = (_("Needed %(amount)d units of resource class "
"%(rc)s, but %(avail)d are available.") %
{'amount': amount,
'rc': rc,
'avail': len(free)})
raise exception.ComputeResourcesUnavailable(reason=reason)
for i in range(amount):
claimed_resources.append(free.pop())
if claimed_resources:
self._add_assigned_resources(claimed_resources)
return objects.ResourceList(objects=claimed_resources)
def _populate_assigned_resources(self, context, instance_by_uuid):
resources = []
# Get resources assigned to migrations
for mig in self.tracked_migrations.values():
mig_ctx = mig.instance.migration_context
# We might have a migration whose instance hasn't arrived here yet.
if not mig_ctx:
continue
if mig.source_compute == self.host and 'old_resources' in mig_ctx:
resources.extend(mig_ctx.old_resources or [])
if mig.dest_compute == self.host and 'new_resources' in mig_ctx:
resources.extend(mig_ctx.new_resources or [])
for uuid in self.tracked_instances:
resources.extend(instance_by_uuid[uuid].resources or [])
self.assigned_resources.clear()
self._add_assigned_resources(resources)
def _check_resources(self, context):
notfound = set()
for rp_uuid in self.assigned_resources:
provider_data = self.provider_tree.data(rp_uuid)
for rc, assigned in self.assigned_resources[rp_uuid].items():
notfound |= (assigned - provider_data.resources[rc])
if not notfound:
return
# or restarted.
resources = [(res.identifier, res.resource_class) for res in notfound]
reason = _("The following resources are assigned to instances, "
"but were not listed in the configuration: %s "
"Please check if this will influence your instances, "
"and restore your configuration if necessary") % resources
raise exception.AssignedResourceNotFound(reason=reason)
def _release_assigned_resources(self, resources):
if not resources:
return
for resource in resources:
rp_uuid = resource.provider_uuid
rc = resource.resource_class
try:
self.assigned_resources[rp_uuid][rc].remove(resource)
except KeyError:
LOG.warning("Release resource %(rc)s: %(id)s of provider "
"%(rp_uuid)s, not tracked in "
"ResourceTracker.assigned_resources.",
{'rc': rc, 'id': resource.identifier,
'rp_uuid': rp_uuid})
def _add_assigned_resources(self, resources):
if not resources:
return
for resource in resources:
rp_uuid = resource.provider_uuid
rc = resource.resource_class
self.assigned_resources[rp_uuid][rc].add(resource)
def _set_instance_host_and_node(self, instance, nodename):
# NOTE(mriedem): ComputeManager._nil_out_instance_obj_host_and_node is
# somewhat tightly coupled to the fields set in this method so if this
# method changes that method might need to be updated.
instance.host = self.host
instance.launched_on = self.host
instance.node = nodename
instance.save()
def _unset_instance_host_and_node(self, instance):
instance.host = None
instance.node = None
instance.save()
@utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE)
def abort_instance_claim(self, context, instance, nodename):
self._update_usage_from_instance(context, instance, nodename,
is_removed=True)
instance.clear_numa_topology()
self._unset_instance_host_and_node(instance)
self._update(context.elevated(), self.compute_nodes[nodename])
def _drop_pci_devices(self, instance, nodename, prefix):
if self.pci_tracker:
# free old/new allocated pci devices
pci_devices = self._get_migration_context_resource(
'pci_devices', instance, prefix=prefix)
if pci_devices:
for pci_device in pci_devices:
self.pci_tracker.free_device(pci_device, instance)
dev_pools_obj = self.pci_tracker.stats.to_device_pools_obj()
self.compute_nodes[nodename].pci_device_pools = dev_pools_obj
@utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE)
def drop_move_claim(self, context, instance, nodename,
instance_type=None, prefix='new_'):
# Remove usage for an instance that is tracked in migrations, such as
# on the dest node during revert resize.
if instance['uuid'] in self.tracked_migrations:
migration = self.tracked_migrations.pop(instance['uuid'])
if not instance_type:
instance_type = self._get_instance_type(instance, prefix,
migration)
# Remove usage for an instance that is not tracked in migrations (such
# as on the source node after a migration).
# NOTE(lbeliveau): On resize on the same node, the instance is
# included in both tracked_migrations and tracked_instances.
elif instance['uuid'] in self.tracked_instances:
self.tracked_instances.remove(instance['uuid'])
if instance_type is not None:
numa_topology = self._get_migration_context_resource(
'numa_topology', instance, prefix=prefix)
usage = self._get_usage_dict(
instance_type, instance, numa_topology=numa_topology)
self._drop_pci_devices(instance, nodename, prefix)
resources = self._get_migration_context_resource(
'resources', instance, prefix=prefix)
self._release_assigned_resources(resources)
self._update_usage(usage, nodename, sign=-1)
ctxt = context.elevated()
self._update(ctxt, self.compute_nodes[nodename])
@utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE)
def update_usage(self, context, instance, nodename):
if self.disabled(nodename):
return
uuid = instance['uuid']
# don't update usage for this instance unless it submitted a resource
if uuid in self.tracked_instances:
self._update_usage_from_instance(context, instance, nodename)
self._update(context.elevated(), self.compute_nodes[nodename])
def disabled(self, nodename):
return (nodename not in self.compute_nodes or
not self.driver.node_is_available(nodename))
def _check_for_nodes_rebalance(self, context, resources, nodename):
if not self.driver.rebalances_nodes:
return False
# check if there is a compute node that already has the correct
# hypervisor_hostname. We can re-use that rather than create a
# new one and have to move existing placement allocations
cn_candidates = objects.ComputeNodeList.get_by_hypervisor(
context, nodename)
if len(cn_candidates) == 1:
cn = cn_candidates[0]
LOG.info("ComputeNode %(name)s moving from %(old)s to %(new)s",
{"name": nodename, "old": cn.host, "new": self.host})
cn.host = self.host
self.compute_nodes[nodename] = cn
self._copy_resources(cn, resources)
self._setup_pci_tracker(context, cn, resources)
self._update(context, cn)
return True
elif len(cn_candidates) > 1:
LOG.error(
"Found more than one ComputeNode for nodename %s. "
"Please clean up the orphaned ComputeNode records in your DB.",
nodename)
return False
def _init_compute_node(self, context, resources):
nodename = resources['hypervisor_hostname']
# if there is already a compute node just use resources
# to initialize
if nodename in self.compute_nodes:
cn = self.compute_nodes[nodename]
self._copy_resources(cn, resources)
self._setup_pci_tracker(context, cn, resources)
return False
# now try to get the compute node record from the
# database. If we get one we use resources to initialize
cn = self._get_compute_node(context, nodename)
if cn:
self.compute_nodes[nodename] = cn
self._copy_resources(cn, resources)
self._setup_pci_tracker(context, cn, resources)
return False
if self._check_for_nodes_rebalance(context, resources, nodename):
return False
# there was no local copy and none in the database
# so we need to create a new compute node. This needs
# to be initialized with resource values.
cn = objects.ComputeNode(context)
cn.host = self.host
self._copy_resources(cn, resources, initial=True)
cn.create()
# Only map the ComputeNode into compute_nodes if create() was OK
# because if create() fails, on the next run through here nodename
# would be in compute_nodes and we won't try to create again (because
self.compute_nodes[nodename] = cn
LOG.info('Compute node record created for '
'%(host)s:%(node)s with uuid: %(uuid)s',
{'host': self.host, 'node': nodename, 'uuid': cn.uuid})
self._setup_pci_tracker(context, cn, resources)
return True
def _setup_pci_tracker(self, context, compute_node, resources):
if not self.pci_tracker:
n_id = compute_node.id
self.pci_tracker = pci_manager.PciDevTracker(context, node_id=n_id)
if 'pci_passthrough_devices' in resources:
dev_json = resources.pop('pci_passthrough_devices')
self.pci_tracker.update_devices_from_hypervisor_resources(
dev_json)
dev_pools_obj = self.pci_tracker.stats.to_device_pools_obj()
compute_node.pci_device_pools = dev_pools_obj
def _copy_resources(self, compute_node, resources, initial=False):
nodename = resources['hypervisor_hostname']
stats = self.stats[nodename]
prev_failed_builds = stats.get('failed_builds', 0)
stats.clear()
stats['failed_builds'] = prev_failed_builds
stats.digest_stats(resources.get('stats'))
compute_node.stats = stats
# ComputeNode.cpu_allocation_ratio of 16.0. We want to avoid
# resetting the ComputeNode fields to None because that will make
# the _resource_change method think something changed when really it
# didn't.
for res in ('cpu', 'disk', 'ram'):
attr = '%s_allocation_ratio' % res
if initial:
conf_alloc_ratio = getattr(CONF, 'initial_%s' % attr)
else:
conf_alloc_ratio = getattr(self, attr)
if conf_alloc_ratio not in (0.0, None):
setattr(compute_node, attr, conf_alloc_ratio)
compute_node.update_from_virt_driver(resources)
def remove_node(self, nodename):
self.stats.pop(nodename, None)
self.compute_nodes.pop(nodename, None)
self.old_resources.pop(nodename, None)
def _get_host_metrics(self, context, nodename):
metrics = objects.MonitorMetricList()
metrics_info = {}
for monitor in self.monitors:
try:
monitor.populate_metrics(metrics)
except NotImplementedError:
LOG.debug("The compute driver doesn't support host "
"metrics for %(mon)s", {'mon': monitor})
except Exception as exc:
LOG.warning("Cannot get the metrics from %(mon)s; "
"error: %(exc)s",
{'mon': monitor, 'exc': exc})
# TODO(jaypipes): Remove this when compute_node.metrics doesn't need
metric_list = metrics.to_list()
if len(metric_list):
metrics_info['nodename'] = nodename
metrics_info['metrics'] = metric_list
metrics_info['host'] = self.host
metrics_info['host_ip'] = CONF.my_ip
notifier = rpc.get_notifier(service='compute', host=nodename)
notifier.info(context, 'compute.metrics.update', metrics_info)
compute_utils.notify_about_metrics_update(
context, self.host, CONF.my_ip, nodename, metrics)
return metric_list
def update_available_resource(self, context, nodename, startup=False):
LOG.debug("Auditing locally available compute resources for "
"%(host)s (node: %(node)s)",
{'node': nodename,
'host': self.host})
resources = self.driver.get_available_resource(nodename)
resources['host_ip'] = CONF.my_ip
if "cpu_info" not in resources or resources["cpu_info"] is None:
resources["cpu_info"] = ''
self._verify_resources(resources)
self._report_hypervisor_resource_view(resources)
self._update_available_resource(context, resources, startup=startup)
def _pair_instances_to_migrations(self, migrations, instance_by_uuid):
for migration in migrations:
try:
migration.instance = instance_by_uuid[migration.instance_uuid]
except KeyError:
# let the code either fail or lazy-load the instance later
# which is what happened before we added this optimization.
# NOTE(tdurakov) this situation is possible for resize/cold
# migration when migration is finished but haven't yet
LOG.debug('Migration for instance %(uuid)s refers to '
'another host\'s instance!',
{'uuid': migration.instance_uuid})
@utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE)
def _update_available_resource(self, context, resources, startup=False):
# initialize the compute node object, creating it
# if it does not already exist.
is_new_compute_node = self._init_compute_node(context, resources)
nodename = resources['hypervisor_hostname']
# if we could not init the compute node the tracker will be
# disabled and we should quit now
if self.disabled(nodename):
return
# Grab all instances assigned to this node:
instances = objects.InstanceList.get_by_host_and_node(
context, self.host, nodename,
expected_attrs=['system_metadata',
'numa_topology',
'flavor', 'migration_context',
'resources'])
# Now calculate usage based on instance utilization:
instance_by_uuid = self._update_usage_from_instances(
context, instances, nodename)
# Grab all in-progress migrations:
migrations = objects.MigrationList.get_in_progress_by_host_and_node(
context, self.host, nodename)
self._pair_instances_to_migrations(migrations, instance_by_uuid)
self._update_usage_from_migrations(context, migrations, nodename)
# A new compute node means there won't be a resource provider yet since
if not is_new_compute_node:
self._remove_deleted_instances_allocations(
context, self.compute_nodes[nodename], migrations,
instance_by_uuid)
orphans = self._find_orphaned_instances()
self._update_usage_from_orphans(orphans, nodename)
cn = self.compute_nodes[nodename]
self.pci_tracker.clean_usage(instances, migrations, orphans)
dev_pools_obj = self.pci_tracker.stats.to_device_pools_obj()
cn.pci_device_pools = dev_pools_obj
self._report_final_resource_view(nodename)
metrics = self._get_host_metrics(context, nodename)
cn.metrics = jsonutils.dumps(metrics)
self._populate_assigned_resources(context, instance_by_uuid)
self._update(context, cn, startup=startup)
LOG.debug('Compute_service record updated for %(host)s:%(node)s',
{'host': self.host, 'node': nodename})
if startup:
self._check_resources(context)
def _get_compute_node(self, context, nodename):
try:
return objects.ComputeNode.get_by_host_and_nodename(
context, self.host, nodename)
except exception.NotFound:
LOG.warning("No compute node record for %(host)s:%(node)s",
{'host': self.host, 'node': nodename})
def _report_hypervisor_resource_view(self, resources):
nodename = resources['hypervisor_hostname']
free_ram_mb = resources['memory_mb'] - resources['memory_mb_used']
free_disk_gb = resources['local_gb'] - resources['local_gb_used']
vcpus = resources['vcpus']
if vcpus:
free_vcpus = vcpus - resources['vcpus_used']
else:
free_vcpus = 'unknown'
pci_devices = resources.get('pci_passthrough_devices')
LOG.debug("Hypervisor/Node resource view: "
"name=%(node)s "
"free_ram=%(free_ram)sMB "
"free_disk=%(free_disk)sGB "
"free_vcpus=%(free_vcpus)s "
"pci_devices=%(pci_devices)s",
{'node': nodename,
'free_ram': free_ram_mb,
'free_disk': free_disk_gb,
'free_vcpus': free_vcpus,
'pci_devices': pci_devices})
def _report_final_resource_view(self, nodename):
cn = self.compute_nodes[nodename]
vcpus = cn.vcpus
if vcpus:
tcpu = vcpus
ucpu = cn.vcpus_used
LOG.debug("Total usable vcpus: %(tcpu)s, "
"total allocated vcpus: %(ucpu)s",
{'tcpu': vcpus,
'ucpu': ucpu})
else:
tcpu = 0
ucpu = 0
pci_stats = (list(cn.pci_device_pools) if
cn.pci_device_pools else [])
LOG.debug("Final resource view: "
"name=%(node)s "
"phys_ram=%(phys_ram)sMB "
"used_ram=%(used_ram)sMB "
"phys_disk=%(phys_disk)sGB "
"used_disk=%(used_disk)sGB "
"total_vcpus=%(total_vcpus)s "
"used_vcpus=%(used_vcpus)s "
"pci_stats=%(pci_stats)s",
{'node': nodename,
'phys_ram': cn.memory_mb,
'used_ram': cn.memory_mb_used,
'phys_disk': cn.local_gb,
'used_disk': cn.local_gb_used,
'total_vcpus': tcpu,
'used_vcpus': ucpu,
'pci_stats': pci_stats})
def _resource_change(self, compute_node):
nodename = compute_node.hypervisor_hostname
old_compute = self.old_resources[nodename]
if not obj_base.obj_equal_prims(
compute_node, old_compute, ['updated_at']):
self.old_resources[nodename] = copy.deepcopy(compute_node)
return True
return False
def _sync_compute_service_disabled_trait(self, context, traits):
trait = os_traits.COMPUTE_STATUS_DISABLED
try:
service = objects.Service.get_by_compute_host(context, self.host)
if service.disabled:
traits.add(trait)
else:
traits.discard(trait)
except exception.NotFound:
LOG.error('Unable to find services table record for nova-compute '
'host %s', self.host)
def _get_traits(self, context, nodename, provider_tree):
traits = provider_tree.data(nodename).traits
# Now get the driver's capabilities and add any supported
for trait, supported in self.driver.capabilities_as_traits().items():
if supported:
traits.add(trait)
elif trait in traits:
traits.remove(trait)
traits.add(os_traits.COMPUTE_NODE)
self._sync_compute_service_disabled_trait(context, traits)
return list(traits)
@retrying.retry(stop_max_attempt_number=4,
retry_on_exception=lambda e: isinstance(
e, exception.ResourceProviderUpdateConflict))
def _update_to_placement(self, context, compute_node, startup):
# there is no resource change for compute_node, we need proceed
# to get inventory and use report client interfaces to update
# inventory to placement. It's report client's responsibility to
# ensure the update request to placement only happens when inventory
# is changed.
nodename = compute_node.hypervisor_hostname
# Persist the stats to the Scheduler
# Retrieve the provider tree associated with this compute node. If
# it doesn't exist yet, this will create it with a (single, root)
prov_tree = self.reportclient.get_provider_tree_and_ensure_root(
context, compute_node.uuid, name=compute_node.hypervisor_hostname)
allocs = None
try:
self.driver.update_provider_tree(prov_tree, nodename)
except exception.ReshapeNeeded:
if not startup:
# it up; the compute manager will treat it specially.
raise
LOG.info("Performing resource provider inventory and "
"allocation data migration during compute service "
"startup or fast-forward upgrade.")
allocs = self.reportclient.get_allocations_for_provider_tree(
context, nodename)
self.driver.update_provider_tree(prov_tree, nodename,
allocations=allocs)
# Inject driver capabilities traits into the provider
# tree. We need to determine the traits that the virt
# driver owns - so those that come from the tree itself
# (via the virt driver) plus the compute capabilities
# traits, and then merge those with the traits set
# externally that the driver does not own - and remove any
# set on the provider externally that the virt owns but
# aren't in the current list of supported traits. For
# trait at t1 and then at t2 it's not, so we need to
# was set externally on the provider.
# We also want to sync the COMPUTE_STATUS_DISABLED trait based
# on the related nova-compute service's disabled status.
traits = self._get_traits(
context, nodename, provider_tree=prov_tree)
prov_tree.update_traits(nodename, traits)
self.provider_tree = prov_tree
self.reportclient.update_from_provider_tree(context, prov_tree,
allocations=allocs)
def _update(self, context, compute_node, startup=False):
# _resource_change will update self.old_resources if it detects changes
# but we want to restore those if compute_node.save() fails.
nodename = compute_node.hypervisor_hostname
old_compute = self.old_resources[nodename]
if self._resource_change(compute_node):
# If the compute_node's resource changed, update to DB. Note that
try:
compute_node.save()
except Exception:
with excutils.save_and_reraise_exception(logger=LOG):
self.old_resources[nodename] = old_compute
self._update_to_placement(context, compute_node, startup)
if self.pci_tracker:
self.pci_tracker.save(context)
def _update_usage(self, usage, nodename, sign=1):
# except 'Aggregate(Core|Ram|Disk)Filter', the 'os-hypervisors' API,
# and perhaps some out-of-tree filters. Once the in-tree stuff is
# removed or updated to use information from placement, we can think
# about dropping the fields from the 'ComputeNode' object entirely
mem_usage = usage['memory_mb']
disk_usage = usage.get('root_gb', 0)
vcpus_usage = usage.get('vcpus', 0)
cn = self.compute_nodes[nodename]
cn.memory_mb_used += sign * mem_usage
cn.local_gb_used += sign * disk_usage
cn.local_gb_used += sign * usage.get('ephemeral_gb', 0)
cn.local_gb_used += sign * usage.get('swap', 0) / 1024
cn.vcpus_used += sign * vcpus_usage
# free ram and disk may be negative, depending on policy:
cn.free_ram_mb = cn.memory_mb - cn.memory_mb_used
cn.free_disk_gb = cn.local_gb - cn.local_gb_used
stats = self.stats[nodename]
cn.running_vms = stats.num_instances
# calculate the NUMA usage, assuming the instance is actually using
# NUMA, of course
if cn.numa_topology and usage.get('numa_topology'):
instance_numa_topology = usage.get('numa_topology')
# the ComputeNode.numa_topology field is a StringField, so
# deserialize
host_numa_topology = objects.NUMATopology.obj_from_db_obj(
cn.numa_topology)
free = sign == -1
# ...and reserialize once we save it back
cn.numa_topology = hardware.numa_usage_from_instance_numa(
host_numa_topology, instance_numa_topology, free)._to_json()
def _get_migration_context_resource(self, resource, instance,
prefix='new_'):
migration_context = instance.migration_context
resource = prefix + resource
if migration_context and resource in migration_context:
return getattr(migration_context, resource)
return None
def _update_usage_from_migration(self, context, instance, migration,
nodename):
uuid = migration.instance_uuid
LOG.info("Updating resource usage from migration %s", migration.uuid,
instance_uuid=uuid)
incoming = (migration.dest_compute == self.host and
migration.dest_node == nodename)
outbound = (migration.source_compute == self.host and
migration.source_node == nodename)
same_node = (incoming and outbound)
tracked = uuid in self.tracked_instances
itype = None
numa_topology = None
sign = 0
if same_node:
# Same node resize. Record usage for the 'new_' resources. This
# is executed on resize_claim().
if (instance['instance_type_id'] ==
migration.old_instance_type_id):
itype = self._get_instance_type(instance, 'new_', migration)
numa_topology = self._get_migration_context_resource(
'numa_topology', instance)
# Allocate pci device(s) for the instance.
sign = 1
else:
# The instance is already set to the new flavor (this is done
# by the compute manager on finish_resize()), hold space for a
# possible revert to the 'old_' resources.
# NOTE(lbeliveau): When the periodic audit timer gets
# triggered, the compute usage gets reset. The usage for an
# instance that is migrated to the new flavor but not yet
# confirmed/reverted will first get accounted for by
# _update_usage_from_instances(). This method will then be
# called, and we need to account for the '_old' resources
# (just in case).
itype = self._get_instance_type(instance, 'old_', migration)
numa_topology = self._get_migration_context_resource(
'numa_topology', instance, prefix='old_')
elif incoming and not tracked:
# instance has not yet migrated here:
itype = self._get_instance_type(instance, 'new_', migration)
numa_topology = self._get_migration_context_resource(
'numa_topology', instance)
# Allocate pci device(s) for the instance.
sign = 1
LOG.debug('Starting to track incoming migration %s with flavor %s',
migration.uuid, itype.flavorid, instance=instance)
elif outbound and not tracked:
# instance migrated, but record usage for a possible revert:
itype = self._get_instance_type(instance, 'old_', migration)
numa_topology = self._get_migration_context_resource(
'numa_topology', instance, prefix='old_')
# We could be racing with confirm_resize setting the
# instance.old_flavor field to None before the migration status
# is "confirmed" so if we did not find the flavor in the outgoing
# resized instance we won't track it.
if itype:
LOG.debug('Starting to track outgoing migration %s with '
'flavor %s', migration.uuid, itype.flavorid,
instance=instance)
if itype:
cn = self.compute_nodes[nodename]
usage = self._get_usage_dict(
itype, instance, numa_topology=numa_topology)
if self.pci_tracker and sign:
self.pci_tracker.update_pci_for_instance(
context, instance, sign=sign)
self._update_usage(usage, nodename)
if self.pci_tracker:
obj = self.pci_tracker.stats.to_device_pools_obj()
cn.pci_device_pools = obj
else:
obj = objects.PciDevicePoolList()
cn.pci_device_pools = obj
self.tracked_migrations[uuid] = migration
def _update_usage_from_migrations(self, context, migrations, nodename):
filtered = {}
instances = {}
self.tracked_migrations.clear()
for migration in migrations:
uuid = migration.instance_uuid
try:
if uuid not in instances:
instances[uuid] = migration.instance
except exception.InstanceNotFound as e:
LOG.debug('Migration instance not found: %s', e)
continue
if (not _instance_in_resize_state(instances[uuid]) and not
_instance_is_live_migrating(instances[uuid])):
LOG.debug('Skipping migration as instance is neither '
'resizing nor live-migrating.', instance_uuid=uuid)
continue
other_migration = filtered.get(uuid, None)
if other_migration:
om = other_migration
other_time = om.updated_at or om.created_at
migration_time = migration.updated_at or migration.created_at
if migration_time > other_time:
filtered[uuid] = migration
else:
filtered[uuid] = migration
for migration in filtered.values():
instance = instances[migration.instance_uuid]
# instance migration id.
# This can happen if we have a stale migration record.
# We want to proceed if instance.migration_context is None
if (instance.migration_context is not None and
instance.migration_context.migration_id != migration.id):
LOG.info("Current instance migration %(im)s doesn't match "
"migration %(m)s, marking migration as error. "
"This can occur if a previous migration for this "
"instance did not complete.",
{'im': instance.migration_context.migration_id,
'm': migration.id})
migration.status = "error"
migration.save()
continue
try:
self._update_usage_from_migration(context, instance, migration,
nodename)
except exception.FlavorNotFound:
LOG.warning("Flavor could not be found, skipping migration.",
instance_uuid=instance.uuid)
continue
def _update_usage_from_instance(self, context, instance, nodename,
is_removed=False):
uuid = instance['uuid']
is_new_instance = uuid not in self.tracked_instances
is_removed_instance = not is_new_instance and (is_removed or
instance['vm_state'] in vm_states.ALLOW_RESOURCE_REMOVAL)
if is_new_instance:
self.tracked_instances.add(uuid)
sign = 1
if is_removed_instance:
self.tracked_instances.remove(uuid)
self._release_assigned_resources(instance.resources)
sign = -1
cn = self.compute_nodes[nodename]
stats = self.stats[nodename]
stats.update_stats_for_instance(instance, is_removed_instance)
cn.stats = stats
if is_new_instance or is_removed_instance:
if self.pci_tracker:
self.pci_tracker.update_pci_for_instance(context,
instance,
sign=sign)
# new instance, update compute node resource usage:
self._update_usage(self._get_usage_dict(instance, instance),
nodename, sign=sign)
# Stop tracking removed instances in the is_bfv cache. This needs to
# happen *after* calling _get_usage_dict() since that relies on the
# is_bfv cache.
if is_removed_instance and uuid in self.is_bfv:
del self.is_bfv[uuid]
cn.current_workload = stats.calculate_workload()
if self.pci_tracker:
obj = self.pci_tracker.stats.to_device_pools_obj()
cn.pci_device_pools = obj
else:
cn.pci_device_pools = objects.PciDevicePoolList()
def _update_usage_from_instances(self, context, instances, nodename):
self.tracked_instances.clear()
cn = self.compute_nodes[nodename]
# set some initial values, reserve room for host/hypervisor:
cn.local_gb_used = CONF.reserved_host_disk_mb / 1024
cn.memory_mb_used = CONF.reserved_host_memory_mb
cn.vcpus_used = CONF.reserved_host_cpus
cn.free_ram_mb = (cn.memory_mb - cn.memory_mb_used)
cn.free_disk_gb = (cn.local_gb - cn.local_gb_used)
cn.current_workload = 0
cn.running_vms = 0
instance_by_uuid = {}
for instance in instances:
if instance.vm_state not in vm_states.ALLOW_RESOURCE_REMOVAL:
self._update_usage_from_instance(context, instance, nodename)
instance_by_uuid[instance.uuid] = instance
return instance_by_uuid
def _remove_deleted_instances_allocations(self, context, cn,
migrations, instance_by_uuid):
migration_uuids = [migration.uuid for migration in migrations
if 'uuid' in migration]
# NOTE(jaypipes): All of this code sucks. It's basically dealing with
# happen according to the normal flow of events where the scheduler
# always creates allocations for an instance
try:
# pai: report.ProviderAllocInfo namedtuple
pai = self.reportclient.get_allocations_for_resource_provider(
context, cn.uuid)
except (exception.ResourceProviderAllocationRetrievalFailed,
ks_exc.ClientException) as e:
LOG.error("Skipping removal of allocations for deleted instances: "
"%s", e)
return
allocations = pai.allocations
if not allocations:
# The main loop below would short-circuit anyway, but this saves us
# the (potentially expensive) context.elevated construction below.
return
read_deleted_context = context.elevated(read_deleted='yes')
for consumer_uuid, alloc in allocations.items():
if consumer_uuid in self.tracked_instances:
LOG.debug("Instance %s actively managed on this compute host "
"and has allocations in placement: %s.",
consumer_uuid, alloc)
continue
if consumer_uuid in migration_uuids:
LOG.debug("Migration %s is active on this compute host "
"and has allocations in placement: %s.",
consumer_uuid, alloc)
continue
# We know these are instances now, so proceed
instance_uuid = consumer_uuid
instance = instance_by_uuid.get(instance_uuid)
if not instance:
try:
instance = objects.Instance.get_by_uuid(
read_deleted_context, consumer_uuid,
expected_attrs=[])
except exception.InstanceNotFound:
# The instance isn't even in the database. Either the
# racing with the creation in the cell database, or the
# instance was deleted and fully archived before we got a
# chance to run this. The former is far more likely than
# the latter. Avoid deleting allocations for a building
# instance here.
LOG.info("Instance %(uuid)s has allocations against this "
"compute host but is not found in the database.",
{'uuid': instance_uuid},
exc_info=False)
continue
if instance.deleted:
# The instance is gone, so we definitely want to remove
# allocations associated with it.
# NOTE(jaypipes): This will not be true if/when we support
# cross-cell migrations...
LOG.debug("Instance %s has been deleted (perhaps locally). "
"Deleting allocations that remained for this "
"instance against this compute host: %s.",
instance_uuid, alloc)
self.reportclient.delete_allocation_for_instance(context,
instance_uuid)
continue
if not instance.host:
# Allocations related to instances being scheduled should not
# be deleted if we already wrote the allocation previously.
LOG.debug("Instance %s has been scheduled to this compute "
"host, the scheduler has made an allocation "
"against this compute node but the instance has "
"yet to start. Skipping heal of allocation: %s.",
instance_uuid, alloc)
continue
if (instance.host == cn.host and
instance.node == cn.hypervisor_hostname):
# The instance is supposed to be on this compute host but is
# not in the list of actively managed instances. This could be
# because we are racing with an instance_claim call during
# initial build or unshelve where the instance host/node is set
# before the instance is added to tracked_instances. If the
# task_state is set, then consider things in motion and log at
# debug level instead of warning.
if instance.task_state:
LOG.debug('Instance with task_state "%s" is not being '
'actively managed by this compute host but has '
'allocations referencing this compute node '
'(%s): %s. Skipping heal of allocations during '
'the task state transition.',
instance.task_state, cn.uuid, alloc,
instance=instance)
else:
LOG.warning("Instance %s is not being actively managed by "
"this compute host but has allocations "
"referencing this compute host: %s. Skipping "
"heal of allocation because we do not know "
"what to do.", instance_uuid, alloc)
continue
if instance.host != cn.host:
# The instance has been moved to another host either via a
# migration, evacuation or unshelve in between the time when we
# ran InstanceList.get_by_host_and_node(), added those
# instances to RT.tracked_instances and the above
# Instance.get_by_uuid() call. We SHOULD attempt to remove any
# allocations that reference this compute host if the VM is in
# a stable terminal state (i.e. it isn't in a state of waiting
# situation here for information but don't attempt to delete or
LOG.warning("Instance %s has been moved to another host "
"%s(%s). There are allocations remaining against "
"the source host that might need to be removed: "
"%s.",
instance_uuid, instance.host, instance.node, alloc)
def delete_allocation_for_evacuated_instance(self, context, instance, node,
node_type='source'):
cn_uuid = self.compute_nodes[node].uuid
if not self.reportclient.remove_provider_tree_from_instance_allocation(
context, instance.uuid, cn_uuid):
LOG.error("Failed to clean allocation of evacuated "
"instance on the %s node %s",
node_type, cn_uuid, instance=instance)
def _find_orphaned_instances(self):
uuids1 = frozenset(self.tracked_instances)
uuids2 = frozenset(self.tracked_migrations.keys())
uuids = uuids1 | uuids2
usage = self.driver.get_per_instance_usage()
vuuids = frozenset(usage.keys())
orphan_uuids = vuuids - uuids
orphans = [usage[uuid] for uuid in orphan_uuids]
return orphans
def _update_usage_from_orphans(self, orphans, nodename):
for orphan in orphans:
memory_mb = orphan['memory_mb']
LOG.warning("Detected running orphan instance: %(uuid)s "
"(consuming %(memory_mb)s MB memory)",
{'uuid': orphan['uuid'], 'memory_mb': memory_mb})
usage = {'memory_mb': memory_mb}
self._update_usage(usage, nodename)
def delete_allocation_for_shelve_offloaded_instance(self, context,
instance):
self.reportclient.delete_allocation_for_instance(context,
instance.uuid)
def _verify_resources(self, resources):
resource_keys = ["vcpus", "memory_mb", "local_gb", "cpu_info",
"vcpus_used", "memory_mb_used", "local_gb_used",
"numa_topology"]
missing_keys = [k for k in resource_keys if k not in resources]
if missing_keys:
reason = _("Missing keys: %s") % missing_keys
raise exception.InvalidInput(reason=reason)
def _get_instance_type(self, instance, prefix, migration):
stashed_flavors = migration.migration_type in ('resize',)
if stashed_flavors:
return getattr(instance, '%sflavor' % prefix)
else:
return instance.flavor
def _get_usage_dict(self, object_or_dict, instance, **updates):
def _is_bfv():
if instance.uuid in self.is_bfv:
is_bfv = self.is_bfv[instance.uuid]
else:
is_bfv = compute_utils.is_volume_backed_instance(
instance._context, instance)
self.is_bfv[instance.uuid] = is_bfv
return is_bfv
usage = {}
if isinstance(object_or_dict, objects.Instance):
is_bfv = _is_bfv()
usage = {'memory_mb': object_or_dict.flavor.memory_mb,
'swap': object_or_dict.flavor.swap,
'vcpus': object_or_dict.flavor.vcpus,
'root_gb': (0 if is_bfv else
object_or_dict.flavor.root_gb),
'ephemeral_gb': object_or_dict.flavor.ephemeral_gb,
'numa_topology': object_or_dict.numa_topology}
elif isinstance(object_or_dict, objects.Flavor):
usage = obj_base.obj_to_primitive(object_or_dict)
if _is_bfv():
usage['root_gb'] = 0
else:
usage.update(object_or_dict)
for key in ('numa_topology',):
if key in updates:
usage[key] = updates[key]
return usage
def build_failed(self, nodename):
self.stats[nodename].build_failed()
def build_succeeded(self, nodename):
self.stats[nodename].build_succeeded()
@utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE)
def claim_pci_devices(self, context, pci_requests):
result = self.pci_tracker.claim_instance(
context, pci_requests, None)
self.pci_tracker.save(context)
return result
@utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE)
def allocate_pci_devices_for_instance(self, context, instance):
self.pci_tracker.allocate_instance(instance)
self.pci_tracker.save(context)
@utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE)
def free_pci_device_allocations_for_instance(self, context, instance):
self.pci_tracker.free_instance_allocations(context, instance)
self.pci_tracker.save(context)
@utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE)
def free_pci_device_claims_for_instance(self, context, instance):
self.pci_tracker.free_instance_claims(context, instance)
self.pci_tracker.save(context)
| true | true |
f7f74cedd8841a5a3ea6d6418f64ff79898b7956 | 834 | py | Python | commands/enable.py | s2ff2/voicechannel | ed35d8a52cf423f81c9f33b316355621555938cf | [
"MIT"
] | 177 | 2020-02-02T18:03:46.000Z | 2022-03-17T06:18:43.000Z | commands/enable.py | zigsphere/Auto-Voice-Channels | 6ae901728580bef4246737a6f1b9f10763badd3e | [
"MIT"
] | 82 | 2020-02-02T17:43:18.000Z | 2022-03-24T20:34:55.000Z | commands/enable.py | zigsphere/Auto-Voice-Channels | 6ae901728580bef4246737a6f1b9f10763badd3e | [
"MIT"
] | 165 | 2019-02-17T20:15:20.000Z | 2022-03-27T23:59:23.000Z | import utils
from functions import log
from commands.base import Cmd
help_text = [
[
("Usage:", "<PREFIX><COMMAND>"),
("Description:",
"Turn me on. If I'm not enabled, I won't create any new voice channels, rename, or delete them."),
]
]
async def execute(ctx, params):
settings = ctx['settings']
guild = ctx['guild']
if settings['enabled']:
return False, "Already enabled. Use '{}disable' to turn off.".format(ctx['print_prefix'])
else:
log("Enabling", guild)
settings['enabled'] = True
utils.set_serv_settings(guild, settings)
return True, "Enabling auto voice channels. Turn off with '{}disable'.".format(ctx['print_prefix'])
command = Cmd(
execute=execute,
help_text=help_text,
params_required=0,
admin_required=True,
)
| 26.0625 | 107 | 0.633094 | import utils
from functions import log
from commands.base import Cmd
help_text = [
[
("Usage:", "<PREFIX><COMMAND>"),
("Description:",
"Turn me on. If I'm not enabled, I won't create any new voice channels, rename, or delete them."),
]
]
async def execute(ctx, params):
settings = ctx['settings']
guild = ctx['guild']
if settings['enabled']:
return False, "Already enabled. Use '{}disable' to turn off.".format(ctx['print_prefix'])
else:
log("Enabling", guild)
settings['enabled'] = True
utils.set_serv_settings(guild, settings)
return True, "Enabling auto voice channels. Turn off with '{}disable'.".format(ctx['print_prefix'])
command = Cmd(
execute=execute,
help_text=help_text,
params_required=0,
admin_required=True,
)
| true | true |
f7f74d5ce4c3b50878aa5b9a5850004c59664f14 | 223 | py | Python | zinnia_ckeditor/__init__.py | pancodia/zinnia-wysiwyg-ckeditor | 79143b9bdfaee44760c1367392869eacb32b7ee2 | [
"BSD-3-Clause"
] | null | null | null | zinnia_ckeditor/__init__.py | pancodia/zinnia-wysiwyg-ckeditor | 79143b9bdfaee44760c1367392869eacb32b7ee2 | [
"BSD-3-Clause"
] | null | null | null | zinnia_ckeditor/__init__.py | pancodia/zinnia-wysiwyg-ckeditor | 79143b9bdfaee44760c1367392869eacb32b7ee2 | [
"BSD-3-Clause"
] | null | null | null | """CKEditor for Django-blog-zinnia"""
__version__ = '1.3'
__license__ = 'BSD License'
__author__ = 'Fantomas42'
__email__ = 'fantomas42@gmail.com'
__url__ = 'https://github.com/django-blog-zinnia/zinnia-wysiwyg-ckeditor'
| 24.777778 | 73 | 0.744395 | __version__ = '1.3'
__license__ = 'BSD License'
__author__ = 'Fantomas42'
__email__ = 'fantomas42@gmail.com'
__url__ = 'https://github.com/django-blog-zinnia/zinnia-wysiwyg-ckeditor'
| true | true |
f7f74d810ddf4f5049e93dcc2ed679b7a44fa491 | 1,069 | py | Python | pathmatcher/mlabwrap/mlabraw.py | lrq3000/pathmatcher | 8baee07542f99e8bfa6fcb65c1e3008c080f037b | [
"MIT"
] | 1 | 2021-01-06T11:53:07.000Z | 2021-01-06T11:53:07.000Z | pathmatcher/mlabwrap/mlabraw.py | lrq3000/pathmatcher | 8baee07542f99e8bfa6fcb65c1e3008c080f037b | [
"MIT"
] | null | null | null | pathmatcher/mlabwrap/mlabraw.py | lrq3000/pathmatcher | 8baee07542f99e8bfa6fcb65c1e3008c080f037b | [
"MIT"
] | null | null | null | #!/usr/bin/env python
""" A quick and extremely dirty hack to wrap matlabpipe/matlabcom as if they
were mlabraw.
Author: Dani Valevski <daniva@gmail.com>
License: MIT
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import sys
is_win = sys.platform == 'win32'
if is_win:
from .matlabcom import MatlabCom as MatlabConnection
from .matlabcom import MatlabError as error
else:
from .matlabpipe import MatlabPipe as MatlabConnection
from .matlabpipe import MatlabError as error
def open(matlab_binary_path):
if is_win:
ret = MatlabConnection()
ret.open()
else:
ret = MatlabConnection(matlab_binary_path)
ret.open()
return ret
def close(matlab):
matlab.close()
def eval(matlab, exp, log=False):
if log or is_win:
matlab.eval(exp)
else:
matlab.eval(exp, print_expression=False, on_new_output=None)
return ''
def get(matlab, var_name):
return matlab.get(var_name)
def put(matlab, var_name, val):
matlab.put({var_name: val})
| 19.436364 | 76 | 0.700655 |
from __future__ import absolute_import
from __future__ import unicode_literals
import sys
is_win = sys.platform == 'win32'
if is_win:
from .matlabcom import MatlabCom as MatlabConnection
from .matlabcom import MatlabError as error
else:
from .matlabpipe import MatlabPipe as MatlabConnection
from .matlabpipe import MatlabError as error
def open(matlab_binary_path):
if is_win:
ret = MatlabConnection()
ret.open()
else:
ret = MatlabConnection(matlab_binary_path)
ret.open()
return ret
def close(matlab):
matlab.close()
def eval(matlab, exp, log=False):
if log or is_win:
matlab.eval(exp)
else:
matlab.eval(exp, print_expression=False, on_new_output=None)
return ''
def get(matlab, var_name):
return matlab.get(var_name)
def put(matlab, var_name, val):
matlab.put({var_name: val})
| true | true |
f7f74dac2c1964ddf3afd52141a596cbc94aab37 | 3,612 | py | Python | test/functional/mining_getblocktemplate_longpoll.py | bizzy401/BazCoin | a8868b45533a7d0d8bd2fbec71a5b2c92517bacd | [
"MIT"
] | null | null | null | test/functional/mining_getblocktemplate_longpoll.py | bizzy401/BazCoin | a8868b45533a7d0d8bd2fbec71a5b2c92517bacd | [
"MIT"
] | null | null | null | test/functional/mining_getblocktemplate_longpoll.py | bizzy401/BazCoin | a8868b45533a7d0d8bd2fbec71a5b2c92517bacd | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# Copyright (c) 2014-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test longpolling with getblocktemplate."""
from decimal import Decimal
import random
import threading
from test_framework.test_framework import BazCoinTestFramework
from test_framework.util import get_rpc_proxy
from test_framework.wallet import MiniWallet
class LongpollThread(threading.Thread):
def __init__(self, node):
threading.Thread.__init__(self)
# query current longpollid
template = node.getblocktemplate({'rules': ['segwit']})
self.longpollid = template['longpollid']
# create a new connection to the node, we can't use the same
# connection from two threads
self.node = get_rpc_proxy(node.url, 1, timeout=600, coveragedir=node.coverage_dir)
def run(self):
self.node.getblocktemplate({'longpollid': self.longpollid, 'rules': ['segwit']})
class GetBlockTemplateLPTest(BazCoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.supports_cli = False
def run_test(self):
self.log.info("Warning: this test will take about 70 seconds in the best case. Be patient.")
self.log.info("Test that longpollid doesn't change between successive getblocktemplate() invocations if nothing else happens")
self.nodes[0].generate(10)
template = self.nodes[0].getblocktemplate({'rules': ['segwit']})
longpollid = template['longpollid']
template2 = self.nodes[0].getblocktemplate({'rules': ['segwit']})
assert template2['longpollid'] == longpollid
self.log.info("Test that longpoll waits if we do nothing")
thr = LongpollThread(self.nodes[0])
thr.start()
# check that thread still lives
thr.join(5) # wait 5 seconds or until thread exits
assert thr.is_alive()
miniwallets = [ MiniWallet(node) for node in self.nodes ]
self.log.info("Test that longpoll will terminate if another node generates a block")
miniwallets[1].generate(1) # generate a block on another node
# check that thread will exit now that new transaction entered mempool
thr.join(5) # wait 5 seconds or until thread exits
assert not thr.is_alive()
self.log.info("Test that longpoll will terminate if we generate a block ourselves")
thr = LongpollThread(self.nodes[0])
thr.start()
miniwallets[0].generate(1) # generate a block on own node
thr.join(5) # wait 5 seconds or until thread exits
assert not thr.is_alive()
# Add enough mature utxos to the wallets, so that all txs spend confirmed coins
self.nodes[0].generate(100)
self.sync_blocks()
self.log.info("Test that introducing a new transaction into the mempool will terminate the longpoll")
thr = LongpollThread(self.nodes[0])
thr.start()
# generate a random transaction and submit it
min_relay_fee = self.nodes[0].getnetworkinfo()["relayfee"]
fee_rate = min_relay_fee + Decimal('0.00000010') * random.randint(0,20)
miniwallets[0].send_self_transfer(from_node=random.choice(self.nodes),
fee_rate=fee_rate)
# after one minute, every 10 seconds the mempool is probed, so in 80 seconds it should have returned
thr.join(60 + 20)
assert not thr.is_alive()
if __name__ == '__main__':
GetBlockTemplateLPTest().main()
| 44.04878 | 134 | 0.680509 |
from decimal import Decimal
import random
import threading
from test_framework.test_framework import BazCoinTestFramework
from test_framework.util import get_rpc_proxy
from test_framework.wallet import MiniWallet
class LongpollThread(threading.Thread):
def __init__(self, node):
threading.Thread.__init__(self)
template = node.getblocktemplate({'rules': ['segwit']})
self.longpollid = template['longpollid']
# connection from two threads
self.node = get_rpc_proxy(node.url, 1, timeout=600, coveragedir=node.coverage_dir)
def run(self):
self.node.getblocktemplate({'longpollid': self.longpollid, 'rules': ['segwit']})
class GetBlockTemplateLPTest(BazCoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.supports_cli = False
def run_test(self):
self.log.info("Warning: this test will take about 70 seconds in the best case. Be patient.")
self.log.info("Test that longpollid doesn't change between successive getblocktemplate() invocations if nothing else happens")
self.nodes[0].generate(10)
template = self.nodes[0].getblocktemplate({'rules': ['segwit']})
longpollid = template['longpollid']
template2 = self.nodes[0].getblocktemplate({'rules': ['segwit']})
assert template2['longpollid'] == longpollid
self.log.info("Test that longpoll waits if we do nothing")
thr = LongpollThread(self.nodes[0])
thr.start()
thr.join(5)
assert thr.is_alive()
miniwallets = [ MiniWallet(node) for node in self.nodes ]
self.log.info("Test that longpoll will terminate if another node generates a block")
miniwallets[1].generate(1)
thr.join(5)
assert not thr.is_alive()
self.log.info("Test that longpoll will terminate if we generate a block ourselves")
thr = LongpollThread(self.nodes[0])
thr.start()
miniwallets[0].generate(1)
thr.join(5)
assert not thr.is_alive()
self.nodes[0].generate(100)
self.sync_blocks()
self.log.info("Test that introducing a new transaction into the mempool will terminate the longpoll")
thr = LongpollThread(self.nodes[0])
thr.start()
min_relay_fee = self.nodes[0].getnetworkinfo()["relayfee"]
fee_rate = min_relay_fee + Decimal('0.00000010') * random.randint(0,20)
miniwallets[0].send_self_transfer(from_node=random.choice(self.nodes),
fee_rate=fee_rate)
thr.join(60 + 20)
assert not thr.is_alive()
if __name__ == '__main__':
GetBlockTemplateLPTest().main()
| true | true |
f7f74db7e24564dc9d0214292ac723a6c63d8f1e | 1,968 | py | Python | meta-yocto-bsp/lib/oeqa/selftest/systemd_boot.py | prakhya/luv_sai | 91d7d83a3e71b63164f683274dcf2392d64892e7 | [
"MIT"
] | null | null | null | meta-yocto-bsp/lib/oeqa/selftest/systemd_boot.py | prakhya/luv_sai | 91d7d83a3e71b63164f683274dcf2392d64892e7 | [
"MIT"
] | null | null | null | meta-yocto-bsp/lib/oeqa/selftest/systemd_boot.py | prakhya/luv_sai | 91d7d83a3e71b63164f683274dcf2392d64892e7 | [
"MIT"
] | null | null | null | from oeqa.selftest.base import oeSelfTest
from oeqa.utils.commands import runCmd, bitbake, get_bb_var, runqemu
from oeqa.utils.decorators import testcase
import re
import os
import sys
import logging
class Systemdboot(oeSelfTest):
def _common_setup(self):
"""
Common setup for test cases: 1445, XXXX
"""
# Set EFI_PROVIDER = "gummiboot" and MACHINE = "genericx86-64" in conf/local.conf
features = 'EFI_PROVIDER = "systemd-boot"\n'
features += 'MACHINE = "genericx86-64"'
self.append_config(features)
def _common_build(self):
"""
Common build for test cases: 1445 , XXXX
"""
# Build a genericx86-64/efi gummiboot image
bitbake('mtools-native core-image-minimal')
@testcase(1445)
def test_efi_systemdboot_images_can_be_built(self):
"""
Summary: Check if systemd-boot images can be built correctly
Expected: 1. File systemd-boot.efi should be available in $poky/build/tmp/deploy/images/genericx86-64
2. 'systemd-boot" can be built correctly
Product: oe-core
Author: Jose Perez Carranza <jose.perez.carranza@intel.com>
AutomatedBy: Jose Perez Carranza <jose.perez.carranza@intel.com>
"""
# We'd use DEPLOY_DIR_IMAGE here, except that we need its value for
# MACHINE="genericx86-64 which is probably not the one configured
systemdbootfile = os.path.join(get_bb_var('DEPLOY_DIR'), 'images', 'genericx86-64', 'systemd-bootx64.efi')
self._common_setup()
# Ensure we're actually testing that this gets built and not that
# it was around from an earlier build
bitbake('-c cleansstate systemd-boot')
runCmd('rm -f %s' % systemdbootfile)
self._common_build()
found = os.path.isfile(systemdbootfile)
self.assertTrue(found, 'Systemd-Boot file %s not found' % systemdbootfile)
| 34.526316 | 114 | 0.657012 | from oeqa.selftest.base import oeSelfTest
from oeqa.utils.commands import runCmd, bitbake, get_bb_var, runqemu
from oeqa.utils.decorators import testcase
import re
import os
import sys
import logging
class Systemdboot(oeSelfTest):
def _common_setup(self):
features = 'EFI_PROVIDER = "systemd-boot"\n'
features += 'MACHINE = "genericx86-64"'
self.append_config(features)
def _common_build(self):
bitbake('mtools-native core-image-minimal')
@testcase(1445)
def test_efi_systemdboot_images_can_be_built(self):
# MACHINE="genericx86-64 which is probably not the one configured
systemdbootfile = os.path.join(get_bb_var('DEPLOY_DIR'), 'images', 'genericx86-64', 'systemd-bootx64.efi')
self._common_setup()
# Ensure we're actually testing that this gets built and not that
# it was around from an earlier build
bitbake('-c cleansstate systemd-boot')
runCmd('rm -f %s' % systemdbootfile)
self._common_build()
found = os.path.isfile(systemdbootfile)
self.assertTrue(found, 'Systemd-Boot file %s not found' % systemdbootfile)
| true | true |
f7f74e48a1fe4265126ce8e2493fb41a5a24b937 | 2,664 | py | Python | predRoC.py | paperclip/tf2-eager-yolo3 | 7f6b137c50525f91ed5026c6cb1d556e9b6d9bed | [
"MIT"
] | null | null | null | predRoC.py | paperclip/tf2-eager-yolo3 | 7f6b137c50525f91ed5026c6cb1d556e9b6d9bed | [
"MIT"
] | null | null | null | predRoC.py | paperclip/tf2-eager-yolo3 | 7f6b137c50525f91ed5026c6cb1d556e9b6d9bed | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
import tensorflow as tf
import argparse
import cv2
import matplotlib.pyplot as plt
import glob
import json
import sys
import os
from yolo.utils.box import visualize_boxes
from yolo.config import ConfigParser
if tf.executing_eagerly():
print("Executing eargerly")
else:
print("Executing lazily")
tf.enable_eager_execution()
argparser = argparse.ArgumentParser(
description='test yolov3 network with coco weights')
argparser.add_argument(
'-c',
'--config',
default="configs/predict_coco.json",
help='config file')
argparser.add_argument(
'images',
nargs='+',
help='path to image files')
CAT = []
NOT_CAT = []
def predictImage(image_path, detector, class_labels):
if "*" in image_path:
images = glob.glob(image_path)
for i in images:
predictImage(i, detector, class_labels)
return
global CAT
global NOT_CAT
# 2. Load image
image = cv2.imread(image_path)
image = image[:,:,::-1]
# 3. Run detection
boxes, labels, probs = detector.detect(image, 0.05)
# print(list(zip(labels, probs)))
cat = 0.0
if len(labels) == 0:
print(image_path, "nothing found")
for (l, p) in zip(labels, probs):
print(image_path, class_labels[l], p)
if class_labels[l] == "cat":
cat = max(cat, p)
is_cat = "not_cat" not in image_path
if is_cat:
CAT.append(cat)
else:
NOT_CAT.append(cat)
# # 4. draw detected boxes
# visualize_boxes(image, boxes, labels, probs, config_parser.get_labels())
#
# # 5. plot
# plt.imshow(image)
# plt.show()
def saveResults():
global CAT
global NOT_CAT
CAT.sort()
NOT_CAT.sort()
if len(CAT) == 0:
print("No cats found")
return
if len(NOT_CAT) == 0:
print("No non-cats found")
return
sys.path.append(
os.path.join(
os.path.dirname(os.getcwd()),
"camera"
)
)
import tensorflow1.generate_roc_data
results = tensorflow1.generate_roc_data.generate_roc_data(CAT, NOT_CAT)
import json
open("roc.json","w").write(json.dumps(results))
def main():
args = argparser.parse_args()
# 1. create yolo model & load weights
config_parser = ConfigParser(args.config)
model = config_parser.create_model(skip_detect_layer=False)
detector = config_parser.create_detector(model)
labels = config_parser.get_labels()
for image in args.images:
predictImage(image, detector, labels)
saveResults()
return 0
if __name__ == '__main__':
sys.exit(main())
| 21.312 | 78 | 0.629505 |
import tensorflow as tf
import argparse
import cv2
import matplotlib.pyplot as plt
import glob
import json
import sys
import os
from yolo.utils.box import visualize_boxes
from yolo.config import ConfigParser
if tf.executing_eagerly():
print("Executing eargerly")
else:
print("Executing lazily")
tf.enable_eager_execution()
argparser = argparse.ArgumentParser(
description='test yolov3 network with coco weights')
argparser.add_argument(
'-c',
'--config',
default="configs/predict_coco.json",
help='config file')
argparser.add_argument(
'images',
nargs='+',
help='path to image files')
CAT = []
NOT_CAT = []
def predictImage(image_path, detector, class_labels):
if "*" in image_path:
images = glob.glob(image_path)
for i in images:
predictImage(i, detector, class_labels)
return
global CAT
global NOT_CAT
image = cv2.imread(image_path)
image = image[:,:,::-1]
boxes, labels, probs = detector.detect(image, 0.05)
cat = 0.0
if len(labels) == 0:
print(image_path, "nothing found")
for (l, p) in zip(labels, probs):
print(image_path, class_labels[l], p)
if class_labels[l] == "cat":
cat = max(cat, p)
is_cat = "not_cat" not in image_path
if is_cat:
CAT.append(cat)
else:
NOT_CAT.append(cat)
veResults():
global CAT
global NOT_CAT
CAT.sort()
NOT_CAT.sort()
if len(CAT) == 0:
print("No cats found")
return
if len(NOT_CAT) == 0:
print("No non-cats found")
return
sys.path.append(
os.path.join(
os.path.dirname(os.getcwd()),
"camera"
)
)
import tensorflow1.generate_roc_data
results = tensorflow1.generate_roc_data.generate_roc_data(CAT, NOT_CAT)
import json
open("roc.json","w").write(json.dumps(results))
def main():
args = argparser.parse_args()
config_parser = ConfigParser(args.config)
model = config_parser.create_model(skip_detect_layer=False)
detector = config_parser.create_detector(model)
labels = config_parser.get_labels()
for image in args.images:
predictImage(image, detector, labels)
saveResults()
return 0
if __name__ == '__main__':
sys.exit(main())
| true | true |
f7f74e55ac96cd6d94790fbf618ec9f9810b3dea | 698 | py | Python | test/test_gender.py | kinow-io/kinow-python-sdk | 4c1699a3c78048b84287bd049a669651a5b4e2d5 | [
"Apache-2.0"
] | 1 | 2019-06-26T14:24:54.000Z | 2019-06-26T14:24:54.000Z | test/test_gender.py | kinow-io/kinow-python-sdk | 4c1699a3c78048b84287bd049a669651a5b4e2d5 | [
"Apache-2.0"
] | null | null | null | test/test_gender.py | kinow-io/kinow-python-sdk | 4c1699a3c78048b84287bd049a669651a5b4e2d5 | [
"Apache-2.0"
] | 1 | 2018-02-01T10:08:40.000Z | 2018-02-01T10:08:40.000Z | # coding: utf-8
"""
Server API
Reference for Server API (REST/Json)
OpenAPI spec version: 1.4.58
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
import unittest
import kinow_client
from kinow_client.rest import ApiException
from kinow_client.models.gender import Gender
class TestGender(unittest.TestCase):
""" Gender unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testGender(self):
"""
Test Gender
"""
model = kinow_client.models.gender.Gender()
if __name__ == '__main__':
unittest.main()
| 16.232558 | 68 | 0.660458 |
from __future__ import absolute_import
import os
import sys
import unittest
import kinow_client
from kinow_client.rest import ApiException
from kinow_client.models.gender import Gender
class TestGender(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testGender(self):
model = kinow_client.models.gender.Gender()
if __name__ == '__main__':
unittest.main()
| true | true |
f7f74eef92c28adef66c4f1ec70ea2a5ac127046 | 20,940 | py | Python | src/ADDA/Networks.py | fol21/domain-adaptation-in-deforestation | ae1c37b1634f54230f1d2217c209dabd6780568a | [
"MIT"
] | null | null | null | src/ADDA/Networks.py | fol21/domain-adaptation-in-deforestation | ae1c37b1634f54230f1d2217c209dabd6780568a | [
"MIT"
] | null | null | null | src/ADDA/Networks.py | fol21/domain-adaptation-in-deforestation | ae1c37b1634f54230f1d2217c209dabd6780568a | [
"MIT"
] | null | null | null | import os
import numpy as np
import tensorflow as tf
class Networks():
def __init__(self, args):
super(Networks, self).__init__()
self.args = args
# Wittich design
def VNET_16L(self, I, is_train, reuse_unet=False, reuse_ada=False, adaption_net=False):
def encoder_conf(name, X, filter, f_size, scale, norm, reuse, is_train, dropout=0.0, stddev=-1.0, slope=0.00,
use_bias=True):
with tf.variable_scope(name) as scope:
if scale > 1:
X = self.conv(name + '_downsample', X, filter, scale, scale, (not norm) and use_bias, "VALID", stddev)
else:
X = self.conv(name + '_conf', X, filter, f_size, 1, (not norm) and use_bias, "VALID", stddev)
if norm == 'I':
X = tf.contrib.layers.instance_norm(X, scope=scope, reuse=reuse)
elif norm == 'B':
X = tf.layers.batch_normalization(X, reuse=reuse, training=is_train, name=name)
elif norm == 'G':
X = tf.contrib.layers.group_norm(X, groups=16, scope=scope, reuse=reuse)
if dropout > 0.0:
X = tf.layers.dropout(X, dropout, training=is_train)
if slope < 1.0:
X = tf.nn.leaky_relu(X, slope) if slope > 0.0 else tf.nn.relu(X)
return X
def decoder_conf(name, X, filter, f_size, scale, norm, reuse, is_train, dropout=0.0, stddev=-1.0, slope=0.00,
use_bias=True):
with tf.variable_scope(name) as scope:
if scale > 1:
X = self.t_conv(name + '_upsample', X, filter, scale, scale, (not norm) and use_bias, "VALID", stddev)
else:
X = self.t_conv(name + '_deconf', X, filter, f_size, 1, (not norm) and use_bias, "VALID", stddev)
if norm == 'I':
X = tf.contrib.layers.instance_norm(X, scope=scope, reuse=reuse)
elif norm == 'B':
X = tf.layers.batch_normalization(X, reuse=reuse, training=is_train, name=name)
elif norm == 'G':
X = tf.contrib.layers.group_norm(X, groups=16, scope=scope, reuse=reuse)
if dropout > 0.0:
X = tf.layers.dropout(X, dropout, training=is_train)
if slope < 1.0:
X = tf.nn.leaky_relu(X, slope) if slope > 0.0 else tf.nn.relu(X)
return X
F = 3
norm = self.args.norm
# print('norm', norm)
# print('skip cons', self.args.skip_connections)
# print('VNET In:', I.get_shape().as_list())
if adaption_net:
# print('ada scope T/R', is_train, reuse_ada)
encoderscope = 'ada_enc'
decoderscope = 'ada_dec'
reuse_encoder = reuse_ada
reuse_decoder = reuse_ada
else:
# print('vnet scope T/R', is_train, reuse_unet)
encoderscope = 'unet_enc'
decoderscope = 'unet_dec'
reuse_encoder = reuse_unet
reuse_decoder = reuse_unet
print([encoderscope, ' ', decoderscope])
# ===============================================================================ENCODER
with tf.variable_scope(encoderscope) as scope:
if reuse_encoder: scope.reuse_variables()
with tf.variable_scope('color_encoder'):
X = encoder_conf('eI', I[:, :, :, :-1], 96, 5, 1, norm, reuse_encoder, is_train, self.args.dropout) # 128 > 124
X0 = encoder_conf('d0', X, 96, 2, 2, norm, reuse_encoder, is_train, self.args.dropout) # 124 > 62 @2
X = encoder_conf('e1', X0, 128, 3, 1, norm, reuse_encoder, is_train, self.args.dropout) # 62 > 60
X_EARLY = X
X1 = encoder_conf('d1', X, 128, 2, 2, norm, reuse_encoder, is_train, self.args.dropout) # 60 > 30 @4
X = encoder_conf('e2', X1, 256, 3, 1, norm, reuse_encoder, is_train, self.args.dropout) # 30 > 28
X2 = encoder_conf('d2', X, 256, 2, 2, norm, reuse_encoder, is_train, self.args.dropout) # 28 > 14 @8
X = encoder_conf('e3', X2, 512, 3, 1, norm, reuse_encoder, is_train, self.args.dropout) # 14 > 12
X_MIDDLE = X
# ===============================================================================DECODER
with tf.variable_scope(decoderscope) as scope:
if reuse_decoder: scope.reuse_variables()
# print('vnet scope', is_train, reuse_unet)
# print('VNET Latent:', X.get_shape().as_list())
with tf.variable_scope('decoder'):
X = decoder_conf('d3', X, 512, F, 1, norm, reuse_decoder, is_train, self.args.dropout) # 12 > 14
if self.args.skip_connections: X = tf.concat((X, X2), axis=-1)
X = decoder_conf('u4', X, 256, F, 2, norm, reuse_decoder, is_train, self.args.dropout) # 14 > 28
X = decoder_conf('d4', X, 256, F, 1, norm, reuse_decoder, is_train, self.args.dropout) # 28 > 30
if self.args.skip_connections: X = tf.concat((X, X1), axis=-1)
X = decoder_conf('u5', X, 128, F, 2, norm, reuse_decoder, is_train, self.args.dropout) # 30 > 60
X_LATE = X
X = decoder_conf('d5', X, 128, F, 1, norm, reuse_decoder, is_train, self.args.dropout) # 60 > 62
if self.args.skip_connections: X = tf.concat((X, X0), axis=-1)
X = decoder_conf('u6', X, 64, F, 2, norm, reuse_decoder, is_train, self.args.dropout) # 62 > 124
X = decoder_conf('d6', X, 64, 5, 1, norm, reuse_decoder, is_train, self.args.dropout) # 124 > 128
X = decoder_conf('out', X, self.args.num_classes, 1, 1, '', reuse_decoder, is_train, slope=1.0, stddev=0.02,
use_bias=False)
prediction = tf.nn.softmax(X, name = 'softmax')
# ============================================================================OUT
# print('VNET Out:', X.get_shape().as_list())
# if self.args.mode == 'adapt':
return X, X_EARLY, X_MIDDLE, X_LATE, prediction
# else:
# return X, prediction
def D_4(self, X, reuse):
def discrim_conv(name, X, out_channels, filtersize, stride=1, norm='', nonlin=True, init_stddev=-1):
with tf.variable_scope(name) as scope:
if init_stddev <= 0.0:
init = tf.contrib.layers.variance_scaling_initializer(dtype=tf.float32)
else:
init = tf.truncated_normal_initializer(stddev=init_stddev)
X = tf.layers.conv2d(X, out_channels, kernel_size=filtersize, strides=(stride, stride), padding="valid",
kernel_initializer=init)
if norm == 'I':
X = tf.contrib.layers.instance_norm(X, scope=scope, reuse=reuse, epsilon=0.001)
elif norm == 'B':
X = tf.layers.batch_normalization(X, reuse=reuse, training=True)
elif norm == 'G':
X = tf.contrib.layers.group_norm(X, groups=16, scope=scope, reuse=reuse)
if nonlin:
X = tf.nn.leaky_relu(X, 0.2)
return X
with tf.variable_scope('discriminator') as scope:
if reuse:
scope.reuse_variables()
print('D in:', X.get_shape().as_list())
X = self.conv('DZ1', X, 512, 1, 1)
X = tf.nn.leaky_relu(X, 0.2)
X = self.conv('DZ2', X, 512, 1, 1)
X = tf.nn.leaky_relu(X, 0.2)
X = self.conv('DZ3', X, 512, 1, 1)
X = tf.nn.leaky_relu(X, 0.2)
X = self.conv('DZ4', X, 512, 1, 1)
X = tf.nn.leaky_relu(X, 0.2)
X = discrim_conv('d_out', X, 1, 1, norm=False, nonlin=False, init_stddev=0.02)
print('D out:', X.get_shape().as_list())
return X
def atrous_discriminator(self, X, reuse):
def atrous_convs(net, scope, rate=None, depth=256, reuse=None):
"""
ASPP layer 1×1 convolution and three 3×3 atrous convolutions
"""
with tf.variable_scope(scope, reuse=reuse):
pyram_1x1_0 = self.conv('_1x1', net, depth, size=1, stride=1, padding="SAME")
pyram_3x3_1 = self.conv('_3x3', net, depth, size=3, stride=1, padding="SAME")
pyram_3x3_2 = self.conv('_atr_3x3_1', net, depth, size=3, stride=1, padding="SAME", dilation=rate[0])
pyram_3x3_3 = self.conv('_atr_3x3_2', net, depth, size=3, stride=1, padding="SAME", dilation=rate[1])
# pyram_3x3_4 = self.z_conv('_atr_3x3_3', net, depth/2, size=3, stride=1, padding="SAME", dilation=rate[2])
net = tf.concat((pyram_1x1_0, pyram_3x3_1, pyram_3x3_2, pyram_3x3_3), axis=3, name="concat")
net = self.conv('_1x1_output', net, depth, size=1, stride=1, padding="SAME")
# pyram_1x1_0 = self.conv('_1x1', net, depth, size=1, stride=1, padding="SAME")
# pyram_3x3_1 = self.conv('_3x3', net, depth/2, size=3, stride=1, padding="SAME")
# pyram_3x3_2 = self.conv('_atr_3x3_1', net, depth/2, size=3, stride=1, padding="SAME", dilation=rate[0])
# pyram_3x3_3 = self.conv('_atr_3x3_2', net, depth/2, size=3, stride=1, padding="SAME", dilation=rate[1])
# # pyram_3x3_4 = self.conv('_atr_3x3_3', net, depth/2, size=3, stride=1, padding="SAME", dilation=rate[2])
# net = tf.concat((pyram_1x1_0, pyram_3x3_1, pyram_3x3_2, pyram_3x3_3), axis=3, name="concat")
# net = self.conv('_1x1_output', net, depth, size=1, stride=1, padding="SAME")
return net
with tf.variable_scope('discriminator') as scope:
if reuse:
scope.reuse_variables()
print('D in:', X.get_shape().as_list())
rate = [2, 3, 4]
X = atrous_convs(X, "d_atrous_0", rate = rate, depth=256, reuse=reuse)
X = tf.nn.leaky_relu(X, 0.2)
X = self.conv('d_1', X, 512, size=1, stride=1, padding="SAME")
X = tf.nn.leaky_relu(X, 0.2)
X = self.conv('d_2', X, 512, size=1, stride=1, padding="SAME")
X = tf.nn.leaky_relu(X, 0.2)
X = self.conv('d_3', X, 512, size=1, stride=1, padding="SAME")
X = tf.nn.leaky_relu(X, 0.2)
X = self.conv('d_out', X, 1, size=1, stride=1, padding="SAME")
print('D out:', X.get_shape().as_list())
return X
def conv(self, id, input, channels, size=3, stride=1, use_bias=True, padding="SAME", init_stddev=-1.0, dilation=1):
assert padding in ["SAME", "VALID", "REFLECT", "PARTIAL"], 'valid paddings: "SAME", "VALID", "REFLECT", "PARTIAL"'
if type(size) == int: size = [size, size]
if init_stddev <= 0.0:
init = tf.contrib.layers.variance_scaling_initializer(dtype=tf.float32)
else:
init = tf.truncated_normal_initializer(stddev=init_stddev)
if padding == "PARTIAL":
with tf.variable_scope('mask'):
_, h, w, _ = input.get_shape().as_list()
slide_window = size[0] * size[1]
mask = tf.ones(shape=[1, h, w, 1])
update_mask = tf.layers.conv2d(mask, filters=1, dilation_rate=(dilation, dilation), name='mask' + id,
kernel_size=size, kernel_initializer=tf.constant_initializer(1.0),
strides=stride, padding="SAME", use_bias=False, trainable=False)
mask_ratio = slide_window / (update_mask + 1e-8)
update_mask = tf.clip_by_value(update_mask, 0.0, 1.0)
mask_ratio = mask_ratio * update_mask
with tf.variable_scope('parconv'):
x = tf.layers.conv2d(input, filters=channels, name='conv' + id, kernel_size=size, kernel_initializer=init,
strides=stride, padding="SAME", use_bias=False)
x = x * mask_ratio
if use_bias:
bias = tf.get_variable("bias" + id, [channels], initializer=tf.constant_initializer(0.0))
x = tf.nn.bias_add(x, bias)
return x * update_mask
if padding == "REFLECT":
assert size[0] % 2 == 1 and size[1] % 2 == 1, "REFLECTION PAD ONLY WORKING FOR ODD FILTER SIZE.. " + str(size)
pad_x = size[0] // 2
pad_y = size[1] // 2
input = tf.pad(input, [[0, 0], [pad_x, pad_x], [pad_y, pad_y], [0, 0]], "REFLECT")
padding = "VALID"
return tf.layers.conv2d(input, channels, kernel_size=size, strides=[stride, stride],
padding=padding, kernel_initializer=init, name='conv' + id,
use_bias=use_bias, dilation_rate=(dilation, dilation))
def z_conv(self, id, input, channels, size, stride=1, padding="SAME", use_bias=False, dilation=1):
# zero mean conv
if type(size) == int: size = [size, size]
in_ch = input.get_shape().as_list()[-1]
# init = tf.contrib.layers.variance_scaling_initializer(dtype=tf.float32)
init = tf.truncated_normal_initializer(mean=0.0, stddev=0.02)
filters = tf.get_variable('zero_conv_weights' + id, initializer=init, shape=[size[0], size[1], in_ch, channels])
filters = filters - tf.reduce_mean(filters, axis=[0, 1, 2], keepdims=True)
if padding == "PARTIAL":
with tf.variable_scope('mask'):
_, h, w, _ = input.get_shape().as_list()
slide_window = size[0] * size[1]
mask = tf.ones(shape=[1, h, w, 1])
update_mask = tf.layers.conv2d(mask, filters=1, name='mask' + id,
kernel_size=size, kernel_initializer=tf.constant_initializer(1.0),
strides=stride, padding="SAME", use_bias=False, trainable=False,
dilation_rate=(dilation, dilation))
mask_ratio = slide_window / (update_mask + 1e-8)
update_mask = tf.clip_by_value(update_mask, 0.0, 1.0)
mask_ratio = mask_ratio * update_mask
with tf.variable_scope('parconv'):
x = tf.nn.conv2d(input, filters, strides=[1, stride, stride, 1], padding="SAME", name='zero-conv_' + id,
dilations=(1, dilation, dilation, 1))
x = x * mask_ratio
if use_bias:
bias = tf.get_variable("bias" + id, [channels], initializer=tf.constant_initializer(0.0))
x = tf.nn.bias_add(x, bias)
return x * update_mask
x = tf.nn.conv2d(input, filters, strides=[1, stride, stride, 1], padding=padding, name='zero-conv_' + id,
dilations=(1, dilation, dilation, 1))
if use_bias:
bias = tf.get_variable("bias", [channels], initializer=tf.constant_initializer(0.0))
x = tf.nn.bias_add(x, bias)
return x
def t_conv(self, id, input, channels, size=3, stride=1, use_bias=True, padding="SAME", init_stddev=-1.0):
# good old t-conv. I love it!
assert padding in ["SAME", "VALID"], 'valid paddings are "SAME", "VALID"'
if type(size) == int:
size = [size, size]
if init_stddev <= 0.0:
init = tf.contrib.layers.variance_scaling_initializer(dtype=tf.float32)
else:
init = tf.truncated_normal_initializer(stddev=init_stddev)
return tf.layers.conv2d_transpose(input, channels, kernel_size=size, strides=[stride, stride],
padding=padding, kernel_initializer=init, name='tr_conv' + id, use_bias=use_bias)
# Traditional U-Net
def build_Unet_Arch(self, input_data, name="Unet_Arch"):
self.base_number_of_features = 32
with tf.variable_scope(name):
# Encoder definition
o_c1 = self.general_conv2d(input_data, self.base_number_of_features, 3, stride = 1, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_conv2d_1')
o_mp1 = tf.layers.max_pooling2d(o_c1, 2, 2, name = name + '_maxpooling_1')
o_c2 = self.general_conv2d(o_mp1, self.base_number_of_features * 2, 3, stride = 1, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_conv2d_2')
o_mp2 = tf.layers.max_pooling2d(o_c2, 2, 2, name = name + '_maxpooling_2')
o_c3 = self.general_conv2d(o_mp2, self.base_number_of_features * 4, 3, stride = 1, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_conv2d_3')
o_mp3 = tf.layers.max_pooling2d(o_c3, 2, 2, name = name + '_maxpooling_3')
o_c4 = self.general_conv2d(o_mp3, self.base_number_of_features * 8, 3, stride = 1, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_conv2d_4')
o_mp4 = tf.layers.max_pooling2d(o_c4, 2, 2, name = name + '_maxpooling_4')
o_c5 = self.general_conv2d(o_mp4, self.base_number_of_features * 16, 3, stride = 1, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_conv2d_5')
# Decoder definition
o_d1 = self.general_deconv2d(o_c5, self.base_number_of_features * 8, 3, stride = 2, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_deconv2d_1')
o_me1 = tf.concat([o_d1, o_c4], 3) # Skip connection
o_d2 = self.general_deconv2d(o_me1, self.base_number_of_features * 4, 3, stride = 2, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_deconv2d_2')
o_me2 = tf.concat([o_d2, o_c3], 3) # Skip connection
o_d3 = self.general_deconv2d(o_me2, self.base_number_of_features * 2, 3, stride = 2, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_deconv2d_3')
o_me3 = tf.concat([o_d3, o_c2], 3) # Skip connection
o_d4 = self.general_deconv2d(o_me3, self.base_number_of_features, 3, stride = 2, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_deconv2d_4')
o_me4 = tf.concat([o_d4, o_c1], 3) # Skip connection
logits = tf.layers.conv2d(o_me4, self.args.num_classes, 1, 1, 'SAME', activation = None)
prediction = tf.nn.softmax(logits, name = name + '_softmax')
return logits, prediction
def general_conv2d(self, input_data, filters = 64, kernel_size = 7, stride = 1, stddev = 0.02, activation_function = "relu", padding = "VALID", do_norm=True, relu_factor = 0, name="conv2d"):
with tf.variable_scope(name):
conv = tf.layers.conv2d(input_data, filters, kernel_size, stride, padding, activation=None)
if do_norm:
conv = tf.layers.batch_normalization(conv, momentum=0.9)
if activation_function == "relu":
conv = tf.nn.relu(conv, name = 'relu')
if activation_function == "leakyrelu":
conv = tf.nn.leaky_relu(conv, alpha=relu_factor)
if activation_function == "elu":
conv = tf.nn.elu(conv, name = 'elu')
return conv
def general_deconv2d(self, input_data, filters = 64, kernel_size = 7, stride = 1, stddev = 0.02, activation_function = "relu", padding = "VALID", do_norm = True, relu_factor = 0, name="deconv2d"):
with tf.variable_scope(name):
deconv = tf.layers.conv2d_transpose(input_data, filters, kernel_size, (stride, stride), padding, activation = None)
if do_norm:
deconv = tf.layers.batch_normalization(deconv, momentum = 0.9)
if activation_function == "relu":
deconv = tf.nn.relu(deconv, name = 'relu')
if activation_function == "leakyrelu":
deconv = tf.nn.leaky_relu(deconv, alpha=relu_factor)
if activation_function == "elu":
deconv = tf.nn.elu(deconv, name = 'elu')
return deconv
| 56.747967 | 200 | 0.545463 | import os
import numpy as np
import tensorflow as tf
class Networks():
def __init__(self, args):
super(Networks, self).__init__()
self.args = args
def VNET_16L(self, I, is_train, reuse_unet=False, reuse_ada=False, adaption_net=False):
def encoder_conf(name, X, filter, f_size, scale, norm, reuse, is_train, dropout=0.0, stddev=-1.0, slope=0.00,
use_bias=True):
with tf.variable_scope(name) as scope:
if scale > 1:
X = self.conv(name + '_downsample', X, filter, scale, scale, (not norm) and use_bias, "VALID", stddev)
else:
X = self.conv(name + '_conf', X, filter, f_size, 1, (not norm) and use_bias, "VALID", stddev)
if norm == 'I':
X = tf.contrib.layers.instance_norm(X, scope=scope, reuse=reuse)
elif norm == 'B':
X = tf.layers.batch_normalization(X, reuse=reuse, training=is_train, name=name)
elif norm == 'G':
X = tf.contrib.layers.group_norm(X, groups=16, scope=scope, reuse=reuse)
if dropout > 0.0:
X = tf.layers.dropout(X, dropout, training=is_train)
if slope < 1.0:
X = tf.nn.leaky_relu(X, slope) if slope > 0.0 else tf.nn.relu(X)
return X
def decoder_conf(name, X, filter, f_size, scale, norm, reuse, is_train, dropout=0.0, stddev=-1.0, slope=0.00,
use_bias=True):
with tf.variable_scope(name) as scope:
if scale > 1:
X = self.t_conv(name + '_upsample', X, filter, scale, scale, (not norm) and use_bias, "VALID", stddev)
else:
X = self.t_conv(name + '_deconf', X, filter, f_size, 1, (not norm) and use_bias, "VALID", stddev)
if norm == 'I':
X = tf.contrib.layers.instance_norm(X, scope=scope, reuse=reuse)
elif norm == 'B':
X = tf.layers.batch_normalization(X, reuse=reuse, training=is_train, name=name)
elif norm == 'G':
X = tf.contrib.layers.group_norm(X, groups=16, scope=scope, reuse=reuse)
if dropout > 0.0:
X = tf.layers.dropout(X, dropout, training=is_train)
if slope < 1.0:
X = tf.nn.leaky_relu(X, slope) if slope > 0.0 else tf.nn.relu(X)
return X
F = 3
norm = self.args.norm
if adaption_net:
encoderscope = 'ada_enc'
decoderscope = 'ada_dec'
reuse_encoder = reuse_ada
reuse_decoder = reuse_ada
else:
encoderscope = 'unet_enc'
decoderscope = 'unet_dec'
reuse_encoder = reuse_unet
reuse_decoder = reuse_unet
print([encoderscope, ' ', decoderscope])
with tf.variable_scope(encoderscope) as scope:
if reuse_encoder: scope.reuse_variables()
with tf.variable_scope('color_encoder'):
X = encoder_conf('eI', I[:, :, :, :-1], 96, 5, 1, norm, reuse_encoder, is_train, self.args.dropout)
X0 = encoder_conf('d0', X, 96, 2, 2, norm, reuse_encoder, is_train, self.args.dropout)
X = encoder_conf('e1', X0, 128, 3, 1, norm, reuse_encoder, is_train, self.args.dropout)
X_EARLY = X
X1 = encoder_conf('d1', X, 128, 2, 2, norm, reuse_encoder, is_train, self.args.dropout)
X = encoder_conf('e2', X1, 256, 3, 1, norm, reuse_encoder, is_train, self.args.dropout)
X2 = encoder_conf('d2', X, 256, 2, 2, norm, reuse_encoder, is_train, self.args.dropout)
X = encoder_conf('e3', X2, 512, 3, 1, norm, reuse_encoder, is_train, self.args.dropout)
X_MIDDLE = X
with tf.variable_scope(decoderscope) as scope:
if reuse_decoder: scope.reuse_variables()
with tf.variable_scope('decoder'):
X = decoder_conf('d3', X, 512, F, 1, norm, reuse_decoder, is_train, self.args.dropout)
if self.args.skip_connections: X = tf.concat((X, X2), axis=-1)
X = decoder_conf('u4', X, 256, F, 2, norm, reuse_decoder, is_train, self.args.dropout)
X = decoder_conf('d4', X, 256, F, 1, norm, reuse_decoder, is_train, self.args.dropout)
if self.args.skip_connections: X = tf.concat((X, X1), axis=-1)
X = decoder_conf('u5', X, 128, F, 2, norm, reuse_decoder, is_train, self.args.dropout)
X_LATE = X
X = decoder_conf('d5', X, 128, F, 1, norm, reuse_decoder, is_train, self.args.dropout)
if self.args.skip_connections: X = tf.concat((X, X0), axis=-1)
X = decoder_conf('u6', X, 64, F, 2, norm, reuse_decoder, is_train, self.args.dropout)
X = decoder_conf('d6', X, 64, 5, 1, norm, reuse_decoder, is_train, self.args.dropout)
X = decoder_conf('out', X, self.args.num_classes, 1, 1, '', reuse_decoder, is_train, slope=1.0, stddev=0.02,
use_bias=False)
prediction = tf.nn.softmax(X, name = 'softmax')
return X, X_EARLY, X_MIDDLE, X_LATE, prediction
def D_4(self, X, reuse):
def discrim_conv(name, X, out_channels, filtersize, stride=1, norm='', nonlin=True, init_stddev=-1):
with tf.variable_scope(name) as scope:
if init_stddev <= 0.0:
init = tf.contrib.layers.variance_scaling_initializer(dtype=tf.float32)
else:
init = tf.truncated_normal_initializer(stddev=init_stddev)
X = tf.layers.conv2d(X, out_channels, kernel_size=filtersize, strides=(stride, stride), padding="valid",
kernel_initializer=init)
if norm == 'I':
X = tf.contrib.layers.instance_norm(X, scope=scope, reuse=reuse, epsilon=0.001)
elif norm == 'B':
X = tf.layers.batch_normalization(X, reuse=reuse, training=True)
elif norm == 'G':
X = tf.contrib.layers.group_norm(X, groups=16, scope=scope, reuse=reuse)
if nonlin:
X = tf.nn.leaky_relu(X, 0.2)
return X
with tf.variable_scope('discriminator') as scope:
if reuse:
scope.reuse_variables()
print('D in:', X.get_shape().as_list())
X = self.conv('DZ1', X, 512, 1, 1)
X = tf.nn.leaky_relu(X, 0.2)
X = self.conv('DZ2', X, 512, 1, 1)
X = tf.nn.leaky_relu(X, 0.2)
X = self.conv('DZ3', X, 512, 1, 1)
X = tf.nn.leaky_relu(X, 0.2)
X = self.conv('DZ4', X, 512, 1, 1)
X = tf.nn.leaky_relu(X, 0.2)
X = discrim_conv('d_out', X, 1, 1, norm=False, nonlin=False, init_stddev=0.02)
print('D out:', X.get_shape().as_list())
return X
def atrous_discriminator(self, X, reuse):
def atrous_convs(net, scope, rate=None, depth=256, reuse=None):
with tf.variable_scope(scope, reuse=reuse):
pyram_1x1_0 = self.conv('_1x1', net, depth, size=1, stride=1, padding="SAME")
pyram_3x3_1 = self.conv('_3x3', net, depth, size=3, stride=1, padding="SAME")
pyram_3x3_2 = self.conv('_atr_3x3_1', net, depth, size=3, stride=1, padding="SAME", dilation=rate[0])
pyram_3x3_3 = self.conv('_atr_3x3_2', net, depth, size=3, stride=1, padding="SAME", dilation=rate[1])
net = tf.concat((pyram_1x1_0, pyram_3x3_1, pyram_3x3_2, pyram_3x3_3), axis=3, name="concat")
net = self.conv('_1x1_output', net, depth, size=1, stride=1, padding="SAME")
.variable_scope('discriminator') as scope:
if reuse:
scope.reuse_variables()
print('D in:', X.get_shape().as_list())
rate = [2, 3, 4]
X = atrous_convs(X, "d_atrous_0", rate = rate, depth=256, reuse=reuse)
X = tf.nn.leaky_relu(X, 0.2)
X = self.conv('d_1', X, 512, size=1, stride=1, padding="SAME")
X = tf.nn.leaky_relu(X, 0.2)
X = self.conv('d_2', X, 512, size=1, stride=1, padding="SAME")
X = tf.nn.leaky_relu(X, 0.2)
X = self.conv('d_3', X, 512, size=1, stride=1, padding="SAME")
X = tf.nn.leaky_relu(X, 0.2)
X = self.conv('d_out', X, 1, size=1, stride=1, padding="SAME")
print('D out:', X.get_shape().as_list())
return X
def conv(self, id, input, channels, size=3, stride=1, use_bias=True, padding="SAME", init_stddev=-1.0, dilation=1):
assert padding in ["SAME", "VALID", "REFLECT", "PARTIAL"], 'valid paddings: "SAME", "VALID", "REFLECT", "PARTIAL"'
if type(size) == int: size = [size, size]
if init_stddev <= 0.0:
init = tf.contrib.layers.variance_scaling_initializer(dtype=tf.float32)
else:
init = tf.truncated_normal_initializer(stddev=init_stddev)
if padding == "PARTIAL":
with tf.variable_scope('mask'):
_, h, w, _ = input.get_shape().as_list()
slide_window = size[0] * size[1]
mask = tf.ones(shape=[1, h, w, 1])
update_mask = tf.layers.conv2d(mask, filters=1, dilation_rate=(dilation, dilation), name='mask' + id,
kernel_size=size, kernel_initializer=tf.constant_initializer(1.0),
strides=stride, padding="SAME", use_bias=False, trainable=False)
mask_ratio = slide_window / (update_mask + 1e-8)
update_mask = tf.clip_by_value(update_mask, 0.0, 1.0)
mask_ratio = mask_ratio * update_mask
with tf.variable_scope('parconv'):
x = tf.layers.conv2d(input, filters=channels, name='conv' + id, kernel_size=size, kernel_initializer=init,
strides=stride, padding="SAME", use_bias=False)
x = x * mask_ratio
if use_bias:
bias = tf.get_variable("bias" + id, [channels], initializer=tf.constant_initializer(0.0))
x = tf.nn.bias_add(x, bias)
return x * update_mask
if padding == "REFLECT":
assert size[0] % 2 == 1 and size[1] % 2 == 1, "REFLECTION PAD ONLY WORKING FOR ODD FILTER SIZE.. " + str(size)
pad_x = size[0] // 2
pad_y = size[1] // 2
input = tf.pad(input, [[0, 0], [pad_x, pad_x], [pad_y, pad_y], [0, 0]], "REFLECT")
padding = "VALID"
return tf.layers.conv2d(input, channels, kernel_size=size, strides=[stride, stride],
padding=padding, kernel_initializer=init, name='conv' + id,
use_bias=use_bias, dilation_rate=(dilation, dilation))
def z_conv(self, id, input, channels, size, stride=1, padding="SAME", use_bias=False, dilation=1):
if type(size) == int: size = [size, size]
in_ch = input.get_shape().as_list()[-1]
init = tf.truncated_normal_initializer(mean=0.0, stddev=0.02)
filters = tf.get_variable('zero_conv_weights' + id, initializer=init, shape=[size[0], size[1], in_ch, channels])
filters = filters - tf.reduce_mean(filters, axis=[0, 1, 2], keepdims=True)
if padding == "PARTIAL":
with tf.variable_scope('mask'):
_, h, w, _ = input.get_shape().as_list()
slide_window = size[0] * size[1]
mask = tf.ones(shape=[1, h, w, 1])
update_mask = tf.layers.conv2d(mask, filters=1, name='mask' + id,
kernel_size=size, kernel_initializer=tf.constant_initializer(1.0),
strides=stride, padding="SAME", use_bias=False, trainable=False,
dilation_rate=(dilation, dilation))
mask_ratio = slide_window / (update_mask + 1e-8)
update_mask = tf.clip_by_value(update_mask, 0.0, 1.0)
mask_ratio = mask_ratio * update_mask
with tf.variable_scope('parconv'):
x = tf.nn.conv2d(input, filters, strides=[1, stride, stride, 1], padding="SAME", name='zero-conv_' + id,
dilations=(1, dilation, dilation, 1))
x = x * mask_ratio
if use_bias:
bias = tf.get_variable("bias" + id, [channels], initializer=tf.constant_initializer(0.0))
x = tf.nn.bias_add(x, bias)
return x * update_mask
x = tf.nn.conv2d(input, filters, strides=[1, stride, stride, 1], padding=padding, name='zero-conv_' + id,
dilations=(1, dilation, dilation, 1))
if use_bias:
bias = tf.get_variable("bias", [channels], initializer=tf.constant_initializer(0.0))
x = tf.nn.bias_add(x, bias)
return x
def t_conv(self, id, input, channels, size=3, stride=1, use_bias=True, padding="SAME", init_stddev=-1.0):
assert padding in ["SAME", "VALID"], 'valid paddings are "SAME", "VALID"'
if type(size) == int:
size = [size, size]
if init_stddev <= 0.0:
init = tf.contrib.layers.variance_scaling_initializer(dtype=tf.float32)
else:
init = tf.truncated_normal_initializer(stddev=init_stddev)
return tf.layers.conv2d_transpose(input, channels, kernel_size=size, strides=[stride, stride],
padding=padding, kernel_initializer=init, name='tr_conv' + id, use_bias=use_bias)
def build_Unet_Arch(self, input_data, name="Unet_Arch"):
self.base_number_of_features = 32
with tf.variable_scope(name):
o_c1 = self.general_conv2d(input_data, self.base_number_of_features, 3, stride = 1, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_conv2d_1')
o_mp1 = tf.layers.max_pooling2d(o_c1, 2, 2, name = name + '_maxpooling_1')
o_c2 = self.general_conv2d(o_mp1, self.base_number_of_features * 2, 3, stride = 1, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_conv2d_2')
o_mp2 = tf.layers.max_pooling2d(o_c2, 2, 2, name = name + '_maxpooling_2')
o_c3 = self.general_conv2d(o_mp2, self.base_number_of_features * 4, 3, stride = 1, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_conv2d_3')
o_mp3 = tf.layers.max_pooling2d(o_c3, 2, 2, name = name + '_maxpooling_3')
o_c4 = self.general_conv2d(o_mp3, self.base_number_of_features * 8, 3, stride = 1, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_conv2d_4')
o_mp4 = tf.layers.max_pooling2d(o_c4, 2, 2, name = name + '_maxpooling_4')
o_c5 = self.general_conv2d(o_mp4, self.base_number_of_features * 16, 3, stride = 1, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_conv2d_5')
o_d1 = self.general_deconv2d(o_c5, self.base_number_of_features * 8, 3, stride = 2, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_deconv2d_1')
o_me1 = tf.concat([o_d1, o_c4], 3)
o_d2 = self.general_deconv2d(o_me1, self.base_number_of_features * 4, 3, stride = 2, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_deconv2d_2')
o_me2 = tf.concat([o_d2, o_c3], 3)
o_d3 = self.general_deconv2d(o_me2, self.base_number_of_features * 2, 3, stride = 2, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_deconv2d_3')
o_me3 = tf.concat([o_d3, o_c2], 3)
o_d4 = self.general_deconv2d(o_me3, self.base_number_of_features, 3, stride = 2, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_deconv2d_4')
o_me4 = tf.concat([o_d4, o_c1], 3)
logits = tf.layers.conv2d(o_me4, self.args.num_classes, 1, 1, 'SAME', activation = None)
prediction = tf.nn.softmax(logits, name = name + '_softmax')
return logits, prediction
def general_conv2d(self, input_data, filters = 64, kernel_size = 7, stride = 1, stddev = 0.02, activation_function = "relu", padding = "VALID", do_norm=True, relu_factor = 0, name="conv2d"):
with tf.variable_scope(name):
conv = tf.layers.conv2d(input_data, filters, kernel_size, stride, padding, activation=None)
if do_norm:
conv = tf.layers.batch_normalization(conv, momentum=0.9)
if activation_function == "relu":
conv = tf.nn.relu(conv, name = 'relu')
if activation_function == "leakyrelu":
conv = tf.nn.leaky_relu(conv, alpha=relu_factor)
if activation_function == "elu":
conv = tf.nn.elu(conv, name = 'elu')
return conv
def general_deconv2d(self, input_data, filters = 64, kernel_size = 7, stride = 1, stddev = 0.02, activation_function = "relu", padding = "VALID", do_norm = True, relu_factor = 0, name="deconv2d"):
with tf.variable_scope(name):
deconv = tf.layers.conv2d_transpose(input_data, filters, kernel_size, (stride, stride), padding, activation = None)
if do_norm:
deconv = tf.layers.batch_normalization(deconv, momentum = 0.9)
if activation_function == "relu":
deconv = tf.nn.relu(deconv, name = 'relu')
if activation_function == "leakyrelu":
deconv = tf.nn.leaky_relu(deconv, alpha=relu_factor)
if activation_function == "elu":
deconv = tf.nn.elu(deconv, name = 'elu')
return deconv
| true | true |
f7f74f5cc4f1243dee69589ce37bced6dbb80b6b | 1,198 | py | Python | src/simulation.py | julinas/town-sim-py | f0fa1671bd5003053957f722d78d90161ff407a7 | [
"BSD-3-Clause"
] | 11 | 2019-06-08T20:27:39.000Z | 2021-11-02T15:02:14.000Z | src/simulation.py | julinas/town-sim-py | f0fa1671bd5003053957f722d78d90161ff407a7 | [
"BSD-3-Clause"
] | 1 | 2020-01-11T18:48:21.000Z | 2020-01-12T22:33:54.000Z | src/simulation.py | julinas/town-sim-py | f0fa1671bd5003053957f722d78d90161ff407a7 | [
"BSD-3-Clause"
] | 2 | 2020-06-09T06:08:51.000Z | 2020-08-31T18:09:15.000Z | # BSD 3-Clause License
#
# Copyright (c) 2019, Augmented Design Lab
# All rights reserved.
import copy
import random
import time
from agent import Agent
from landscape import Landscape
from lot import Lot
import gc
class Simulation:
def __init__(self, size=200, r1=3, r2=5, r3=10, r4=10, load_filename=None):
self.landscape = Landscape(size, size, self, r1, r2, r3, r4, load_filename)
if not load_filename:
self.agents = set()
for i in range(100): #200
self.add_agent(Agent(self.landscape, self))
def step(self, phase, maNum=10, miNum=400, byNum=2000, brNum=5000, buNum=400, pDecay=0.75, tDecay=0.25, corNum=5):
self.landscape.step(phase, maNum, miNum, byNum, brNum, buNum, pDecay, tDecay, corNum)
killlist = []
for agent in list(self.agents):
agent.step(self.landscape)
if agent.water < 0 or agent.resource < 0:
killlist.append(agent)
for agent in killlist:
self.kill(agent)
gc.collect()
def add_agent(self, agent):
self.agents.add(agent)
def kill(self, agent):
self.agents.discard(agent)
self.landscape.remove_agent(agent)
def view(self, step):
return self.landscape.view(step)
def output(self, filedir):
self.landscape.output(filedir)
| 26.622222 | 115 | 0.717863 |
import copy
import random
import time
from agent import Agent
from landscape import Landscape
from lot import Lot
import gc
class Simulation:
def __init__(self, size=200, r1=3, r2=5, r3=10, r4=10, load_filename=None):
self.landscape = Landscape(size, size, self, r1, r2, r3, r4, load_filename)
if not load_filename:
self.agents = set()
for i in range(100):
self.add_agent(Agent(self.landscape, self))
def step(self, phase, maNum=10, miNum=400, byNum=2000, brNum=5000, buNum=400, pDecay=0.75, tDecay=0.25, corNum=5):
self.landscape.step(phase, maNum, miNum, byNum, brNum, buNum, pDecay, tDecay, corNum)
killlist = []
for agent in list(self.agents):
agent.step(self.landscape)
if agent.water < 0 or agent.resource < 0:
killlist.append(agent)
for agent in killlist:
self.kill(agent)
gc.collect()
def add_agent(self, agent):
self.agents.add(agent)
def kill(self, agent):
self.agents.discard(agent)
self.landscape.remove_agent(agent)
def view(self, step):
return self.landscape.view(step)
def output(self, filedir):
self.landscape.output(filedir)
| true | true |
f7f750029073ef7e7effd0f2582d27e265caa3bd | 720 | py | Python | examples/dft/32-xcfun_as_default.py | QuESt-Calculator/pyscf | 0ed03633b699505c7278f1eb501342667d0aa910 | [
"Apache-2.0"
] | 501 | 2018-12-06T23:48:17.000Z | 2022-03-31T11:53:18.000Z | examples/dft/32-xcfun_as_default.py | QuESt-Calculator/pyscf | 0ed03633b699505c7278f1eb501342667d0aa910 | [
"Apache-2.0"
] | 710 | 2018-11-26T22:04:52.000Z | 2022-03-30T03:53:12.000Z | examples/dft/32-xcfun_as_default.py | QuESt-Calculator/pyscf | 0ed03633b699505c7278f1eb501342667d0aa910 | [
"Apache-2.0"
] | 273 | 2018-11-26T10:10:24.000Z | 2022-03-30T12:25:28.000Z | #!/usr/bin/env python
'''
Set the default XC functional library to XCFun (https://github.com/dftlibs/xcfun)
'''
from pyscf import gto, dft, grad
mol = gto.M(
atom = '''
F 0. 0. 0.
H 0. 0. 1.587 ''',
basis = 'ccpvdz')
#
# Scheme 1: Change ._numint of MF object for a single calculation.
#
mf = dft.RKS(mol)
mf._numint.libxc = dft.xcfun
mf.xc = 'b88,lyp'
mf.kernel()
mf.nuc_grad_method().run()
mf.xc = 'scan'
mf.kernel()
#
# Scheme 2: Change the default XC library globally. All DFT calculations will
# call xcfun for XC functional values.
#
dft.numint.NumInt.libxc = dft.xcfun
mf = dft.RKS(mol)
mf.xc = 'b88,lyp'
mf.kernel()
mf.nuc_grad_method().run()
mf.xc = 'scan'
mf.kernel()
| 18.461538 | 81 | 0.640278 |
from pyscf import gto, dft, grad
mol = gto.M(
atom = '''
F 0. 0. 0.
H 0. 0. 1.587 ''',
basis = 'ccpvdz')
mf = dft.RKS(mol)
mf._numint.libxc = dft.xcfun
mf.xc = 'b88,lyp'
mf.kernel()
mf.nuc_grad_method().run()
mf.xc = 'scan'
mf.kernel()
dft.numint.NumInt.libxc = dft.xcfun
mf = dft.RKS(mol)
mf.xc = 'b88,lyp'
mf.kernel()
mf.nuc_grad_method().run()
mf.xc = 'scan'
mf.kernel()
| true | true |
f7f75070c9c1069c11fc9c9d8af25c07064cd6e8 | 9,290 | py | Python | src/grading.py | TMinuzzo/berkeleyRL3 | 2f69c6239d1a4328ac36ec923d88d577c9e37a28 | [
"MIT"
] | 2 | 2021-05-12T22:24:18.000Z | 2021-05-13T12:12:51.000Z | src/grading.py | TMinuzzo/berkeleyRL3 | 2f69c6239d1a4328ac36ec923d88d577c9e37a28 | [
"MIT"
] | 1 | 2021-10-20T00:15:14.000Z | 2021-10-20T00:15:14.000Z | src/grading.py | TMinuzzo/berkeleyRL3 | 2f69c6239d1a4328ac36ec923d88d577c9e37a28 | [
"MIT"
] | 9 | 2021-05-02T01:27:03.000Z | 2021-10-29T22:24:29.000Z | # grading.py
# ----------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
"Common code for autograders"
import html
import time
import sys
import traceback
import pdb
from collections import defaultdict
import util
class Grades:
"A data structure for project grades, along with formatting code to display them"
def __init__(self, projectName, questionsAndMaxesList, edxOutput=False, muteOutput=False):
"""
Defines the grading scheme for a project
projectName: project name
questionsAndMaxesDict: a list of (question name, max points per question)
"""
self.questions = [el[0] for el in questionsAndMaxesList]
self.maxes = dict(questionsAndMaxesList)
self.points = Counter()
self.messages = dict([(q, []) for q in self.questions])
self.project = projectName
self.start = time.localtime()[1:6]
self.sane = True # Sanity checks
self.currentQuestion = None # Which question we're grading
self.edxOutput = edxOutput
self.mute = muteOutput
self.prereqs = defaultdict(set)
#print 'Autograder transcript for %s' % self.project
print('Starting on %d-%d at %d:%02d:%02d' % self.start)
def addPrereq(self, question, prereq):
self.prereqs[question].add(prereq)
def grade(self, gradingModule, exceptionMap = {}, bonusPic = False):
"""
Grades each question
gradingModule: the module with all the grading functions (pass in with sys.modules[__name__])
"""
completedQuestions = set([])
for q in self.questions:
print('\nQuestion %s' % q)
print('=' * (9 + len(q)))
print()
self.currentQuestion = q
incompleted = self.prereqs[q].difference(completedQuestions)
if len(incompleted) > 0:
prereq = incompleted.pop()
print("""*** NOTE: Make sure to complete Question %s before working on Question %s,
*** because Question %s builds upon your answer for Question %s.
""" % (prereq, q, q, prereq))
continue
if self.mute: util.mutePrint()
try:
util.TimeoutFunction(getattr(gradingModule, q),300)(self) # Call the question's function
#TimeoutFunction(getattr(gradingModule, q),1200)(self) # Call the question's function
except Exception as inst:
self.addExceptionMessage(q, inst, traceback)
self.addErrorHints(exceptionMap, inst, q[1])
except:
self.fail('FAIL: Terminated with a string exception.')
finally:
if self.mute: util.unmutePrint()
if self.points[q] >= self.maxes[q]:
completedQuestions.add(q)
print('\n### Question %s: %d/%d ###\n' % (q, self.points[q], self.maxes[q]))
print('\nFinished at %d:%02d:%02d' % time.localtime()[3:6])
print("\nProvisional grades\n==================")
for q in self.questions:
print('Question %s: %d/%d' % (q, self.points[q], self.maxes[q]))
print('------------------')
print('Total: %d/%d' % (self.points.totalCount(), sum(self.maxes.values())))
if bonusPic and self.points.totalCount() == 25:
print("""
ALL HAIL GRANDPAC.
LONG LIVE THE GHOSTBUSTING KING.
--- ---- ---
| \ / + \ / |
| + \--/ \--/ + |
| + + |
| + + + |
@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
\ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
\ / @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
V \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@
\ / @@@@@@@@@@@@@@@@@@@@@@@@@@
V @@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@
/\ @@@@@@@@@@@@@@@@@@@@@@
/ \ @@@@@@@@@@@@@@@@@@@@@@@@@
/\ / @@@@@@@@@@@@@@@@@@@@@@@@@@@
/ \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
/ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@
""")
print("""
Your grades are NOT yet registered. To register your grades, make sure
to follow your instructor's guidelines to receive credit on your project.
""")
if self.edxOutput:
self.produceOutput()
def addExceptionMessage(self, q, inst, traceback):
"""
Method to format the exception message, this is more complicated because
we need to html.escape the traceback but wrap the exception in a <pre> tag
"""
self.fail('FAIL: Exception raised: %s' % inst)
self.addMessage('')
for line in traceback.format_exc().split('\n'):
self.addMessage(line)
def addErrorHints(self, exceptionMap, errorInstance, questionNum):
typeOf = str(type(errorInstance))
questionName = 'q' + questionNum
errorHint = ''
# question specific error hints
if exceptionMap.get(questionName):
questionMap = exceptionMap.get(questionName)
if (questionMap.get(typeOf)):
errorHint = questionMap.get(typeOf)
# fall back to general error messages if a question specific
# one does not exist
if (exceptionMap.get(typeOf)):
errorHint = exceptionMap.get(typeOf)
# dont include the HTML if we have no error hint
if not errorHint:
return ''
for line in errorHint.split('\n'):
self.addMessage(line)
def produceOutput(self):
edxOutput = open('edx_response.html', 'w')
edxOutput.write("<div>")
# first sum
total_possible = sum(self.maxes.values())
total_score = sum(self.points.values())
checkOrX = '<span class="incorrect"/>'
if (total_score >= total_possible):
checkOrX = '<span class="correct"/>'
header = """
<h3>
Total score ({total_score} / {total_possible})
</h3>
""".format(total_score = total_score,
total_possible = total_possible,
checkOrX = checkOrX
)
edxOutput.write(header)
for q in self.questions:
if len(q) == 2:
name = q[1]
else:
name = q
checkOrX = '<span class="incorrect"/>'
if (self.points[q] == self.maxes[q]):
checkOrX = '<span class="correct"/>'
#messages = '\n<br/>\n'.join(self.messages[q])
messages = "<pre>%s</pre>" % '\n'.join(self.messages[q])
output = """
<div class="test">
<section>
<div class="shortform">
Question {q} ({points}/{max}) {checkOrX}
</div>
<div class="longform">
{messages}
</div>
</section>
</div>
""".format(q = name,
max = self.maxes[q],
messages = messages,
checkOrX = checkOrX,
points = self.points[q]
)
# print "*** output for Question %s " % q[1]
# print output
edxOutput.write(output)
edxOutput.write("</div>")
edxOutput.close()
edxOutput = open('edx_grade', 'w')
edxOutput.write(str(self.points.totalCount()))
edxOutput.close()
def fail(self, message, raw=False):
"Sets sanity check bit to false and outputs a message"
self.sane = False
self.assignZeroCredit()
self.addMessage(message, raw)
def assignZeroCredit(self):
self.points[self.currentQuestion] = 0
def addPoints(self, amt):
self.points[self.currentQuestion] += amt
def deductPoints(self, amt):
self.points[self.currentQuestion] -= amt
def assignFullCredit(self, message="", raw=False):
self.points[self.currentQuestion] = self.maxes[self.currentQuestion]
if message != "":
self.addMessage(message, raw)
def addMessage(self, message, raw=False):
if not raw:
# We assume raw messages, formatted for HTML, are printed separately
if self.mute: util.unmutePrint()
print('*** ' + message)
if self.mute: util.mutePrint()
message = html.escape(message)
self.messages[self.currentQuestion].append(message)
def addMessageToEmail(self, message):
print("WARNING**** addMessageToEmail is deprecated %s" % message)
for line in message.split('\n'):
pass
#print '%%% ' + line + ' %%%'
#self.messages[self.currentQuestion].append(line)
class Counter(dict):
"""
Dict with default 0
"""
def __getitem__(self, idx):
try:
return dict.__getitem__(self, idx)
except KeyError:
return 0
def totalCount(self):
"""
Returns the sum of counts for all keys.
"""
return sum(self.values())
| 32.943262 | 99 | 0.557266 |
import html
import time
import sys
import traceback
import pdb
from collections import defaultdict
import util
class Grades:
def __init__(self, projectName, questionsAndMaxesList, edxOutput=False, muteOutput=False):
self.questions = [el[0] for el in questionsAndMaxesList]
self.maxes = dict(questionsAndMaxesList)
self.points = Counter()
self.messages = dict([(q, []) for q in self.questions])
self.project = projectName
self.start = time.localtime()[1:6]
self.sane = True
self.currentQuestion = None
self.edxOutput = edxOutput
self.mute = muteOutput
self.prereqs = defaultdict(set)
#print 'Autograder transcript for %s' % self.project
print('Starting on %d-%d at %d:%02d:%02d' % self.start)
def addPrereq(self, question, prereq):
self.prereqs[question].add(prereq)
def grade(self, gradingModule, exceptionMap = {}, bonusPic = False):
completedQuestions = set([])
for q in self.questions:
print('\nQuestion %s' % q)
print('=' * (9 + len(q)))
print()
self.currentQuestion = q
incompleted = self.prereqs[q].difference(completedQuestions)
if len(incompleted) > 0:
prereq = incompleted.pop()
print("""*** NOTE: Make sure to complete Question %s before working on Question %s,
*** because Question %s builds upon your answer for Question %s.
""" % (prereq, q, q, prereq))
continue
if self.mute: util.mutePrint()
try:
util.TimeoutFunction(getattr(gradingModule, q),300)(self) # Call the question's function
t:
self.addExceptionMessage(q, inst, traceback)
self.addErrorHints(exceptionMap, inst, q[1])
except:
self.fail('FAIL: Terminated with a string exception.')
finally:
if self.mute: util.unmutePrint()
if self.points[q] >= self.maxes[q]:
completedQuestions.add(q)
print('\nint('Total: %d/%d' % (self.points.totalCount(), sum(self.maxes.values())))
if bonusPic and self.points.totalCount() == 25:
print("""
ALL HAIL GRANDPAC.
LONG LIVE THE GHOSTBUSTING KING.
--- ---- ---
| \ / + \ / |
| + \--/ \--/ + |
| + + |
| + + + |
@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
\ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
\ / @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
V \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@
\ / @@@@@@@@@@@@@@@@@@@@@@@@@@
V @@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@
/\ @@@@@@@@@@@@@@@@@@@@@@
/ \ @@@@@@@@@@@@@@@@@@@@@@@@@
/\ / @@@@@@@@@@@@@@@@@@@@@@@@@@@
/ \ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
/ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@
""")
print("""
Your grades are NOT yet registered. To register your grades, make sure
to follow your instructor's guidelines to receive credit on your project.
""")
if self.edxOutput:
self.produceOutput()
def addExceptionMessage(self, q, inst, traceback):
self.fail('FAIL: Exception raised: %s' % inst)
self.addMessage('')
for line in traceback.format_exc().split('\n'):
self.addMessage(line)
def addErrorHints(self, exceptionMap, errorInstance, questionNum):
typeOf = str(type(errorInstance))
questionName = 'q' + questionNum
errorHint = ''
if exceptionMap.get(questionName):
questionMap = exceptionMap.get(questionName)
if (questionMap.get(typeOf)):
errorHint = questionMap.get(typeOf)
if (exceptionMap.get(typeOf)):
errorHint = exceptionMap.get(typeOf)
if not errorHint:
return ''
for line in errorHint.split('\n'):
self.addMessage(line)
def produceOutput(self):
edxOutput = open('edx_response.html', 'w')
edxOutput.write("<div>")
total_possible = sum(self.maxes.values())
total_score = sum(self.points.values())
checkOrX = '<span class="incorrect"/>'
if (total_score >= total_possible):
checkOrX = '<span class="correct"/>'
header = """
<h3>
Total score ({total_score} / {total_possible})
</h3>
""".format(total_score = total_score,
total_possible = total_possible,
checkOrX = checkOrX
)
edxOutput.write(header)
for q in self.questions:
if len(q) == 2:
name = q[1]
else:
name = q
checkOrX = '<span class="incorrect"/>'
if (self.points[q] == self.maxes[q]):
checkOrX = '<span class="correct"/>'
messages = "<pre>%s</pre>" % '\n'.join(self.messages[q])
output = """
<div class="test">
<section>
<div class="shortform">
Question {q} ({points}/{max}) {checkOrX}
</div>
<div class="longform">
{messages}
</div>
</section>
</div>
""".format(q = name,
max = self.maxes[q],
messages = messages,
checkOrX = checkOrX,
points = self.points[q]
)
edxOutput.write(output)
edxOutput.write("</div>")
edxOutput.close()
edxOutput = open('edx_grade', 'w')
edxOutput.write(str(self.points.totalCount()))
edxOutput.close()
def fail(self, message, raw=False):
self.sane = False
self.assignZeroCredit()
self.addMessage(message, raw)
def assignZeroCredit(self):
self.points[self.currentQuestion] = 0
def addPoints(self, amt):
self.points[self.currentQuestion] += amt
def deductPoints(self, amt):
self.points[self.currentQuestion] -= amt
def assignFullCredit(self, message="", raw=False):
self.points[self.currentQuestion] = self.maxes[self.currentQuestion]
if message != "":
self.addMessage(message, raw)
def addMessage(self, message, raw=False):
if not raw:
if self.mute: util.unmutePrint()
print('*** ' + message)
if self.mute: util.mutePrint()
message = html.escape(message)
self.messages[self.currentQuestion].append(message)
def addMessageToEmail(self, message):
print("WARNING**** addMessageToEmail is deprecated %s" % message)
for line in message.split('\n'):
pass
class Counter(dict):
def __getitem__(self, idx):
try:
return dict.__getitem__(self, idx)
except KeyError:
return 0
def totalCount(self):
return sum(self.values())
| true | true |
f7f7509c12387da9c3493856e291768b196daa46 | 12,568 | py | Python | sdk/python/pulumi_azure/eventhub/namespace.py | suresh198526/pulumi-azure | bf27206a38d7a5c58b3c2c57ec8769fe3d0fc5d7 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_azure/eventhub/namespace.py | suresh198526/pulumi-azure | bf27206a38d7a5c58b3c2c57ec8769fe3d0fc5d7 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_azure/eventhub/namespace.py | suresh198526/pulumi-azure | bf27206a38d7a5c58b3c2c57ec8769fe3d0fc5d7 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilities, _tables
__all__ = ['Namespace']
warnings.warn("""azure.eventhub.Namespace has been deprecated in favor of azure.servicebus.Namespace""", DeprecationWarning)
class Namespace(pulumi.CustomResource):
warnings.warn("""azure.eventhub.Namespace has been deprecated in favor of azure.servicebus.Namespace""", DeprecationWarning)
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
capacity: Optional[pulumi.Input[int]] = None,
location: Optional[pulumi.Input[str]] = None,
name: Optional[pulumi.Input[str]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
sku: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
zone_redundant: Optional[pulumi.Input[bool]] = None,
__props__=None,
__name__=None,
__opts__=None):
"""
Manages a ServiceBus Namespace.
## Example Usage
```python
import pulumi
import pulumi_azure as azure
example_resource_group = azure.core.ResourceGroup("exampleResourceGroup", location="West Europe")
example_namespace = azure.servicebus.Namespace("exampleNamespace",
location=example_resource_group.location,
resource_group_name=example_resource_group.name,
sku="Standard",
tags={
"source": "example",
})
```
## Import
Service Bus Namespace can be imported using the `resource id`, e.g.
```sh
$ pulumi import azure:eventhub/namespace:Namespace example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mygroup1/providers/microsoft.servicebus/namespaces/sbns1
```
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[int] capacity: Specifies the capacity. When `sku` is `Premium`, capacity can be `1`, `2`, `4` or `8`. When `sku` is `Basic` or `Standard`, capacity can be `0` only.
:param pulumi.Input[str] location: Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created.
:param pulumi.Input[str] name: Specifies the name of the ServiceBus Namespace resource . Changing this forces a
new resource to be created.
:param pulumi.Input[str] resource_group_name: The name of the resource group in which to
create the namespace.
:param pulumi.Input[str] sku: Defines which tier to use. Options are basic, standard or premium. Changing this forces a new resource to be created.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: A mapping of tags to assign to the resource.
:param pulumi.Input[bool] zone_redundant: Whether or not this resource is zone redundant. `sku` needs to be `Premium`. Defaults to `false`.
"""
pulumi.log.warn("Namespace is deprecated: azure.eventhub.Namespace has been deprecated in favor of azure.servicebus.Namespace")
if __name__ is not None:
warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning)
resource_name = __name__
if __opts__ is not None:
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = dict()
__props__['capacity'] = capacity
__props__['location'] = location
__props__['name'] = name
if resource_group_name is None:
raise TypeError("Missing required property 'resource_group_name'")
__props__['resource_group_name'] = resource_group_name
if sku is None:
raise TypeError("Missing required property 'sku'")
__props__['sku'] = sku
__props__['tags'] = tags
__props__['zone_redundant'] = zone_redundant
__props__['default_primary_connection_string'] = None
__props__['default_primary_key'] = None
__props__['default_secondary_connection_string'] = None
__props__['default_secondary_key'] = None
super(Namespace, __self__).__init__(
'azure:eventhub/namespace:Namespace',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None,
capacity: Optional[pulumi.Input[int]] = None,
default_primary_connection_string: Optional[pulumi.Input[str]] = None,
default_primary_key: Optional[pulumi.Input[str]] = None,
default_secondary_connection_string: Optional[pulumi.Input[str]] = None,
default_secondary_key: Optional[pulumi.Input[str]] = None,
location: Optional[pulumi.Input[str]] = None,
name: Optional[pulumi.Input[str]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
sku: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
zone_redundant: Optional[pulumi.Input[bool]] = None) -> 'Namespace':
"""
Get an existing Namespace resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[int] capacity: Specifies the capacity. When `sku` is `Premium`, capacity can be `1`, `2`, `4` or `8`. When `sku` is `Basic` or `Standard`, capacity can be `0` only.
:param pulumi.Input[str] default_primary_connection_string: The primary connection string for the authorization
rule `RootManageSharedAccessKey`.
:param pulumi.Input[str] default_primary_key: The primary access key for the authorization rule `RootManageSharedAccessKey`.
:param pulumi.Input[str] default_secondary_connection_string: The secondary connection string for the
authorization rule `RootManageSharedAccessKey`.
:param pulumi.Input[str] default_secondary_key: The secondary access key for the authorization rule `RootManageSharedAccessKey`.
:param pulumi.Input[str] location: Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created.
:param pulumi.Input[str] name: Specifies the name of the ServiceBus Namespace resource . Changing this forces a
new resource to be created.
:param pulumi.Input[str] resource_group_name: The name of the resource group in which to
create the namespace.
:param pulumi.Input[str] sku: Defines which tier to use. Options are basic, standard or premium. Changing this forces a new resource to be created.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: A mapping of tags to assign to the resource.
:param pulumi.Input[bool] zone_redundant: Whether or not this resource is zone redundant. `sku` needs to be `Premium`. Defaults to `false`.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = dict()
__props__["capacity"] = capacity
__props__["default_primary_connection_string"] = default_primary_connection_string
__props__["default_primary_key"] = default_primary_key
__props__["default_secondary_connection_string"] = default_secondary_connection_string
__props__["default_secondary_key"] = default_secondary_key
__props__["location"] = location
__props__["name"] = name
__props__["resource_group_name"] = resource_group_name
__props__["sku"] = sku
__props__["tags"] = tags
__props__["zone_redundant"] = zone_redundant
return Namespace(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter
def capacity(self) -> pulumi.Output[Optional[int]]:
"""
Specifies the capacity. When `sku` is `Premium`, capacity can be `1`, `2`, `4` or `8`. When `sku` is `Basic` or `Standard`, capacity can be `0` only.
"""
return pulumi.get(self, "capacity")
@property
@pulumi.getter(name="defaultPrimaryConnectionString")
def default_primary_connection_string(self) -> pulumi.Output[str]:
"""
The primary connection string for the authorization
rule `RootManageSharedAccessKey`.
"""
return pulumi.get(self, "default_primary_connection_string")
@property
@pulumi.getter(name="defaultPrimaryKey")
def default_primary_key(self) -> pulumi.Output[str]:
"""
The primary access key for the authorization rule `RootManageSharedAccessKey`.
"""
return pulumi.get(self, "default_primary_key")
@property
@pulumi.getter(name="defaultSecondaryConnectionString")
def default_secondary_connection_string(self) -> pulumi.Output[str]:
"""
The secondary connection string for the
authorization rule `RootManageSharedAccessKey`.
"""
return pulumi.get(self, "default_secondary_connection_string")
@property
@pulumi.getter(name="defaultSecondaryKey")
def default_secondary_key(self) -> pulumi.Output[str]:
"""
The secondary access key for the authorization rule `RootManageSharedAccessKey`.
"""
return pulumi.get(self, "default_secondary_key")
@property
@pulumi.getter
def location(self) -> pulumi.Output[str]:
"""
Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created.
"""
return pulumi.get(self, "location")
@property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
"""
Specifies the name of the ServiceBus Namespace resource . Changing this forces a
new resource to be created.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="resourceGroupName")
def resource_group_name(self) -> pulumi.Output[str]:
"""
The name of the resource group in which to
create the namespace.
"""
return pulumi.get(self, "resource_group_name")
@property
@pulumi.getter
def sku(self) -> pulumi.Output[str]:
"""
Defines which tier to use. Options are basic, standard or premium. Changing this forces a new resource to be created.
"""
return pulumi.get(self, "sku")
@property
@pulumi.getter
def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]:
"""
A mapping of tags to assign to the resource.
"""
return pulumi.get(self, "tags")
@property
@pulumi.getter(name="zoneRedundant")
def zone_redundant(self) -> pulumi.Output[Optional[bool]]:
"""
Whether or not this resource is zone redundant. `sku` needs to be `Premium`. Defaults to `false`.
"""
return pulumi.get(self, "zone_redundant")
def translate_output_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
def translate_input_property(self, prop):
return _tables.SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
| 47.787072 | 192 | 0.660487 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilities, _tables
__all__ = ['Namespace']
warnings.warn("""azure.eventhub.Namespace has been deprecated in favor of azure.servicebus.Namespace""", DeprecationWarning)
class Namespace(pulumi.CustomResource):
warnings.warn("""azure.eventhub.Namespace has been deprecated in favor of azure.servicebus.Namespace""", DeprecationWarning)
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
capacity: Optional[pulumi.Input[int]] = None,
location: Optional[pulumi.Input[str]] = None,
name: Optional[pulumi.Input[str]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
sku: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
zone_redundant: Optional[pulumi.Input[bool]] = None,
__props__=None,
__name__=None,
__opts__=None):
pulumi.log.warn("Namespace is deprecated: azure.eventhub.Namespace has been deprecated in favor of azure.servicebus.Namespace")
if __name__ is not None:
warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning)
resource_name = __name__
if __opts__ is not None:
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = dict()
__props__['capacity'] = capacity
__props__['location'] = location
__props__['name'] = name
if resource_group_name is None:
raise TypeError("Missing required property 'resource_group_name'")
__props__['resource_group_name'] = resource_group_name
if sku is None:
raise TypeError("Missing required property 'sku'")
__props__['sku'] = sku
__props__['tags'] = tags
__props__['zone_redundant'] = zone_redundant
__props__['default_primary_connection_string'] = None
__props__['default_primary_key'] = None
__props__['default_secondary_connection_string'] = None
__props__['default_secondary_key'] = None
super(Namespace, __self__).__init__(
'azure:eventhub/namespace:Namespace',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None,
capacity: Optional[pulumi.Input[int]] = None,
default_primary_connection_string: Optional[pulumi.Input[str]] = None,
default_primary_key: Optional[pulumi.Input[str]] = None,
default_secondary_connection_string: Optional[pulumi.Input[str]] = None,
default_secondary_key: Optional[pulumi.Input[str]] = None,
location: Optional[pulumi.Input[str]] = None,
name: Optional[pulumi.Input[str]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
sku: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
zone_redundant: Optional[pulumi.Input[bool]] = None) -> 'Namespace':
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = dict()
__props__["capacity"] = capacity
__props__["default_primary_connection_string"] = default_primary_connection_string
__props__["default_primary_key"] = default_primary_key
__props__["default_secondary_connection_string"] = default_secondary_connection_string
__props__["default_secondary_key"] = default_secondary_key
__props__["location"] = location
__props__["name"] = name
__props__["resource_group_name"] = resource_group_name
__props__["sku"] = sku
__props__["tags"] = tags
__props__["zone_redundant"] = zone_redundant
return Namespace(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter
def capacity(self) -> pulumi.Output[Optional[int]]:
return pulumi.get(self, "capacity")
@property
@pulumi.getter(name="defaultPrimaryConnectionString")
def default_primary_connection_string(self) -> pulumi.Output[str]:
return pulumi.get(self, "default_primary_connection_string")
@property
@pulumi.getter(name="defaultPrimaryKey")
def default_primary_key(self) -> pulumi.Output[str]:
return pulumi.get(self, "default_primary_key")
@property
@pulumi.getter(name="defaultSecondaryConnectionString")
def default_secondary_connection_string(self) -> pulumi.Output[str]:
return pulumi.get(self, "default_secondary_connection_string")
@property
@pulumi.getter(name="defaultSecondaryKey")
def default_secondary_key(self) -> pulumi.Output[str]:
return pulumi.get(self, "default_secondary_key")
@property
@pulumi.getter
def location(self) -> pulumi.Output[str]:
return pulumi.get(self, "location")
@property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
return pulumi.get(self, "name")
@property
@pulumi.getter(name="resourceGroupName")
def resource_group_name(self) -> pulumi.Output[str]:
return pulumi.get(self, "resource_group_name")
@property
@pulumi.getter
def sku(self) -> pulumi.Output[str]:
return pulumi.get(self, "sku")
@property
@pulumi.getter
def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]:
return pulumi.get(self, "tags")
@property
@pulumi.getter(name="zoneRedundant")
def zone_redundant(self) -> pulumi.Output[Optional[bool]]:
return pulumi.get(self, "zone_redundant")
def translate_output_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
def translate_input_property(self, prop):
return _tables.SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
| true | true |
f7f7517c6272bbbf39f0892d3d627ebf0d939075 | 10,527 | py | Python | ASR_TransV1/Dataloader_for_AM_v3_dev.py | BUTSpeechFIT/ASR_Transformer | 814f720aa8265e9a377869f93dc65b251338e985 | [
"MIT"
] | 1 | 2020-10-25T00:21:40.000Z | 2020-10-25T00:21:40.000Z | ASR_TransV1/Dataloader_for_AM_v3_dev.py | BUTSpeechFIT/ASR_Transformer | 814f720aa8265e9a377869f93dc65b251338e985 | [
"MIT"
] | null | null | null | ASR_TransV1/Dataloader_for_AM_v3_dev.py | BUTSpeechFIT/ASR_Transformer | 814f720aa8265e9a377869f93dc65b251338e985 | [
"MIT"
] | 1 | 2021-09-08T10:32:55.000Z | 2021-09-08T10:32:55.000Z | #!/usr/bin/python
import kaldi_io
import sys
import os
from os.path import join, isdir
from numpy.random import permutation
import itertools
import keras
import numpy as np
from keras.preprocessing.sequence import pad_sequences
import queue
from threading import Thread
import random
import glob
import sys
sys.path.insert(0, '/home/vydana/ASR_Transformer/ASR_TransV1')
import CMVN
from CMVN import CMVN
from Load_sp_model import Load_sp_models
from random import sample
import copy
#===============================================
#-----------------------------------------------
class DataLoader(object):
def __init__(self,files, max_batch_label_len, max_batch_len, max_feat_len, max_label_len, Word_model, Char_model, queue_size=500,apply_cmvn=1):
self.files = files
if self.files==[]:
print('input to data generator in empty')
exit(0)
self.text_file_dict ={}
self.Word_model = Word_model
self.Char_model = Char_model
self.expand_n=40
self.resamp_batches_start_flag=False
self.max_batch_len = max_batch_len
self.max_batch_label_len = max_batch_label_len
self.max_batch_label_len = self.max_batch_label_len
self.max_feat_len = max_feat_len
self.max_label_len = max_label_len
self.apply_cmvn = apply_cmvn
self.queue = queue.Queue(queue_size)
self.Word_padding_id = self.Word_model.__len__()
self.Char_padding_id = self.Char_model.__len__()
self.word_space_token = self.Word_model.EncodeAsIds('_____')[0]
self._thread = Thread(target=self.__load_data)
self._thread.daemon = True
#print(self._thread)
self._thread.start()
#--------------------------------
#self._threads = []
#for i in range(10):
# self._thread = Thread(target=self.__load_data)
# self._thread.daemon = True
# self._thread.start()
# self._threads.append(self._thread)
#for process in self._threads:
# process.join()
#-------------------------------
def __reset_the_data_holders(self):
self.batch_data=[]
self.batch_labels=[]
self.batch_names=[]
self.batch_length=[]
self.batch_label_length=[]
self.batch_word_labels=[]
self.batch_word_label_length=[]
self.batch_word_text=[]
self.batch_word_text_length=[]
self.batch_word_text_tgt=[]
self.batch_word_text_length_tgt=[]
#---------------------------------------------------------------------
def make_batching_dict(self):
#----------------------------------------
smp_feat = pad_sequences(self.batch_data,maxlen=max(self.batch_length),dtype='float32',padding='post',value=0.0)
smp_char_labels = pad_sequences(self.batch_word_labels,maxlen=max(self.batch_word_label_length),dtype='int32',padding='post',value=self.Word_padding_id)
smp_word_label = pad_sequences(self.batch_word_labels,maxlen=max(self.batch_word_label_length),dtype='int32',padding='post',value=self.Word_padding_id)
smp_trans_text = pad_sequences(self.batch_word_text_tgt, maxlen=max(self.batch_word_text_length_tgt),dtype=object,padding='post',value=' ')
smp_trans_text_tgt = pad_sequences(self.batch_word_text_tgt, maxlen=max(self.batch_word_text_length_tgt),dtype=object,padding='post',value=' ')
batch_data_dict={
'smp_names':self.batch_names,
'smp_feat':smp_feat,
'smp_char_label':smp_char_labels,
'smp_word_label':smp_word_label,
'smp_trans_text':smp_trans_text,
'smp_trans_text_tgt': smp_trans_text_tgt,
'smp_feat_length':self.batch_length,
'smp_label_length':self.batch_label_length,
'smp_word_label_length':self.batch_word_label_length,
'smp_word_text_length':self.batch_word_text_length,
'smp_word_text_length_tgt':self.batch_word_text_length_tgt}
return batch_data_dict
#------------------------------------------
def __load_data(self):
###initilize the lists
while True:
self.__reset_the_data_holders()
max_batch_label_len = self.max_batch_label_len
random.shuffle(self.files)
for inp_file in self.files:
#print(inp_file)
with open(inp_file) as f:
for line in f:
#print('---->',line)
#============================
split_lines=line.split(' @@@@ ')
#============================
##assigining
key = split_lines[0]
#print(key)
scp_path = split_lines[1]
#============================
### Char labels
#============================
src_text = split_lines[3]
src_tok = split_lines[4]
#=============================
if len(src_tok)>0:
src_tok = [int(i) for i in src_tok.split(' ')]
else:
continue;
#============================
word_tokens = src_tok
##*********#########*************
###CHanged to match the JOint training
word_labels = src_text.split(' ')
##*********#########*************
#--------------------------
if not (scp_path == 'None'):
mat = kaldi_io.read_mat(scp_path)
if self.apply_cmvn:
mat = CMVN(mat)
#print(key,mat.shape)
else:
mat=np.zeros((100,249),dtype=np.float32)
#--------------------------
if (mat.shape[0]>self.max_feat_len) or (mat.shape[0]<len(word_labels)) or (len(word_tokens) > self.max_label_len):
#print("key,mat.shape,char_labels,char_tokens,self.max_label_len",key,mat.shape,len(char_labels),len(char_tokens),self.max_label_len)
continue;
#==============================================================
###Add to the list
####
self.batch_data.append(mat)
self.batch_names.append(key)
self.batch_length.append(mat.shape[0])
self.batch_word_labels.append(word_tokens)
self.batch_word_label_length.append(len(word_tokens))
self.batch_word_text_tgt.append(word_labels)
self.batch_word_text_length_tgt.append(len(word_labels))
#==============================================================
#==============================================================
# total_labels_in_batch is used to keep track of the length of sequences in a batch, just make sure it does not overflow the gpu
##in general lstm training we are not using this because self.max_batch_len will be around 10-20 and self.max_batch_label_len is usuvally set very high
expect_len_of_features = max(max(self.batch_length,default=0), mat.shape[0])
expect_len_of_labels = max(max(self.batch_word_label_length, default=0),len(word_tokens))
total_labels_in_batch = (expect_len_of_features + expect_len_of_labels)*(len(self.batch_names)+4)
#print(expect_len_of_features,expect_len_of_labels,total_labels_in_batch,self.max_batch_label_len)
###check if ypu have enough labels output and if you have then push to the queue
###else keep adding them to the lists
###if the queue has less than three batches and the next batch is not ready yet fill them with reampleed batches
if (total_labels_in_batch > self.max_batch_label_len) or (len(self.batch_data)==self.max_batch_len):
batch_data_dict = self.make_batching_dict()
self.queue.put(batch_data_dict)
self.__reset_the_data_holders()
if len(self.batch_names)>0:
### Collect the left over stuff as the last batch
#-----------------------------------------------
batch_data_dict = self.make_batching_dict()
self.queue.put(batch_data_dict)
def next(self, timeout=3000):
return self.queue.get(block=True, timeout=timeout)
#===================================================================
# sys.path.insert(0,'/mnt/matylda3/vydana/HOW2_EXP/KAT_Attention')
# import Attention_arg
# from Attention_arg import parser
# args = parser.parse_args()
# print(args)
# ###debugger
# args.Word_model_path='/mnt/matylda3/vydana/benchmarking_datasets/Timit/models/Timit_PHSEQ_100/Timit_PHSEQ__100__word.model'
# args.Char_model_path='/mnt/matylda3/vydana/benchmarking_datasets/Timit/models/Timit_PHSEQ_100/Timit_PHSEQ__100__word.model'
# args.text_file = '/mnt/matylda3/vydana/benchmarking_datasets/Timit/All_text'
# args.train_path='/mnt/matylda3/vydana/benchmarking_datasets/Timit/scp_files/train/'
# args.dev_path='/mnt/matylda3/vydana/benchmarking_datasets/Timit/scp_files/dev/'
# Word_model=Load_sp_models(args.Word_model_path)
# Char_model=Load_sp_models(args.Char_model_path)
# train_gen = DataLoader(files=glob.glob(args.train_path + "*"),max_batch_label_len=20000, max_batch_len=4,max_feat_len=2000,max_label_len=200,Word_model=Word_model,Char_model=Char_model,text_file=args.text_file)
# for i in range(10):
# B1 = train_gen.next()
# print(B1.keys())
# #breakpoint()
| 45.969432 | 212 | 0.533295 |
import kaldi_io
import sys
import os
from os.path import join, isdir
from numpy.random import permutation
import itertools
import keras
import numpy as np
from keras.preprocessing.sequence import pad_sequences
import queue
from threading import Thread
import random
import glob
import sys
sys.path.insert(0, '/home/vydana/ASR_Transformer/ASR_TransV1')
import CMVN
from CMVN import CMVN
from Load_sp_model import Load_sp_models
from random import sample
import copy
class DataLoader(object):
def __init__(self,files, max_batch_label_len, max_batch_len, max_feat_len, max_label_len, Word_model, Char_model, queue_size=500,apply_cmvn=1):
self.files = files
if self.files==[]:
print('input to data generator in empty')
exit(0)
self.text_file_dict ={}
self.Word_model = Word_model
self.Char_model = Char_model
self.expand_n=40
self.resamp_batches_start_flag=False
self.max_batch_len = max_batch_len
self.max_batch_label_len = max_batch_label_len
self.max_batch_label_len = self.max_batch_label_len
self.max_feat_len = max_feat_len
self.max_label_len = max_label_len
self.apply_cmvn = apply_cmvn
self.queue = queue.Queue(queue_size)
self.Word_padding_id = self.Word_model.__len__()
self.Char_padding_id = self.Char_model.__len__()
self.word_space_token = self.Word_model.EncodeAsIds('_____')[0]
self._thread = Thread(target=self.__load_data)
self._thread.daemon = True
self._thread.start()
def __reset_the_data_holders(self):
self.batch_data=[]
self.batch_labels=[]
self.batch_names=[]
self.batch_length=[]
self.batch_label_length=[]
self.batch_word_labels=[]
self.batch_word_label_length=[]
self.batch_word_text=[]
self.batch_word_text_length=[]
self.batch_word_text_tgt=[]
self.batch_word_text_length_tgt=[]
def make_batching_dict(self):
smp_feat = pad_sequences(self.batch_data,maxlen=max(self.batch_length),dtype='float32',padding='post',value=0.0)
smp_char_labels = pad_sequences(self.batch_word_labels,maxlen=max(self.batch_word_label_length),dtype='int32',padding='post',value=self.Word_padding_id)
smp_word_label = pad_sequences(self.batch_word_labels,maxlen=max(self.batch_word_label_length),dtype='int32',padding='post',value=self.Word_padding_id)
smp_trans_text = pad_sequences(self.batch_word_text_tgt, maxlen=max(self.batch_word_text_length_tgt),dtype=object,padding='post',value=' ')
smp_trans_text_tgt = pad_sequences(self.batch_word_text_tgt, maxlen=max(self.batch_word_text_length_tgt),dtype=object,padding='post',value=' ')
batch_data_dict={
'smp_names':self.batch_names,
'smp_feat':smp_feat,
'smp_char_label':smp_char_labels,
'smp_word_label':smp_word_label,
'smp_trans_text':smp_trans_text,
'smp_trans_text_tgt': smp_trans_text_tgt,
'smp_feat_length':self.batch_length,
'smp_label_length':self.batch_label_length,
'smp_word_label_length':self.batch_word_label_length,
'smp_word_text_length':self.batch_word_text_length,
'smp_word_text_length_tgt':self.batch_word_text_length_tgt}
return batch_data_dict
def __load_data(self):
eset_the_data_holders()
max_batch_label_len = self.max_batch_label_len
random.shuffle(self.files)
for inp_file in self.files:
with open(inp_file) as f:
for line in f:
split_lines=line.split(' @@@@ ')
key = split_lines[0]
scp_path = split_lines[1]
src_text = split_lines[3]
src_tok = split_lines[4]
if len(src_tok)>0:
src_tok = [int(i) for i in src_tok.split(' ')]
else:
continue;
word_tokens = src_tok
if (mat.shape[0]>self.max_feat_len) or (mat.shape[0]<len(word_labels)) or (len(word_tokens) > self.max_label_len):
continue;
self.batch_data.append(mat)
self.batch_names.append(key)
self.batch_length.append(mat.shape[0])
self.batch_word_labels.append(word_tokens)
self.batch_word_label_length.append(len(word_tokens))
self.batch_word_text_tgt.append(word_labels)
self.batch_word_text_length_tgt.append(len(word_labels))
bel_length, default=0),len(word_tokens))
total_labels_in_batch = (expect_len_of_features + expect_len_of_labels)*(len(self.batch_names)+4)
data_holders()
if len(self.batch_names)>0:
f.queue.put(batch_data_dict)
def next(self, timeout=3000):
return self.queue.get(block=True, timeout=timeout)
| true | true |
f7f7519652b4dd1057c2877c1a69a72c9a4f8e67 | 2,366 | py | Python | lxmls/classifiers/mira.py | SimonSuster/lxmls-toolkit | 6a57884f8b7c98da816a60eb88593e0a1585d434 | [
"MIT"
] | 1 | 2015-09-20T05:16:38.000Z | 2015-09-20T05:16:38.000Z | lxmls/classifiers/mira.py | daviddao/LxMLS-labs-solution | 78413c1ee61752ca33988c454e3b2c27326e7063 | [
"MIT"
] | null | null | null | lxmls/classifiers/mira.py | daviddao/LxMLS-labs-solution | 78413c1ee61752ca33988c454e3b2c27326e7063 | [
"MIT"
] | null | null | null | import sys
import numpy as np
import lxmls.classifiers.linear_classifier as lc
from lxmls.util.my_math_utils import *
class Mira(lc.LinearClassifier):
def __init__(self,nr_rounds = 10,regularizer = 1.0, averaged = True):
lc.LinearClassifier.__init__(self)
self.trained = False
self.nr_rounds = nr_rounds
self.regularizer = regularizer
self.params_per_round = []
self.averaged = averaged
def train(self,x,y):
self.params_per_round = []
x_orig = x[:,:]
x = self.add_intercept_term(x)
nr_x,nr_f = x.shape
nr_c = np.unique(y).shape[0]
w = np.zeros((nr_f,nr_c))
## Randomize the examples
perm = np.random.permutation(nr_x)
for round_nr in xrange(self.nr_rounds):
for nr in xrange(nr_x):
inst = perm[nr]
scores = self.get_scores(x[inst:inst+1,:],w)
y_true = y[inst:inst+1,0]
y_hat = self.get_label(x[inst:inst+1,:],w)
true_margin = scores[:,y_true]
predicted_margin = scores[:,y_hat]
dist = np.abs(y_true-y_hat)
## Compute loss
loss = predicted_margin - true_margin + dist
## Compute stepsize
if(y_hat != y_true):
if( predicted_margin == true_margin):
stepsize = 1/self.regularizer
else:
#stepsize = np.min([1/self.agress,loss/l2norm_squared(true_margin-predicted_margin)])
stepsize = np.min([1/self.regularizer,loss/l2norm_squared(x[inst:inst+1])])
w[:,y_true] += stepsize*x[inst:inst+1,:].transpose()
w[:,y_hat] -= stepsize*x[inst:inst+1,:].transpose()
self.params_per_round.append(w.copy())
self.trained = True
y_pred = self.test(x_orig,w)
acc = self.evaluate(y,y_pred)
self.trained = False
print "Rounds: %i Accuracy: %f" %( round_nr,acc)
self.trained = True
if(self.averaged == True):
new_w = 0
for old_w in self.params_per_round:
new_w += old_w
new_w = new_w / len(self.params_per_round)
return new_w
return w
| 38.16129 | 109 | 0.536348 | import sys
import numpy as np
import lxmls.classifiers.linear_classifier as lc
from lxmls.util.my_math_utils import *
class Mira(lc.LinearClassifier):
def __init__(self,nr_rounds = 10,regularizer = 1.0, averaged = True):
lc.LinearClassifier.__init__(self)
self.trained = False
self.nr_rounds = nr_rounds
self.regularizer = regularizer
self.params_per_round = []
self.averaged = averaged
def train(self,x,y):
self.params_per_round = []
x_orig = x[:,:]
x = self.add_intercept_term(x)
nr_x,nr_f = x.shape
nr_c = np.unique(y).shape[0]
w = np.zeros((nr_f,nr_c))
m.permutation(nr_x)
for round_nr in xrange(self.nr_rounds):
for nr in xrange(nr_x):
inst = perm[nr]
scores = self.get_scores(x[inst:inst+1,:],w)
y_true = y[inst:inst+1,0]
y_hat = self.get_label(x[inst:inst+1,:],w)
true_margin = scores[:,y_true]
predicted_margin = scores[:,y_hat]
dist = np.abs(y_true-y_hat)
loss = predicted_margin - true_margin + dist
f(y_hat != y_true):
if( predicted_margin == true_margin):
stepsize = 1/self.regularizer
else:
stepsize = np.min([1/self.regularizer,loss/l2norm_squared(x[inst:inst+1])])
w[:,y_true] += stepsize*x[inst:inst+1,:].transpose()
w[:,y_hat] -= stepsize*x[inst:inst+1,:].transpose()
self.params_per_round.append(w.copy())
self.trained = True
y_pred = self.test(x_orig,w)
acc = self.evaluate(y,y_pred)
self.trained = False
print "Rounds: %i Accuracy: %f" %( round_nr,acc)
self.trained = True
if(self.averaged == True):
new_w = 0
for old_w in self.params_per_round:
new_w += old_w
new_w = new_w / len(self.params_per_round)
return new_w
return w
| false | true |
f7f751eb5a1a3a813fcef511924ca68864fa3ff2 | 18,483 | py | Python | pydefect/tests/cli/vasp/test_main_function.py | KazMorita/pydefect | 681e4bfe92c53edfe8b50cb72768114b28daabc9 | [
"MIT"
] | 1 | 2021-09-10T05:07:39.000Z | 2021-09-10T05:07:39.000Z | pydefect/tests/cli/vasp/test_main_function.py | obaica/pydefect-1 | 31e5ad774845f436554ef15000b8eba3b168a65c | [
"MIT"
] | null | null | null | pydefect/tests/cli/vasp/test_main_function.py | obaica/pydefect-1 | 31e5ad774845f436554ef15000b8eba3b168a65c | [
"MIT"
] | 1 | 2022-01-07T10:14:16.000Z | 2022-01-07T10:14:16.000Z | # -*- coding: utf-8 -*-
# Copyright (c) 2020. Distributed under the terms of the MIT License.
from argparse import Namespace
from pathlib import Path
import numpy as np
import pytest
from monty.serialization import loadfn
from pydefect.analyzer.band_edge_states import EdgeCharacters, BandEdgeStates
from pydefect.analyzer.calc_results import CalcResults
from pydefect.analyzer.unitcell import Unitcell
from pydefect.cli.vasp.main_function import make_supercell, make_defect_set, \
make_defect_entries, make_unitcell, make_competing_phase_dirs, \
make_chem_pot_diag, make_calc_results, print_file, \
make_efnv_correction_from_vasp, make_defect_formation_energy, \
make_defect_eigenvalues, make_edge_characters, \
append_interstitial_to_supercell_info, pop_interstitial_from_supercell_info, \
plot_chem_pot_diag, make_gkfo_correction_from_vasp
from pydefect.corrections.efnv_correction import \
ExtendedFnvCorrection
from pydefect.defaults import defaults
from pydefect.input_maker.defect import SimpleDefect
from pydefect.input_maker.defect_entry import DefectEntry
from pydefect.input_maker.defect_set import DefectSet
from pymatgen import IStructure, Composition, Structure, Lattice, Element
from pymatgen.io.vasp import Vasprun, Outcar
def test_print():
args = Namespace(obj="a")
print_file(args)
def test_make_unitcell(mocker):
vasprun_band_mock = mocker.Mock(spec=Vasprun, autospec=True)
outcar_band_mock = mocker.Mock(spec=Outcar, autospec=True)
outcar_dielectric_mock = mocker.Mock(spec=Outcar, autospec=True)
args = Namespace(vasprun_band=vasprun_band_mock,
outcar_band=outcar_band_mock,
outcar_dielectric_clamped=outcar_dielectric_mock,
outcar_dielectric_ionic=outcar_dielectric_mock)
mock = mocker.patch("pydefect.cli.vasp.main_function.make_unitcell_from_vasp")
mock.return_value = Unitcell(vbm=1.0,
cbm=2.0,
ele_dielectric_const=np.eye(3),
ion_dielectric_const=np.eye(3))
make_unitcell(args)
mock.assert_called_once_with(vasprun_band=vasprun_band_mock,
outcar_band=outcar_band_mock,
outcar_dielectric_clamped=outcar_dielectric_mock,
outcar_dielectric_ionic=outcar_dielectric_mock)
def test_make_competing_phase_dirs(mocker):
args = Namespace(elements=["Mg", "O"],
e_above_hull=0.1)
mock = mocker.patch("pydefect.cli.vasp.main_function.MpQuery")
mock_make = mocker.patch("pydefect.cli.vasp.main_function.make_poscars_from_query")
make_competing_phase_dirs(args)
mock.assert_called_once_with(element_list=args.elements,
e_above_hull=args.e_above_hull)
mock_make.assert_called_once_with(materials_query=mock.return_value.materials, path=Path.cwd())
def test_make_chem_pot_diag(mocker, tmpdir):
def side_effect(key):
mock_vasprun = mocker.Mock()
if key == Path("Mg") / defaults.vasprun:
mock_vasprun.final_structure.composition = Composition("Mg2")
mock_vasprun.final_energy = -10
elif key == Path("O") / defaults.vasprun:
mock_vasprun.final_structure.composition = Composition("O2")
mock_vasprun.final_energy = -20
elif key == Path("MgO") / defaults.vasprun:
mock_vasprun.final_structure.composition = Composition("MgO")
mock_vasprun.final_energy = -30
elif key == Path("Al") / defaults.vasprun:
mock_vasprun.final_structure.composition = Composition("Al")
mock_vasprun.final_energy = 0
elif key == Path("MgAl2O4") / defaults.vasprun:
mock_vasprun.final_structure.composition = Composition("MgAl2O4")
mock_vasprun.final_energy = -70
else:
raise ValueError
return mock_vasprun
tmpdir.chdir()
mock = mocker.patch("pydefect.cli.vasp.main_function.Vasprun", side_effect=side_effect)
args_1 = Namespace(elements=None, functional=None, yaml="cpd.yaml", update=False,
dirs=[Path("Mg"), Path("MgO"), Path("O"), Path("Al"), Path("MgAl2O4")],
target=Composition("MgO"))
make_chem_pot_diag(args_1)
args = Namespace(yaml="cpd.yaml")
plot_chem_pot_diag(args)
args_2 = Namespace(elements=None, functional=None, yaml="cpd.yaml", update=False,
dirs=[Path("Mg"), Path("MgO"), Path("O"), Path("Al"), Path("MgAl2O4")],
target=Composition("MgAl2O4"))
make_chem_pot_diag(args_2)
args = Namespace(yaml="cpd.yaml")
plot_chem_pot_diag(args)
def test_make_supercell_from_matrix(simple_cubic, simple_cubic_2x1x1, tmpdir):
matrix = [2, 1, 1]
args = Namespace(unitcell=simple_cubic, matrix=matrix, min_num_atoms=None, max_num_atoms=None)
tmpdir.chdir()
make_supercell(args)
info = loadfn("supercell_info.json")
assert IStructure.from_file("SPOSCAR") == simple_cubic_2x1x1
assert info.structure == simple_cubic_2x1x1
assert info.transformation_matrix == [[2, 0, 0], [0, 1, 0], [0, 0, 1]]
def test_make_recommended_supercell(simple_cubic, simple_cubic_2x2x2, tmpdir):
args = Namespace(unitcell=simple_cubic, matrix=None, min_num_atoms=8, max_num_atoms=8)
tmpdir.chdir()
make_supercell(args)
info = loadfn("supercell_info.json")
assert IStructure.from_file("SPOSCAR") == simple_cubic_2x2x2
assert info.structure == simple_cubic_2x2x2
assert info.transformation_matrix == [[2, 0, 0], [0, 2, 0], [0, 0, 2]]
def test_add_interstitials(mocker):
mock_1 = mocker.Mock()
mock_2 = mocker.Mock()
mock_3 = mocker.Mock()
args = Namespace(supercell_info=mock_1, base_structure=mock_2, frac_coords=mock_3)
mock = mocker.patch("pydefect.cli.vasp.main_function.append_interstitial")
append_interstitial_to_supercell_info(args)
mock.assert_called_once_with(mock_1, mock_2, mock_3)
mock.return_value.to_json_file.assert_called_once_with()
def test_pop_interstitials(mocker):
mock_si = mocker.MagicMock()
args = Namespace(supercell_info=mock_si, index=1000)
pop_interstitial_from_supercell_info(args)
mock_si.interstitials.pop.assert_called_once_with(999)
mock_si.to_json_file.assert_called_once_with()
@pytest.mark.parametrize("oxi_states,he_vacancy_charge",
([None, [0]], [["He", 1, "Li", 1], [-1, 0, 1]]))
def test_make_defect_set(oxi_states, he_vacancy_charge, tmpdir, supercell_info):
tmpdir.chdir()
supercell_info.to_json_file()
args = Namespace(oxi_states=oxi_states, dopants=["Li"], kwargs=["Li_H1", "Va_He1", "Va_H1_-1"])
make_defect_set(args)
simple_defects = {SimpleDefect(None, "He1", he_vacancy_charge),
SimpleDefect(None, "H1", [-1]),
SimpleDefect("Li", "H1", [0])}
DefectSet(defects=simple_defects).to_yaml("expected.yaml")
assert Path("defect_in.yaml").read_text() == Path("expected.yaml").read_text()
def test_make_defect_entries(tmpdir, supercell_info):
tmpdir.chdir()
supercell_info.to_json_file()
defect_set = DefectSet({SimpleDefect(None, "He1", [-1, 0])})
defect_set.to_yaml()
args = Namespace()
make_defect_entries(args)
names = {str(name) for name in Path(".").glob("*")}
assert names == {'Va_He1_-1', 'defect_in.yaml', 'perfect', 'Va_He1_0', 'supercell_info.json'}
perfect_structure = Structure.from_file(Path("perfect") / "POSCAR")
assert perfect_structure == supercell_info.structure
file_names = {str(file_name.name) for file_name in Path("Va_He1_-1").glob("*")}
assert file_names == {"POSCAR", "defect_entry.json", "prior_info.yaml"}
expected = """charge: -1
"""
assert Path("Va_He1_-1/prior_info.yaml").read_text() == expected
def test_make_calc_results(tmpdir, mocker):
tmpdir.chdir()
mock = mocker.patch("pydefect.cli.vasp.main_function.make_calc_results_from_vasp")
mock_vasprun = mocker.patch("pydefect.cli.vasp.main_function.Vasprun")
mock_outcar = mocker.patch("pydefect.cli.vasp.main_function.Outcar")
mock_calc_results = mocker.Mock(spec=CalcResults)
mock.return_value = mock_calc_results
args = Namespace(dirs=[Path("a")])
make_calc_results(args)
mock_vasprun.assert_called_with(Path("a") / defaults.vasprun)
mock_outcar.assert_called_with(Path("a") / defaults.outcar)
mock.assert_called_with(vasprun=mock_vasprun.return_value, outcar=mock_outcar.return_value)
mock_calc_results.to_json_file.assert_called_with(filename=Path("a") / "calc_results.json")
def test_make_efnv_correction_from_vasp(tmpdir, mocker):
mock_defect_entry = mocker.Mock(spec=DefectEntry, autospec=True)
mock_calc_results = mocker.Mock(spec=CalcResults, autospec=True)
def side_effect(key):
if str(key) == "Va_O1_2/defect_entry.json":
mock_defect_entry.full_name = "Va_O1_2"
mock_defect_entry.charge = 2
return mock_defect_entry
elif str(key) == "Va_O1_2/calc_results.json":
return mock_calc_results
else:
raise ValueError
mock_perfect_calc_results = mocker.Mock(spec=CalcResults)
mock_loadfn = mocker.patch("pydefect.cli.vasp.main_function.loadfn", side_effect=side_effect)
mock_unitcell = mocker.Mock(spec=Unitcell)
mock_make_efnv = mocker.patch("pydefect.cli.vasp.main_function.make_efnv_correction")
mock_efnv = mocker.Mock(spec=ExtendedFnvCorrection, autospec=True)
mock_make_efnv.return_value = mock_efnv
mock_pot_plotter = mocker.patch("pydefect.cli.vasp.main_function.SitePotentialMplPlotter")
args = Namespace(dirs=[Path("Va_O1_2")],
perfect_calc_results=mock_perfect_calc_results,
unitcell=mock_unitcell)
make_efnv_correction_from_vasp(args)
mock_loadfn.assert_any_call(Path("Va_O1_2") / "defect_entry.json")
mock_loadfn.assert_any_call(Path("Va_O1_2") / "calc_results.json")
mock_make_efnv.assert_called_with(mock_defect_entry.charge, mock_calc_results, mock_perfect_calc_results, mock_unitcell.dielectric_constant)
mock_efnv.to_json_file.assert_called_with(Path("Va_O1_2") / "correction.json")
mock_pot_plotter.from_efnv_corr.assert_called_with(title="Va_O1_2", efnv_correction=mock_efnv)
mock_pot_plotter.from_efnv_corr.return_value.construct_plot.assert_called_once_with()
mock_pot_plotter.from_efnv_corr.return_value.plt.savefig.assert_called_once_with(fname=Path("Va_O1_2") / "correction.pdf")
def test_make_gkfo_correction_from_vasp(tmpdir, mocker):
mock_i_correction = mocker.Mock(spec=ExtendedFnvCorrection, autospec=True)
mock_i_calc_results = mocker.Mock(spec=CalcResults, autospec=True)
mock_f_calc_results = mocker.Mock(spec=CalcResults, autospec=True)
mock_unitcell = mocker.Mock()
mock_pot_plotter = mocker.patch("pydefect.cli.vasp.main_function.SitePotentialMplPlotter")
mock_make_gkfo = mocker.patch("pydefect.cli.vasp.main_function.make_gkfo_correction")
args = Namespace(
initial_efnv_correction=mock_i_correction,
initial_calc_results=mock_i_calc_results,
final_calc_results=mock_f_calc_results,
charge_diff=1,
unitcell=mock_unitcell)
make_gkfo_correction_from_vasp(args)
mock_make_gkfo.assert_called_with(
efnv_correction=mock_i_correction,
additional_charge=1,
final_calc_results=mock_f_calc_results,
initial_calc_results=mock_i_calc_results,
diele_tensor=mock_unitcell.dielectric_constant,
ion_clamped_diele_tensor=mock_unitcell.ele_dielectric_const)
def test_make_defect_eigenvalues(mocker):
mock_vasprun = mocker.patch("pydefect.cli.vasp.main_function.Vasprun")
mock_make_eigvals = mocker.patch(
"pydefect.cli.vasp.main_function.make_band_edge_eigenvalues")
mock_perfect_calc_results = mocker.Mock(spec=CalcResults)
mock_perfect_calc_results.vbm = 10
mock_perfect_calc_results.cbm = 20
mock_defect_entry = mocker.Mock(spec=DefectEntry, autospec=True)
mock_eigval_plotter = mocker.patch(
"pydefect.cli.vasp.main_function.EigenvalueMplPlotter")
def side_effect(key):
if str(key) == "Va_O1_2/defect_entry.json":
mock_defect_entry.name = "Va_O1"
mock_defect_entry.charge = 2
return mock_defect_entry
else:
raise ValueError
mock_loadfn = mocker.patch("pydefect.cli.vasp.main_function.loadfn",
side_effect=side_effect)
args = Namespace(dirs=[Path("Va_O1_2")],
perfect_calc_results=mock_perfect_calc_results)
make_defect_eigenvalues(args)
mock_vasprun.assert_called_with(Path("Va_O1_2") / defaults.vasprun)
mock_make_eigvals.assert_called_with(mock_vasprun.return_value, 10, 20)
mock_make_eigvals.return_value.to_json_file.assert_called_with(
Path("Va_O1_2") / "band_edge_eigenvalues.json")
mock_loadfn.assert_any_call(Path("Va_O1_2") / "defect_entry.json")
mock_eigval_plotter.assert_called_with(
title="Va_O1",
band_edge_eigenvalues=mock_make_eigvals.return_value,
supercell_vbm=10,
supercell_cbm=20)
def test_make_edge_characters(mocker):
mock_vasprun = mocker.patch("pydefect.cli.vasp.main_function.Vasprun")
mock_procar = mocker.patch("pydefect.cli.vasp.main_function.Procar")
mock_outcar = mocker.patch("pydefect.cli.vasp.main_function.Outcar")
mock_perfect_calc_results = mocker.Mock(spec=CalcResults, autospec=True)
mock_perfect_calc_results.structure = mocker.Mock(spec=Structure)
mock_calc_results = mocker.Mock(spec=CalcResults, autospec=True)
mock_analyzer = mocker.patch(
"pydefect.cli.vasp.main_function.DefectStructureAnalyzer")
mock_characters = mocker.patch(
"pydefect.cli.vasp.main_function.MakeEdgeCharacters")
def side_effect(key):
if str(key) == "Va_O1_2/calc_results.json":
mock_calc_results.structure = mocker.Mock(spec=Structure, autospec=True)
return mock_calc_results
else:
raise ValueError
mocker.patch("pydefect.cli.vasp.main_function.loadfn", side_effect=side_effect)
args = Namespace(dirs=[Path("Va_O1_2")],
perfect_calc_results=mock_perfect_calc_results)
make_edge_characters(args)
mock_vasprun.assert_called_with(Path("Va_O1_2") / defaults.vasprun)
mock_procar.assert_called_with(Path("Va_O1_2") / defaults.procar)
mock_outcar.assert_called_with(Path("Va_O1_2") / defaults.outcar)
mock_analyzer.assert_called_with(mock_calc_results.structure,
mock_perfect_calc_results.structure)
mock_characters.assert_called_with(mock_procar.return_value,
mock_vasprun.return_value,
mock_outcar.return_value,
mock_analyzer.return_value.neighboring_atom_indices)
def test_make_edge_state(mocker):
mock_perf_edge_chars = mocker.Mock(spec=EdgeCharacters, autospec=True)
args = Namespace(dirs=[Path("Va_O1_2")],
perfect_edge_characters=mock_perf_edge_chars)
mock_edge_chars = mocker.Mock(spec=EdgeCharacters, autospec=True)
def side_effect(key):
if str(key) == "Va_O1_2/edge_characters.json":
return mock_edge_chars
else:
raise ValueError
mocker.patch("pydefect.cli.vasp.main_function.loadfn", side_effect=side_effect)
mocker.patch("pydefect.cli.vasp.main_function.make_band_edge_state")
mocker.patch("pydefect.cli.vasp.main_function.BandEdgeStates")
@pytest.mark.parametrize("skip_shallow", [False, True])
def test_make_defect_formation_energy(skip_shallow, tmpdir, mocker):
tmpdir.chdir()
mock_perfect_calc_results = mocker.Mock(spec=CalcResults)
mock_perfect_calc_results.structure = Structure(Lattice.cubic(1), species=["H"] * 2, coords=[[0]*3] * 2)
mock_perfect_calc_results.energy = 10
mock_perfect_calc_results.vbm = 10
mock_perfect_calc_results.cbm = 20
mock_chem_pot_diag = mocker.patch("pydefect.cli.vasp.main_function.ChemPotDiag")
mock_chem_pot_diag.from_yaml.return_value.abs_chem_pot_dict.return_value = {Element.H: 0}
mock_defect_entry = mocker.Mock(spec=DefectEntry, autospec=True)
mock_calc_results = mocker.Mock(spec=CalcResults, autospec=True)
mock_correction = mocker.Mock(spec=ExtendedFnvCorrection, autospec=True)
def side_effect(key):
if str(key) == "Va_O1_2/defect_entry.json":
mock_defect_entry.name = "Va_H1"
mock_defect_entry.charge = 2
return mock_defect_entry
elif str(key) == "Va_O1_2/calc_results.json":
mock_calc_results.structure = Structure(Lattice.cubic(1), species=["H"], coords=[[0]*3])
mock_calc_results.energy = 10
return mock_calc_results
elif str(key) == "Va_O1_2/correction.json":
mock_correction.correction_energy = 20
return mock_correction
elif str(key) == "Va_O1_2/band_edge_states.json":
mock_band_edge_states = mocker.Mock(spec=BandEdgeStates, autospec=True)
mock_band_edge_states.is_shallow = True
return mock_band_edge_states
else:
raise ValueError
mock_loadfn = mocker.patch("pydefect.cli.vasp.main_function.loadfn", side_effect=side_effect)
mock_unitcell = mocker.Mock(spec=Unitcell)
mock_unitcell.vbm = 11
mock_unitcell.cbm = 19
args = Namespace(dirs=[Path("Va_O1_2")],
perfect_calc_results=mock_perfect_calc_results,
unitcell=mock_unitcell,
chem_pot_diag="cpd.yaml",
label="A",
y_range=[-100, 100],
skip_shallow=skip_shallow,
print=True)
make_defect_formation_energy(args)
if skip_shallow is True:
mock_loadfn.assert_any_call(Path("Va_O1_2") / "band_edge_states.json")
else:
mock_loadfn.assert_any_call(Path("Va_O1_2") / "defect_entry.json")
mock_loadfn.assert_any_call(Path("Va_O1_2") / "calc_results.json")
mock_loadfn.assert_any_call(Path("Va_O1_2") / "correction.json")
| 43.387324 | 144 | 0.707569 |
from argparse import Namespace
from pathlib import Path
import numpy as np
import pytest
from monty.serialization import loadfn
from pydefect.analyzer.band_edge_states import EdgeCharacters, BandEdgeStates
from pydefect.analyzer.calc_results import CalcResults
from pydefect.analyzer.unitcell import Unitcell
from pydefect.cli.vasp.main_function import make_supercell, make_defect_set, \
make_defect_entries, make_unitcell, make_competing_phase_dirs, \
make_chem_pot_diag, make_calc_results, print_file, \
make_efnv_correction_from_vasp, make_defect_formation_energy, \
make_defect_eigenvalues, make_edge_characters, \
append_interstitial_to_supercell_info, pop_interstitial_from_supercell_info, \
plot_chem_pot_diag, make_gkfo_correction_from_vasp
from pydefect.corrections.efnv_correction import \
ExtendedFnvCorrection
from pydefect.defaults import defaults
from pydefect.input_maker.defect import SimpleDefect
from pydefect.input_maker.defect_entry import DefectEntry
from pydefect.input_maker.defect_set import DefectSet
from pymatgen import IStructure, Composition, Structure, Lattice, Element
from pymatgen.io.vasp import Vasprun, Outcar
def test_print():
args = Namespace(obj="a")
print_file(args)
def test_make_unitcell(mocker):
vasprun_band_mock = mocker.Mock(spec=Vasprun, autospec=True)
outcar_band_mock = mocker.Mock(spec=Outcar, autospec=True)
outcar_dielectric_mock = mocker.Mock(spec=Outcar, autospec=True)
args = Namespace(vasprun_band=vasprun_band_mock,
outcar_band=outcar_band_mock,
outcar_dielectric_clamped=outcar_dielectric_mock,
outcar_dielectric_ionic=outcar_dielectric_mock)
mock = mocker.patch("pydefect.cli.vasp.main_function.make_unitcell_from_vasp")
mock.return_value = Unitcell(vbm=1.0,
cbm=2.0,
ele_dielectric_const=np.eye(3),
ion_dielectric_const=np.eye(3))
make_unitcell(args)
mock.assert_called_once_with(vasprun_band=vasprun_band_mock,
outcar_band=outcar_band_mock,
outcar_dielectric_clamped=outcar_dielectric_mock,
outcar_dielectric_ionic=outcar_dielectric_mock)
def test_make_competing_phase_dirs(mocker):
args = Namespace(elements=["Mg", "O"],
e_above_hull=0.1)
mock = mocker.patch("pydefect.cli.vasp.main_function.MpQuery")
mock_make = mocker.patch("pydefect.cli.vasp.main_function.make_poscars_from_query")
make_competing_phase_dirs(args)
mock.assert_called_once_with(element_list=args.elements,
e_above_hull=args.e_above_hull)
mock_make.assert_called_once_with(materials_query=mock.return_value.materials, path=Path.cwd())
def test_make_chem_pot_diag(mocker, tmpdir):
def side_effect(key):
mock_vasprun = mocker.Mock()
if key == Path("Mg") / defaults.vasprun:
mock_vasprun.final_structure.composition = Composition("Mg2")
mock_vasprun.final_energy = -10
elif key == Path("O") / defaults.vasprun:
mock_vasprun.final_structure.composition = Composition("O2")
mock_vasprun.final_energy = -20
elif key == Path("MgO") / defaults.vasprun:
mock_vasprun.final_structure.composition = Composition("MgO")
mock_vasprun.final_energy = -30
elif key == Path("Al") / defaults.vasprun:
mock_vasprun.final_structure.composition = Composition("Al")
mock_vasprun.final_energy = 0
elif key == Path("MgAl2O4") / defaults.vasprun:
mock_vasprun.final_structure.composition = Composition("MgAl2O4")
mock_vasprun.final_energy = -70
else:
raise ValueError
return mock_vasprun
tmpdir.chdir()
mock = mocker.patch("pydefect.cli.vasp.main_function.Vasprun", side_effect=side_effect)
args_1 = Namespace(elements=None, functional=None, yaml="cpd.yaml", update=False,
dirs=[Path("Mg"), Path("MgO"), Path("O"), Path("Al"), Path("MgAl2O4")],
target=Composition("MgO"))
make_chem_pot_diag(args_1)
args = Namespace(yaml="cpd.yaml")
plot_chem_pot_diag(args)
args_2 = Namespace(elements=None, functional=None, yaml="cpd.yaml", update=False,
dirs=[Path("Mg"), Path("MgO"), Path("O"), Path("Al"), Path("MgAl2O4")],
target=Composition("MgAl2O4"))
make_chem_pot_diag(args_2)
args = Namespace(yaml="cpd.yaml")
plot_chem_pot_diag(args)
def test_make_supercell_from_matrix(simple_cubic, simple_cubic_2x1x1, tmpdir):
matrix = [2, 1, 1]
args = Namespace(unitcell=simple_cubic, matrix=matrix, min_num_atoms=None, max_num_atoms=None)
tmpdir.chdir()
make_supercell(args)
info = loadfn("supercell_info.json")
assert IStructure.from_file("SPOSCAR") == simple_cubic_2x1x1
assert info.structure == simple_cubic_2x1x1
assert info.transformation_matrix == [[2, 0, 0], [0, 1, 0], [0, 0, 1]]
def test_make_recommended_supercell(simple_cubic, simple_cubic_2x2x2, tmpdir):
args = Namespace(unitcell=simple_cubic, matrix=None, min_num_atoms=8, max_num_atoms=8)
tmpdir.chdir()
make_supercell(args)
info = loadfn("supercell_info.json")
assert IStructure.from_file("SPOSCAR") == simple_cubic_2x2x2
assert info.structure == simple_cubic_2x2x2
assert info.transformation_matrix == [[2, 0, 0], [0, 2, 0], [0, 0, 2]]
def test_add_interstitials(mocker):
mock_1 = mocker.Mock()
mock_2 = mocker.Mock()
mock_3 = mocker.Mock()
args = Namespace(supercell_info=mock_1, base_structure=mock_2, frac_coords=mock_3)
mock = mocker.patch("pydefect.cli.vasp.main_function.append_interstitial")
append_interstitial_to_supercell_info(args)
mock.assert_called_once_with(mock_1, mock_2, mock_3)
mock.return_value.to_json_file.assert_called_once_with()
def test_pop_interstitials(mocker):
mock_si = mocker.MagicMock()
args = Namespace(supercell_info=mock_si, index=1000)
pop_interstitial_from_supercell_info(args)
mock_si.interstitials.pop.assert_called_once_with(999)
mock_si.to_json_file.assert_called_once_with()
@pytest.mark.parametrize("oxi_states,he_vacancy_charge",
([None, [0]], [["He", 1, "Li", 1], [-1, 0, 1]]))
def test_make_defect_set(oxi_states, he_vacancy_charge, tmpdir, supercell_info):
tmpdir.chdir()
supercell_info.to_json_file()
args = Namespace(oxi_states=oxi_states, dopants=["Li"], kwargs=["Li_H1", "Va_He1", "Va_H1_-1"])
make_defect_set(args)
simple_defects = {SimpleDefect(None, "He1", he_vacancy_charge),
SimpleDefect(None, "H1", [-1]),
SimpleDefect("Li", "H1", [0])}
DefectSet(defects=simple_defects).to_yaml("expected.yaml")
assert Path("defect_in.yaml").read_text() == Path("expected.yaml").read_text()
def test_make_defect_entries(tmpdir, supercell_info):
tmpdir.chdir()
supercell_info.to_json_file()
defect_set = DefectSet({SimpleDefect(None, "He1", [-1, 0])})
defect_set.to_yaml()
args = Namespace()
make_defect_entries(args)
names = {str(name) for name in Path(".").glob("*")}
assert names == {'Va_He1_-1', 'defect_in.yaml', 'perfect', 'Va_He1_0', 'supercell_info.json'}
perfect_structure = Structure.from_file(Path("perfect") / "POSCAR")
assert perfect_structure == supercell_info.structure
file_names = {str(file_name.name) for file_name in Path("Va_He1_-1").glob("*")}
assert file_names == {"POSCAR", "defect_entry.json", "prior_info.yaml"}
expected = """charge: -1
"""
assert Path("Va_He1_-1/prior_info.yaml").read_text() == expected
def test_make_calc_results(tmpdir, mocker):
tmpdir.chdir()
mock = mocker.patch("pydefect.cli.vasp.main_function.make_calc_results_from_vasp")
mock_vasprun = mocker.patch("pydefect.cli.vasp.main_function.Vasprun")
mock_outcar = mocker.patch("pydefect.cli.vasp.main_function.Outcar")
mock_calc_results = mocker.Mock(spec=CalcResults)
mock.return_value = mock_calc_results
args = Namespace(dirs=[Path("a")])
make_calc_results(args)
mock_vasprun.assert_called_with(Path("a") / defaults.vasprun)
mock_outcar.assert_called_with(Path("a") / defaults.outcar)
mock.assert_called_with(vasprun=mock_vasprun.return_value, outcar=mock_outcar.return_value)
mock_calc_results.to_json_file.assert_called_with(filename=Path("a") / "calc_results.json")
def test_make_efnv_correction_from_vasp(tmpdir, mocker):
mock_defect_entry = mocker.Mock(spec=DefectEntry, autospec=True)
mock_calc_results = mocker.Mock(spec=CalcResults, autospec=True)
def side_effect(key):
if str(key) == "Va_O1_2/defect_entry.json":
mock_defect_entry.full_name = "Va_O1_2"
mock_defect_entry.charge = 2
return mock_defect_entry
elif str(key) == "Va_O1_2/calc_results.json":
return mock_calc_results
else:
raise ValueError
mock_perfect_calc_results = mocker.Mock(spec=CalcResults)
mock_loadfn = mocker.patch("pydefect.cli.vasp.main_function.loadfn", side_effect=side_effect)
mock_unitcell = mocker.Mock(spec=Unitcell)
mock_make_efnv = mocker.patch("pydefect.cli.vasp.main_function.make_efnv_correction")
mock_efnv = mocker.Mock(spec=ExtendedFnvCorrection, autospec=True)
mock_make_efnv.return_value = mock_efnv
mock_pot_plotter = mocker.patch("pydefect.cli.vasp.main_function.SitePotentialMplPlotter")
args = Namespace(dirs=[Path("Va_O1_2")],
perfect_calc_results=mock_perfect_calc_results,
unitcell=mock_unitcell)
make_efnv_correction_from_vasp(args)
mock_loadfn.assert_any_call(Path("Va_O1_2") / "defect_entry.json")
mock_loadfn.assert_any_call(Path("Va_O1_2") / "calc_results.json")
mock_make_efnv.assert_called_with(mock_defect_entry.charge, mock_calc_results, mock_perfect_calc_results, mock_unitcell.dielectric_constant)
mock_efnv.to_json_file.assert_called_with(Path("Va_O1_2") / "correction.json")
mock_pot_plotter.from_efnv_corr.assert_called_with(title="Va_O1_2", efnv_correction=mock_efnv)
mock_pot_plotter.from_efnv_corr.return_value.construct_plot.assert_called_once_with()
mock_pot_plotter.from_efnv_corr.return_value.plt.savefig.assert_called_once_with(fname=Path("Va_O1_2") / "correction.pdf")
def test_make_gkfo_correction_from_vasp(tmpdir, mocker):
mock_i_correction = mocker.Mock(spec=ExtendedFnvCorrection, autospec=True)
mock_i_calc_results = mocker.Mock(spec=CalcResults, autospec=True)
mock_f_calc_results = mocker.Mock(spec=CalcResults, autospec=True)
mock_unitcell = mocker.Mock()
mock_pot_plotter = mocker.patch("pydefect.cli.vasp.main_function.SitePotentialMplPlotter")
mock_make_gkfo = mocker.patch("pydefect.cli.vasp.main_function.make_gkfo_correction")
args = Namespace(
initial_efnv_correction=mock_i_correction,
initial_calc_results=mock_i_calc_results,
final_calc_results=mock_f_calc_results,
charge_diff=1,
unitcell=mock_unitcell)
make_gkfo_correction_from_vasp(args)
mock_make_gkfo.assert_called_with(
efnv_correction=mock_i_correction,
additional_charge=1,
final_calc_results=mock_f_calc_results,
initial_calc_results=mock_i_calc_results,
diele_tensor=mock_unitcell.dielectric_constant,
ion_clamped_diele_tensor=mock_unitcell.ele_dielectric_const)
def test_make_defect_eigenvalues(mocker):
mock_vasprun = mocker.patch("pydefect.cli.vasp.main_function.Vasprun")
mock_make_eigvals = mocker.patch(
"pydefect.cli.vasp.main_function.make_band_edge_eigenvalues")
mock_perfect_calc_results = mocker.Mock(spec=CalcResults)
mock_perfect_calc_results.vbm = 10
mock_perfect_calc_results.cbm = 20
mock_defect_entry = mocker.Mock(spec=DefectEntry, autospec=True)
mock_eigval_plotter = mocker.patch(
"pydefect.cli.vasp.main_function.EigenvalueMplPlotter")
def side_effect(key):
if str(key) == "Va_O1_2/defect_entry.json":
mock_defect_entry.name = "Va_O1"
mock_defect_entry.charge = 2
return mock_defect_entry
else:
raise ValueError
mock_loadfn = mocker.patch("pydefect.cli.vasp.main_function.loadfn",
side_effect=side_effect)
args = Namespace(dirs=[Path("Va_O1_2")],
perfect_calc_results=mock_perfect_calc_results)
make_defect_eigenvalues(args)
mock_vasprun.assert_called_with(Path("Va_O1_2") / defaults.vasprun)
mock_make_eigvals.assert_called_with(mock_vasprun.return_value, 10, 20)
mock_make_eigvals.return_value.to_json_file.assert_called_with(
Path("Va_O1_2") / "band_edge_eigenvalues.json")
mock_loadfn.assert_any_call(Path("Va_O1_2") / "defect_entry.json")
mock_eigval_plotter.assert_called_with(
title="Va_O1",
band_edge_eigenvalues=mock_make_eigvals.return_value,
supercell_vbm=10,
supercell_cbm=20)
def test_make_edge_characters(mocker):
mock_vasprun = mocker.patch("pydefect.cli.vasp.main_function.Vasprun")
mock_procar = mocker.patch("pydefect.cli.vasp.main_function.Procar")
mock_outcar = mocker.patch("pydefect.cli.vasp.main_function.Outcar")
mock_perfect_calc_results = mocker.Mock(spec=CalcResults, autospec=True)
mock_perfect_calc_results.structure = mocker.Mock(spec=Structure)
mock_calc_results = mocker.Mock(spec=CalcResults, autospec=True)
mock_analyzer = mocker.patch(
"pydefect.cli.vasp.main_function.DefectStructureAnalyzer")
mock_characters = mocker.patch(
"pydefect.cli.vasp.main_function.MakeEdgeCharacters")
def side_effect(key):
if str(key) == "Va_O1_2/calc_results.json":
mock_calc_results.structure = mocker.Mock(spec=Structure, autospec=True)
return mock_calc_results
else:
raise ValueError
mocker.patch("pydefect.cli.vasp.main_function.loadfn", side_effect=side_effect)
args = Namespace(dirs=[Path("Va_O1_2")],
perfect_calc_results=mock_perfect_calc_results)
make_edge_characters(args)
mock_vasprun.assert_called_with(Path("Va_O1_2") / defaults.vasprun)
mock_procar.assert_called_with(Path("Va_O1_2") / defaults.procar)
mock_outcar.assert_called_with(Path("Va_O1_2") / defaults.outcar)
mock_analyzer.assert_called_with(mock_calc_results.structure,
mock_perfect_calc_results.structure)
mock_characters.assert_called_with(mock_procar.return_value,
mock_vasprun.return_value,
mock_outcar.return_value,
mock_analyzer.return_value.neighboring_atom_indices)
def test_make_edge_state(mocker):
mock_perf_edge_chars = mocker.Mock(spec=EdgeCharacters, autospec=True)
args = Namespace(dirs=[Path("Va_O1_2")],
perfect_edge_characters=mock_perf_edge_chars)
mock_edge_chars = mocker.Mock(spec=EdgeCharacters, autospec=True)
def side_effect(key):
if str(key) == "Va_O1_2/edge_characters.json":
return mock_edge_chars
else:
raise ValueError
mocker.patch("pydefect.cli.vasp.main_function.loadfn", side_effect=side_effect)
mocker.patch("pydefect.cli.vasp.main_function.make_band_edge_state")
mocker.patch("pydefect.cli.vasp.main_function.BandEdgeStates")
@pytest.mark.parametrize("skip_shallow", [False, True])
def test_make_defect_formation_energy(skip_shallow, tmpdir, mocker):
tmpdir.chdir()
mock_perfect_calc_results = mocker.Mock(spec=CalcResults)
mock_perfect_calc_results.structure = Structure(Lattice.cubic(1), species=["H"] * 2, coords=[[0]*3] * 2)
mock_perfect_calc_results.energy = 10
mock_perfect_calc_results.vbm = 10
mock_perfect_calc_results.cbm = 20
mock_chem_pot_diag = mocker.patch("pydefect.cli.vasp.main_function.ChemPotDiag")
mock_chem_pot_diag.from_yaml.return_value.abs_chem_pot_dict.return_value = {Element.H: 0}
mock_defect_entry = mocker.Mock(spec=DefectEntry, autospec=True)
mock_calc_results = mocker.Mock(spec=CalcResults, autospec=True)
mock_correction = mocker.Mock(spec=ExtendedFnvCorrection, autospec=True)
def side_effect(key):
if str(key) == "Va_O1_2/defect_entry.json":
mock_defect_entry.name = "Va_H1"
mock_defect_entry.charge = 2
return mock_defect_entry
elif str(key) == "Va_O1_2/calc_results.json":
mock_calc_results.structure = Structure(Lattice.cubic(1), species=["H"], coords=[[0]*3])
mock_calc_results.energy = 10
return mock_calc_results
elif str(key) == "Va_O1_2/correction.json":
mock_correction.correction_energy = 20
return mock_correction
elif str(key) == "Va_O1_2/band_edge_states.json":
mock_band_edge_states = mocker.Mock(spec=BandEdgeStates, autospec=True)
mock_band_edge_states.is_shallow = True
return mock_band_edge_states
else:
raise ValueError
mock_loadfn = mocker.patch("pydefect.cli.vasp.main_function.loadfn", side_effect=side_effect)
mock_unitcell = mocker.Mock(spec=Unitcell)
mock_unitcell.vbm = 11
mock_unitcell.cbm = 19
args = Namespace(dirs=[Path("Va_O1_2")],
perfect_calc_results=mock_perfect_calc_results,
unitcell=mock_unitcell,
chem_pot_diag="cpd.yaml",
label="A",
y_range=[-100, 100],
skip_shallow=skip_shallow,
print=True)
make_defect_formation_energy(args)
if skip_shallow is True:
mock_loadfn.assert_any_call(Path("Va_O1_2") / "band_edge_states.json")
else:
mock_loadfn.assert_any_call(Path("Va_O1_2") / "defect_entry.json")
mock_loadfn.assert_any_call(Path("Va_O1_2") / "calc_results.json")
mock_loadfn.assert_any_call(Path("Va_O1_2") / "correction.json")
| true | true |
f7f752c31e2eeeafff5313258ef00d4f89156fb2 | 8,740 | py | Python | src/dacirco/scheduler/scheduler.py | albertoblanc/dacirco | 965a2e4ad49ec7754eb42442a570bf6d1bf00e89 | [
"MIT"
] | null | null | null | src/dacirco/scheduler/scheduler.py | albertoblanc/dacirco | 965a2e4ad49ec7754eb42442a570bf6d1bf00e89 | [
"MIT"
] | null | null | null | src/dacirco/scheduler/scheduler.py | albertoblanc/dacirco | 965a2e4ad49ec7754eb42442a570bf6d1bf00e89 | [
"MIT"
] | null | null | null | import logging
import os
from collections import deque
from typing import Optional
from dataclasses import asdict
from datetime import timedelta
from dacirco.grpc_service.events import (
TCWorkerErrorEvent,
TCWorkerEvent,
TCWorkerEventType,
)
from dacirco.scheduler.container_manager import ContainerManager
from dacirco.scheduler.dacirco_dataclasses import (
MinIoParameters,
RunnerType,
SchedRes,
SchedulerParameters,
AlgorithmType,
TCRequestDesc,
VMParameters,
)
from dacirco.scheduler.event_logger import EventLogger
from dacirco.scheduler.request_tracker import RequestStatus, RequestTracker
from dacirco.scheduler.vm_manager import VMManager
_logger = logging.getLogger(__name__)
class Scheduler:
def __init__(
self,
vm_parameters: VMParameters,
minio_parameters: MinIoParameters,
local_ip_address: str,
event_log_file: str,
sched_parameters: SchedulerParameters,
) -> None:
self._request_queue = deque[TCRequestDesc]()
if event_log_file:
self._EVENT_LOG_FILE_NAME = event_log_file
else:
self._EVENT_LOG_FILE_NAME = self._pick_event_log_file_name()
self._event_logger = EventLogger(self._EVENT_LOG_FILE_NAME)
self._request_tracker = RequestTracker()
self._algorithm = sched_parameters.algorithm
self._max_idle_time = sched_parameters.max_idle_time
if sched_parameters.runner_type is RunnerType.CONTAINER:
self._runner_manager = ContainerManager(
self._event_logger,
request_tracker=self._request_tracker,
max_workers=sched_parameters.max_workers,
)
elif sched_parameters.runner_type is RunnerType.VM:
self._runner_manager = VMManager(
event_logger=self._event_logger,
vm_parameters=vm_parameters,
minio_parameters=minio_parameters,
request_tracker=self._request_tracker,
max_workers=sched_parameters.max_workers,
local_ip_address=local_ip_address,
)
self._write_config_log_file(
vm_parameters=vm_parameters, sched_parameters=sched_parameters
)
def _pick_event_log_file_name(self) -> str:
"""Finds the first unused log file name
To avoid overwriting the same event log, this function looks for the
first available name of the form `tc-events-01.txt`, `tc-events-02.txt`
etc. The base name is hard coded to `tc-events`.
Raises: SystemExit: If there are already 99 files of this type, this
function causes the program to exit.
Returns: str: The complete name for the event log file.
"""
base_name = "tc-events"
i = 1
while os.path.exists(f"{base_name}-{i:02d}.txt"):
i += 1
if i == 100:
_logger.error("Too many existing log files, giving up")
raise SystemExit
return f"{base_name}-{i:02d}.txt"
def _write_config_log_file(
self, vm_parameters: VMParameters, sched_parameters: SchedulerParameters
) -> None:
with open(self._EVENT_LOG_FILE_NAME[:-4] + ".config.txt", "w") as of:
of.write(str(asdict(sched_parameters)) + "\n")
of.write(str(asdict(vm_parameters)))
def new_request(
self,
input_video: str,
output_video: str,
bitrate: int,
speed: str,
request_id: str,
) -> SchedRes:
q_size = len(self._request_queue)
res = SchedRes(success=True)
req = TCRequestDesc(
input_video=input_video,
output_video=output_video,
bitrate=bitrate,
speed=speed,
request_id=request_id,
)
_logger.info(
"Received new request. Queue size: %i, id: %s, bitrate: %i, speed: %s",
q_size,
input_video,
bitrate,
speed,
)
self._event_logger.request_received(req)
worker = self._runner_manager.get_idle_worker()
self._request_tracker.add_request(req)
if worker:
_logger.debug("Assigning request to worker %s", worker.name)
tc_task_desc = worker.assign_tc_task(req)
if tc_task_desc:
res.tc_task_desc = tc_task_desc
else:
_logger.debug("Enqueueing request (no available worker)")
self._request_queue.appendleft(req)
return res
def register_worker(self, name: str, worker_id: str) -> SchedRes:
res = SchedRes(success=True)
worker = self._runner_manager.get_tc_worker(worker_id=worker_id)
if not worker:
msg = f"Received registration request from unknown worker {worker_id}"
_logger.error(msg)
res.success = False
res.error_message = msg
else:
if len(self._request_queue):
req = self._request_queue.pop()
_logger.debug("Found enqueued request, video: %s", req.input_video)
_logger.debug(
"Assigning request to worker %s (%s)", worker.name, worker.id
)
tc_task_desc = worker.assign_tc_task(req)
if tc_task_desc:
res.tc_task_desc = tc_task_desc
res = worker.handle_registration()
return res
def process_event(self, event: TCWorkerEvent) -> SchedRes:
res = SchedRes(success=True)
worker = self._runner_manager.get_tc_worker(worker_id=event.worker_id)
if not worker:
msg = f"Received event from unknown worker {event.worker_id}"
_logger.error(msg)
res.success = False
res.error_message = msg
else:
if event.type is TCWorkerEventType.FILE_DOWNLOADED:
res = worker.handle_file_downloaded(event.task_id)
elif event.type is TCWorkerEventType.TRANSCODING_COMPLETED:
res = worker.handle_transcoding_completed(event.task_id)
elif event.type is TCWorkerEventType.KEEPALIVE:
worker.handle_keepalive(event.worker_id)
elif event.type is TCWorkerEventType.FILE_UPLOADED:
res = worker.handle_file_uploaded(event.task_id)
if len(self._request_queue):
req = self._request_queue.pop()
_logger.debug("Found enqueued request, video: %s", req.input_video)
_logger.debug(
"Assigning request to worker %s (%s)", worker.name, worker.id
)
tc_task_desc = worker.assign_tc_task(req)
if tc_task_desc:
res.tc_task_desc = tc_task_desc
else:
_logger.info("No enqueued requests")
if self._algorithm is AlgorithmType.MINIMIZE_WORKERS:
self._runner_manager.destroy_runner(worker_id=worker.id)
return res
def process_error_event(self, event: TCWorkerErrorEvent) -> None:
worker = self._runner_manager.get_tc_worker(worker_id=event.worker_id)
if not worker:
msg = f"Received an event from unknown worker {event.worker_id}"
_logger.error(msg)
else:
worker.handle_error(event)
self._runner_manager.destroy_runner(worker_id=event.worker_id)
if len(self._request_queue):
worker = self._runner_manager.get_idle_worker()
if worker:
req = self._request_queue.pop()
_logger.debug("Found enqueued request, video: %s", req.input_video)
_logger.debug(
"Assigning request to worker %s (%s)", worker.name, worker.id
)
tc_task_desc = worker.assign_tc_task(req)
if tc_task_desc:
_logger.error("Internal Error E643")
def periodic_function(self) -> None:
if self._algorithm is AlgorithmType.GRACE_PERIOD:
self._runner_manager.destroy_idle_workers(
timedelta(seconds=self._max_idle_time)
)
def get_requests(self) -> list[str]:
return self._request_tracker.get_requests()
def get_request(self, request_id: str) -> Optional[TCRequestDesc]:
return self._request_tracker.get_request(request_id)
def get_request_status(self, request_id: str) -> RequestStatus:
return self._request_tracker.get_request_status(request_id)
| 39.727273 | 87 | 0.615675 | import logging
import os
from collections import deque
from typing import Optional
from dataclasses import asdict
from datetime import timedelta
from dacirco.grpc_service.events import (
TCWorkerErrorEvent,
TCWorkerEvent,
TCWorkerEventType,
)
from dacirco.scheduler.container_manager import ContainerManager
from dacirco.scheduler.dacirco_dataclasses import (
MinIoParameters,
RunnerType,
SchedRes,
SchedulerParameters,
AlgorithmType,
TCRequestDesc,
VMParameters,
)
from dacirco.scheduler.event_logger import EventLogger
from dacirco.scheduler.request_tracker import RequestStatus, RequestTracker
from dacirco.scheduler.vm_manager import VMManager
_logger = logging.getLogger(__name__)
class Scheduler:
def __init__(
self,
vm_parameters: VMParameters,
minio_parameters: MinIoParameters,
local_ip_address: str,
event_log_file: str,
sched_parameters: SchedulerParameters,
) -> None:
self._request_queue = deque[TCRequestDesc]()
if event_log_file:
self._EVENT_LOG_FILE_NAME = event_log_file
else:
self._EVENT_LOG_FILE_NAME = self._pick_event_log_file_name()
self._event_logger = EventLogger(self._EVENT_LOG_FILE_NAME)
self._request_tracker = RequestTracker()
self._algorithm = sched_parameters.algorithm
self._max_idle_time = sched_parameters.max_idle_time
if sched_parameters.runner_type is RunnerType.CONTAINER:
self._runner_manager = ContainerManager(
self._event_logger,
request_tracker=self._request_tracker,
max_workers=sched_parameters.max_workers,
)
elif sched_parameters.runner_type is RunnerType.VM:
self._runner_manager = VMManager(
event_logger=self._event_logger,
vm_parameters=vm_parameters,
minio_parameters=minio_parameters,
request_tracker=self._request_tracker,
max_workers=sched_parameters.max_workers,
local_ip_address=local_ip_address,
)
self._write_config_log_file(
vm_parameters=vm_parameters, sched_parameters=sched_parameters
)
def _pick_event_log_file_name(self) -> str:
base_name = "tc-events"
i = 1
while os.path.exists(f"{base_name}-{i:02d}.txt"):
i += 1
if i == 100:
_logger.error("Too many existing log files, giving up")
raise SystemExit
return f"{base_name}-{i:02d}.txt"
def _write_config_log_file(
self, vm_parameters: VMParameters, sched_parameters: SchedulerParameters
) -> None:
with open(self._EVENT_LOG_FILE_NAME[:-4] + ".config.txt", "w") as of:
of.write(str(asdict(sched_parameters)) + "\n")
of.write(str(asdict(vm_parameters)))
def new_request(
self,
input_video: str,
output_video: str,
bitrate: int,
speed: str,
request_id: str,
) -> SchedRes:
q_size = len(self._request_queue)
res = SchedRes(success=True)
req = TCRequestDesc(
input_video=input_video,
output_video=output_video,
bitrate=bitrate,
speed=speed,
request_id=request_id,
)
_logger.info(
"Received new request. Queue size: %i, id: %s, bitrate: %i, speed: %s",
q_size,
input_video,
bitrate,
speed,
)
self._event_logger.request_received(req)
worker = self._runner_manager.get_idle_worker()
self._request_tracker.add_request(req)
if worker:
_logger.debug("Assigning request to worker %s", worker.name)
tc_task_desc = worker.assign_tc_task(req)
if tc_task_desc:
res.tc_task_desc = tc_task_desc
else:
_logger.debug("Enqueueing request (no available worker)")
self._request_queue.appendleft(req)
return res
def register_worker(self, name: str, worker_id: str) -> SchedRes:
res = SchedRes(success=True)
worker = self._runner_manager.get_tc_worker(worker_id=worker_id)
if not worker:
msg = f"Received registration request from unknown worker {worker_id}"
_logger.error(msg)
res.success = False
res.error_message = msg
else:
if len(self._request_queue):
req = self._request_queue.pop()
_logger.debug("Found enqueued request, video: %s", req.input_video)
_logger.debug(
"Assigning request to worker %s (%s)", worker.name, worker.id
)
tc_task_desc = worker.assign_tc_task(req)
if tc_task_desc:
res.tc_task_desc = tc_task_desc
res = worker.handle_registration()
return res
def process_event(self, event: TCWorkerEvent) -> SchedRes:
res = SchedRes(success=True)
worker = self._runner_manager.get_tc_worker(worker_id=event.worker_id)
if not worker:
msg = f"Received event from unknown worker {event.worker_id}"
_logger.error(msg)
res.success = False
res.error_message = msg
else:
if event.type is TCWorkerEventType.FILE_DOWNLOADED:
res = worker.handle_file_downloaded(event.task_id)
elif event.type is TCWorkerEventType.TRANSCODING_COMPLETED:
res = worker.handle_transcoding_completed(event.task_id)
elif event.type is TCWorkerEventType.KEEPALIVE:
worker.handle_keepalive(event.worker_id)
elif event.type is TCWorkerEventType.FILE_UPLOADED:
res = worker.handle_file_uploaded(event.task_id)
if len(self._request_queue):
req = self._request_queue.pop()
_logger.debug("Found enqueued request, video: %s", req.input_video)
_logger.debug(
"Assigning request to worker %s (%s)", worker.name, worker.id
)
tc_task_desc = worker.assign_tc_task(req)
if tc_task_desc:
res.tc_task_desc = tc_task_desc
else:
_logger.info("No enqueued requests")
if self._algorithm is AlgorithmType.MINIMIZE_WORKERS:
self._runner_manager.destroy_runner(worker_id=worker.id)
return res
def process_error_event(self, event: TCWorkerErrorEvent) -> None:
worker = self._runner_manager.get_tc_worker(worker_id=event.worker_id)
if not worker:
msg = f"Received an event from unknown worker {event.worker_id}"
_logger.error(msg)
else:
worker.handle_error(event)
self._runner_manager.destroy_runner(worker_id=event.worker_id)
if len(self._request_queue):
worker = self._runner_manager.get_idle_worker()
if worker:
req = self._request_queue.pop()
_logger.debug("Found enqueued request, video: %s", req.input_video)
_logger.debug(
"Assigning request to worker %s (%s)", worker.name, worker.id
)
tc_task_desc = worker.assign_tc_task(req)
if tc_task_desc:
_logger.error("Internal Error E643")
def periodic_function(self) -> None:
if self._algorithm is AlgorithmType.GRACE_PERIOD:
self._runner_manager.destroy_idle_workers(
timedelta(seconds=self._max_idle_time)
)
def get_requests(self) -> list[str]:
return self._request_tracker.get_requests()
def get_request(self, request_id: str) -> Optional[TCRequestDesc]:
return self._request_tracker.get_request(request_id)
def get_request_status(self, request_id: str) -> RequestStatus:
return self._request_tracker.get_request_status(request_id)
| true | true |
f7f75320ba9854dd84f539c4ce20a0915dd92aab | 14,442 | py | Python | tests/storage/test_client_ips.py | rkfg/synapse | 0b3112123da5fae4964db784e3bab0c4d83d9d62 | [
"Apache-2.0"
] | 1 | 2021-09-09T08:50:13.000Z | 2021-09-09T08:50:13.000Z | tests/storage/test_client_ips.py | rkfg/synapse | 0b3112123da5fae4964db784e3bab0c4d83d9d62 | [
"Apache-2.0"
] | null | null | null | tests/storage/test_client_ips.py | rkfg/synapse | 0b3112123da5fae4964db784e3bab0c4d83d9d62 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
# Copyright 2016 OpenMarket Ltd
# Copyright 2018 New Vector Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from unittest.mock import Mock
import synapse.rest.admin
from synapse.http.site import XForwardedForRequest
from synapse.rest.client.v1 import login
from tests import unittest
from tests.server import make_request
from tests.test_utils import make_awaitable
from tests.unittest import override_config
class ClientIpStoreTestCase(unittest.HomeserverTestCase):
def make_homeserver(self, reactor, clock):
hs = self.setup_test_homeserver()
return hs
def prepare(self, hs, reactor, clock):
self.store = self.hs.get_datastore()
def test_insert_new_client_ip(self):
self.reactor.advance(12345678)
user_id = "@user:id"
device_id = "MY_DEVICE"
# Insert a user IP
self.get_success(
self.store.store_device(
user_id,
device_id,
"display name",
)
)
self.get_success(
self.store.insert_client_ip(
user_id, "access_token", "ip", "user_agent", device_id
)
)
# Trigger the storage loop
self.reactor.advance(10)
result = self.get_success(
self.store.get_last_client_ip_by_device(user_id, device_id)
)
r = result[(user_id, device_id)]
self.assertDictContainsSubset(
{
"user_id": user_id,
"device_id": device_id,
"ip": "ip",
"user_agent": "user_agent",
"last_seen": 12345678000,
},
r,
)
def test_insert_new_client_ip_none_device_id(self):
"""
An insert with a device ID of NULL will not create a new entry, but
update an existing entry in the user_ips table.
"""
self.reactor.advance(12345678)
user_id = "@user:id"
# Add & trigger the storage loop
self.get_success(
self.store.insert_client_ip(
user_id, "access_token", "ip", "user_agent", None
)
)
self.reactor.advance(200)
self.pump(0)
result = self.get_success(
self.store.db_pool.simple_select_list(
table="user_ips",
keyvalues={"user_id": user_id},
retcols=["access_token", "ip", "user_agent", "device_id", "last_seen"],
desc="get_user_ip_and_agents",
)
)
self.assertEqual(
result,
[
{
"access_token": "access_token",
"ip": "ip",
"user_agent": "user_agent",
"device_id": None,
"last_seen": 12345678000,
}
],
)
# Add another & trigger the storage loop
self.get_success(
self.store.insert_client_ip(
user_id, "access_token", "ip", "user_agent", None
)
)
self.reactor.advance(10)
self.pump(0)
result = self.get_success(
self.store.db_pool.simple_select_list(
table="user_ips",
keyvalues={"user_id": user_id},
retcols=["access_token", "ip", "user_agent", "device_id", "last_seen"],
desc="get_user_ip_and_agents",
)
)
# Only one result, has been upserted.
self.assertEqual(
result,
[
{
"access_token": "access_token",
"ip": "ip",
"user_agent": "user_agent",
"device_id": None,
"last_seen": 12345878000,
}
],
)
@override_config({"limit_usage_by_mau": False, "max_mau_value": 50})
def test_disabled_monthly_active_user(self):
user_id = "@user:server"
self.get_success(
self.store.insert_client_ip(
user_id, "access_token", "ip", "user_agent", "device_id"
)
)
active = self.get_success(self.store.user_last_seen_monthly_active(user_id))
self.assertFalse(active)
@override_config({"limit_usage_by_mau": True, "max_mau_value": 50})
def test_adding_monthly_active_user_when_full(self):
lots_of_users = 100
user_id = "@user:server"
self.store.get_monthly_active_count = Mock(
return_value=make_awaitable(lots_of_users)
)
self.get_success(
self.store.insert_client_ip(
user_id, "access_token", "ip", "user_agent", "device_id"
)
)
active = self.get_success(self.store.user_last_seen_monthly_active(user_id))
self.assertFalse(active)
@override_config({"limit_usage_by_mau": True, "max_mau_value": 50})
def test_adding_monthly_active_user_when_space(self):
user_id = "@user:server"
active = self.get_success(self.store.user_last_seen_monthly_active(user_id))
self.assertFalse(active)
# Trigger the saving loop
self.reactor.advance(10)
self.get_success(
self.store.insert_client_ip(
user_id, "access_token", "ip", "user_agent", "device_id"
)
)
active = self.get_success(self.store.user_last_seen_monthly_active(user_id))
self.assertTrue(active)
@override_config({"limit_usage_by_mau": True, "max_mau_value": 50})
def test_updating_monthly_active_user_when_space(self):
user_id = "@user:server"
self.get_success(self.store.register_user(user_id=user_id, password_hash=None))
active = self.get_success(self.store.user_last_seen_monthly_active(user_id))
self.assertFalse(active)
# Trigger the saving loop
self.reactor.advance(10)
self.get_success(
self.store.insert_client_ip(
user_id, "access_token", "ip", "user_agent", "device_id"
)
)
active = self.get_success(self.store.user_last_seen_monthly_active(user_id))
self.assertTrue(active)
def test_devices_last_seen_bg_update(self):
# First make sure we have completed all updates.
while not self.get_success(
self.store.db_pool.updates.has_completed_background_updates()
):
self.get_success(
self.store.db_pool.updates.do_next_background_update(100), by=0.1
)
user_id = "@user:id"
device_id = "MY_DEVICE"
# Insert a user IP
self.get_success(
self.store.store_device(
user_id,
device_id,
"display name",
)
)
self.get_success(
self.store.insert_client_ip(
user_id, "access_token", "ip", "user_agent", device_id
)
)
# Force persisting to disk
self.reactor.advance(200)
# But clear the associated entry in devices table
self.get_success(
self.store.db_pool.simple_update(
table="devices",
keyvalues={"user_id": user_id, "device_id": device_id},
updatevalues={"last_seen": None, "ip": None, "user_agent": None},
desc="test_devices_last_seen_bg_update",
)
)
# We should now get nulls when querying
result = self.get_success(
self.store.get_last_client_ip_by_device(user_id, device_id)
)
r = result[(user_id, device_id)]
self.assertDictContainsSubset(
{
"user_id": user_id,
"device_id": device_id,
"ip": None,
"user_agent": None,
"last_seen": None,
},
r,
)
# Register the background update to run again.
self.get_success(
self.store.db_pool.simple_insert(
table="background_updates",
values={
"update_name": "devices_last_seen",
"progress_json": "{}",
"depends_on": None,
},
)
)
# ... and tell the DataStore that it hasn't finished all updates yet
self.store.db_pool.updates._all_done = False
# Now let's actually drive the updates to completion
while not self.get_success(
self.store.db_pool.updates.has_completed_background_updates()
):
self.get_success(
self.store.db_pool.updates.do_next_background_update(100), by=0.1
)
# We should now get the correct result again
result = self.get_success(
self.store.get_last_client_ip_by_device(user_id, device_id)
)
r = result[(user_id, device_id)]
self.assertDictContainsSubset(
{
"user_id": user_id,
"device_id": device_id,
"ip": "ip",
"user_agent": "user_agent",
"last_seen": 0,
},
r,
)
def test_old_user_ips_pruned(self):
# First make sure we have completed all updates.
while not self.get_success(
self.store.db_pool.updates.has_completed_background_updates()
):
self.get_success(
self.store.db_pool.updates.do_next_background_update(100), by=0.1
)
user_id = "@user:id"
device_id = "MY_DEVICE"
# Insert a user IP
self.get_success(
self.store.store_device(
user_id,
device_id,
"display name",
)
)
self.get_success(
self.store.insert_client_ip(
user_id, "access_token", "ip", "user_agent", device_id
)
)
# Force persisting to disk
self.reactor.advance(200)
# We should see that in the DB
result = self.get_success(
self.store.db_pool.simple_select_list(
table="user_ips",
keyvalues={"user_id": user_id},
retcols=["access_token", "ip", "user_agent", "device_id", "last_seen"],
desc="get_user_ip_and_agents",
)
)
self.assertEqual(
result,
[
{
"access_token": "access_token",
"ip": "ip",
"user_agent": "user_agent",
"device_id": device_id,
"last_seen": 0,
}
],
)
# Now advance by a couple of months
self.reactor.advance(60 * 24 * 60 * 60)
# We should get no results.
result = self.get_success(
self.store.db_pool.simple_select_list(
table="user_ips",
keyvalues={"user_id": user_id},
retcols=["access_token", "ip", "user_agent", "device_id", "last_seen"],
desc="get_user_ip_and_agents",
)
)
self.assertEqual(result, [])
# But we should still get the correct values for the device
result = self.get_success(
self.store.get_last_client_ip_by_device(user_id, device_id)
)
r = result[(user_id, device_id)]
self.assertDictContainsSubset(
{
"user_id": user_id,
"device_id": device_id,
"ip": "ip",
"user_agent": "user_agent",
"last_seen": 0,
},
r,
)
class ClientIpAuthTestCase(unittest.HomeserverTestCase):
servlets = [
synapse.rest.admin.register_servlets,
login.register_servlets,
]
def make_homeserver(self, reactor, clock):
hs = self.setup_test_homeserver()
return hs
def prepare(self, hs, reactor, clock):
self.store = self.hs.get_datastore()
self.user_id = self.register_user("bob", "abc123", True)
def test_request_with_xforwarded(self):
"""
The IP in X-Forwarded-For is entered into the client IPs table.
"""
self._runtest(
{b"X-Forwarded-For": b"127.9.0.1"},
"127.9.0.1",
{"request": XForwardedForRequest},
)
def test_request_from_getPeer(self):
"""
The IP returned by getPeer is entered into the client IPs table, if
there's no X-Forwarded-For header.
"""
self._runtest({}, "127.0.0.1", {})
def _runtest(self, headers, expected_ip, make_request_args):
device_id = "bleb"
access_token = self.login("bob", "abc123", device_id=device_id)
# Advance to a known time
self.reactor.advance(123456 - self.reactor.seconds())
headers1 = {b"User-Agent": b"Mozzila pizza"}
headers1.update(headers)
make_request(
self.reactor,
self.site,
"GET",
"/_synapse/admin/v2/users/" + self.user_id,
access_token=access_token,
custom_headers=headers1.items(),
**make_request_args,
)
# Advance so the save loop occurs
self.reactor.advance(100)
result = self.get_success(
self.store.get_last_client_ip_by_device(self.user_id, device_id)
)
r = result[(self.user_id, device_id)]
self.assertDictContainsSubset(
{
"user_id": self.user_id,
"device_id": device_id,
"ip": expected_ip,
"user_agent": "Mozzila pizza",
"last_seen": 123456100,
},
r,
)
| 31.395652 | 87 | 0.549439 |
from unittest.mock import Mock
import synapse.rest.admin
from synapse.http.site import XForwardedForRequest
from synapse.rest.client.v1 import login
from tests import unittest
from tests.server import make_request
from tests.test_utils import make_awaitable
from tests.unittest import override_config
class ClientIpStoreTestCase(unittest.HomeserverTestCase):
def make_homeserver(self, reactor, clock):
hs = self.setup_test_homeserver()
return hs
def prepare(self, hs, reactor, clock):
self.store = self.hs.get_datastore()
def test_insert_new_client_ip(self):
self.reactor.advance(12345678)
user_id = "@user:id"
device_id = "MY_DEVICE"
self.get_success(
self.store.store_device(
user_id,
device_id,
"display name",
)
)
self.get_success(
self.store.insert_client_ip(
user_id, "access_token", "ip", "user_agent", device_id
)
)
self.reactor.advance(10)
result = self.get_success(
self.store.get_last_client_ip_by_device(user_id, device_id)
)
r = result[(user_id, device_id)]
self.assertDictContainsSubset(
{
"user_id": user_id,
"device_id": device_id,
"ip": "ip",
"user_agent": "user_agent",
"last_seen": 12345678000,
},
r,
)
def test_insert_new_client_ip_none_device_id(self):
self.reactor.advance(12345678)
user_id = "@user:id"
self.get_success(
self.store.insert_client_ip(
user_id, "access_token", "ip", "user_agent", None
)
)
self.reactor.advance(200)
self.pump(0)
result = self.get_success(
self.store.db_pool.simple_select_list(
table="user_ips",
keyvalues={"user_id": user_id},
retcols=["access_token", "ip", "user_agent", "device_id", "last_seen"],
desc="get_user_ip_and_agents",
)
)
self.assertEqual(
result,
[
{
"access_token": "access_token",
"ip": "ip",
"user_agent": "user_agent",
"device_id": None,
"last_seen": 12345678000,
}
],
)
self.get_success(
self.store.insert_client_ip(
user_id, "access_token", "ip", "user_agent", None
)
)
self.reactor.advance(10)
self.pump(0)
result = self.get_success(
self.store.db_pool.simple_select_list(
table="user_ips",
keyvalues={"user_id": user_id},
retcols=["access_token", "ip", "user_agent", "device_id", "last_seen"],
desc="get_user_ip_and_agents",
)
)
self.assertEqual(
result,
[
{
"access_token": "access_token",
"ip": "ip",
"user_agent": "user_agent",
"device_id": None,
"last_seen": 12345878000,
}
],
)
@override_config({"limit_usage_by_mau": False, "max_mau_value": 50})
def test_disabled_monthly_active_user(self):
user_id = "@user:server"
self.get_success(
self.store.insert_client_ip(
user_id, "access_token", "ip", "user_agent", "device_id"
)
)
active = self.get_success(self.store.user_last_seen_monthly_active(user_id))
self.assertFalse(active)
@override_config({"limit_usage_by_mau": True, "max_mau_value": 50})
def test_adding_monthly_active_user_when_full(self):
lots_of_users = 100
user_id = "@user:server"
self.store.get_monthly_active_count = Mock(
return_value=make_awaitable(lots_of_users)
)
self.get_success(
self.store.insert_client_ip(
user_id, "access_token", "ip", "user_agent", "device_id"
)
)
active = self.get_success(self.store.user_last_seen_monthly_active(user_id))
self.assertFalse(active)
@override_config({"limit_usage_by_mau": True, "max_mau_value": 50})
def test_adding_monthly_active_user_when_space(self):
user_id = "@user:server"
active = self.get_success(self.store.user_last_seen_monthly_active(user_id))
self.assertFalse(active)
self.reactor.advance(10)
self.get_success(
self.store.insert_client_ip(
user_id, "access_token", "ip", "user_agent", "device_id"
)
)
active = self.get_success(self.store.user_last_seen_monthly_active(user_id))
self.assertTrue(active)
@override_config({"limit_usage_by_mau": True, "max_mau_value": 50})
def test_updating_monthly_active_user_when_space(self):
user_id = "@user:server"
self.get_success(self.store.register_user(user_id=user_id, password_hash=None))
active = self.get_success(self.store.user_last_seen_monthly_active(user_id))
self.assertFalse(active)
self.reactor.advance(10)
self.get_success(
self.store.insert_client_ip(
user_id, "access_token", "ip", "user_agent", "device_id"
)
)
active = self.get_success(self.store.user_last_seen_monthly_active(user_id))
self.assertTrue(active)
def test_devices_last_seen_bg_update(self):
while not self.get_success(
self.store.db_pool.updates.has_completed_background_updates()
):
self.get_success(
self.store.db_pool.updates.do_next_background_update(100), by=0.1
)
user_id = "@user:id"
device_id = "MY_DEVICE"
self.get_success(
self.store.store_device(
user_id,
device_id,
"display name",
)
)
self.get_success(
self.store.insert_client_ip(
user_id, "access_token", "ip", "user_agent", device_id
)
)
self.reactor.advance(200)
self.get_success(
self.store.db_pool.simple_update(
table="devices",
keyvalues={"user_id": user_id, "device_id": device_id},
updatevalues={"last_seen": None, "ip": None, "user_agent": None},
desc="test_devices_last_seen_bg_update",
)
)
result = self.get_success(
self.store.get_last_client_ip_by_device(user_id, device_id)
)
r = result[(user_id, device_id)]
self.assertDictContainsSubset(
{
"user_id": user_id,
"device_id": device_id,
"ip": None,
"user_agent": None,
"last_seen": None,
},
r,
)
self.get_success(
self.store.db_pool.simple_insert(
table="background_updates",
values={
"update_name": "devices_last_seen",
"progress_json": "{}",
"depends_on": None,
},
)
)
self.store.db_pool.updates._all_done = False
# Now let's actually drive the updates to completion
while not self.get_success(
self.store.db_pool.updates.has_completed_background_updates()
):
self.get_success(
self.store.db_pool.updates.do_next_background_update(100), by=0.1
)
result = self.get_success(
self.store.get_last_client_ip_by_device(user_id, device_id)
)
r = result[(user_id, device_id)]
self.assertDictContainsSubset(
{
"user_id": user_id,
"device_id": device_id,
"ip": "ip",
"user_agent": "user_agent",
"last_seen": 0,
},
r,
)
def test_old_user_ips_pruned(self):
while not self.get_success(
self.store.db_pool.updates.has_completed_background_updates()
):
self.get_success(
self.store.db_pool.updates.do_next_background_update(100), by=0.1
)
user_id = "@user:id"
device_id = "MY_DEVICE"
self.get_success(
self.store.store_device(
user_id,
device_id,
"display name",
)
)
self.get_success(
self.store.insert_client_ip(
user_id, "access_token", "ip", "user_agent", device_id
)
)
self.reactor.advance(200)
result = self.get_success(
self.store.db_pool.simple_select_list(
table="user_ips",
keyvalues={"user_id": user_id},
retcols=["access_token", "ip", "user_agent", "device_id", "last_seen"],
desc="get_user_ip_and_agents",
)
)
self.assertEqual(
result,
[
{
"access_token": "access_token",
"ip": "ip",
"user_agent": "user_agent",
"device_id": device_id,
"last_seen": 0,
}
],
)
self.reactor.advance(60 * 24 * 60 * 60)
result = self.get_success(
self.store.db_pool.simple_select_list(
table="user_ips",
keyvalues={"user_id": user_id},
retcols=["access_token", "ip", "user_agent", "device_id", "last_seen"],
desc="get_user_ip_and_agents",
)
)
self.assertEqual(result, [])
result = self.get_success(
self.store.get_last_client_ip_by_device(user_id, device_id)
)
r = result[(user_id, device_id)]
self.assertDictContainsSubset(
{
"user_id": user_id,
"device_id": device_id,
"ip": "ip",
"user_agent": "user_agent",
"last_seen": 0,
},
r,
)
class ClientIpAuthTestCase(unittest.HomeserverTestCase):
servlets = [
synapse.rest.admin.register_servlets,
login.register_servlets,
]
def make_homeserver(self, reactor, clock):
hs = self.setup_test_homeserver()
return hs
def prepare(self, hs, reactor, clock):
self.store = self.hs.get_datastore()
self.user_id = self.register_user("bob", "abc123", True)
def test_request_with_xforwarded(self):
self._runtest(
{b"X-Forwarded-For": b"127.9.0.1"},
"127.9.0.1",
{"request": XForwardedForRequest},
)
def test_request_from_getPeer(self):
self._runtest({}, "127.0.0.1", {})
def _runtest(self, headers, expected_ip, make_request_args):
device_id = "bleb"
access_token = self.login("bob", "abc123", device_id=device_id)
self.reactor.advance(123456 - self.reactor.seconds())
headers1 = {b"User-Agent": b"Mozzila pizza"}
headers1.update(headers)
make_request(
self.reactor,
self.site,
"GET",
"/_synapse/admin/v2/users/" + self.user_id,
access_token=access_token,
custom_headers=headers1.items(),
**make_request_args,
)
self.reactor.advance(100)
result = self.get_success(
self.store.get_last_client_ip_by_device(self.user_id, device_id)
)
r = result[(self.user_id, device_id)]
self.assertDictContainsSubset(
{
"user_id": self.user_id,
"device_id": device_id,
"ip": expected_ip,
"user_agent": "Mozzila pizza",
"last_seen": 123456100,
},
r,
)
| true | true |
f7f753631736997093b14272740f46e184248add | 4,286 | py | Python | models/LSTM_Attn.py | lxh5147/Text-Classification-Pytorch | 51f9189aad62051127c5a537c72ab3a8b0f97c60 | [
"MIT"
] | 1 | 2019-09-20T18:16:33.000Z | 2019-09-20T18:16:33.000Z | models/LSTM_Attn.py | lxh5147/Text-Classification-Pytorch | 51f9189aad62051127c5a537c72ab3a8b0f97c60 | [
"MIT"
] | null | null | null | models/LSTM_Attn.py | lxh5147/Text-Classification-Pytorch | 51f9189aad62051127c5a537c72ab3a8b0f97c60 | [
"MIT"
] | null | null | null | # _*_ coding: utf-8 _*_
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.nn import functional as F
class AttentionModel(torch.nn.Module):
def __init__(self, batch_size, output_size, hidden_size, vocab_size, embedding_length, weights):
super(AttentionModel, self).__init__()
"""
Arguments
---------
batch_size : Size of the batch which is same as the batch_size of the data returned by the TorchText BucketIterator
output_size : 2 = (pos, neg)
hidden_sie : Size of the hidden_state of the LSTM
vocab_size : Size of the vocabulary containing unique words
embedding_length : Embeddding dimension of GloVe word embeddings
weights : Pre-trained GloVe word_embeddings which we will use to create our word_embedding look-up table
--------
"""
self.batch_size = batch_size
self.output_size = output_size
self.hidden_size = hidden_size
self.vocab_size = vocab_size
self.embedding_length = embedding_length
self.word_embeddings = nn.Embedding(vocab_size, embedding_length)
self.word_embeddings.weights = nn.Parameter(weights, requires_grad=False)
self.lstm = nn.LSTM(embedding_length, hidden_size)
self.label = nn.Linear(hidden_size, output_size)
# self.attn_fc_layer = nn.Linear()
def attention_net(self, lstm_output, final_state):
"""
Now we will incorporate Attention mechanism in our LSTM model. In this new model, we will use attention to compute soft alignment score corresponding
between each of the hidden_state and the last hidden_state of the LSTM. We will be using torch.bmm for the batch matrix multiplication.
Arguments
---------
lstm_output : Final output of the LSTM which contains hidden layer outputs for each sequence.
final_state : Final time-step hidden state (h_n) of the LSTM
---------
Returns : It performs attention mechanism by first computing weights for each of the sequence present in lstm_output and and then finally computing the
new hidden state.
Tensor Size :
hidden.size() = (batch_size, hidden_size)
attn_weights.size() = (batch_size, num_seq)
soft_attn_weights.size() = (batch_size, num_seq)
new_hidden_state.size() = (batch_size, hidden_size)
"""
hidden = final_state.squeeze(0)
attn_weights = torch.bmm(lstm_output, hidden.unsqueeze(2)).squeeze(2)
soft_attn_weights = F.softmax(attn_weights, 1)
new_hidden_state = torch.bmm(lstm_output.transpose(1, 2), soft_attn_weights.unsqueeze(2)).squeeze(2)
return new_hidden_state
def forward(self, input_sentences, batch_size=None):
"""
Parameters
----------
input_sentence: input_sentence of shape = (batch_size, num_sequences)
batch_size : default = None. Used only for prediction on a single sentence after training (batch_size = 1)
Returns
-------
Output of the linear layer containing logits for pos & neg class which receives its input as the new_hidden_state which is basically the output of the Attention network.
final_output.shape = (batch_size, output_size)
"""
input = self.word_embeddings(input_sentences)
input = input.permute(1, 0, 2)
if batch_size is None:
h_0 = torch.zeros(1, self.batch_size, self.hidden_size)
c_0 = torch.zeros(1, self.batch_size, self.hidden_size)
else:
h_0 = torch.zeros(1, batch_size, self.hidden_size)
c_0 = torch.zeros(1, batch_size, self.hidden_size)
if torch.cuda.is_available():
h_0 = h_0.cuda()
c_0 = c_0.cuda()
output, (final_hidden_state, final_cell_state) = self.lstm(input, (
h_0, c_0)) # final_hidden_state.size() = (1, batch_size, hidden_size)
output = output.permute(1, 0, 2) # output.size() = (batch_size, num_seq, hidden_size)
attn_output = self.attention_net(output, final_hidden_state)
logits = self.label(attn_output)
return logits
| 39.685185 | 177 | 0.654456 |
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.nn import functional as F
class AttentionModel(torch.nn.Module):
def __init__(self, batch_size, output_size, hidden_size, vocab_size, embedding_length, weights):
super(AttentionModel, self).__init__()
self.batch_size = batch_size
self.output_size = output_size
self.hidden_size = hidden_size
self.vocab_size = vocab_size
self.embedding_length = embedding_length
self.word_embeddings = nn.Embedding(vocab_size, embedding_length)
self.word_embeddings.weights = nn.Parameter(weights, requires_grad=False)
self.lstm = nn.LSTM(embedding_length, hidden_size)
self.label = nn.Linear(hidden_size, output_size)
def attention_net(self, lstm_output, final_state):
hidden = final_state.squeeze(0)
attn_weights = torch.bmm(lstm_output, hidden.unsqueeze(2)).squeeze(2)
soft_attn_weights = F.softmax(attn_weights, 1)
new_hidden_state = torch.bmm(lstm_output.transpose(1, 2), soft_attn_weights.unsqueeze(2)).squeeze(2)
return new_hidden_state
def forward(self, input_sentences, batch_size=None):
input = self.word_embeddings(input_sentences)
input = input.permute(1, 0, 2)
if batch_size is None:
h_0 = torch.zeros(1, self.batch_size, self.hidden_size)
c_0 = torch.zeros(1, self.batch_size, self.hidden_size)
else:
h_0 = torch.zeros(1, batch_size, self.hidden_size)
c_0 = torch.zeros(1, batch_size, self.hidden_size)
if torch.cuda.is_available():
h_0 = h_0.cuda()
c_0 = c_0.cuda()
output, (final_hidden_state, final_cell_state) = self.lstm(input, (
h_0, c_0))
output = output.permute(1, 0, 2)
attn_output = self.attention_net(output, final_hidden_state)
logits = self.label(attn_output)
return logits
| true | true |
f7f7536ba50888f24d4f09fb8604303ffc29a4a1 | 3,198 | py | Python | tests/func/test_remove.py | mrstegeman/dvc | 03fc531a5c1f3814061e83bc26e7af5b0ff02f1d | [
"Apache-2.0"
] | null | null | null | tests/func/test_remove.py | mrstegeman/dvc | 03fc531a5c1f3814061e83bc26e7af5b0ff02f1d | [
"Apache-2.0"
] | 2 | 2020-02-10T03:57:58.000Z | 2020-10-12T00:33:01.000Z | tests/func/test_remove.py | mrstegeman/dvc | 03fc531a5c1f3814061e83bc26e7af5b0ff02f1d | [
"Apache-2.0"
] | 1 | 2021-02-06T12:48:24.000Z | 2021-02-06T12:48:24.000Z | import os
import pytest
from dvc.exceptions import DvcException
from dvc.main import main
from dvc.stage.exceptions import StageFileDoesNotExistError
from dvc.system import System
from dvc.utils.fs import remove
from tests.utils import get_gitignore_content
@pytest.mark.parametrize("remove_outs", [True, False])
def test_remove(tmp_dir, scm, dvc, run_copy, remove_outs):
(stage1,) = tmp_dir.dvc_gen("foo", "foo")
stage2 = run_copy("foo", "bar", single_stage=True)
stage3 = run_copy("bar", "foobar", name="copy-bar-foobar")
assert "/foo" in get_gitignore_content()
assert "/bar" in get_gitignore_content()
assert "/foobar" in get_gitignore_content()
for stage in [stage1, stage2, stage3]:
dvc.remove(stage.addressing, outs=remove_outs)
out_exists = (out.exists for out in stage.outs)
assert stage not in dvc.stage.collect_repo()
if remove_outs:
assert not any(out_exists)
else:
assert all(out_exists)
assert not (tmp_dir / ".gitignore").exists()
def test_remove_non_existent_file(tmp_dir, dvc):
with pytest.raises(StageFileDoesNotExistError):
dvc.remove("non_existent_dvc_file.dvc")
with pytest.raises(StageFileDoesNotExistError):
dvc.remove("non_existent_stage_name")
def test_remove_broken_symlink(tmp_dir, dvc):
tmp_dir.gen("foo", "foo")
dvc.cache.local.cache_types = ["symlink"]
(stage,) = dvc.add("foo")
remove(dvc.cache.local.cache_dir)
assert System.is_symlink("foo")
with pytest.raises(DvcException):
dvc.remove(stage.addressing)
assert os.path.lexists("foo")
assert (tmp_dir / stage.relpath).exists()
dvc.remove(stage.addressing, outs=True)
assert not os.path.lexists("foo")
assert not (tmp_dir / stage.relpath).exists()
def test_cmd_remove(tmp_dir, dvc):
assert main(["remove", "non-existing-dvc-file"]) == 1
(stage,) = tmp_dir.dvc_gen("foo", "foo")
assert main(["remove", stage.addressing]) == 0
assert not (tmp_dir / stage.relpath).exists()
assert (tmp_dir / "foo").exists()
(stage,) = tmp_dir.dvc_gen("foo", "foo")
assert main(["remove", stage.addressing, "--outs"]) == 0
assert not (tmp_dir / stage.relpath).exists()
assert not (tmp_dir / "foo").exists()
def test_cmd_remove_gitignore_single_stage(tmp_dir, scm, dvc, run_copy):
stage = dvc.run(
name="my", cmd='echo "hello" > out', deps=[], outs=["out"],
)
assert (tmp_dir / ".gitignore").exists()
assert main(["remove", stage.addressing]) == 0
assert not (tmp_dir / stage.relpath).exists()
assert not (stage.dvcfile._lockfile).exists()
assert not (tmp_dir / ".gitignore").exists()
def test_cmd_remove_gitignore_multistage(tmp_dir, scm, dvc, run_copy):
(stage,) = tmp_dir.dvc_gen("foo", "foo")
stage1 = run_copy("foo", "foo1", single_stage=True)
stage2 = run_copy("foo1", "foo2", name="copy-foo1-foo2")
assert (tmp_dir / ".gitignore").exists()
assert main(["remove", stage2.addressing]) == 0
assert main(["remove", stage1.addressing]) == 0
assert main(["remove", stage.addressing]) == 0
assert not (tmp_dir / ".gitignore").exists()
| 32.632653 | 72 | 0.674484 | import os
import pytest
from dvc.exceptions import DvcException
from dvc.main import main
from dvc.stage.exceptions import StageFileDoesNotExistError
from dvc.system import System
from dvc.utils.fs import remove
from tests.utils import get_gitignore_content
@pytest.mark.parametrize("remove_outs", [True, False])
def test_remove(tmp_dir, scm, dvc, run_copy, remove_outs):
(stage1,) = tmp_dir.dvc_gen("foo", "foo")
stage2 = run_copy("foo", "bar", single_stage=True)
stage3 = run_copy("bar", "foobar", name="copy-bar-foobar")
assert "/foo" in get_gitignore_content()
assert "/bar" in get_gitignore_content()
assert "/foobar" in get_gitignore_content()
for stage in [stage1, stage2, stage3]:
dvc.remove(stage.addressing, outs=remove_outs)
out_exists = (out.exists for out in stage.outs)
assert stage not in dvc.stage.collect_repo()
if remove_outs:
assert not any(out_exists)
else:
assert all(out_exists)
assert not (tmp_dir / ".gitignore").exists()
def test_remove_non_existent_file(tmp_dir, dvc):
with pytest.raises(StageFileDoesNotExistError):
dvc.remove("non_existent_dvc_file.dvc")
with pytest.raises(StageFileDoesNotExistError):
dvc.remove("non_existent_stage_name")
def test_remove_broken_symlink(tmp_dir, dvc):
tmp_dir.gen("foo", "foo")
dvc.cache.local.cache_types = ["symlink"]
(stage,) = dvc.add("foo")
remove(dvc.cache.local.cache_dir)
assert System.is_symlink("foo")
with pytest.raises(DvcException):
dvc.remove(stage.addressing)
assert os.path.lexists("foo")
assert (tmp_dir / stage.relpath).exists()
dvc.remove(stage.addressing, outs=True)
assert not os.path.lexists("foo")
assert not (tmp_dir / stage.relpath).exists()
def test_cmd_remove(tmp_dir, dvc):
assert main(["remove", "non-existing-dvc-file"]) == 1
(stage,) = tmp_dir.dvc_gen("foo", "foo")
assert main(["remove", stage.addressing]) == 0
assert not (tmp_dir / stage.relpath).exists()
assert (tmp_dir / "foo").exists()
(stage,) = tmp_dir.dvc_gen("foo", "foo")
assert main(["remove", stage.addressing, "--outs"]) == 0
assert not (tmp_dir / stage.relpath).exists()
assert not (tmp_dir / "foo").exists()
def test_cmd_remove_gitignore_single_stage(tmp_dir, scm, dvc, run_copy):
stage = dvc.run(
name="my", cmd='echo "hello" > out', deps=[], outs=["out"],
)
assert (tmp_dir / ".gitignore").exists()
assert main(["remove", stage.addressing]) == 0
assert not (tmp_dir / stage.relpath).exists()
assert not (stage.dvcfile._lockfile).exists()
assert not (tmp_dir / ".gitignore").exists()
def test_cmd_remove_gitignore_multistage(tmp_dir, scm, dvc, run_copy):
(stage,) = tmp_dir.dvc_gen("foo", "foo")
stage1 = run_copy("foo", "foo1", single_stage=True)
stage2 = run_copy("foo1", "foo2", name="copy-foo1-foo2")
assert (tmp_dir / ".gitignore").exists()
assert main(["remove", stage2.addressing]) == 0
assert main(["remove", stage1.addressing]) == 0
assert main(["remove", stage.addressing]) == 0
assert not (tmp_dir / ".gitignore").exists()
| true | true |
f7f7543cf04437475c253ab4731019e1fc5df3d2 | 9,624 | py | Python | robosat_pink/tools/rasterize.py | MinnDevelopment/robosat.pink | 0e4b88a7b1fc91e2a20e5e3bf0c4f742be9ea2c5 | [
"MIT"
] | null | null | null | robosat_pink/tools/rasterize.py | MinnDevelopment/robosat.pink | 0e4b88a7b1fc91e2a20e5e3bf0c4f742be9ea2c5 | [
"MIT"
] | null | null | null | robosat_pink/tools/rasterize.py | MinnDevelopment/robosat.pink | 0e4b88a7b1fc91e2a20e5e3bf0c4f742be9ea2c5 | [
"MIT"
] | null | null | null | import os
import sys
import json
import collections
import numpy as np
from tqdm import tqdm
import mercantile
from rasterio.crs import CRS
from rasterio.transform import from_bounds
from rasterio.features import rasterize
from rasterio.warp import transform
from supermercado import burntiles
import psycopg2
from robosat_pink.core import load_config, check_classes, make_palette, web_ui, Logs
from robosat_pink.tiles import tiles_from_csv, tile_label_to_file, tile_bbox
def add_parser(subparser, formatter_class):
parser = subparser.add_parser(
"rasterize", help="Rasterize GeoJSON or PostGIS features to tiles", formatter_class=formatter_class
)
inp = parser.add_argument_group("Inputs [either --postgis or --geojson is required]")
inp.add_argument("--cover", type=str, help="path to csv tiles cover file [required]")
inp.add_argument("--config", type=str, help="path to config file [required]")
inp.add_argument("--type", type=str, required=True, help="type of feature to rasterize (e.g Building, Road) [required]")
inp.add_argument("--pg", type=str, help="PostgreSQL dsn using psycopg2 syntax (e.g 'dbname=db user=postgres')")
inp.add_argument("--sql", type=str, help="SQL to retrieve geometry features [e.g SELECT geom FROM your_table]")
inp.add_argument("--geojson", type=str, nargs="+", help="path to GeoJSON features files")
out = parser.add_argument_group("Outputs")
out.add_argument("out", type=str, help="output directory path [required]")
out.add_argument("--ts", type=int, default=512, help="output tile size [default: 512]")
ui = parser.add_argument_group("Web UI")
ui.add_argument("--web_ui_base_url", type=str, help="alternate Web UI base URL")
ui.add_argument("--web_ui_template", type=str, help="alternate Web UI template path")
ui.add_argument("--no_web_ui", action="store_true", help="desactivate Web UI output")
parser.set_defaults(func=main)
def geojson_reproject(feature, srid_in, srid_out):
"""Reproject GeoJSON Polygon feature coords
Inspired by: https://gist.github.com/dnomadb/5cbc116aacc352c7126e779c29ab7abe
"""
if feature["geometry"]["type"] == "Polygon":
xys = (zip(*ring) for ring in feature["geometry"]["coordinates"])
xys = (list(zip(*transform(CRS.from_epsg(srid_in), CRS.from_epsg(srid_out), *xy))) for xy in xys)
yield {"coordinates": list(xys), "type": "Polygon"}
def geojson_tile_burn(tile, features, srid, ts, burn_value=1):
"""Burn tile with GeoJSON features."""
shapes = ((geometry, burn_value) for feature in features for geometry in geojson_reproject(feature, srid, 3857))
bounds = tile_bbox(tile, mercator=True)
transform = from_bounds(*bounds, ts, ts)
try:
return rasterize(shapes, out_shape=(ts, ts), transform=transform)
except:
return None
def main(args):
if args.pg:
if not args.sql:
sys.exit("ERROR: With PostgreSQL db, --sql must be provided")
if (args.sql and args.geojson) or (args.sql and not args.pg):
sys.exit("ERROR: You can use either --pg or --geojson inputs, but only one at once.")
config = load_config(args.config)
check_classes(config)
palette = make_palette(*[classe["color"] for classe in config["classes"]], complementary=True)
burn_value = next(config["classes"].index(classe) for classe in config["classes"] if classe["title"] == args.type)
if "burn_value" not in locals():
sys.exit("ERROR: asked type to rasterize is not contains in your config file classes.")
args.out = os.path.expanduser(args.out)
os.makedirs(args.out, exist_ok=True)
log = Logs(os.path.join(args.out, "log"), out=sys.stderr)
def geojson_parse_polygon(zoom, srid, feature_map, polygon, i):
try:
if srid != 4326:
polygon = [xy for xy in geojson_reproject({"type": "feature", "geometry": polygon}, srid, 4326)][0]
for i, ring in enumerate(polygon["coordinates"]): # GeoJSON coordinates could be N dimensionals
polygon["coordinates"][i] = [[x, y] for point in ring for x, y in zip([point[0]], [point[1]])]
if polygon["coordinates"]:
for tile in burntiles.burn([{"type": "feature", "geometry": polygon}], zoom=zoom):
feature_map[mercantile.Tile(*tile)].append({"type": "feature", "geometry": polygon})
except ValueError:
log.log("Warning: invalid feature {}, skipping".format(i))
return feature_map
def geojson_parse_geometry(zoom, srid, feature_map, geometry, i):
if geometry["type"] == "Polygon":
feature_map = geojson_parse_polygon(zoom, srid, feature_map, geometry, i)
elif geometry["type"] == "MultiPolygon":
for polygon in geometry["coordinates"]:
feature_map = geojson_parse_polygon(zoom, srid, feature_map, {"type": "Polygon", "coordinates": polygon}, i)
else:
log.log("Notice: {} is a non surfacic geometry type, skipping feature {}".format(geometry["type"], i))
return feature_map
if args.geojson:
tiles = [tile for tile in tiles_from_csv(os.path.expanduser(args.cover))]
assert tiles, "Empty cover"
zoom = tiles[0].z
assert not [tile for tile in tiles if tile.z != zoom], "Unsupported zoom mixed cover. Use PostGIS instead"
feature_map = collections.defaultdict(list)
log.log("RoboSat.pink - rasterize - Compute spatial index")
for geojson_file in args.geojson:
with open(os.path.expanduser(geojson_file)) as geojson:
feature_collection = json.load(geojson)
try:
crs_mapping = {"CRS84": "4326", "900913": "3857"}
srid = feature_collection["crs"]["properties"]["name"].split(":")[-1]
srid = int(srid) if srid not in crs_mapping else int(crs_mapping[srid])
except:
srid = int(4326)
for i, feature in enumerate(tqdm(feature_collection["features"], ascii=True, unit="feature")):
if feature["geometry"]["type"] == "GeometryCollection":
for geometry in feature["geometry"]["geometries"]:
feature_map = geojson_parse_geometry(zoom, srid, feature_map, geometry, i)
else:
feature_map = geojson_parse_geometry(zoom, srid, feature_map, feature["geometry"], i)
features = args.geojson
if args.pg:
conn = psycopg2.connect(args.pg)
db = conn.cursor()
assert "limit" not in args.sql.lower(), "LIMIT is not supported"
db.execute("SELECT ST_Srid(geom) AS srid FROM ({} LIMIT 1) AS sub".format(args.sql))
srid = db.fetchone()[0]
assert srid, "Unable to retrieve geometry SRID."
if "where" not in args.sql.lower(): # TODO: Find a more reliable way to handle feature filtering
args.sql += " WHERE ST_Intersects(tile.geom, geom)"
else:
args.sql += " AND ST_Intersects(tile.geom, geom)"
features = args.sql
log.log("RoboSat.pink - rasterize - rasterizing {} from {} on cover {}".format(args.type, features, args.cover))
with open(os.path.join(os.path.expanduser(args.out), "instances.cover"), mode="w") as cover:
for tile in tqdm(list(tiles_from_csv(os.path.expanduser(args.cover))), ascii=True, unit="tile"):
geojson = None
if args.pg:
w, s, e, n = tile_bbox(tile)
query = """
WITH
tile AS (SELECT ST_Transform(ST_MakeEnvelope({},{},{},{}, 4326), {}) AS geom),
geom AS (SELECT ST_Intersection(tile.geom, sql.geom) AS geom FROM tile CROSS JOIN LATERAL ({}) sql),
json AS (SELECT '{{"type": "Feature", "geometry": '
|| ST_AsGeoJSON((ST_Dump(ST_Transform(ST_Force2D(geom.geom), 4326))).geom, 6)
|| '}}' AS features
FROM geom)
SELECT '{{"type": "FeatureCollection", "features": [' || Array_To_String(array_agg(features), ',') || ']}}'
FROM json
""".format(
w, s, e, n, srid, args.sql
)
db.execute(query)
row = db.fetchone()
try:
geojson = json.loads(row[0])["features"] if row and row[0] else None
except Exception:
log.log("Warning: Invalid geometries, skipping {}".format(tile))
conn = psycopg2.connect(args.pg)
db = conn.cursor()
if args.geojson:
geojson = feature_map[tile] if tile in feature_map else None
if geojson:
num = len(geojson)
out = geojson_tile_burn(tile, geojson, 4326, args.ts, burn_value)
if not geojson or out is None:
num = 0
out = np.zeros(shape=(args.ts, args.ts), dtype=np.uint8)
tile_label_to_file(args.out, tile, palette, out)
cover.write("{},{},{} {}{}".format(tile.x, tile.y, tile.z, num, os.linesep))
if not args.no_web_ui:
template = "leaflet.html" if not args.web_ui_template else args.web_ui_template
base_url = args.web_ui_base_url if args.web_ui_base_url else "./"
tiles = [tile for tile in tiles_from_csv(args.cover)]
web_ui(args.out, base_url, tiles, tiles, "png", template)
| 42.773333 | 124 | 0.617623 | import os
import sys
import json
import collections
import numpy as np
from tqdm import tqdm
import mercantile
from rasterio.crs import CRS
from rasterio.transform import from_bounds
from rasterio.features import rasterize
from rasterio.warp import transform
from supermercado import burntiles
import psycopg2
from robosat_pink.core import load_config, check_classes, make_palette, web_ui, Logs
from robosat_pink.tiles import tiles_from_csv, tile_label_to_file, tile_bbox
def add_parser(subparser, formatter_class):
parser = subparser.add_parser(
"rasterize", help="Rasterize GeoJSON or PostGIS features to tiles", formatter_class=formatter_class
)
inp = parser.add_argument_group("Inputs [either --postgis or --geojson is required]")
inp.add_argument("--cover", type=str, help="path to csv tiles cover file [required]")
inp.add_argument("--config", type=str, help="path to config file [required]")
inp.add_argument("--type", type=str, required=True, help="type of feature to rasterize (e.g Building, Road) [required]")
inp.add_argument("--pg", type=str, help="PostgreSQL dsn using psycopg2 syntax (e.g 'dbname=db user=postgres')")
inp.add_argument("--sql", type=str, help="SQL to retrieve geometry features [e.g SELECT geom FROM your_table]")
inp.add_argument("--geojson", type=str, nargs="+", help="path to GeoJSON features files")
out = parser.add_argument_group("Outputs")
out.add_argument("out", type=str, help="output directory path [required]")
out.add_argument("--ts", type=int, default=512, help="output tile size [default: 512]")
ui = parser.add_argument_group("Web UI")
ui.add_argument("--web_ui_base_url", type=str, help="alternate Web UI base URL")
ui.add_argument("--web_ui_template", type=str, help="alternate Web UI template path")
ui.add_argument("--no_web_ui", action="store_true", help="desactivate Web UI output")
parser.set_defaults(func=main)
def geojson_reproject(feature, srid_in, srid_out):
if feature["geometry"]["type"] == "Polygon":
xys = (zip(*ring) for ring in feature["geometry"]["coordinates"])
xys = (list(zip(*transform(CRS.from_epsg(srid_in), CRS.from_epsg(srid_out), *xy))) for xy in xys)
yield {"coordinates": list(xys), "type": "Polygon"}
def geojson_tile_burn(tile, features, srid, ts, burn_value=1):
shapes = ((geometry, burn_value) for feature in features for geometry in geojson_reproject(feature, srid, 3857))
bounds = tile_bbox(tile, mercator=True)
transform = from_bounds(*bounds, ts, ts)
try:
return rasterize(shapes, out_shape=(ts, ts), transform=transform)
except:
return None
def main(args):
if args.pg:
if not args.sql:
sys.exit("ERROR: With PostgreSQL db, --sql must be provided")
if (args.sql and args.geojson) or (args.sql and not args.pg):
sys.exit("ERROR: You can use either --pg or --geojson inputs, but only one at once.")
config = load_config(args.config)
check_classes(config)
palette = make_palette(*[classe["color"] for classe in config["classes"]], complementary=True)
burn_value = next(config["classes"].index(classe) for classe in config["classes"] if classe["title"] == args.type)
if "burn_value" not in locals():
sys.exit("ERROR: asked type to rasterize is not contains in your config file classes.")
args.out = os.path.expanduser(args.out)
os.makedirs(args.out, exist_ok=True)
log = Logs(os.path.join(args.out, "log"), out=sys.stderr)
def geojson_parse_polygon(zoom, srid, feature_map, polygon, i):
try:
if srid != 4326:
polygon = [xy for xy in geojson_reproject({"type": "feature", "geometry": polygon}, srid, 4326)][0]
for i, ring in enumerate(polygon["coordinates"]):
polygon["coordinates"][i] = [[x, y] for point in ring for x, y in zip([point[0]], [point[1]])]
if polygon["coordinates"]:
for tile in burntiles.burn([{"type": "feature", "geometry": polygon}], zoom=zoom):
feature_map[mercantile.Tile(*tile)].append({"type": "feature", "geometry": polygon})
except ValueError:
log.log("Warning: invalid feature {}, skipping".format(i))
return feature_map
def geojson_parse_geometry(zoom, srid, feature_map, geometry, i):
if geometry["type"] == "Polygon":
feature_map = geojson_parse_polygon(zoom, srid, feature_map, geometry, i)
elif geometry["type"] == "MultiPolygon":
for polygon in geometry["coordinates"]:
feature_map = geojson_parse_polygon(zoom, srid, feature_map, {"type": "Polygon", "coordinates": polygon}, i)
else:
log.log("Notice: {} is a non surfacic geometry type, skipping feature {}".format(geometry["type"], i))
return feature_map
if args.geojson:
tiles = [tile for tile in tiles_from_csv(os.path.expanduser(args.cover))]
assert tiles, "Empty cover"
zoom = tiles[0].z
assert not [tile for tile in tiles if tile.z != zoom], "Unsupported zoom mixed cover. Use PostGIS instead"
feature_map = collections.defaultdict(list)
log.log("RoboSat.pink - rasterize - Compute spatial index")
for geojson_file in args.geojson:
with open(os.path.expanduser(geojson_file)) as geojson:
feature_collection = json.load(geojson)
try:
crs_mapping = {"CRS84": "4326", "900913": "3857"}
srid = feature_collection["crs"]["properties"]["name"].split(":")[-1]
srid = int(srid) if srid not in crs_mapping else int(crs_mapping[srid])
except:
srid = int(4326)
for i, feature in enumerate(tqdm(feature_collection["features"], ascii=True, unit="feature")):
if feature["geometry"]["type"] == "GeometryCollection":
for geometry in feature["geometry"]["geometries"]:
feature_map = geojson_parse_geometry(zoom, srid, feature_map, geometry, i)
else:
feature_map = geojson_parse_geometry(zoom, srid, feature_map, feature["geometry"], i)
features = args.geojson
if args.pg:
conn = psycopg2.connect(args.pg)
db = conn.cursor()
assert "limit" not in args.sql.lower(), "LIMIT is not supported"
db.execute("SELECT ST_Srid(geom) AS srid FROM ({} LIMIT 1) AS sub".format(args.sql))
srid = db.fetchone()[0]
assert srid, "Unable to retrieve geometry SRID."
if "where" not in args.sql.lower():
args.sql += " WHERE ST_Intersects(tile.geom, geom)"
else:
args.sql += " AND ST_Intersects(tile.geom, geom)"
features = args.sql
log.log("RoboSat.pink - rasterize - rasterizing {} from {} on cover {}".format(args.type, features, args.cover))
with open(os.path.join(os.path.expanduser(args.out), "instances.cover"), mode="w") as cover:
for tile in tqdm(list(tiles_from_csv(os.path.expanduser(args.cover))), ascii=True, unit="tile"):
geojson = None
if args.pg:
w, s, e, n = tile_bbox(tile)
query = """
WITH
tile AS (SELECT ST_Transform(ST_MakeEnvelope({},{},{},{}, 4326), {}) AS geom),
geom AS (SELECT ST_Intersection(tile.geom, sql.geom) AS geom FROM tile CROSS JOIN LATERAL ({}) sql),
json AS (SELECT '{{"type": "Feature", "geometry": '
|| ST_AsGeoJSON((ST_Dump(ST_Transform(ST_Force2D(geom.geom), 4326))).geom, 6)
|| '}}' AS features
FROM geom)
SELECT '{{"type": "FeatureCollection", "features": [' || Array_To_String(array_agg(features), ',') || ']}}'
FROM json
""".format(
w, s, e, n, srid, args.sql
)
db.execute(query)
row = db.fetchone()
try:
geojson = json.loads(row[0])["features"] if row and row[0] else None
except Exception:
log.log("Warning: Invalid geometries, skipping {}".format(tile))
conn = psycopg2.connect(args.pg)
db = conn.cursor()
if args.geojson:
geojson = feature_map[tile] if tile in feature_map else None
if geojson:
num = len(geojson)
out = geojson_tile_burn(tile, geojson, 4326, args.ts, burn_value)
if not geojson or out is None:
num = 0
out = np.zeros(shape=(args.ts, args.ts), dtype=np.uint8)
tile_label_to_file(args.out, tile, palette, out)
cover.write("{},{},{} {}{}".format(tile.x, tile.y, tile.z, num, os.linesep))
if not args.no_web_ui:
template = "leaflet.html" if not args.web_ui_template else args.web_ui_template
base_url = args.web_ui_base_url if args.web_ui_base_url else "./"
tiles = [tile for tile in tiles_from_csv(args.cover)]
web_ui(args.out, base_url, tiles, tiles, "png", template)
| true | true |
f7f75508c9afb6ec184e85b4b6b62ae88a847469 | 8,772 | py | Python | app/src/main/python/image.py | CCH852573130/3DPrinting10 | ca843d728bd7501f332a7946976c40d86b362930 | [
"MIT"
] | null | null | null | app/src/main/python/image.py | CCH852573130/3DPrinting10 | ca843d728bd7501f332a7946976c40d86b362930 | [
"MIT"
] | null | null | null | app/src/main/python/image.py | CCH852573130/3DPrinting10 | ca843d728bd7501f332a7946976c40d86b362930 | [
"MIT"
] | 3 | 2020-04-12T01:53:41.000Z | 2020-07-06T08:07:49.000Z | # coding=utf-8
import numpy
import time
import struct
from PIL import Image
from MeshBuilder import MeshBuilder
from Vector import Vector
from CuraSceneNode import CuraSceneNode as SceneNode
def generateSceneNode(file_name, xz_size, peak_height, base_height, blur_iterations, max_size,lighter_is_higher,file):
scene_node = SceneNode()
mesh = MeshBuilder()#初始化
# img = QImage(file_name)
im= Image.open(file_name)
# if im.isNull():
# Logger.log("e", "Image is corrupt.")
# return None
# width = max(img.width(), 2)
# height = max(img.height(), 2)
width = max(im.size[0], 2)
height = max(im.size[1], 2)
aspect = height / width
# if im.width() < 2 or im.height() < 2:
# img = img.scaled(width, height, Qt.IgnoreAspectRatio)
# im = im.resize(width, height, Image.ANTIALIAS)
base_height = max(base_height, 0)
peak_height = max(peak_height, -base_height)
xz_size = max(xz_size, blur_iterations)
scale_vector = Vector(xz_size, peak_height, xz_size)
if width > height:
scale_vector = scale_vector.set(z=scale_vector.z * aspect)
elif height > width:
scale_vector = scale_vector.set(x=scale_vector.x / aspect)
if width > max_size or height > max_size:
scale_factor = max_size / width
if height > width:
scale_factor = max_size / height
width = int(max(round(width * scale_factor), 2))
height = int(max(round(height * scale_factor), 2))
# img = img.scaled(width, height, Qt.IgnoreAspectRatio)
im = im.resize((width, height), Image.ANTIALIAS)
width_minus_one = width - 1
height_minus_one = height - 1
#Job.yieldThread()
texel_width = 1.0 / (width_minus_one) * scale_vector.x
texel_height = 1.0 / (height_minus_one) * scale_vector.z
height_data = numpy.zeros((height, width), dtype=numpy.float32)
for x in range(0, width):
for y in range(0, height):
# qrgb = img.pixel(x, y)
qrgb = im.getpixel((x, y))
R=qrgb[0]
G=qrgb[1]
B=qrgb[2]
avg=float(R+G+B)/(3*255)
# qR=qRed(qrgb)
# qG=qGreen(qrgb)
# qB=qBlue(qrgb)
# avg=float(qR+qG+qB)/(3 * 255)
# avg = float(qRed(qrgb) + qGreen(qrgb) + qBlue(qrgb)) / (3 * 255)
height_data[y, x] = avg
#Job.yieldThread()
if not lighter_is_higher:
height_data = 1 - height_data
for _ in range(0,blur_iterations):
copy = numpy.pad(height_data, ((1, 1), (1, 1)), mode="edge")
height_data += copy[1:-1, 2:]
height_data += copy[1:-1, :-2]
height_data += copy[2:, 1:-1]
height_data += copy[:-2, 1:-1]
height_data += copy[2:, 2:]
height_data += copy[:-2, 2:]
height_data += copy[2:, :-2]
height_data += copy[:-2, :-2]
height_data /= 9
# Job.yieldThread()
height_data *= scale_vector.y
height_data += base_height
heightmap_face_count = 2 * height_minus_one * width_minus_one
total_face_count = heightmap_face_count + (width_minus_one * 2) * (height_minus_one * 2) + 2
mesh.reserveFaceCount(total_face_count)
# initialize to texel space vertex offsets.
# 6 is for 6 vertices for each texel quad.
heightmap_vertices = numpy.zeros((width_minus_one * height_minus_one, 6, 3), dtype=numpy.float32)
heightmap_vertices = heightmap_vertices + numpy.array([[
[0, base_height, 0],
[0, base_height, texel_height],
[texel_width, base_height, texel_height],
[texel_width, base_height, texel_height],
[texel_width, base_height, 0],
[0, base_height, 0]
]], dtype=numpy.float32)
offsetsz, offsetsx = numpy.mgrid[0: height_minus_one, 0: width - 1]
offsetsx = numpy.array(offsetsx, numpy.float32).reshape(-1, 1) * texel_width
offsetsz = numpy.array(offsetsz, numpy.float32).reshape(-1, 1) * texel_height
# offsets for each texel quad
heightmap_vertex_offsets = numpy.concatenate(
[offsetsx, numpy.zeros((offsetsx.shape[0], offsetsx.shape[1]), dtype=numpy.float32), offsetsz], 1)
heightmap_vertices += heightmap_vertex_offsets.repeat(6, 0).reshape(-1, 6, 3)
# apply height data to y values
heightmap_vertices[:, 0, 1] = heightmap_vertices[:, 5, 1] = height_data[:-1, :-1].reshape(-1)
heightmap_vertices[:, 1, 1] = height_data[1:, :-1].reshape(-1)
heightmap_vertices[:, 2, 1] = heightmap_vertices[:, 3, 1] = height_data[1:, 1:].reshape(-1)
heightmap_vertices[:, 4, 1] = height_data[:-1, 1:].reshape(-1)
heightmap_indices = numpy.array(numpy.mgrid[0:heightmap_face_count * 3], dtype=numpy.int32).reshape(-1, 3)
mesh._vertices[0:(heightmap_vertices.size // 3), :] = heightmap_vertices.reshape(-1, 3)
mesh._indices[0:(heightmap_indices.size // 3), :] = heightmap_indices
mesh._vertex_count = heightmap_vertices.size // 3
mesh._face_count = heightmap_indices.size // 3
geo_width = width_minus_one * texel_width
geo_height = height_minus_one * texel_height
# bottom
mesh.addFaceByPoints(0, 0, 0, 0, 0, geo_height, geo_width, 0, geo_height)
mesh.addFaceByPoints(geo_width, 0, geo_height, geo_width, 0, 0, 0, 0, 0)
# north and south walls
for n in range(0, width_minus_one):
x = n * texel_width
nx = (n + 1) * texel_width
hn0 = height_data[0, n]
hn1 = height_data[0, n + 1]
hs0 = height_data[height_minus_one, n]
hs1 = height_data[height_minus_one, n + 1]
mesh.addFaceByPoints(x, 0, 0, nx, 0, 0, nx, hn1, 0)
mesh.addFaceByPoints(nx, hn1, 0, x, hn0, 0, x, 0, 0)
mesh.addFaceByPoints(x, 0, geo_height, nx, 0, geo_height, nx, hs1, geo_height)
mesh.addFaceByPoints(nx, hs1, geo_height, x, hs0, geo_height, x, 0, geo_height)
# west and east walls
for n in range(0, height_minus_one):
y = n * texel_height
ny = (n + 1) * texel_height
hw0 = height_data[n, 0]
hw1 = height_data[n + 1, 0]
he0 = height_data[n, width_minus_one]
he1 = height_data[n + 1, width_minus_one]
mesh.addFaceByPoints(0, 0, y, 0, 0, ny, 0, hw1, ny)
mesh.addFaceByPoints(0, hw1, ny, 0, hw0, y, 0, 0, y)
mesh.addFaceByPoints(geo_width, 0, y, geo_width, 0, ny, geo_width, he1, ny)
mesh.addFaceByPoints(geo_width, he1, ny, geo_width, he0, y, geo_width, 0, y)
mesh.calculateNormals(fast=True)
scene_node.setMeshData(mesh.build())
saveScene(file, scene_node)
# return scene_node
def saveScene(filename, object):
f = open(filename, 'wb')
_writeBinary(f, object)
f.close()
def _writeBinary(stream, node):
stream.write("Uranium STLWriter {0}".format(time.strftime("%a %d %b %Y %H:%M:%S")).encode().ljust(80, b"\000"))
face_count = 0
# nodes = list(node)
# for node in nodes:
if node.getMeshData().hasIndices():
face_count += node.getMeshData().getFaceCount()
else:
face_count += node.getMeshData().getVertexCount() / 3
stream.write(struct.pack("<I", int(face_count))) # Write number of faces to STL
# for node in node:
mesh_data = node.getMeshData().getTransformed(node.getWorldTransformation())
if mesh_data.hasIndices():
verts = mesh_data.getVertices()
for face in mesh_data.getIndices():
v1 = verts[face[0]]
v2 = verts[face[1]]
v3 = verts[face[2]]
stream.write(struct.pack("<fff", 0.0, 0.0, 0.0))
stream.write(struct.pack("<fff", v1[0], -v1[2], v1[1]))
stream.write(struct.pack("<fff", v2[0], -v2[2], v2[1]))
stream.write(struct.pack("<fff", v3[0], -v3[2], v3[1]))
stream.write(struct.pack("<H", 0))
else:
num_verts = mesh_data.getVertexCount()
verts = mesh_data.getVertices()
for index in range(0, num_verts - 1, 3):
v1 = verts[index]
v2 = verts[index + 1]
v3 = verts[index + 2]
stream.write(struct.pack("<fff", 0.0, 0.0, 0.0))
stream.write(struct.pack("<fff", v1[0], -v1[2], v1[1]))
stream.write(struct.pack("<fff", v2[0], -v2[2], v2[1]))
stream.write(struct.pack("<fff", v3[0], -v3[2], v3[1]))
stream.write(struct.pack("<H", 0))
#file = "/sdcard/Android/data/com.android.browser/files/yushengnan4.stl"
#xz_size = 120.0
#peak_height = 20
#base_height = 0.4
#blur_iterations= 1
#max_size = 512
#lighter_is_higher = False
#object = generateSceneNode(file_name, xz_size, peak_height, base_height, blur_iterations, max_size, lighter_is_higher,file)
#generateSceneNode(file_name, 120, 20, 0.4, 1, 512, False)
#file = 'F:\\111\\img5.stl'
#saveScene(file,object)
| 35.804082 | 124 | 0.621979 |
import numpy
import time
import struct
from PIL import Image
from MeshBuilder import MeshBuilder
from Vector import Vector
from CuraSceneNode import CuraSceneNode as SceneNode
def generateSceneNode(file_name, xz_size, peak_height, base_height, blur_iterations, max_size,lighter_is_higher,file):
scene_node = SceneNode()
mesh = MeshBuilder()
im= Image.open(file_name)
width = max(im.size[0], 2)
height = max(im.size[1], 2)
aspect = height / width
base_height = max(base_height, 0)
peak_height = max(peak_height, -base_height)
xz_size = max(xz_size, blur_iterations)
scale_vector = Vector(xz_size, peak_height, xz_size)
if width > height:
scale_vector = scale_vector.set(z=scale_vector.z * aspect)
elif height > width:
scale_vector = scale_vector.set(x=scale_vector.x / aspect)
if width > max_size or height > max_size:
scale_factor = max_size / width
if height > width:
scale_factor = max_size / height
width = int(max(round(width * scale_factor), 2))
height = int(max(round(height * scale_factor), 2))
im = im.resize((width, height), Image.ANTIALIAS)
width_minus_one = width - 1
height_minus_one = height - 1
texel_width = 1.0 / (width_minus_one) * scale_vector.x
texel_height = 1.0 / (height_minus_one) * scale_vector.z
height_data = numpy.zeros((height, width), dtype=numpy.float32)
for x in range(0, width):
for y in range(0, height):
qrgb = im.getpixel((x, y))
R=qrgb[0]
G=qrgb[1]
B=qrgb[2]
avg=float(R+G+B)/(3*255)
height_data[y, x] = avg
if not lighter_is_higher:
height_data = 1 - height_data
for _ in range(0,blur_iterations):
copy = numpy.pad(height_data, ((1, 1), (1, 1)), mode="edge")
height_data += copy[1:-1, 2:]
height_data += copy[1:-1, :-2]
height_data += copy[2:, 1:-1]
height_data += copy[:-2, 1:-1]
height_data += copy[2:, 2:]
height_data += copy[:-2, 2:]
height_data += copy[2:, :-2]
height_data += copy[:-2, :-2]
height_data /= 9
height_data *= scale_vector.y
height_data += base_height
heightmap_face_count = 2 * height_minus_one * width_minus_one
total_face_count = heightmap_face_count + (width_minus_one * 2) * (height_minus_one * 2) + 2
mesh.reserveFaceCount(total_face_count)
heightmap_vertices = numpy.zeros((width_minus_one * height_minus_one, 6, 3), dtype=numpy.float32)
heightmap_vertices = heightmap_vertices + numpy.array([[
[0, base_height, 0],
[0, base_height, texel_height],
[texel_width, base_height, texel_height],
[texel_width, base_height, texel_height],
[texel_width, base_height, 0],
[0, base_height, 0]
]], dtype=numpy.float32)
offsetsz, offsetsx = numpy.mgrid[0: height_minus_one, 0: width - 1]
offsetsx = numpy.array(offsetsx, numpy.float32).reshape(-1, 1) * texel_width
offsetsz = numpy.array(offsetsz, numpy.float32).reshape(-1, 1) * texel_height
heightmap_vertex_offsets = numpy.concatenate(
[offsetsx, numpy.zeros((offsetsx.shape[0], offsetsx.shape[1]), dtype=numpy.float32), offsetsz], 1)
heightmap_vertices += heightmap_vertex_offsets.repeat(6, 0).reshape(-1, 6, 3)
heightmap_vertices[:, 0, 1] = heightmap_vertices[:, 5, 1] = height_data[:-1, :-1].reshape(-1)
heightmap_vertices[:, 1, 1] = height_data[1:, :-1].reshape(-1)
heightmap_vertices[:, 2, 1] = heightmap_vertices[:, 3, 1] = height_data[1:, 1:].reshape(-1)
heightmap_vertices[:, 4, 1] = height_data[:-1, 1:].reshape(-1)
heightmap_indices = numpy.array(numpy.mgrid[0:heightmap_face_count * 3], dtype=numpy.int32).reshape(-1, 3)
mesh._vertices[0:(heightmap_vertices.size // 3), :] = heightmap_vertices.reshape(-1, 3)
mesh._indices[0:(heightmap_indices.size // 3), :] = heightmap_indices
mesh._vertex_count = heightmap_vertices.size // 3
mesh._face_count = heightmap_indices.size // 3
geo_width = width_minus_one * texel_width
geo_height = height_minus_one * texel_height
mesh.addFaceByPoints(0, 0, 0, 0, 0, geo_height, geo_width, 0, geo_height)
mesh.addFaceByPoints(geo_width, 0, geo_height, geo_width, 0, 0, 0, 0, 0)
for n in range(0, width_minus_one):
x = n * texel_width
nx = (n + 1) * texel_width
hn0 = height_data[0, n]
hn1 = height_data[0, n + 1]
hs0 = height_data[height_minus_one, n]
hs1 = height_data[height_minus_one, n + 1]
mesh.addFaceByPoints(x, 0, 0, nx, 0, 0, nx, hn1, 0)
mesh.addFaceByPoints(nx, hn1, 0, x, hn0, 0, x, 0, 0)
mesh.addFaceByPoints(x, 0, geo_height, nx, 0, geo_height, nx, hs1, geo_height)
mesh.addFaceByPoints(nx, hs1, geo_height, x, hs0, geo_height, x, 0, geo_height)
for n in range(0, height_minus_one):
y = n * texel_height
ny = (n + 1) * texel_height
hw0 = height_data[n, 0]
hw1 = height_data[n + 1, 0]
he0 = height_data[n, width_minus_one]
he1 = height_data[n + 1, width_minus_one]
mesh.addFaceByPoints(0, 0, y, 0, 0, ny, 0, hw1, ny)
mesh.addFaceByPoints(0, hw1, ny, 0, hw0, y, 0, 0, y)
mesh.addFaceByPoints(geo_width, 0, y, geo_width, 0, ny, geo_width, he1, ny)
mesh.addFaceByPoints(geo_width, he1, ny, geo_width, he0, y, geo_width, 0, y)
mesh.calculateNormals(fast=True)
scene_node.setMeshData(mesh.build())
saveScene(file, scene_node)
def saveScene(filename, object):
f = open(filename, 'wb')
_writeBinary(f, object)
f.close()
def _writeBinary(stream, node):
stream.write("Uranium STLWriter {0}".format(time.strftime("%a %d %b %Y %H:%M:%S")).encode().ljust(80, b"\000"))
face_count = 0
if node.getMeshData().hasIndices():
face_count += node.getMeshData().getFaceCount()
else:
face_count += node.getMeshData().getVertexCount() / 3
stream.write(struct.pack("<I", int(face_count)))
mesh_data = node.getMeshData().getTransformed(node.getWorldTransformation())
if mesh_data.hasIndices():
verts = mesh_data.getVertices()
for face in mesh_data.getIndices():
v1 = verts[face[0]]
v2 = verts[face[1]]
v3 = verts[face[2]]
stream.write(struct.pack("<fff", 0.0, 0.0, 0.0))
stream.write(struct.pack("<fff", v1[0], -v1[2], v1[1]))
stream.write(struct.pack("<fff", v2[0], -v2[2], v2[1]))
stream.write(struct.pack("<fff", v3[0], -v3[2], v3[1]))
stream.write(struct.pack("<H", 0))
else:
num_verts = mesh_data.getVertexCount()
verts = mesh_data.getVertices()
for index in range(0, num_verts - 1, 3):
v1 = verts[index]
v2 = verts[index + 1]
v3 = verts[index + 2]
stream.write(struct.pack("<fff", 0.0, 0.0, 0.0))
stream.write(struct.pack("<fff", v1[0], -v1[2], v1[1]))
stream.write(struct.pack("<fff", v2[0], -v2[2], v2[1]))
stream.write(struct.pack("<fff", v3[0], -v3[2], v3[1]))
stream.write(struct.pack("<H", 0))
| true | true |
f7f755fdb958e86c397a6ec2994c176c678ee8d4 | 8,630 | py | Python | tests/test_conv_internal.py | CalebBell/ht | 3b95f9cfff30c8c0272443d523a484977eedbf0d | [
"MIT"
] | 118 | 2016-01-04T07:46:23.000Z | 2022-03-29T14:12:59.000Z | tests/test_conv_internal.py | CalebBell/ht | 3b95f9cfff30c8c0272443d523a484977eedbf0d | [
"MIT"
] | 4 | 2017-06-27T08:01:02.000Z | 2020-10-06T14:18:46.000Z | tests/test_conv_internal.py | CalebBell/ht | 3b95f9cfff30c8c0272443d523a484977eedbf0d | [
"MIT"
] | 22 | 2016-04-20T06:17:35.000Z | 2022-03-07T01:40:25.000Z | # -*- coding: utf-8 -*-
'''Chemical Engineering Design Library (ChEDL). Utilities for process modeling.
Copyright (C) 2016, 2017, 2018, 2019, Caleb Bell <Caleb.Andrew.Bell@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.'''
from __future__ import division
import ht.conv_internal
from ht.conv_internal import *
from fluids.numerics import linspace, assert_close, assert_close1d, assert_close2d
from ht.boiling_nucleic import _angles_Stephan_Abdelsalam
import pytest
### conv_internal
def test_Nu_const():
assert_close(laminar_T_const(), 3.66)
assert_close(laminar_Q_const(), 48/11.)
def test_laminar_entry_region():
Nu = laminar_entry_thermal_Hausen(100000.0, 1.1, 5.0, .5)
assert_close(Nu, 39.01352358988535)
Nu = laminar_entry_Seider_Tate(Re=100000, Pr=1.1, L=5, Di=.5)
assert_close(Nu, 41.366029684589265)
Nu_wall = laminar_entry_Seider_Tate(100000, 1.1, 5, .5, 1E-3, 1.2E-3)
assert_close(Nu_wall, 40.32352264095969)
Nu = laminar_entry_Baehr_Stephan(100000, 1.1, 5, .5)
assert_close(Nu, 72.65402046550976)
def test_turbulent_complicated():
Nu1 = turbulent_Dittus_Boelter(1E5, 1.2, True, False)
Nu2 = turbulent_Dittus_Boelter(Re=1E5, Pr=1.2, heating=False, revised=False)
Nu3 = turbulent_Dittus_Boelter(Re=1E5, Pr=1.2, heating=False)
Nu4 = turbulent_Dittus_Boelter(Re=1E5, Pr=1.2)
Nu_values = [261.3838629346147, 279.89829163640354, 242.9305927410295, 247.40036409449127]
assert_close1d([Nu1, Nu2, Nu3, Nu4], Nu_values)
Nu1 = turbulent_Sieder_Tate(Re=1E5, Pr=1.2)
Nu2 = turbulent_Sieder_Tate(1E5, 1.2, 0.01, 0.067)
assert_close1d([Nu1, Nu2], [286.9178136793052, 219.84016455766044])
Nus = [turbulent_entry_Hausen(1E5, 1.2, 0.154, i) for i in linspace(1e-3,1,11)]
Nus_values = [6464.503822124652, 505.67127136455525, 399.6147653094695, 356.6182206114823, 332.39191624636305, 316.53483318707475, 305.21220965431286, 296.6521831991236, 289.91358493027764, 284.4463173972796, 279.90553997822707]
assert_close1d(Nus, Nus_values)
def test_turbulent_simple():
Nu = turbulent_Colburn(1E5, 1.2)
assert_close(Nu, 244.41147091200068)
Nu = turbulent_Drexel_McAdams(1E5, 0.6)
assert_close(Nu, 171.19055301724387)
Nu = turbulent_von_Karman(1E5, 1.2, 0.0185)
assert_close(Nu, 255.7243541243272)
Nu = turbulent_Prandtl(1E5, 1.2, 0.0185)
assert_close(Nu, 256.073339689557)
Nu = turbulent_Friend_Metzner(1E5, 100., 0.0185)
assert_close(Nu, 1738.3356262055322)
Nu = turbulent_Petukhov_Kirillov_Popov(1E5, 1.2, 0.0185)
assert_close(Nu, 250.11935088905105)
Nu = turbulent_Webb(1E5, 1.2, 0.0185)
assert_close(Nu, 239.10130376815872)
Nu = turbulent_Sandall(1E5, 1.2, 0.0185)
assert_close(Nu, 229.0514352970239)
Nu = turbulent_Gnielinski(1E5, 1.2, 0.0185)
assert_close(Nu, 254.62682749359632)
Nu = turbulent_Gnielinski_smooth_1(1E5, 1.2)
assert_close(Nu, 227.88800494373442)
Nu = turbulent_Gnielinski_smooth_2(1E5, 7.)
assert_close(Nu, 577.7692524513449)
Nu = turbulent_Churchill_Zajic(1E5, 1.2, 0.0185)
assert_close(Nu, 260.5564907817961)
Nu = turbulent_ESDU(1E5, 1.2)
assert_close(Nu, 232.3017143430645)
def test_turbulent_rough():
Nu = turbulent_Martinelli(1E5, 100., 0.0185)
assert_close(Nu, 887.1710686396347)
Nu = turbulent_Nunner(1E5, 0.7, 0.0185, 0.005)
assert_close(Nu, 101.15841010919947)
Nu = turbulent_Dipprey_Sabersky(1E5, 1.2, 0.0185, 1E-3)
assert_close(Nu, 288.33365198566656)
Nu = turbulent_Gowen_Smith(1E5, 1.2, 0.0185)
assert_close(Nu, 131.72530453824106)
Nu = turbulent_Kawase_Ulbrecht(1E5, 1.2, 0.0185)
assert_close(Nu, 389.6262247333975)
Nu = turbulent_Kawase_De(1E5, 1.2, 0.0185)
assert_close(Nu, 296.5019733271324)
Nu = turbulent_Bhatti_Shah(1E5, 1.2, 0.0185, 1E-3)
assert_close(Nu, 302.7037617414273)
# TODO meta function Nu internal
def test_Morimoto_Hotta():
Nu = Morimoto_Hotta(1E5, 5.7, .05, .5)
assert_close(Nu, 634.4879473869859)
def test_helical_turbulent_Nu_Mori_Nakayama():
Nu = helical_turbulent_Nu_Mori_Nakayama(2E5, 0.7, 0.01, .2)
assert_close(Nu, 496.2522480663327)
# High Pr
Nu = helical_turbulent_Nu_Mori_Nakayama(2E5, 4.0, 0.01, .2)
assert_close(Nu, 889.3060078437253)
# Bad behavior!
# 1 sun power output per m^2 per K
assert 4E24 < helical_turbulent_Nu_Mori_Nakayama(2E6, 0.7, 1.0, 1E80)
# .[3]_ specified that the high-Pr formula is calculated using Dean number,
# but the actual article says it is not. We use the 2.5 power specified
# in the original.
def test_helical_turbulent_Nu_Schmidt():
Nu = helical_turbulent_Nu_Schmidt(2E5, 0.7, 0.01, .2)
assert_close(Nu, 466.2569996832083)
Nus = [helical_turbulent_Nu_Schmidt(i, 0.7, 0.01, .2) for i in [2.2E4, 2.2E4+1E-9]]
assert_close1d(Nus, [80.1111786843, 79.75161984693375])
def test_helical_turbulent_Nu_Xin_Ebadian():
Nu = helical_turbulent_Nu_Xin_Ebadian(2E5, 0.7, 0.01, .2)
assert_close(Nu, 474.11413424344755)
# No bad behavior
# Checked with the original
def test_Nu_laminar_rectangular_Shan_London():
Nu = Nu_laminar_rectangular_Shan_London(.7)
assert_close(Nu, 3.751762675455)
def test_Nu_conv_internal_methods():
from fluids.units import func_args
for name, (func, args) in conv_tube_methods.items():
assert tuple(list(func_args(func))[0:len(args)]) == args
def test_Nu_conv_internal():
Nu = Nu_conv_internal(1E2, .7)
assert_close(Nu, laminar_T_const())
Nu = Nu_conv_internal(1E2, .7, Method='Laminar - constant Q')
assert_close(Nu, laminar_Q_const())
Nu = Nu_conv_internal(1E2, .7, x=.01, Di=.1)
assert_close(Nu, 14.91799128769779)
# test the other laminar entrylength methods
Nu = Nu_conv_internal(1E2, .7, x=.01, Di=.1, Method='Hausen laminar thermal entry')
assert_close(Nu, 16.51501443241237)
Nu = Nu_conv_internal(1E2, .7, x=.01, Di=.1, Method='Seider-Tate laminar thermal entry')
assert_close(Nu, 21.054212255270848)
# martinili
Nu = Nu_conv_internal(1E5, .02, eD=0.0)
assert_close(Nu, 8.246171632616187)
Nu = Nu_conv_internal(1E5, .7, x=.01, Di=.1)
assert_close(Nu, 978.1729258857774)
Nu = Nu_conv_internal(1E5, .7)
assert_close(Nu, 183.71057902604906)
other_methods = ['Churchill-Zajic', 'Petukhov-Kirillov-Popov', 'Gnielinski',
'Bhatti-Shah', 'Dipprey-Sabersky', 'Sandall', 'Webb',
'Friend-Metzner', 'Prandtl', 'von-Karman', 'Gowen-Smith',
'Kawase-Ulbrecht', 'Kawase-De', 'Nunner', 'Dittus-Boelter',
'Sieder-Tate', 'Drexel-McAdams', 'Colburn', 'ESDU',
'Gnielinski smooth low Pr','Gnielinski smooth high Pr']
expected = [103.65851760127596, 96.66083769419261, 95.7206648591076,
124.96666518189072, 124.96666518189072, 126.8559349821517,
89.04183860378171, 82.62190521404274, 96.39509181385534,
97.64409839390211, 63.69345925482798, 218.78659693866075,
169.9758751276217, 113.72592148878971, 199.41923780765848,
239.73408047050233, 182.078434520036, 204.21792040079825,
177.52639370276017, 183.6911292257849, 230.01408232621412]
for method, expect in zip(other_methods, expected):
Nu = Nu_conv_internal(1E5, .7, fd=.01, Method=method)
assert_close(Nu, expect)
with pytest.raises(Exception):
Nu_conv_internal(1E5, .7, Method='NOTAMETHOD')
l = Nu_conv_internal_methods(1E5, .7)
assert len(l) == 21
test_Nu_conv_internal() | 38.017621 | 232 | 0.714253 |
from __future__ import division
import ht.conv_internal
from ht.conv_internal import *
from fluids.numerics import linspace, assert_close, assert_close1d, assert_close2d
from ht.boiling_nucleic import _angles_Stephan_Abdelsalam
import pytest
t_close(laminar_T_const(), 3.66)
assert_close(laminar_Q_const(), 48/11.)
def test_laminar_entry_region():
Nu = laminar_entry_thermal_Hausen(100000.0, 1.1, 5.0, .5)
assert_close(Nu, 39.01352358988535)
Nu = laminar_entry_Seider_Tate(Re=100000, Pr=1.1, L=5, Di=.5)
assert_close(Nu, 41.366029684589265)
Nu_wall = laminar_entry_Seider_Tate(100000, 1.1, 5, .5, 1E-3, 1.2E-3)
assert_close(Nu_wall, 40.32352264095969)
Nu = laminar_entry_Baehr_Stephan(100000, 1.1, 5, .5)
assert_close(Nu, 72.65402046550976)
def test_turbulent_complicated():
Nu1 = turbulent_Dittus_Boelter(1E5, 1.2, True, False)
Nu2 = turbulent_Dittus_Boelter(Re=1E5, Pr=1.2, heating=False, revised=False)
Nu3 = turbulent_Dittus_Boelter(Re=1E5, Pr=1.2, heating=False)
Nu4 = turbulent_Dittus_Boelter(Re=1E5, Pr=1.2)
Nu_values = [261.3838629346147, 279.89829163640354, 242.9305927410295, 247.40036409449127]
assert_close1d([Nu1, Nu2, Nu3, Nu4], Nu_values)
Nu1 = turbulent_Sieder_Tate(Re=1E5, Pr=1.2)
Nu2 = turbulent_Sieder_Tate(1E5, 1.2, 0.01, 0.067)
assert_close1d([Nu1, Nu2], [286.9178136793052, 219.84016455766044])
Nus = [turbulent_entry_Hausen(1E5, 1.2, 0.154, i) for i in linspace(1e-3,1,11)]
Nus_values = [6464.503822124652, 505.67127136455525, 399.6147653094695, 356.6182206114823, 332.39191624636305, 316.53483318707475, 305.21220965431286, 296.6521831991236, 289.91358493027764, 284.4463173972796, 279.90553997822707]
assert_close1d(Nus, Nus_values)
def test_turbulent_simple():
Nu = turbulent_Colburn(1E5, 1.2)
assert_close(Nu, 244.41147091200068)
Nu = turbulent_Drexel_McAdams(1E5, 0.6)
assert_close(Nu, 171.19055301724387)
Nu = turbulent_von_Karman(1E5, 1.2, 0.0185)
assert_close(Nu, 255.7243541243272)
Nu = turbulent_Prandtl(1E5, 1.2, 0.0185)
assert_close(Nu, 256.073339689557)
Nu = turbulent_Friend_Metzner(1E5, 100., 0.0185)
assert_close(Nu, 1738.3356262055322)
Nu = turbulent_Petukhov_Kirillov_Popov(1E5, 1.2, 0.0185)
assert_close(Nu, 250.11935088905105)
Nu = turbulent_Webb(1E5, 1.2, 0.0185)
assert_close(Nu, 239.10130376815872)
Nu = turbulent_Sandall(1E5, 1.2, 0.0185)
assert_close(Nu, 229.0514352970239)
Nu = turbulent_Gnielinski(1E5, 1.2, 0.0185)
assert_close(Nu, 254.62682749359632)
Nu = turbulent_Gnielinski_smooth_1(1E5, 1.2)
assert_close(Nu, 227.88800494373442)
Nu = turbulent_Gnielinski_smooth_2(1E5, 7.)
assert_close(Nu, 577.7692524513449)
Nu = turbulent_Churchill_Zajic(1E5, 1.2, 0.0185)
assert_close(Nu, 260.5564907817961)
Nu = turbulent_ESDU(1E5, 1.2)
assert_close(Nu, 232.3017143430645)
def test_turbulent_rough():
Nu = turbulent_Martinelli(1E5, 100., 0.0185)
assert_close(Nu, 887.1710686396347)
Nu = turbulent_Nunner(1E5, 0.7, 0.0185, 0.005)
assert_close(Nu, 101.15841010919947)
Nu = turbulent_Dipprey_Sabersky(1E5, 1.2, 0.0185, 1E-3)
assert_close(Nu, 288.33365198566656)
Nu = turbulent_Gowen_Smith(1E5, 1.2, 0.0185)
assert_close(Nu, 131.72530453824106)
Nu = turbulent_Kawase_Ulbrecht(1E5, 1.2, 0.0185)
assert_close(Nu, 389.6262247333975)
Nu = turbulent_Kawase_De(1E5, 1.2, 0.0185)
assert_close(Nu, 296.5019733271324)
Nu = turbulent_Bhatti_Shah(1E5, 1.2, 0.0185, 1E-3)
assert_close(Nu, 302.7037617414273)
def test_Morimoto_Hotta():
Nu = Morimoto_Hotta(1E5, 5.7, .05, .5)
assert_close(Nu, 634.4879473869859)
def test_helical_turbulent_Nu_Mori_Nakayama():
Nu = helical_turbulent_Nu_Mori_Nakayama(2E5, 0.7, 0.01, .2)
assert_close(Nu, 496.2522480663327)
Nu = helical_turbulent_Nu_Mori_Nakayama(2E5, 4.0, 0.01, .2)
assert_close(Nu, 889.3060078437253)
assert 4E24 < helical_turbulent_Nu_Mori_Nakayama(2E6, 0.7, 1.0, 1E80)
def test_helical_turbulent_Nu_Schmidt():
Nu = helical_turbulent_Nu_Schmidt(2E5, 0.7, 0.01, .2)
assert_close(Nu, 466.2569996832083)
Nus = [helical_turbulent_Nu_Schmidt(i, 0.7, 0.01, .2) for i in [2.2E4, 2.2E4+1E-9]]
assert_close1d(Nus, [80.1111786843, 79.75161984693375])
def test_helical_turbulent_Nu_Xin_Ebadian():
Nu = helical_turbulent_Nu_Xin_Ebadian(2E5, 0.7, 0.01, .2)
assert_close(Nu, 474.11413424344755)
def test_Nu_laminar_rectangular_Shan_London():
Nu = Nu_laminar_rectangular_Shan_London(.7)
assert_close(Nu, 3.751762675455)
def test_Nu_conv_internal_methods():
from fluids.units import func_args
for name, (func, args) in conv_tube_methods.items():
assert tuple(list(func_args(func))[0:len(args)]) == args
def test_Nu_conv_internal():
Nu = Nu_conv_internal(1E2, .7)
assert_close(Nu, laminar_T_const())
Nu = Nu_conv_internal(1E2, .7, Method='Laminar - constant Q')
assert_close(Nu, laminar_Q_const())
Nu = Nu_conv_internal(1E2, .7, x=.01, Di=.1)
assert_close(Nu, 14.91799128769779)
Nu = Nu_conv_internal(1E2, .7, x=.01, Di=.1, Method='Hausen laminar thermal entry')
assert_close(Nu, 16.51501443241237)
Nu = Nu_conv_internal(1E2, .7, x=.01, Di=.1, Method='Seider-Tate laminar thermal entry')
assert_close(Nu, 21.054212255270848)
Nu = Nu_conv_internal(1E5, .02, eD=0.0)
assert_close(Nu, 8.246171632616187)
Nu = Nu_conv_internal(1E5, .7, x=.01, Di=.1)
assert_close(Nu, 978.1729258857774)
Nu = Nu_conv_internal(1E5, .7)
assert_close(Nu, 183.71057902604906)
other_methods = ['Churchill-Zajic', 'Petukhov-Kirillov-Popov', 'Gnielinski',
'Bhatti-Shah', 'Dipprey-Sabersky', 'Sandall', 'Webb',
'Friend-Metzner', 'Prandtl', 'von-Karman', 'Gowen-Smith',
'Kawase-Ulbrecht', 'Kawase-De', 'Nunner', 'Dittus-Boelter',
'Sieder-Tate', 'Drexel-McAdams', 'Colburn', 'ESDU',
'Gnielinski smooth low Pr','Gnielinski smooth high Pr']
expected = [103.65851760127596, 96.66083769419261, 95.7206648591076,
124.96666518189072, 124.96666518189072, 126.8559349821517,
89.04183860378171, 82.62190521404274, 96.39509181385534,
97.64409839390211, 63.69345925482798, 218.78659693866075,
169.9758751276217, 113.72592148878971, 199.41923780765848,
239.73408047050233, 182.078434520036, 204.21792040079825,
177.52639370276017, 183.6911292257849, 230.01408232621412]
for method, expect in zip(other_methods, expected):
Nu = Nu_conv_internal(1E5, .7, fd=.01, Method=method)
assert_close(Nu, expect)
with pytest.raises(Exception):
Nu_conv_internal(1E5, .7, Method='NOTAMETHOD')
l = Nu_conv_internal_methods(1E5, .7)
assert len(l) == 21
test_Nu_conv_internal() | true | true |
f7f75607fb80c2e93bbb8101fb10225c200e68c5 | 1,185 | py | Python | code/python/ProcuretoPayAPISCIM/v1/setup.py | factset/enterprise-sdk | 3fd4d1360756c515c9737a0c9a992c7451d7de7e | [
"Apache-2.0"
] | 6 | 2022-02-07T16:34:18.000Z | 2022-03-30T08:04:57.000Z | code/python/ProcuretoPayAPISCIM/v1/setup.py | factset/enterprise-sdk | 3fd4d1360756c515c9737a0c9a992c7451d7de7e | [
"Apache-2.0"
] | 2 | 2022-02-07T05:25:57.000Z | 2022-03-07T14:18:04.000Z | code/python/ProcuretoPayAPISCIM/v1/setup.py | factset/enterprise-sdk | 3fd4d1360756c515c9737a0c9a992c7451d7de7e | [
"Apache-2.0"
] | null | null | null | """
FactSet SCIM API
FactSet's SCIM API implementation. # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
"""
from setuptools import setup, find_packages # noqa: H301
import os
def read(filename):
return open(os.path.join(os.path.dirname(__file__), filename)).read()
NAME = "fds.sdk.ProcuretoPayAPISCIM"
VERSION = "0.20.0"
# To install the library, run the following
#
# python setup.py install
#
# prerequisite: setuptools
# http://pypi.python.org/pypi/setuptools
REQUIRES = [
"urllib3 >= 1.25.3",
"python-dateutil",
"fds.sdk.utils >= 1.0.0",
]
setup(
name=NAME,
version=VERSION,
description="Procure to Pay API: SCIM client library for Python",
author="FactSet Research Systems",
url="https://github.com/FactSet/enterprise-sdk/tree/main/code/python/ProcuretoPayAPISCIM/v1",
keywords=["FactSet", "API", "SDK"],
python_requires=">=3.6",
install_requires=REQUIRES,
packages=find_packages(exclude=["test", "tests"]),
include_package_data=True,
license="Apache-2.0",
long_description_content_type="text/markdown",
long_description=read("README.md")
)
| 25.212766 | 97 | 0.697046 |
from setuptools import setup, find_packages
import os
def read(filename):
return open(os.path.join(os.path.dirname(__file__), filename)).read()
NAME = "fds.sdk.ProcuretoPayAPISCIM"
VERSION = "0.20.0"
REQUIRES = [
"urllib3 >= 1.25.3",
"python-dateutil",
"fds.sdk.utils >= 1.0.0",
]
setup(
name=NAME,
version=VERSION,
description="Procure to Pay API: SCIM client library for Python",
author="FactSet Research Systems",
url="https://github.com/FactSet/enterprise-sdk/tree/main/code/python/ProcuretoPayAPISCIM/v1",
keywords=["FactSet", "API", "SDK"],
python_requires=">=3.6",
install_requires=REQUIRES,
packages=find_packages(exclude=["test", "tests"]),
include_package_data=True,
license="Apache-2.0",
long_description_content_type="text/markdown",
long_description=read("README.md")
)
| true | true |
f7f75617f7246e8d3ad11994cbe5145c2cd3ddbb | 2,170 | py | Python | ocr_service/service/main.py | onlycska/depersonalization-of-data | d11497d0f0708496975d682ae447e97bfd9177d9 | [
"MIT"
] | null | null | null | ocr_service/service/main.py | onlycska/depersonalization-of-data | d11497d0f0708496975d682ae447e97bfd9177d9 | [
"MIT"
] | null | null | null | ocr_service/service/main.py | onlycska/depersonalization-of-data | d11497d0f0708496975d682ae447e97bfd9177d9 | [
"MIT"
] | null | null | null | import time
import fastapi
import uvicorn
import logging
import os
from process_doc import process_image
from models.document_model import DocumentModel
from pdf2jpg import pdf2jpg
from datetime import datetime
logs_folder_path = os.path.join(os.getcwd(), 'logs')
os.makedirs(logs_folder_path, exist_ok=True)
log_path = os.path.join(f'{logs_folder_path}', f'{datetime.date(datetime.now())}.log')
logging.basicConfig(format=u'%(levelname)-8s [%(asctime)s] %(message)s',
level=logging.DEBUG,
filename=log_path,
filemode='a',
datefmt='%d-%b-%y %H:%M:%S')
app = fastapi.FastAPI()
@app.get('/')
def index():
return {
'message': "Hello World!"
}
@app.get('/process_doc/{filename}', response_model=DocumentModel)
def process_doc(filename: str):
file_extension = filename.split('.')[-1]
if file_extension == "pdf":
return process_pdf(filename)
elif file_extension == "jpg" \
or file_extension == "jpeg" \
or file_extension == "png":
return process_img(filename)
def process_pdf(filename: str):
pages_paths = pdf2jpg(filename)
pages = []
for page_path in pages_paths:
pages.append(process_image(page_path))
result = {
"document_path": filename,
"temporal_files_dir": f"/data/converted/{filename.split('.')[-2]}",
"num_pages": len(pages),
"pages": pages
}
return DocumentModel(**result).dict()
def process_img(filename: str):
try:
filepath = '/data/' + filename
for i in range(10):
if os.path.exists(filepath):
break
time.sleep(1)
result = {
"document_path": filename,
"temporal_files_dir": "",
"num_pages": 1,
"pages": [process_image("/data/" + filename)]
}
return DocumentModel(**result).dict()
except Exception as e:
logging.error(f'Error occured: {e}', exc_info=True)
return {
'message': 'Error occured, see logs for details.'
}
if __name__ == '__main__':
uvicorn.run(app)
| 27.125 | 86 | 0.599539 | import time
import fastapi
import uvicorn
import logging
import os
from process_doc import process_image
from models.document_model import DocumentModel
from pdf2jpg import pdf2jpg
from datetime import datetime
logs_folder_path = os.path.join(os.getcwd(), 'logs')
os.makedirs(logs_folder_path, exist_ok=True)
log_path = os.path.join(f'{logs_folder_path}', f'{datetime.date(datetime.now())}.log')
logging.basicConfig(format=u'%(levelname)-8s [%(asctime)s] %(message)s',
level=logging.DEBUG,
filename=log_path,
filemode='a',
datefmt='%d-%b-%y %H:%M:%S')
app = fastapi.FastAPI()
@app.get('/')
def index():
return {
'message': "Hello World!"
}
@app.get('/process_doc/{filename}', response_model=DocumentModel)
def process_doc(filename: str):
file_extension = filename.split('.')[-1]
if file_extension == "pdf":
return process_pdf(filename)
elif file_extension == "jpg" \
or file_extension == "jpeg" \
or file_extension == "png":
return process_img(filename)
def process_pdf(filename: str):
pages_paths = pdf2jpg(filename)
pages = []
for page_path in pages_paths:
pages.append(process_image(page_path))
result = {
"document_path": filename,
"temporal_files_dir": f"/data/converted/{filename.split('.')[-2]}",
"num_pages": len(pages),
"pages": pages
}
return DocumentModel(**result).dict()
def process_img(filename: str):
try:
filepath = '/data/' + filename
for i in range(10):
if os.path.exists(filepath):
break
time.sleep(1)
result = {
"document_path": filename,
"temporal_files_dir": "",
"num_pages": 1,
"pages": [process_image("/data/" + filename)]
}
return DocumentModel(**result).dict()
except Exception as e:
logging.error(f'Error occured: {e}', exc_info=True)
return {
'message': 'Error occured, see logs for details.'
}
if __name__ == '__main__':
uvicorn.run(app)
| true | true |
f7f756bdd65cb3accc511c823b1331f7b2394d34 | 418 | py | Python | molsysmt/tools/openmm_Modeller/to_molsysmt_MolSys.py | dprada/molsysmt | 83f150bfe3cfa7603566a0ed4aed79d9b0c97f5d | [
"MIT"
] | null | null | null | molsysmt/tools/openmm_Modeller/to_molsysmt_MolSys.py | dprada/molsysmt | 83f150bfe3cfa7603566a0ed4aed79d9b0c97f5d | [
"MIT"
] | null | null | null | molsysmt/tools/openmm_Modeller/to_molsysmt_MolSys.py | dprada/molsysmt | 83f150bfe3cfa7603566a0ed4aed79d9b0c97f5d | [
"MIT"
] | null | null | null | def to_molsysmt_MolSys(item, selection='all', frame_indices='all', syntaxis='MolSysMT'):
from molsysmt.tools.openmm_Modeller import is_openmm_Modeller
from molsysmt.basic import convert
if not is_openmm_Modeller(item):
raise ValueError
tmp_item = convert(item, to_form='molsysmt.MolSys', selection=selection,
frame_indices=frame_indices, syntaxis=syntaxis)
return tmp_item
| 29.857143 | 88 | 0.744019 | def to_molsysmt_MolSys(item, selection='all', frame_indices='all', syntaxis='MolSysMT'):
from molsysmt.tools.openmm_Modeller import is_openmm_Modeller
from molsysmt.basic import convert
if not is_openmm_Modeller(item):
raise ValueError
tmp_item = convert(item, to_form='molsysmt.MolSys', selection=selection,
frame_indices=frame_indices, syntaxis=syntaxis)
return tmp_item
| true | true |
f7f756f6a2cb0bef58469a1c4ce6c3c8090f97f8 | 4,711 | py | Python | rr/experiment/database.py | sdevenes/M05_MiniProject | 38f81c6cc0b0d8f777c51609118b160c010c5590 | [
"MIT"
] | 1 | 2022-03-25T06:44:42.000Z | 2022-03-25T06:44:42.000Z | rr/experiment/database.py | sdevenes/M05_MiniProject | 38f81c6cc0b0d8f777c51609118b160c010c5590 | [
"MIT"
] | 22 | 2020-09-15T14:56:25.000Z | 2020-10-12T08:31:21.000Z | rr/experiment/database.py | sdevenes/M05_MiniProject | 38f81c6cc0b0d8f777c51609118b160c010c5590 | [
"MIT"
] | null | null | null | import numpy as np
import csv
from sklearn.model_selection import train_test_split
PROTOCOLS = {
"proto1": {"train": 0.8, "test": 0.2, "random": 1},
"proto2": {"train": 0.8, "test": 0.2, "random": 2},
}
SUBSETS = ["train", "validation", "test"]
CLASSES = [
"Other_Activity",
"Watch_TV",
"Sleep_Out_Of_Bed",
"Bathe",
"Cook_Breakfast",
"Dress",
"Toilet",
"Personal_Hygiene",
"Sleep",
"Read",
"Relax",
"Cook_Dinner",
"Drink",
"Eat_Breakfast",
"Morning_Meds",
"Evening_Meds",
"Wash_Breakfast_Dishes",
"Cook_Lunch",
"Wash_Dishes",
"Leave_Home",
"Cook",
"Enter_Home",
"Entertain_Guests",
"Wash_Dinner_Dishes",
"Phone",
"Groom",
"Step_Out",
"Eat_Dinner",
"Eat_Lunch",
"Wash_Lunch_Dishes",
"Bed_Toilet_Transition",
"Eat",
"Go_To_Sleep",
"Wake_Up",
"Work_At_Table",
]
VARIABLES = [
"lastSensorEventHours",
"lastSensorEventSeconds",
"lastSensorDayOfWeek",
"windowDuration",
"timeSinceLastSensorEvent",
"prevDominantSensor1",
"prevDominantSensor2",
"lastSensorID",
"lastSensorLocation",
"lastMotionLocation",
"complexity",
"activityChange",
"areaTransitions",
"numDistinctSensors",
"sensorCount-Bathroom",
"sensorCount-Bedroom",
"sensorCount-Chair",
"sensorCount-DiningRoom",
"sensorCount-Hall",
"sensorCount-Ignore",
"sensorCount-Kitchen",
"sensorCount-LivingRoom",
"sensorCount-Office",
"sensorCount-OutsideDoor",
"sensorCount-WorkArea",
"sensorElTime-Bathroom",
"sensorElTime-Bedroom",
"sensorElTime-Chair",
"sensorElTime-DiningRoom",
"sensorElTime-Hall",
"sensorElTime-Ignore",
"sensorElTime-Kitchen",
"sensorElTime-LivingRoom",
"sensorElTime-Office",
"sensorElTime-OutsideDoor",
"sensorElTime-WorkArea",
]
def load(filepath="./data/csh101/csh101.ann.features.csv"):
"""Loads the dataset
Args:
filepath (str): path to the file containing the dataset to load
Returns:
x (numpy.ndarray):A NxM 2D-array where each row corresponds to a sample and each column to a feature
y (numpy.ndarray): A 1D-array of length N, where each element corresponds to a sample label
Raises:
None
"""
x = []
y = []
with open(filepath, "rt") as f:
reader = csv.reader(f, delimiter=",")
for k, row in enumerate(reader):
if not k:
continue
x.append(row[:-1])
y.append(row[-1])
return np.array(x), np.array(y)
def split_data(x, y, subset, splits):
"""Splits the data set
Args:
x (numpy.ndarray):A NxM 2D-array where each row corresponds to a sample and each column to a feature
y (numpy.ndarray): A 1D-array of length N, where each element corresponds to a sample label
subset (str): subset to extract (train or test)
splits (dict): a dictionary mapping the subsets to their dataset proportion and the random state to use for splitting
Returns:
x_split (numpy.ndarray):A PxM 2D-array containing only a subset of samples
y_split (numpy.ndarray): A 1D-array of length P containing only the labels corresponding to the subset x_split
Raises:
None
"""
x_train, x_test, y_train, y_test = train_test_split(
x,
y,
test_size=splits["test"],
train_size=splits["train"],
random_state=splits["random"],
stratify=y,
)
(x_split, y_split) = (x_train, y_train) if subset == "train" else (x_test, y_test)
return x_split, y_split
def get(
protocol,
subset,
classes=CLASSES,
variables=VARIABLES,
filepath="./data/csh101/csh101.ann.features.csv",
):
"""Get the desired subset
Args:
protocol (str): protocol to use
subset (str): subset to extract (train or test)
classes (list): list of desired classes
variables (list): list of desired variables (features)
filepath (str): path to the file containing the dataset to load
Returns:
ret_x (numpy.ndarray):A PxQ 2D-array containing only the desired subset of samples with the Q desired features
ret_y (numpy.ndarray): A 1D-array of length P containing only the labels corresponding to the subset ret_x
Raises:
None
"""
x, y = load(filepath)
x_split, y_split = split_data(x, y, subset, PROTOCOLS[protocol])
var_index = [VARIABLES.index(k) for k in variables]
classes_condition = np.isin(y_split, classes)
ret_x = x_split[classes_condition][:, var_index]
ret_y = y_split[classes_condition]
return ret_x, ret_y
| 28.209581 | 125 | 0.637869 | import numpy as np
import csv
from sklearn.model_selection import train_test_split
PROTOCOLS = {
"proto1": {"train": 0.8, "test": 0.2, "random": 1},
"proto2": {"train": 0.8, "test": 0.2, "random": 2},
}
SUBSETS = ["train", "validation", "test"]
CLASSES = [
"Other_Activity",
"Watch_TV",
"Sleep_Out_Of_Bed",
"Bathe",
"Cook_Breakfast",
"Dress",
"Toilet",
"Personal_Hygiene",
"Sleep",
"Read",
"Relax",
"Cook_Dinner",
"Drink",
"Eat_Breakfast",
"Morning_Meds",
"Evening_Meds",
"Wash_Breakfast_Dishes",
"Cook_Lunch",
"Wash_Dishes",
"Leave_Home",
"Cook",
"Enter_Home",
"Entertain_Guests",
"Wash_Dinner_Dishes",
"Phone",
"Groom",
"Step_Out",
"Eat_Dinner",
"Eat_Lunch",
"Wash_Lunch_Dishes",
"Bed_Toilet_Transition",
"Eat",
"Go_To_Sleep",
"Wake_Up",
"Work_At_Table",
]
VARIABLES = [
"lastSensorEventHours",
"lastSensorEventSeconds",
"lastSensorDayOfWeek",
"windowDuration",
"timeSinceLastSensorEvent",
"prevDominantSensor1",
"prevDominantSensor2",
"lastSensorID",
"lastSensorLocation",
"lastMotionLocation",
"complexity",
"activityChange",
"areaTransitions",
"numDistinctSensors",
"sensorCount-Bathroom",
"sensorCount-Bedroom",
"sensorCount-Chair",
"sensorCount-DiningRoom",
"sensorCount-Hall",
"sensorCount-Ignore",
"sensorCount-Kitchen",
"sensorCount-LivingRoom",
"sensorCount-Office",
"sensorCount-OutsideDoor",
"sensorCount-WorkArea",
"sensorElTime-Bathroom",
"sensorElTime-Bedroom",
"sensorElTime-Chair",
"sensorElTime-DiningRoom",
"sensorElTime-Hall",
"sensorElTime-Ignore",
"sensorElTime-Kitchen",
"sensorElTime-LivingRoom",
"sensorElTime-Office",
"sensorElTime-OutsideDoor",
"sensorElTime-WorkArea",
]
def load(filepath="./data/csh101/csh101.ann.features.csv"):
x = []
y = []
with open(filepath, "rt") as f:
reader = csv.reader(f, delimiter=",")
for k, row in enumerate(reader):
if not k:
continue
x.append(row[:-1])
y.append(row[-1])
return np.array(x), np.array(y)
def split_data(x, y, subset, splits):
x_train, x_test, y_train, y_test = train_test_split(
x,
y,
test_size=splits["test"],
train_size=splits["train"],
random_state=splits["random"],
stratify=y,
)
(x_split, y_split) = (x_train, y_train) if subset == "train" else (x_test, y_test)
return x_split, y_split
def get(
protocol,
subset,
classes=CLASSES,
variables=VARIABLES,
filepath="./data/csh101/csh101.ann.features.csv",
):
x, y = load(filepath)
x_split, y_split = split_data(x, y, subset, PROTOCOLS[protocol])
var_index = [VARIABLES.index(k) for k in variables]
classes_condition = np.isin(y_split, classes)
ret_x = x_split[classes_condition][:, var_index]
ret_y = y_split[classes_condition]
return ret_x, ret_y
| true | true |
f7f7577be18813be11da8db7ee9a682a9c76edaa | 1,874 | py | Python | test/dvc/test_stages.py | giganticode/bohr-framework | fd364a1f036123985ac96e9076e5dce3bbc2ca2c | [
"MIT"
] | null | null | null | test/dvc/test_stages.py | giganticode/bohr-framework | fd364a1f036123985ac96e9076e5dce3bbc2ca2c | [
"MIT"
] | 54 | 2021-02-17T13:36:51.000Z | 2021-08-25T05:06:57.000Z | test/dvc/test_stages.py | giganticode/bohr-framework | fd364a1f036123985ac96e9076e5dce3bbc2ca2c | [
"MIT"
] | null | null | null | from pathlib import Path
from test.testutils import stub_commit_mapper, stub_task
from bohr.config.pathconfig import PathConfig
from bohr.dvc.stages import ApplyHeuristicsCommand, ParseLabelsCommand
def test_parse_labels_command():
command = ParseLabelsCommand(
PathConfig(Path("/project_root"), Path("/software_root"))
)
assert command.summary() == "parse labels"
assert command.get_name() == "parse_labels"
assert command.to_string() == [
"dvc",
"run",
"-v",
"--no-exec",
"--force",
"-n",
"parse_labels",
"-d",
"/project_root/labels",
"-O",
"labels.py",
"bohr",
"porcelain",
"parse-labels",
]
def test_apply_heuristics_command():
command = ApplyHeuristicsCommand(
PathConfig(Path("/project_root"), Path("/software_root")),
stub_task,
"group.1",
datasets=["dataset1"],
execute_immediately=True,
)
assert (
command.summary() == "[bugginess] apply heuristics (group: group.1) to dataset1"
)
assert command.get_name() == "bugginess_apply_heuristics__group_1__dataset1"
assert command.to_string() == [
"dvc",
"run",
"-v",
"--force",
"-n",
"bugginess_apply_heuristics__group_1__dataset1",
"-d",
"labels.py",
"-d",
"group/1.py",
"-d",
"prep_path/dataset1",
"-p",
"bohr.json:bohr_framework_version",
"-o",
"generated/bugginess/group.1/heuristic_matrix_dataset1.pkl",
"-M",
"metrics/bugginess/group.1/heuristic_metrics_dataset1.json",
"bohr",
"porcelain",
"apply-heuristics",
"bugginess",
"--heuristic-group",
"group.1",
"--dataset",
"dataset1",
]
| 26.027778 | 88 | 0.5619 | from pathlib import Path
from test.testutils import stub_commit_mapper, stub_task
from bohr.config.pathconfig import PathConfig
from bohr.dvc.stages import ApplyHeuristicsCommand, ParseLabelsCommand
def test_parse_labels_command():
command = ParseLabelsCommand(
PathConfig(Path("/project_root"), Path("/software_root"))
)
assert command.summary() == "parse labels"
assert command.get_name() == "parse_labels"
assert command.to_string() == [
"dvc",
"run",
"-v",
"--no-exec",
"--force",
"-n",
"parse_labels",
"-d",
"/project_root/labels",
"-O",
"labels.py",
"bohr",
"porcelain",
"parse-labels",
]
def test_apply_heuristics_command():
command = ApplyHeuristicsCommand(
PathConfig(Path("/project_root"), Path("/software_root")),
stub_task,
"group.1",
datasets=["dataset1"],
execute_immediately=True,
)
assert (
command.summary() == "[bugginess] apply heuristics (group: group.1) to dataset1"
)
assert command.get_name() == "bugginess_apply_heuristics__group_1__dataset1"
assert command.to_string() == [
"dvc",
"run",
"-v",
"--force",
"-n",
"bugginess_apply_heuristics__group_1__dataset1",
"-d",
"labels.py",
"-d",
"group/1.py",
"-d",
"prep_path/dataset1",
"-p",
"bohr.json:bohr_framework_version",
"-o",
"generated/bugginess/group.1/heuristic_matrix_dataset1.pkl",
"-M",
"metrics/bugginess/group.1/heuristic_metrics_dataset1.json",
"bohr",
"porcelain",
"apply-heuristics",
"bugginess",
"--heuristic-group",
"group.1",
"--dataset",
"dataset1",
]
| true | true |
f7f75821b79fd09f670067d0c26839a8e5b0bdae | 1,134 | py | Python | tensorboard/__init__.py | lgeiger/tensorboard | 6b012202689ae3c55e27c3690455e47f8d18c54d | [
"Apache-2.0"
] | 1 | 2018-07-03T08:08:42.000Z | 2018-07-03T08:08:42.000Z | tensorboard/__init__.py | lgeiger/tensorboard | 6b012202689ae3c55e27c3690455e47f8d18c54d | [
"Apache-2.0"
] | null | null | null | tensorboard/__init__.py | lgeiger/tensorboard | 6b012202689ae3c55e27c3690455e47f8d18c54d | [
"Apache-2.0"
] | 1 | 2020-09-11T19:10:19.000Z | 2020-09-11T19:10:19.000Z | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""TensorBoard is a webapp for understanding TensorFlow runs and graphs.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorboard import lazy
pkg = lambda i: i # helps google sync process
mod = lambda i: lazy.LazyLoader(i[i.rindex('.') + 1:], globals(), i)
program = mod(pkg('tensorboard.program'))
summary = mod(pkg('tensorboard.summary'))
del lazy
del mod
del pkg
| 34.363636 | 80 | 0.707231 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorboard import lazy
pkg = lambda i: i
mod = lambda i: lazy.LazyLoader(i[i.rindex('.') + 1:], globals(), i)
program = mod(pkg('tensorboard.program'))
summary = mod(pkg('tensorboard.summary'))
del lazy
del mod
del pkg
| true | true |
f7f75835308c2019c9691223c754b5a36ad105a5 | 6,134 | py | Python | pygame_gui/elements/ui_label.py | halfninja/pygame_gui | 71b1150cb0c789339a9f8d781da15bdfad604f6c | [
"MIT"
] | null | null | null | pygame_gui/elements/ui_label.py | halfninja/pygame_gui | 71b1150cb0c789339a9f8d781da15bdfad604f6c | [
"MIT"
] | null | null | null | pygame_gui/elements/ui_label.py | halfninja/pygame_gui | 71b1150cb0c789339a9f8d781da15bdfad604f6c | [
"MIT"
] | null | null | null | import pygame
import warnings
from typing import Union
from pygame_gui import ui_manager
from pygame_gui.core import ui_container
from pygame_gui.core.ui_element import UIElement
class UILabel(UIElement):
"""
A label lets us display a single line of text with a single font style. It's a quick to redraw and simple
alternative to the text box element.
:param relative_rect: The rectangle that contains and positions the label relative to it's container.
:param text: The text to display in the label.
:param manager: The UIManager that manages this label.
:param container: The container that this element is within. If set to None will be the root window's container.
:param parent_element: The element this element 'belongs to' in the theming hierarchy.
:param object_id: A custom defined ID for fine tuning of theming.
"""
def __init__(self, relative_rect: pygame.Rect, text: str, manager: ui_manager.UIManager,
container: ui_container.UIContainer = None,
parent_element: UIElement = None,
object_id: Union[str, None] = None):
new_element_ids, new_object_ids = self.create_valid_ids(parent_element=parent_element,
object_id=object_id,
element_id='label')
super().__init__(relative_rect, manager, container,
starting_height=1,
layer_thickness=1,
object_ids=new_object_ids,
element_ids=new_element_ids)
self.text = text
self.redraw()
def set_text(self, text: str):
"""
Changes the string displayed by the label element. Labels do not support HTML styling.
:param text: the text to set the label to.
"""
self.text = text
self.redraw()
def redraw(self):
"""
Re-render the text to the label's underlying sprite image. This allows us to change what the displayed text is
or remake it with different theming (if the theming has changed).
"""
font = self.ui_theme.get_font(self.object_ids, self.element_ids)
text_colour = self.ui_theme.get_colour(self.object_ids, self.element_ids, 'normal_text')
bg_colour = self.ui_theme.get_colour(self.object_ids, self.element_ids, 'dark_bg')
text_shadow_colour = self.ui_theme.get_colour(self.object_ids, self.element_ids, 'text_shadow')
shadow_enabled = False
shadow_enable_param = self.ui_theme.get_misc_data(self.object_ids, self.element_ids, 'text_shadow')
if shadow_enable_param is not None:
shadow_enabled = bool(int(shadow_enable_param))
shadow_size = 1
shadow_size_param = self.ui_theme.get_misc_data(self.object_ids, self.element_ids, 'text_shadow_size')
if shadow_size_param is not None:
shadow_size = int(shadow_size_param)
shadow_offset = [0, 0]
shadow_offset_param = self.ui_theme.get_misc_data(self.object_ids, self.element_ids, 'text_shadow_offset')
if shadow_offset_param is not None:
offset_string_list = shadow_offset_param.split(',')
if len(offset_string_list) == 2:
shadow_offset = [int(offset_string_list[0]), int(offset_string_list[1])]
text_size = font.size(self.text)
if text_size[1] > self.rect.height or text_size[0] > self.rect.width:
width_overlap = self.rect.width - text_size[0]
height_overlap = self.rect.height - text_size[1]
warn_text = 'Label Rect is too small for text: ' + self.text + ' - size diff: ' + str((width_overlap,
height_overlap))
warnings.warn(warn_text, UserWarning)
if bg_colour.a != 255 or shadow_enabled:
text_render = font.render(self.text, True, text_colour)
else:
text_render = font.render(self.text, True, text_colour, bg_colour)
text_render_rect = text_render.get_rect(centerx=self.rect.width/2, centery=self.rect.height/2)
self.image = pygame.Surface(self.rect.size, flags=pygame.SRCALPHA)
self.image.fill(bg_colour)
if shadow_enabled:
shadow_text_render = font.render(self.text, True, text_shadow_colour)
for y in range(-shadow_size, shadow_size+1):
shadow_text_render_rect = pygame.Rect((text_render_rect.x + shadow_offset[0],
text_render_rect.y + shadow_offset[1] + y),
text_render_rect.size)
self.image.blit(shadow_text_render, shadow_text_render_rect)
for x in range(-shadow_size, shadow_size+1):
shadow_text_render_rect = pygame.Rect((text_render_rect.x + shadow_offset[0] + x,
text_render_rect.y + shadow_offset[1]), text_render_rect.size)
self.image.blit(shadow_text_render, shadow_text_render_rect)
for x_and_y in range(-shadow_size, shadow_size+1):
shadow_text_render_rect = pygame.Rect((text_render_rect.x + shadow_offset[0] + x_and_y,
text_render_rect.y + shadow_offset[1] + x_and_y),
text_render_rect.size)
self.image.blit(shadow_text_render, shadow_text_render_rect)
for x_and_y in range(-shadow_size, shadow_size+1):
shadow_text_render_rect = pygame.Rect((text_render_rect.x + shadow_offset[0] - x_and_y,
text_render_rect.y + shadow_offset[1] + x_and_y),
text_render_rect.size)
self.image.blit(shadow_text_render, shadow_text_render_rect)
self.image.blit(text_render, text_render_rect)
| 52.42735 | 118 | 0.612488 | import pygame
import warnings
from typing import Union
from pygame_gui import ui_manager
from pygame_gui.core import ui_container
from pygame_gui.core.ui_element import UIElement
class UILabel(UIElement):
def __init__(self, relative_rect: pygame.Rect, text: str, manager: ui_manager.UIManager,
container: ui_container.UIContainer = None,
parent_element: UIElement = None,
object_id: Union[str, None] = None):
new_element_ids, new_object_ids = self.create_valid_ids(parent_element=parent_element,
object_id=object_id,
element_id='label')
super().__init__(relative_rect, manager, container,
starting_height=1,
layer_thickness=1,
object_ids=new_object_ids,
element_ids=new_element_ids)
self.text = text
self.redraw()
def set_text(self, text: str):
self.text = text
self.redraw()
def redraw(self):
font = self.ui_theme.get_font(self.object_ids, self.element_ids)
text_colour = self.ui_theme.get_colour(self.object_ids, self.element_ids, 'normal_text')
bg_colour = self.ui_theme.get_colour(self.object_ids, self.element_ids, 'dark_bg')
text_shadow_colour = self.ui_theme.get_colour(self.object_ids, self.element_ids, 'text_shadow')
shadow_enabled = False
shadow_enable_param = self.ui_theme.get_misc_data(self.object_ids, self.element_ids, 'text_shadow')
if shadow_enable_param is not None:
shadow_enabled = bool(int(shadow_enable_param))
shadow_size = 1
shadow_size_param = self.ui_theme.get_misc_data(self.object_ids, self.element_ids, 'text_shadow_size')
if shadow_size_param is not None:
shadow_size = int(shadow_size_param)
shadow_offset = [0, 0]
shadow_offset_param = self.ui_theme.get_misc_data(self.object_ids, self.element_ids, 'text_shadow_offset')
if shadow_offset_param is not None:
offset_string_list = shadow_offset_param.split(',')
if len(offset_string_list) == 2:
shadow_offset = [int(offset_string_list[0]), int(offset_string_list[1])]
text_size = font.size(self.text)
if text_size[1] > self.rect.height or text_size[0] > self.rect.width:
width_overlap = self.rect.width - text_size[0]
height_overlap = self.rect.height - text_size[1]
warn_text = 'Label Rect is too small for text: ' + self.text + ' - size diff: ' + str((width_overlap,
height_overlap))
warnings.warn(warn_text, UserWarning)
if bg_colour.a != 255 or shadow_enabled:
text_render = font.render(self.text, True, text_colour)
else:
text_render = font.render(self.text, True, text_colour, bg_colour)
text_render_rect = text_render.get_rect(centerx=self.rect.width/2, centery=self.rect.height/2)
self.image = pygame.Surface(self.rect.size, flags=pygame.SRCALPHA)
self.image.fill(bg_colour)
if shadow_enabled:
shadow_text_render = font.render(self.text, True, text_shadow_colour)
for y in range(-shadow_size, shadow_size+1):
shadow_text_render_rect = pygame.Rect((text_render_rect.x + shadow_offset[0],
text_render_rect.y + shadow_offset[1] + y),
text_render_rect.size)
self.image.blit(shadow_text_render, shadow_text_render_rect)
for x in range(-shadow_size, shadow_size+1):
shadow_text_render_rect = pygame.Rect((text_render_rect.x + shadow_offset[0] + x,
text_render_rect.y + shadow_offset[1]), text_render_rect.size)
self.image.blit(shadow_text_render, shadow_text_render_rect)
for x_and_y in range(-shadow_size, shadow_size+1):
shadow_text_render_rect = pygame.Rect((text_render_rect.x + shadow_offset[0] + x_and_y,
text_render_rect.y + shadow_offset[1] + x_and_y),
text_render_rect.size)
self.image.blit(shadow_text_render, shadow_text_render_rect)
for x_and_y in range(-shadow_size, shadow_size+1):
shadow_text_render_rect = pygame.Rect((text_render_rect.x + shadow_offset[0] - x_and_y,
text_render_rect.y + shadow_offset[1] + x_and_y),
text_render_rect.size)
self.image.blit(shadow_text_render, shadow_text_render_rect)
self.image.blit(text_render, text_render_rect)
| true | true |
f7f75998c2c90f0a89be5cab6b41f53ab97c8e4d | 165 | py | Python | behavior/iterator/iterator_gen.py | lockeCucumber/DesignPatterns | 9681aea059d6b29466077910662889801cee3703 | [
"MIT"
] | 2 | 2019-07-22T09:22:30.000Z | 2021-04-24T22:32:35.000Z | behavior/iterator/iterator_gen.py | lockeCucumber/DesignPatterns | 9681aea059d6b29466077910662889801cee3703 | [
"MIT"
] | null | null | null | behavior/iterator/iterator_gen.py | lockeCucumber/DesignPatterns | 9681aea059d6b29466077910662889801cee3703 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
'结合yield做一个生成器,实现一个迭代器'
def gen(value, max_count):
for _ in range(max_count):
yield value
for _ in gen('hello', 3):
print _ | 18.333333 | 30 | 0.612121 |
'结合yield做一个生成器,实现一个迭代器'
def gen(value, max_count):
for _ in range(max_count):
yield value
for _ in gen('hello', 3):
print _ | false | true |
f7f75a094258132d14f75dd5cc77e2cb274ea7ce | 2,028 | py | Python | MHCSeqNet/PredictionModel/Utility/AllelePrimarySequenceManager.py | cmbcu/-MHCSeqNet | 707edbd204e4b78d7fd04cecc9168691c8469d00 | [
"Apache-2.0"
] | 14 | 2018-07-24T14:49:51.000Z | 2019-10-03T20:35:11.000Z | MHCSeqNet/PredictionModel/Utility/AllelePrimarySequenceManager.py | cmbcu/-MHCSeqNet | 707edbd204e4b78d7fd04cecc9168691c8469d00 | [
"Apache-2.0"
] | 4 | 2018-08-24T14:18:58.000Z | 2019-03-28T13:53:06.000Z | MHCSeqNet/PredictionModel/Utility/AllelePrimarySequenceManager.py | cmbcu/-MHCSeqNet | 707edbd204e4b78d7fd04cecc9168691c8469d00 | [
"Apache-2.0"
] | 10 | 2019-11-12T16:59:05.000Z | 2021-08-02T11:37:04.000Z | import csv
class AllelePrimarySequenceManager:
AMINO_ACIDS_WITH_UNKNOWN = ['^', '-', 'A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R',
'S', 'T', 'V', 'W', 'Y', 'X']
NUM_AMINO_ACID = len(AMINO_ACIDS_WITH_UNKNOWN)
sequence_index_dict = {}
sequence_char_dict = {}
sequence_lengths = []
def __init__(self,
allele_primary_sequence_information_filename):
with open(allele_primary_sequence_information_filename, "r") as file:
csv_data = csv.reader(file, delimiter=',', quotechar="|")
for row in csv_data:
self.sequence_lengths = [len(row[1]), len(row[2]), len(row[3])]
#print(len(row))
assert(len(row) == 4)
self.sequence_char_dict[row[0]] = row[1:4]
self.sequence_index_dict[row[0]] = [self._char_to_index(row[1]),
self._char_to_index(row[2]),
self._char_to_index(row[3])]
assert(len(self.sequence_char_dict[row[0]]) == 3)
assert(len(self.sequence_index_dict[row[0]]) == 3)
def _char_to_index(self,
peptide):
indexes = []
for ac in peptide:
indexes.append(self.AMINO_ACIDS_WITH_UNKNOWN.index(ac))
return indexes
def get_char_sequence(self,
type_name):
return self.sequence_char_dict[type_name]
def get_index_sequence(self,
type_name):
try:
return self.sequence_index_dict[type_name]
except KeyError:
print("Error:", type_name)
return self.sequence_index_dict["HLA-A*01:01"]
def get_type_list(self):
_types = []
for _type in self.sequence_index_dict:
_types.append(_type)
return _types
def get_sequence_length(self):
return self.sequence_lengths
| 36.872727 | 116 | 0.533037 | import csv
class AllelePrimarySequenceManager:
AMINO_ACIDS_WITH_UNKNOWN = ['^', '-', 'A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R',
'S', 'T', 'V', 'W', 'Y', 'X']
NUM_AMINO_ACID = len(AMINO_ACIDS_WITH_UNKNOWN)
sequence_index_dict = {}
sequence_char_dict = {}
sequence_lengths = []
def __init__(self,
allele_primary_sequence_information_filename):
with open(allele_primary_sequence_information_filename, "r") as file:
csv_data = csv.reader(file, delimiter=',', quotechar="|")
for row in csv_data:
self.sequence_lengths = [len(row[1]), len(row[2]), len(row[3])]
assert(len(row) == 4)
self.sequence_char_dict[row[0]] = row[1:4]
self.sequence_index_dict[row[0]] = [self._char_to_index(row[1]),
self._char_to_index(row[2]),
self._char_to_index(row[3])]
assert(len(self.sequence_char_dict[row[0]]) == 3)
assert(len(self.sequence_index_dict[row[0]]) == 3)
def _char_to_index(self,
peptide):
indexes = []
for ac in peptide:
indexes.append(self.AMINO_ACIDS_WITH_UNKNOWN.index(ac))
return indexes
def get_char_sequence(self,
type_name):
return self.sequence_char_dict[type_name]
def get_index_sequence(self,
type_name):
try:
return self.sequence_index_dict[type_name]
except KeyError:
print("Error:", type_name)
return self.sequence_index_dict["HLA-A*01:01"]
def get_type_list(self):
_types = []
for _type in self.sequence_index_dict:
_types.append(_type)
return _types
def get_sequence_length(self):
return self.sequence_lengths
| true | true |
f7f75a4ef8094682a7058e35f93e95067b0925d6 | 41,880 | py | Python | proteus/mprans/MoveMesh.py | dloney/proteus | 615cdf57f765b2e99bac904bb6eb71e39e58ab56 | [
"MIT"
] | null | null | null | proteus/mprans/MoveMesh.py | dloney/proteus | 615cdf57f765b2e99bac904bb6eb71e39e58ab56 | [
"MIT"
] | null | null | null | proteus/mprans/MoveMesh.py | dloney/proteus | 615cdf57f765b2e99bac904bb6eb71e39e58ab56 | [
"MIT"
] | null | null | null | from __future__ import division
from builtins import str
from builtins import range
from past.utils import old_div
import proteus
from proteus.mprans.cMoveMesh import *
from proteus.mprans.cMoveMesh2D import *
class Coefficients(proteus.TransportCoefficients.TC_base):
def __init__(self,
modelType_block,
modelParams_block,
g=[0.0, 0.0, -9.8], # gravitational acceleration
rhow=998.2, # kg/m^3 water density (used if pore pressures specified)
nd=3,
meIndex=0,
V_model=0,
nullSpace='NoNullSpace'):
self.flowModelIndex = V_model
self.modelType_block = modelType_block
self.modelParams_block = modelParams_block
self.materialProperties = self.modelParams_block
self.nMaterialProperties = len(self.materialProperties[-1])
self.g = numpy.array(g)
self.gmag = sqrt(sum([gi**2 for gi in g]))
self.rhow = rhow
self.nd = nd
mass = {}
advection = {}
diffusion = {}
potential = {}
reaction = {}
hamiltonian = {}
stress = {}
if nd == 2:
variableNames = ['hx', 'hy']
mass = {0: {0: 'linear'},
1: {1: 'linear'}}
reaction = {0: {0: 'constant'},
1: {1: 'constant'}}
stress = {0: {0: 'linear', 1: 'linear'},
1: {0: 'linear', 1: 'linear'}}
TC_base.__init__(self,
2,
mass,
advection,
diffusion,
potential,
reaction,
hamiltonian,
variableNames,
stress=stress)
self.vectorComponents = [0, 1]
self.vectorName = "displacement"
else:
assert(nd == 3)
variableNames = ['hx', 'hy', 'hz']
mass = {0: {0: 'linear'},
1: {1: 'linear'},
2: {2: 'linear'}}
reaction = {0: {0: 'constant'},
1: {1: 'constant'},
2: {2: 'constant'}}
stress = {0: {0: 'linear', 1: 'linear', 2: 'linear'},
1: {0: 'linear', 1: 'linear', 2: 'linear'},
2: {0: 'linear', 1: 'linear', 2: 'linear'}}
TC_base.__init__(self,
3,
mass,
advection,
diffusion,
potential,
reaction,
hamiltonian,
variableNames,
stress=stress)
self.vectorComponents = [0, 1, 2]
self.vectorName = "displacement"
self.firstCall = True
self.gravityStep = True
self.meIndex = meIndex
self.dt_last = None
self.solidsList = []
self.nullSpace = nullSpace
def attachModels(self, modelList):
self.model = modelList[self.meIndex]
self.flowModel = modelList[self.flowModelIndex]
def initializeElementQuadrature(self, t, cq):
"""
Give the TC object access to the element quadrature storage
"""
if self.firstCall:
self.firstCall = False
self.cq = cq
self.bodyForce = cq['bodyForce']
# for eN in range(self.bodyForce.shape[0]):
# for k in range(self.bodyForce.shape[1]):
# self.bodyForce[eN,k,:] = self.g
def initializeGlobalExteriorElementBoundaryQuadrature(self, t, cebqe):
"""
Give the TC object access to the element quadrature storage
"""
pass
def initializeMesh(self, mesh):
self.mesh = mesh
def postStep(self, t, firstStep=False):
self.model.postStep()
self.mesh.nodeArray[:, 0] += self.model.u[0].dof
self.mesh.nodeVelocityArray[:, 0] = self.model.u[0].dof
self.model.u[0].dof[:] = 0.0
self.mesh.nodeArray[:, 1] += self.model.u[1].dof
self.mesh.nodeVelocityArray[:, 1] = self.model.u[1].dof
self.model.u[1].dof[:] = 0.0
if self.nd == 3:
self.mesh.nodeArray[:, 2] += self.model.u[2].dof
self.mesh.nodeVelocityArray[:, 2] = self.model.u[2].dof
self.model.u[2].dof[:] = 0.0
if self.dt_last is None:
dt = self.model.timeIntegration.dt
else:
dt = self.dt_last
self.mesh.nodeVelocityArray /= dt
self.dt_last = self.model.timeIntegration.dt
copyInstructions = {'clear_uList': True}
return copyInstructions
def preStep(self, t, firstStep=False):
logEvent("MoveMesh preStep")
self.model.preStep()
for s in self.solidsList:
logEvent("Calling step on solids")
logEvent(repr(s))
s.step()
def evaluate(self, t, c):
pass
class LevelModel(proteus.Transport.OneLevelTransport):
nCalls = 0
def __init__(self,
uDict,
phiDict,
testSpaceDict,
matType,
dofBoundaryConditionsDict,
dofBoundaryConditionsSetterDict,
coefficients,
elementQuadrature,
elementBoundaryQuadrature,
fluxBoundaryConditionsDict=None,
advectiveFluxBoundaryConditionsSetterDict=None,
diffusiveFluxBoundaryConditionsSetterDictDict=None,
stressFluxBoundaryConditionsSetterDict=None,
stabilization=None,
shockCapturing=None,
conservativeFluxDict=None,
numericalFluxType=None,
TimeIntegrationClass=None,
massLumping=False,
reactionLumping=False,
options=None,
name='Plasticity',
reuse_trial_and_test_quadrature=True,
sd=True,
movingDomain=False,
bdyNullSpace=False):
#
# set the objects describing the method and boundary conditions
#
self.bdyNullSpace=bdyNullSpace
self.moveCalls = 0
self.movingDomain = movingDomain
self.tLast_mesh = None
self.bdyNullSpace = bdyNullSpace
#
# cek todo clean up these flags in the optimized version
self.bcsTimeDependent = options.bcsTimeDependent
self.bcsSet = False
self.name = name
self.sd = sd
self.lowmem = True
self.timeTerm = True # allow turning off the time derivative
self.testIsTrial = True
self.phiTrialIsTrial = True
self.u = uDict
self.Hess = False
if isinstance(self.u[0].femSpace, C0_AffineQuadraticOnSimplexWithNodalBasis):
self.Hess = True
self.ua = {} # analytical solutions
self.phi = phiDict
self.dphi = {}
self.matType = matType
# mwf try to reuse test and trial information across components if spaces are the same
self.reuse_test_trial_quadrature = reuse_trial_and_test_quadrature # True#False
if self.reuse_test_trial_quadrature:
for ci in range(1, coefficients.nc):
assert self.u[ci].femSpace.__class__.__name__ == self.u[0].femSpace.__class__.__name__, "to reuse_test_trial_quad all femSpaces must be the same!"
# Simplicial Mesh
self.mesh = self.u[0].femSpace.mesh # assume the same mesh for all components for now
self.testSpace = testSpaceDict
self.dirichletConditions = dofBoundaryConditionsDict
self.dirichletNodeSetList = None # explicit Dirichlet conditions for now, no Dirichlet BC constraints
self.coefficients = coefficients
self.coefficients.initializeMesh(self.mesh)
self.nc = self.coefficients.nc
self.stabilization = stabilization
self.shockCapturing = shockCapturing
self.conservativeFlux = conservativeFluxDict # no velocity post-processing for now
self.fluxBoundaryConditions = fluxBoundaryConditionsDict
self.stressFluxBoundaryConditionsSetterDict = stressFluxBoundaryConditionsSetterDict
# determine whether the stabilization term is nonlinear
self.stabilizationIsNonlinear = False
# cek come back
if self.stabilization is not None:
for ci in range(self.nc):
if ci in coefficients.mass:
for flag in list(coefficients.mass[ci].values()):
if flag == 'nonlinear':
self.stabilizationIsNonlinear = True
if ci in coefficients.advection:
for flag in list(coefficients.advection[ci].values()):
if flag == 'nonlinear':
self.stabilizationIsNonlinear = True
if ci in coefficients.diffusion:
for diffusionDict in list(coefficients.diffusion[ci].values()):
for flag in list(diffusionDict.values()):
if flag != 'constant':
self.stabilizationIsNonlinear = True
if ci in coefficients.potential:
for flag in list(coefficients.potential[ci].values()):
if flag == 'nonlinear':
self.stabilizationIsNonlinear = True
if ci in coefficients.reaction:
for flag in list(coefficients.reaction[ci].values()):
if flag == 'nonlinear':
self.stabilizationIsNonlinear = True
if ci in coefficients.hamiltonian:
for flag in list(coefficients.hamiltonian[ci].values()):
if flag == 'nonlinear':
self.stabilizationIsNonlinear = True
# determine if we need element boundary storage
self.elementBoundaryIntegrals = {}
for ci in range(self.nc):
self.elementBoundaryIntegrals[ci] = ((self.conservativeFlux is not None) or
(numericalFluxType is not None) or
(self.fluxBoundaryConditions[ci] == 'outFlow') or
(self.fluxBoundaryConditions[ci] == 'mixedFlow') or
(self.fluxBoundaryConditions[ci] == 'setFlow'))
#
# calculate some dimensions
#
self.nSpace_global = self.u[0].femSpace.nSpace_global # assume same space dim for all variables
self.nDOF_trial_element = [u_j.femSpace.max_nDOF_element for u_j in list(self.u.values())]
self.nDOF_phi_trial_element = [phi_k.femSpace.max_nDOF_element for phi_k in list(self.phi.values())]
self.n_phi_ip_element = [phi_k.femSpace.referenceFiniteElement.interpolationConditions.nQuadraturePoints for phi_k in list(self.phi.values())]
self.nDOF_test_element = [femSpace.max_nDOF_element for femSpace in list(self.testSpace.values())]
self.nFreeDOF_global = [dc.nFreeDOF_global for dc in list(self.dirichletConditions.values())]
self.nVDOF_element = sum(self.nDOF_trial_element)
self.nFreeVDOF_global = sum(self.nFreeDOF_global)
#
NonlinearEquation.__init__(self, self.nFreeVDOF_global)
#
# build the quadrature point dictionaries from the input (this
# is just for convenience so that the input doesn't have to be
# complete)
#
elementQuadratureDict = {}
elemQuadIsDict = isinstance(elementQuadrature, dict)
if elemQuadIsDict: # set terms manually
for I in self.coefficients.elementIntegralKeys:
if I in elementQuadrature:
elementQuadratureDict[I] = elementQuadrature[I]
else:
elementQuadratureDict[I] = elementQuadrature['default']
else:
for I in self.coefficients.elementIntegralKeys:
elementQuadratureDict[I] = elementQuadrature
if self.stabilization is not None:
for I in self.coefficients.elementIntegralKeys:
if elemQuadIsDict:
if I in elementQuadrature:
elementQuadratureDict[('stab',) + I[1:]] = elementQuadrature[I]
else:
elementQuadratureDict[('stab',) + I[1:]] = elementQuadrature['default']
else:
elementQuadratureDict[('stab',) + I[1:]] = elementQuadrature
if self.shockCapturing is not None:
for ci in self.shockCapturing.components:
if elemQuadIsDict:
if ('numDiff', ci, ci) in elementQuadrature:
elementQuadratureDict[('numDiff', ci, ci)] = elementQuadrature[('numDiff', ci, ci)]
else:
elementQuadratureDict[('numDiff', ci, ci)] = elementQuadrature['default']
else:
elementQuadratureDict[('numDiff', ci, ci)] = elementQuadrature
if massLumping:
for ci in list(self.coefficients.mass.keys()):
elementQuadratureDict[('m', ci)] = Quadrature.SimplexLobattoQuadrature(self.nSpace_global, 1)
for I in self.coefficients.elementIntegralKeys:
elementQuadratureDict[('stab',) + I[1:]] = Quadrature.SimplexLobattoQuadrature(self.nSpace_global, 1)
if reactionLumping:
for ci in list(self.coefficients.mass.keys()):
elementQuadratureDict[('r', ci)] = Quadrature.SimplexLobattoQuadrature(self.nSpace_global, 1)
for I in self.coefficients.elementIntegralKeys:
elementQuadratureDict[('stab',) + I[1:]] = Quadrature.SimplexLobattoQuadrature(self.nSpace_global, 1)
elementBoundaryQuadratureDict = {}
if isinstance(elementBoundaryQuadrature, dict): # set terms manually
for I in self.coefficients.elementBoundaryIntegralKeys:
if I in elementBoundaryQuadrature:
elementBoundaryQuadratureDict[I] = elementBoundaryQuadrature[I]
else:
elementBoundaryQuadratureDict[I] = elementBoundaryQuadrature['default']
else:
for I in self.coefficients.elementBoundaryIntegralKeys:
elementBoundaryQuadratureDict[I] = elementBoundaryQuadrature
#
# find the union of all element quadrature points and
# build a quadrature rule for each integral that has a
# weight at each point in the union
# mwf include tag telling me which indices are which quadrature rule?
(self.elementQuadraturePoints, self.elementQuadratureWeights,
self.elementQuadratureRuleIndeces) = Quadrature.buildUnion(elementQuadratureDict)
self.nQuadraturePoints_element = self.elementQuadraturePoints.shape[0]
self.nQuadraturePoints_global = self.nQuadraturePoints_element * self.mesh.nElements_global
#
# Repeat the same thing for the element boundary quadrature
#
(self.elementBoundaryQuadraturePoints,
self.elementBoundaryQuadratureWeights,
self.elementBoundaryQuadratureRuleIndeces) = Quadrature.buildUnion(elementBoundaryQuadratureDict)
self.nElementBoundaryQuadraturePoints_elementBoundary = self.elementBoundaryQuadraturePoints.shape[0]
self.nElementBoundaryQuadraturePoints_global = (self.mesh.nElements_global *
self.mesh.nElementBoundaries_element *
self.nElementBoundaryQuadraturePoints_elementBoundary)
#
# simplified allocations for test==trial and also check if space is mixed or not
#
self.q = {}
self.ebq = {}
self.ebq_global = {}
self.ebqe = {}
self.phi_ip = {}
# mesh
self.ebqe['x'] = numpy.zeros((self.mesh.nExteriorElementBoundaries_global, self.nElementBoundaryQuadraturePoints_elementBoundary, 3), 'd')
self.q['bodyForce'] = numpy.zeros((self.mesh.nElements_global, self.nQuadraturePoints_element, self.nSpace_global), 'd')
self.ebqe[('u', 0)] = numpy.zeros((self.mesh.nExteriorElementBoundaries_global, self.nElementBoundaryQuadraturePoints_elementBoundary), 'd')
self.ebqe[('u', 1)] = numpy.zeros((self.mesh.nExteriorElementBoundaries_global, self.nElementBoundaryQuadraturePoints_elementBoundary), 'd')
self.ebqe[('u', 2)] = numpy.zeros((self.mesh.nExteriorElementBoundaries_global, self.nElementBoundaryQuadraturePoints_elementBoundary), 'd')
self.ebqe[('stressFlux_bc_flag', 0)] = numpy.zeros(
(self.mesh.nExteriorElementBoundaries_global, self.nElementBoundaryQuadraturePoints_elementBoundary), 'i')
self.ebqe[('stressFlux_bc_flag', 1)] = numpy.zeros(
(self.mesh.nExteriorElementBoundaries_global, self.nElementBoundaryQuadraturePoints_elementBoundary), 'i')
self.ebqe[('stressFlux_bc_flag', 2)] = numpy.zeros(
(self.mesh.nExteriorElementBoundaries_global, self.nElementBoundaryQuadraturePoints_elementBoundary), 'i')
self.ebqe[('stressFlux_bc', 0)] = numpy.zeros((self.mesh.nExteriorElementBoundaries_global, self.nElementBoundaryQuadraturePoints_elementBoundary), 'd')
self.ebqe[('stressFlux_bc', 1)] = numpy.zeros((self.mesh.nExteriorElementBoundaries_global, self.nElementBoundaryQuadraturePoints_elementBoundary), 'd')
self.ebqe[('stressFlux_bc', 2)] = numpy.zeros((self.mesh.nExteriorElementBoundaries_global, self.nElementBoundaryQuadraturePoints_elementBoundary), 'd')
self.points_elementBoundaryQuadrature = set()
self.scalars_elementBoundaryQuadrature = set([('u', ci) for ci in range(self.nc)])
self.vectors_elementBoundaryQuadrature = set()
self.tensors_elementBoundaryQuadrature = set()
#
# show quadrature
#
logEvent("Dumping quadrature shapes for model %s" % self.name, level=9)
logEvent("Element quadrature array (q)", level=9)
for (k, v) in list(self.q.items()):
logEvent(str((k, v.shape)), level=9)
logEvent("Element boundary quadrature (ebq)", level=9)
for (k, v) in list(self.ebq.items()):
logEvent(str((k, v.shape)), level=9)
logEvent("Global element boundary quadrature (ebq_global)", level=9)
for (k, v) in list(self.ebq_global.items()):
logEvent(str((k, v.shape)), level=9)
logEvent("Exterior element boundary quadrature (ebqe)", level=9)
for (k, v) in list(self.ebqe.items()):
logEvent(str((k, v.shape)), level=9)
logEvent("Interpolation points for nonlinear diffusion potential (phi_ip)", level=9)
for (k, v) in list(self.phi_ip.items()):
logEvent(str((k, v.shape)), level=9)
#
# allocate residual and Jacobian storage
#
self.elementResidual = [numpy.zeros(
(self.mesh.nElements_global,
self.nDOF_test_element[ci]),
'd') for ci in range(self.nc)]
self.elementSpatialResidual = [numpy.zeros(
(self.mesh.nElements_global,
self.nDOF_test_element[ci]),
'd') for ci in range(self.nc)]
self.inflowBoundaryBC = {}
self.inflowBoundaryBC_values = {}
self.inflowFlux = {}
for cj in range(self.nc):
self.inflowBoundaryBC[cj] = numpy.zeros((self.mesh.nExteriorElementBoundaries_global,), 'i')
self.inflowBoundaryBC_values[cj] = numpy.zeros((self.mesh.nExteriorElementBoundaries_global, self.nDOF_trial_element[cj]), 'd')
self.inflowFlux[cj] = numpy.zeros((self.mesh.nExteriorElementBoundaries_global, self.nElementBoundaryQuadraturePoints_elementBoundary), 'd')
self.internalNodes = set(range(self.mesh.nNodes_global))
# identify the internal nodes this is ought to be in mesh
# \todo move this to mesh
for ebNE in range(self.mesh.nExteriorElementBoundaries_global):
ebN = self.mesh.exteriorElementBoundariesArray[ebNE]
eN_global = self.mesh.elementBoundaryElementsArray[ebN, 0]
ebN_element = self.mesh.elementBoundaryLocalElementBoundariesArray[ebN, 0]
for i in range(self.mesh.nNodes_element):
if i != ebN_element:
I = self.mesh.elementNodesArray[eN_global, i]
self.internalNodes -= set([I])
self.nNodes_internal = len(self.internalNodes)
self.internalNodesArray = numpy.zeros((self.nNodes_internal,), 'i')
for nI, n in enumerate(self.internalNodes):
self.internalNodesArray[nI] = n
#
del self.internalNodes
self.internalNodes = None
logEvent("Updating local to global mappings", 2)
self.updateLocal2Global()
logEvent("Building time integration object", 2)
logEvent(memory("inflowBC, internalNodes,updateLocal2Global", "OneLevelTransport"), level=4)
# mwf for interpolating subgrid error for gradients etc
if self.stabilization and self.stabilization.usesGradientStabilization:
self.timeIntegration = TimeIntegrationClass(self, integrateInterpolationPoints=True)
else:
self.timeIntegration = TimeIntegrationClass(self)
if options is not None:
self.timeIntegration.setFromOptions(options)
logEvent(memory("TimeIntegration", "OneLevelTransport"), level=4)
logEvent("Calculating numerical quadrature formulas", 2)
self.calculateQuadrature()
self.setupFieldStrides()
comm = Comm.get()
self.comm = comm
if comm.size() > 1:
assert numericalFluxType is not None and numericalFluxType.useWeakDirichletConditions, "You must use a numerical flux to apply weak boundary conditions for parallel runs"
logEvent(memory("stride+offset", "OneLevelTransport"), level=4)
if numericalFluxType is not None:
if options is None or options.periodicDirichletConditions is None:
self.numericalFlux = numericalFluxType(self,
dofBoundaryConditionsSetterDict,
advectiveFluxBoundaryConditionsSetterDict,
diffusiveFluxBoundaryConditionsSetterDictDict)
else:
self.numericalFlux = numericalFluxType(self,
dofBoundaryConditionsSetterDict,
advectiveFluxBoundaryConditionsSetterDict,
diffusiveFluxBoundaryConditionsSetterDictDict,
options.periodicDirichletConditions)
else:
self.numericalFlux = None
# set penalty terms
# cek todo move into numerical flux initialization
if 'penalty' in self.ebq_global:
for ebN in range(self.mesh.nElementBoundaries_global):
for k in range(self.nElementBoundaryQuadraturePoints_elementBoundary):
self.ebq_global['penalty'][ebN, k] = old_div(self.numericalFlux.penalty_constant, \
(self.mesh.elementBoundaryDiametersArray[ebN]**self.numericalFlux.penalty_power))
# penalty term
# cek move to Numerical flux initialization
if 'penalty' in self.ebqe:
for ebNE in range(self.mesh.nExteriorElementBoundaries_global):
ebN = self.mesh.exteriorElementBoundariesArray[ebNE]
for k in range(self.nElementBoundaryQuadraturePoints_elementBoundary):
self.ebqe['penalty'][ebNE, k] = old_div(self.numericalFlux.penalty_constant, \
self.mesh.elementBoundaryDiametersArray[ebN]**self.numericalFlux.penalty_power)
logEvent(memory("numericalFlux", "OneLevelTransport"), level=4)
self.elementEffectiveDiametersArray = self.mesh.elementInnerDiametersArray
# use post processing tools to get conservative fluxes, None by default
# helper for writing out data storage
import proteus.Archiver
self.elementQuadratureDictionaryWriter = Archiver.XdmfWriter()
self.elementBoundaryQuadratureDictionaryWriter = Archiver.XdmfWriter()
self.exteriorElementBoundaryQuadratureDictionaryWriter = Archiver.XdmfWriter()
for ci, sbcObject in list(self.stressFluxBoundaryConditionsObjectsDict.items()):
self.ebqe[('stressFlux_bc_flag', ci)] = numpy.zeros(self.ebqe[('stressFlux_bc', ci)].shape, 'i')
for t, g in list(sbcObject.stressFluxBoundaryConditionsDict.items()):
self.ebqe[('stressFlux_bc', ci)][t[0], t[1]] = g(self.ebqe[('x')][t[0], t[1]], self.timeIntegration.t)
self.ebqe[('stressFlux_bc_flag', ci)][t[0], t[1]] = 1
self.numericalFlux.setDirichletValues(self.ebqe)
if self.mesh.nodeVelocityArray is None:
self.mesh.nodeVelocityArray = numpy.zeros(self.mesh.nodeArray.shape, 'd')
compKernelFlag = 0
if self.nSpace_global == 2:
import copy
self.u[2] = self.u[1].copy()
self.u[2].name = 'hz'
self.offset.append(self.offset[1])
self.stride.append(self.stride[1])
self.numericalFlux.isDOFBoundary[2] = self.numericalFlux.isDOFBoundary[1].copy()
self.numericalFlux.ebqe[('u', 2)] = self.numericalFlux.ebqe[('u', 1)].copy()
logEvent("calling cMoveMesh2D_base ctor")
self.moveMesh = cMoveMesh2D_base(self.nSpace_global,
self.nQuadraturePoints_element,
self.u[0].femSpace.elementMaps.localFunctionSpace.dim,
self.u[0].femSpace.referenceFiniteElement.localFunctionSpace.dim,
self.testSpace[0].referenceFiniteElement.localFunctionSpace.dim,
self.nElementBoundaryQuadraturePoints_elementBoundary,
compKernelFlag)
else:
logEvent("calling cMoveMesh_base ctor")
self.moveMesh = cMoveMesh_base(self.nSpace_global,
self.nQuadraturePoints_element,
self.u[0].femSpace.elementMaps.localFunctionSpace.dim,
self.u[0].femSpace.referenceFiniteElement.localFunctionSpace.dim,
self.testSpace[0].referenceFiniteElement.localFunctionSpace.dim,
self.nElementBoundaryQuadraturePoints_elementBoundary,
compKernelFlag)
self.disp0 = numpy.zeros(self.nSpace_global, 'd')
self.disp1 = numpy.zeros(self.nSpace_global, 'd')
self.vel0 = numpy.zeros(self.nSpace_global, 'd')
self.vel1 = numpy.zeros(self.nSpace_global, 'd')
self.rot0 = numpy.eye(self.nSpace_global, dtype=float)
self.rot1 = numpy.eye(self.nSpace_global, dtype=float)
self.angVel0 = numpy.zeros(self.nSpace_global, 'd')
self.angVel1 = numpy.zeros(self.nSpace_global, 'd')
self.forceStrongConditions = True # False#True
self.dirichletConditionsForceDOF = {}
if self.forceStrongConditions:
for cj in range(self.nc):
self.dirichletConditionsForceDOF[cj] = DOFBoundaryConditions(
self.u[cj].femSpace, dofBoundaryConditionsSetterDict[cj], weakDirichletConditions=False)
from proteus import PostProcessingTools
self.velocityPostProcessor = PostProcessingTools.VelocityPostProcessingChooser(self)
logEvent(memory("velocity postprocessor", "OneLevelTransport"), level=4)
def getResidual(self, u, r):
"""
Calculate the element residuals and add in to the global residual
"""
# Load the unknowns into the finite element dof
self.timeIntegration.calculateCoefs()
self.timeIntegration.calculateU(u)
self.setUnknowns(self.timeIntegration.u)
if self.bcsTimeDependent or not self.bcsSet:
self.bcsSet = True
# Dirichlet boundary conditions
self.numericalFlux.setDirichletValues(self.ebqe)
# Flux boundary conditions
for ci, fbcObject in list(self.stressFluxBoundaryConditionsObjectsDict.items()):
for t, g in list(fbcObject.stressFluxBoundaryConditionsDict.items()):
self.ebqe[('stressFlux_bc', ci)][t[0], t[1]] = g(self.ebqe[('x')][t[0], t[1]], self.timeIntegration.t)
self.ebqe[('stressFlux_bc_flag', ci)][t[0], t[1]] = 1
r.fill(0.0)
self.elementResidual[0].fill(0.0)
self.elementResidual[1].fill(0.0)
if self.nSpace_global == 3:
self.elementResidual[2].fill(0.0)
if self.forceStrongConditions:
for cj in range(self.nc):
for dofN, g in list(self.dirichletConditionsForceDOF[cj].DOFBoundaryConditionsDict.items()):
self.u[cj].dof[dofN] = g(self.dirichletConditionsForceDOF[cj].DOFBoundaryPointDict[dofN], self.timeIntegration.t)
self.moveMesh.calculateResidual( # element
self.u[0].femSpace.elementMaps.psi,
self.u[0].femSpace.elementMaps.grad_psi,
self.mesh.nodeArray,
self.mesh.elementNodesArray,
self.elementQuadratureWeights[('u', 0)],
self.u[0].femSpace.psi,
self.u[0].femSpace.grad_psi,
self.u[0].femSpace.psi,
self.u[0].femSpace.grad_psi,
# element boundary
self.u[0].femSpace.elementMaps.psi_trace,
self.u[0].femSpace.elementMaps.grad_psi_trace,
self.elementBoundaryQuadratureWeights[('u', 0)],
self.u[0].femSpace.psi_trace,
self.u[0].femSpace.grad_psi_trace,
self.u[0].femSpace.psi_trace,
self.u[0].femSpace.grad_psi_trace,
self.u[0].femSpace.elementMaps.boundaryNormals,
self.u[0].femSpace.elementMaps.boundaryJacobians,
# physics
self.mesh.nElements_global,
self.mesh.elementMaterialTypes,
self.coefficients.nMaterialProperties,
self.coefficients.materialProperties,
self.u[0].femSpace.dofMap.l2g,
self.u[0].dof,
self.u[1].dof,
self.u[2].dof,
self.coefficients.bodyForce,
self.offset[0], self.offset[1], self.offset[2],
self.stride[0], self.stride[1], self.stride[2],
r,
self.mesh.nExteriorElementBoundaries_global,
self.mesh.exteriorElementBoundariesArray,
self.mesh.elementBoundaryElementsArray,
self.mesh.elementBoundaryLocalElementBoundariesArray,
self.numericalFlux.isDOFBoundary[0],
self.numericalFlux.isDOFBoundary[1],
self.numericalFlux.isDOFBoundary[2],
self.ebqe[('stressFlux_bc_flag', 0)],
self.ebqe[('stressFlux_bc_flag', 1)],
self.ebqe[('stressFlux_bc_flag', 2)],
self.numericalFlux.ebqe[('u', 0)],
self.numericalFlux.ebqe[('u', 1)],
self.numericalFlux.ebqe[('u', 2)],
self.ebqe[('stressFlux_bc', 0)],
self.ebqe[('stressFlux_bc', 1)],
self.ebqe[('stressFlux_bc', 2)])
if self.forceStrongConditions:
for cj in range(self.nc):
for dofN, g in list(self.dirichletConditionsForceDOF[cj].DOFBoundaryConditionsDict.items()):
r[self.offset[cj] + self.stride[cj] * dofN] = self.u[cj].dof[dofN] - \
g(self.dirichletConditionsForceDOF[cj].DOFBoundaryPointDict[dofN], self.timeIntegration.t)
logEvent("Global residual", level=9, data=r)
self.nonlinear_function_evaluations += 1
def getJacobian(self, jacobian):
cfemIntegrals.zeroJacobian_CSR(self.nNonzerosInJacobian,
jacobian)
if self.nSpace_global == 2:
self.csrRowIndeces[(0, 2)] = self.csrRowIndeces[(0, 1)]
self.csrColumnOffsets[(0, 2)] = self.csrColumnOffsets[(0, 1)]
self.csrRowIndeces[(1, 2)] = self.csrRowIndeces[(0, 1)]
self.csrColumnOffsets[(1, 2)] = self.csrColumnOffsets[(0, 1)]
self.csrRowIndeces[(2, 0)] = self.csrRowIndeces[(1, 0)]
self.csrColumnOffsets[(2, 0)] = self.csrColumnOffsets[(1, 0)]
self.csrRowIndeces[(2, 1)] = self.csrRowIndeces[(1, 0)]
self.csrColumnOffsets[(2, 1)] = self.csrColumnOffsets[(1, 0)]
self.csrRowIndeces[(2, 2)] = self.csrRowIndeces[(1, 0)]
self.csrColumnOffsets[(2, 2)] = self.csrColumnOffsets[(1, 0)]
self.csrColumnOffsets_eb[(0, 2)] = self.csrColumnOffsets[(0, 1)]
self.csrColumnOffsets_eb[(1, 2)] = self.csrColumnOffsets[(0, 1)]
self.csrColumnOffsets_eb[(2, 2)] = self.csrColumnOffsets[(0, 1)]
self.csrColumnOffsets_eb[(2, 0)] = self.csrColumnOffsets[(0, 1)]
self.csrColumnOffsets_eb[(2, 1)] = self.csrColumnOffsets[(0, 1)]
self.csrColumnOffsets_eb[(2, 2)] = self.csrColumnOffsets[(0, 1)]
self.moveMesh.calculateJacobian( # element
self.u[0].femSpace.elementMaps.psi,
self.u[0].femSpace.elementMaps.grad_psi,
self.mesh.nodeArray,
self.mesh.elementNodesArray,
self.elementQuadratureWeights[('u', 0)],
self.u[0].femSpace.psi,
self.u[0].femSpace.grad_psi,
self.u[0].femSpace.psi,
self.u[0].femSpace.grad_psi,
# element boundary
self.u[0].femSpace.elementMaps.psi_trace,
self.u[0].femSpace.elementMaps.grad_psi_trace,
self.elementBoundaryQuadratureWeights[('u', 0)],
self.u[0].femSpace.psi_trace,
self.u[0].femSpace.grad_psi_trace,
self.u[0].femSpace.psi_trace,
self.u[0].femSpace.grad_psi_trace,
self.u[0].femSpace.elementMaps.boundaryNormals,
self.u[0].femSpace.elementMaps.boundaryJacobians,
self.mesh.nElements_global,
self.mesh.elementMaterialTypes,
self.coefficients.nMaterialProperties,
self.coefficients.materialProperties,
self.u[0].femSpace.dofMap.l2g,
self.u[0].dof,
self.u[1].dof,
self.u[2].dof,
self.coefficients.bodyForce,
self.csrRowIndeces[(0, 0)], self.csrColumnOffsets[(0, 0)],
self.csrRowIndeces[(0, 1)], self.csrColumnOffsets[(0, 1)],
self.csrRowIndeces[(0, 2)], self.csrColumnOffsets[(0, 2)],
self.csrRowIndeces[(1, 0)], self.csrColumnOffsets[(1, 0)],
self.csrRowIndeces[(1, 1)], self.csrColumnOffsets[(1, 1)],
self.csrRowIndeces[(1, 2)], self.csrColumnOffsets[(1, 2)],
self.csrRowIndeces[(2, 0)], self.csrColumnOffsets[(2, 0)],
self.csrRowIndeces[(2, 1)], self.csrColumnOffsets[(2, 1)],
self.csrRowIndeces[(2, 2)], self.csrColumnOffsets[(2, 2)],
jacobian,
self.mesh.nExteriorElementBoundaries_global,
self.mesh.exteriorElementBoundariesArray,
self.mesh.elementBoundaryElementsArray,
self.mesh.elementBoundaryLocalElementBoundariesArray,
self.numericalFlux.isDOFBoundary[0],
self.numericalFlux.isDOFBoundary[1],
self.numericalFlux.isDOFBoundary[2],
self.ebqe[('stressFlux_bc_flag', 0)],
self.ebqe[('stressFlux_bc_flag', 1)],
self.ebqe[('stressFlux_bc_flag', 2)],
self.csrColumnOffsets_eb[(0, 0)],
self.csrColumnOffsets_eb[(0, 1)],
self.csrColumnOffsets_eb[(0, 2)],
self.csrColumnOffsets_eb[(1, 0)],
self.csrColumnOffsets_eb[(1, 1)],
self.csrColumnOffsets_eb[(1, 2)],
self.csrColumnOffsets_eb[(2, 0)],
self.csrColumnOffsets_eb[(2, 1)],
self.csrColumnOffsets_eb[(2, 2)])
# Load the Dirichlet conditions directly into residual
if self.forceStrongConditions:
scaling = 1.0 # probably want to add some scaling to match non-dirichlet diagonals in linear system
for cj in range(self.nc):
for dofN in list(self.dirichletConditionsForceDOF[cj].DOFBoundaryConditionsDict.keys()):
global_dofN = self.offset[cj] + self.stride[cj] * dofN
for i in range(self.rowptr[global_dofN], self.rowptr[global_dofN + 1]):
if (self.colind[i] == global_dofN):
self.nzval[i] = scaling
else:
self.nzval[i] = 0.0
logEvent("Jacobian ", level=10, data=jacobian)
# mwf decide if this is reasonable for solver statistics
self.nonlinear_function_jacobian_evaluations += 1
# jacobian.fwrite("jacobian_p"+`self.nonlinear_function_jacobian_evaluations`)
return jacobian
def calculateElementQuadrature(self):
"""
Calculate the physical location and weights of the quadrature rules
and the shape information at the quadrature points.
This function should be called only when the mesh changes.
"""
self.u[0].femSpace.elementMaps.getBasisValuesRef(self.elementQuadraturePoints)
self.u[0].femSpace.elementMaps.getBasisGradientValuesRef(self.elementQuadraturePoints)
self.u[0].femSpace.getBasisValuesRef(self.elementQuadraturePoints)
self.u[0].femSpace.getBasisGradientValuesRef(self.elementQuadraturePoints)
self.coefficients.initializeElementQuadrature(self.timeIntegration.t, self.q)
def calculateElementBoundaryQuadrature(self):
"""
Calculate the physical location and weights of the quadrature rules
and the shape information at the quadrature points on element boundaries.
This function should be called only when the mesh changes.
"""
pass
def calculateExteriorElementBoundaryQuadrature(self):
"""
Calculate the physical location and weights of the quadrature rules
and the shape information at the quadrature points on global element boundaries.
This function should be called only when the mesh changes.
"""
#
# get physical locations of element boundary quadrature points
#
# assume all components live on the same mesh
self.u[0].femSpace.elementMaps.getBasisValuesTraceRef(self.elementBoundaryQuadraturePoints)
self.u[0].femSpace.elementMaps.getBasisGradientValuesTraceRef(self.elementBoundaryQuadraturePoints)
self.u[0].femSpace.getBasisValuesTraceRef(self.elementBoundaryQuadraturePoints)
self.u[0].femSpace.getBasisGradientValuesTraceRef(self.elementBoundaryQuadraturePoints)
self.u[0].femSpace.elementMaps.getValuesGlobalExteriorTrace(self.elementBoundaryQuadraturePoints,
self.ebqe['x'])
self.stressFluxBoundaryConditionsObjectsDict = dict([(cj, FluxBoundaryConditions(self.mesh,
self.nElementBoundaryQuadraturePoints_elementBoundary,
self.ebqe[('x')],
self.stressFluxBoundaryConditionsSetterDict[cj]))
for cj in list(self.stressFluxBoundaryConditionsSetterDict.keys())])
self.coefficients.initializeGlobalExteriorElementBoundaryQuadrature(self.timeIntegration.t, self.ebqe)
def estimate_mt(self):
pass
def calculateSolutionAtQuadrature(self):
pass
def calculateAuxiliaryQuantitiesAfterStep(self):
OneLevelTransport.calculateAuxiliaryQuantitiesAfterStep(self)
def preStep(self):
pass
def postStep(self):
pass
def updateAfterMeshMotion(self):
# cek todo: this needs to be cleaned up and generalized for other models under moving conditions
# few models actually use the ebqe['x'] for boundary conditions, but we need to make it
# consistent (the physical coordinates and not the reference domain coordinates)
self.calculateElementQuadrature()
self.ebqe_old_x = self.ebqe['x'].copy()
self.calculateExteriorElementBoundaryQuadrature() # pass
for cj in range(self.nc):
self.u[cj].femSpace.updateInterpolationPoints()
for dofN, g in list(self.dirichletConditionsForceDOF[cj].DOFBoundaryConditionsDict.items()):
self.dirichletConditionsForceDOF[cj].DOFBoundaryPointDict[dofN] = self.mesh.nodeArray[dofN]
| 53.079848 | 182 | 0.601695 | from __future__ import division
from builtins import str
from builtins import range
from past.utils import old_div
import proteus
from proteus.mprans.cMoveMesh import *
from proteus.mprans.cMoveMesh2D import *
class Coefficients(proteus.TransportCoefficients.TC_base):
def __init__(self,
modelType_block,
modelParams_block,
g=[0.0, 0.0, -9.8],
rhow=998.2,
nd=3,
meIndex=0,
V_model=0,
nullSpace='NoNullSpace'):
self.flowModelIndex = V_model
self.modelType_block = modelType_block
self.modelParams_block = modelParams_block
self.materialProperties = self.modelParams_block
self.nMaterialProperties = len(self.materialProperties[-1])
self.g = numpy.array(g)
self.gmag = sqrt(sum([gi**2 for gi in g]))
self.rhow = rhow
self.nd = nd
mass = {}
advection = {}
diffusion = {}
potential = {}
reaction = {}
hamiltonian = {}
stress = {}
if nd == 2:
variableNames = ['hx', 'hy']
mass = {0: {0: 'linear'},
1: {1: 'linear'}}
reaction = {0: {0: 'constant'},
1: {1: 'constant'}}
stress = {0: {0: 'linear', 1: 'linear'},
1: {0: 'linear', 1: 'linear'}}
TC_base.__init__(self,
2,
mass,
advection,
diffusion,
potential,
reaction,
hamiltonian,
variableNames,
stress=stress)
self.vectorComponents = [0, 1]
self.vectorName = "displacement"
else:
assert(nd == 3)
variableNames = ['hx', 'hy', 'hz']
mass = {0: {0: 'linear'},
1: {1: 'linear'},
2: {2: 'linear'}}
reaction = {0: {0: 'constant'},
1: {1: 'constant'},
2: {2: 'constant'}}
stress = {0: {0: 'linear', 1: 'linear', 2: 'linear'},
1: {0: 'linear', 1: 'linear', 2: 'linear'},
2: {0: 'linear', 1: 'linear', 2: 'linear'}}
TC_base.__init__(self,
3,
mass,
advection,
diffusion,
potential,
reaction,
hamiltonian,
variableNames,
stress=stress)
self.vectorComponents = [0, 1, 2]
self.vectorName = "displacement"
self.firstCall = True
self.gravityStep = True
self.meIndex = meIndex
self.dt_last = None
self.solidsList = []
self.nullSpace = nullSpace
def attachModels(self, modelList):
self.model = modelList[self.meIndex]
self.flowModel = modelList[self.flowModelIndex]
def initializeElementQuadrature(self, t, cq):
if self.firstCall:
self.firstCall = False
self.cq = cq
self.bodyForce = cq['bodyForce']
def initializeGlobalExteriorElementBoundaryQuadrature(self, t, cebqe):
pass
def initializeMesh(self, mesh):
self.mesh = mesh
def postStep(self, t, firstStep=False):
self.model.postStep()
self.mesh.nodeArray[:, 0] += self.model.u[0].dof
self.mesh.nodeVelocityArray[:, 0] = self.model.u[0].dof
self.model.u[0].dof[:] = 0.0
self.mesh.nodeArray[:, 1] += self.model.u[1].dof
self.mesh.nodeVelocityArray[:, 1] = self.model.u[1].dof
self.model.u[1].dof[:] = 0.0
if self.nd == 3:
self.mesh.nodeArray[:, 2] += self.model.u[2].dof
self.mesh.nodeVelocityArray[:, 2] = self.model.u[2].dof
self.model.u[2].dof[:] = 0.0
if self.dt_last is None:
dt = self.model.timeIntegration.dt
else:
dt = self.dt_last
self.mesh.nodeVelocityArray /= dt
self.dt_last = self.model.timeIntegration.dt
copyInstructions = {'clear_uList': True}
return copyInstructions
def preStep(self, t, firstStep=False):
logEvent("MoveMesh preStep")
self.model.preStep()
for s in self.solidsList:
logEvent("Calling step on solids")
logEvent(repr(s))
s.step()
def evaluate(self, t, c):
pass
class LevelModel(proteus.Transport.OneLevelTransport):
nCalls = 0
def __init__(self,
uDict,
phiDict,
testSpaceDict,
matType,
dofBoundaryConditionsDict,
dofBoundaryConditionsSetterDict,
coefficients,
elementQuadrature,
elementBoundaryQuadrature,
fluxBoundaryConditionsDict=None,
advectiveFluxBoundaryConditionsSetterDict=None,
diffusiveFluxBoundaryConditionsSetterDictDict=None,
stressFluxBoundaryConditionsSetterDict=None,
stabilization=None,
shockCapturing=None,
conservativeFluxDict=None,
numericalFluxType=None,
TimeIntegrationClass=None,
massLumping=False,
reactionLumping=False,
options=None,
name='Plasticity',
reuse_trial_and_test_quadrature=True,
sd=True,
movingDomain=False,
bdyNullSpace=False):
self.bdyNullSpace=bdyNullSpace
self.moveCalls = 0
self.movingDomain = movingDomain
self.tLast_mesh = None
self.bdyNullSpace = bdyNullSpace
self.bcsTimeDependent = options.bcsTimeDependent
self.bcsSet = False
self.name = name
self.sd = sd
self.lowmem = True
self.timeTerm = True
self.testIsTrial = True
self.phiTrialIsTrial = True
self.u = uDict
self.Hess = False
if isinstance(self.u[0].femSpace, C0_AffineQuadraticOnSimplexWithNodalBasis):
self.Hess = True
self.ua = {}
self.phi = phiDict
self.dphi = {}
self.matType = matType
self.reuse_test_trial_quadrature = reuse_trial_and_test_quadrature if self.reuse_test_trial_quadrature:
for ci in range(1, coefficients.nc):
assert self.u[ci].femSpace.__class__.__name__ == self.u[0].femSpace.__class__.__name__, "to reuse_test_trial_quad all femSpaces must be the same!"
self.mesh = self.u[0].femSpace.mesh
self.testSpace = testSpaceDict
self.dirichletConditions = dofBoundaryConditionsDict
self.dirichletNodeSetList = None
self.coefficients = coefficients
self.coefficients.initializeMesh(self.mesh)
self.nc = self.coefficients.nc
self.stabilization = stabilization
self.shockCapturing = shockCapturing
self.conservativeFlux = conservativeFluxDict
self.fluxBoundaryConditions = fluxBoundaryConditionsDict
self.stressFluxBoundaryConditionsSetterDict = stressFluxBoundaryConditionsSetterDict
self.stabilizationIsNonlinear = False
if self.stabilization is not None:
for ci in range(self.nc):
if ci in coefficients.mass:
for flag in list(coefficients.mass[ci].values()):
if flag == 'nonlinear':
self.stabilizationIsNonlinear = True
if ci in coefficients.advection:
for flag in list(coefficients.advection[ci].values()):
if flag == 'nonlinear':
self.stabilizationIsNonlinear = True
if ci in coefficients.diffusion:
for diffusionDict in list(coefficients.diffusion[ci].values()):
for flag in list(diffusionDict.values()):
if flag != 'constant':
self.stabilizationIsNonlinear = True
if ci in coefficients.potential:
for flag in list(coefficients.potential[ci].values()):
if flag == 'nonlinear':
self.stabilizationIsNonlinear = True
if ci in coefficients.reaction:
for flag in list(coefficients.reaction[ci].values()):
if flag == 'nonlinear':
self.stabilizationIsNonlinear = True
if ci in coefficients.hamiltonian:
for flag in list(coefficients.hamiltonian[ci].values()):
if flag == 'nonlinear':
self.stabilizationIsNonlinear = True
self.elementBoundaryIntegrals = {}
for ci in range(self.nc):
self.elementBoundaryIntegrals[ci] = ((self.conservativeFlux is not None) or
(numericalFluxType is not None) or
(self.fluxBoundaryConditions[ci] == 'outFlow') or
(self.fluxBoundaryConditions[ci] == 'mixedFlow') or
(self.fluxBoundaryConditions[ci] == 'setFlow'))
self.nSpace_global = self.u[0].femSpace.nSpace_global
self.nDOF_trial_element = [u_j.femSpace.max_nDOF_element for u_j in list(self.u.values())]
self.nDOF_phi_trial_element = [phi_k.femSpace.max_nDOF_element for phi_k in list(self.phi.values())]
self.n_phi_ip_element = [phi_k.femSpace.referenceFiniteElement.interpolationConditions.nQuadraturePoints for phi_k in list(self.phi.values())]
self.nDOF_test_element = [femSpace.max_nDOF_element for femSpace in list(self.testSpace.values())]
self.nFreeDOF_global = [dc.nFreeDOF_global for dc in list(self.dirichletConditions.values())]
self.nVDOF_element = sum(self.nDOF_trial_element)
self.nFreeVDOF_global = sum(self.nFreeDOF_global)
NonlinearEquation.__init__(self, self.nFreeVDOF_global)
# complete)
#
elementQuadratureDict = {}
elemQuadIsDict = isinstance(elementQuadrature, dict)
if elemQuadIsDict: # set terms manually
for I in self.coefficients.elementIntegralKeys:
if I in elementQuadrature:
elementQuadratureDict[I] = elementQuadrature[I]
else:
elementQuadratureDict[I] = elementQuadrature['default']
else:
for I in self.coefficients.elementIntegralKeys:
elementQuadratureDict[I] = elementQuadrature
if self.stabilization is not None:
for I in self.coefficients.elementIntegralKeys:
if elemQuadIsDict:
if I in elementQuadrature:
elementQuadratureDict[('stab',) + I[1:]] = elementQuadrature[I]
else:
elementQuadratureDict[('stab',) + I[1:]] = elementQuadrature['default']
else:
elementQuadratureDict[('stab',) + I[1:]] = elementQuadrature
if self.shockCapturing is not None:
for ci in self.shockCapturing.components:
if elemQuadIsDict:
if ('numDiff', ci, ci) in elementQuadrature:
elementQuadratureDict[('numDiff', ci, ci)] = elementQuadrature[('numDiff', ci, ci)]
else:
elementQuadratureDict[('numDiff', ci, ci)] = elementQuadrature['default']
else:
elementQuadratureDict[('numDiff', ci, ci)] = elementQuadrature
if massLumping:
for ci in list(self.coefficients.mass.keys()):
elementQuadratureDict[('m', ci)] = Quadrature.SimplexLobattoQuadrature(self.nSpace_global, 1)
for I in self.coefficients.elementIntegralKeys:
elementQuadratureDict[('stab',) + I[1:]] = Quadrature.SimplexLobattoQuadrature(self.nSpace_global, 1)
if reactionLumping:
for ci in list(self.coefficients.mass.keys()):
elementQuadratureDict[('r', ci)] = Quadrature.SimplexLobattoQuadrature(self.nSpace_global, 1)
for I in self.coefficients.elementIntegralKeys:
elementQuadratureDict[('stab',) + I[1:]] = Quadrature.SimplexLobattoQuadrature(self.nSpace_global, 1)
elementBoundaryQuadratureDict = {}
if isinstance(elementBoundaryQuadrature, dict): # set terms manually
for I in self.coefficients.elementBoundaryIntegralKeys:
if I in elementBoundaryQuadrature:
elementBoundaryQuadratureDict[I] = elementBoundaryQuadrature[I]
else:
elementBoundaryQuadratureDict[I] = elementBoundaryQuadrature['default']
else:
for I in self.coefficients.elementBoundaryIntegralKeys:
elementBoundaryQuadratureDict[I] = elementBoundaryQuadrature
#
# find the union of all element quadrature points and
# build a quadrature rule for each integral that has a
# weight at each point in the union
# mwf include tag telling me which indices are which quadrature rule?
(self.elementQuadraturePoints, self.elementQuadratureWeights,
self.elementQuadratureRuleIndeces) = Quadrature.buildUnion(elementQuadratureDict)
self.nQuadraturePoints_element = self.elementQuadraturePoints.shape[0]
self.nQuadraturePoints_global = self.nQuadraturePoints_element * self.mesh.nElements_global
#
# Repeat the same thing for the element boundary quadrature
#
(self.elementBoundaryQuadraturePoints,
self.elementBoundaryQuadratureWeights,
self.elementBoundaryQuadratureRuleIndeces) = Quadrature.buildUnion(elementBoundaryQuadratureDict)
self.nElementBoundaryQuadraturePoints_elementBoundary = self.elementBoundaryQuadraturePoints.shape[0]
self.nElementBoundaryQuadraturePoints_global = (self.mesh.nElements_global *
self.mesh.nElementBoundaries_element *
self.nElementBoundaryQuadraturePoints_elementBoundary)
#
# simplified allocations for test==trial and also check if space is mixed or not
#
self.q = {}
self.ebq = {}
self.ebq_global = {}
self.ebqe = {}
self.phi_ip = {}
# mesh
self.ebqe['x'] = numpy.zeros((self.mesh.nExteriorElementBoundaries_global, self.nElementBoundaryQuadraturePoints_elementBoundary, 3), 'd')
self.q['bodyForce'] = numpy.zeros((self.mesh.nElements_global, self.nQuadraturePoints_element, self.nSpace_global), 'd')
self.ebqe[('u', 0)] = numpy.zeros((self.mesh.nExteriorElementBoundaries_global, self.nElementBoundaryQuadraturePoints_elementBoundary), 'd')
self.ebqe[('u', 1)] = numpy.zeros((self.mesh.nExteriorElementBoundaries_global, self.nElementBoundaryQuadraturePoints_elementBoundary), 'd')
self.ebqe[('u', 2)] = numpy.zeros((self.mesh.nExteriorElementBoundaries_global, self.nElementBoundaryQuadraturePoints_elementBoundary), 'd')
self.ebqe[('stressFlux_bc_flag', 0)] = numpy.zeros(
(self.mesh.nExteriorElementBoundaries_global, self.nElementBoundaryQuadraturePoints_elementBoundary), 'i')
self.ebqe[('stressFlux_bc_flag', 1)] = numpy.zeros(
(self.mesh.nExteriorElementBoundaries_global, self.nElementBoundaryQuadraturePoints_elementBoundary), 'i')
self.ebqe[('stressFlux_bc_flag', 2)] = numpy.zeros(
(self.mesh.nExteriorElementBoundaries_global, self.nElementBoundaryQuadraturePoints_elementBoundary), 'i')
self.ebqe[('stressFlux_bc', 0)] = numpy.zeros((self.mesh.nExteriorElementBoundaries_global, self.nElementBoundaryQuadraturePoints_elementBoundary), 'd')
self.ebqe[('stressFlux_bc', 1)] = numpy.zeros((self.mesh.nExteriorElementBoundaries_global, self.nElementBoundaryQuadraturePoints_elementBoundary), 'd')
self.ebqe[('stressFlux_bc', 2)] = numpy.zeros((self.mesh.nExteriorElementBoundaries_global, self.nElementBoundaryQuadraturePoints_elementBoundary), 'd')
self.points_elementBoundaryQuadrature = set()
self.scalars_elementBoundaryQuadrature = set([('u', ci) for ci in range(self.nc)])
self.vectors_elementBoundaryQuadrature = set()
self.tensors_elementBoundaryQuadrature = set()
#
# show quadrature
#
logEvent("Dumping quadrature shapes for model %s" % self.name, level=9)
logEvent("Element quadrature array (q)", level=9)
for (k, v) in list(self.q.items()):
logEvent(str((k, v.shape)), level=9)
logEvent("Element boundary quadrature (ebq)", level=9)
for (k, v) in list(self.ebq.items()):
logEvent(str((k, v.shape)), level=9)
logEvent("Global element boundary quadrature (ebq_global)", level=9)
for (k, v) in list(self.ebq_global.items()):
logEvent(str((k, v.shape)), level=9)
logEvent("Exterior element boundary quadrature (ebqe)", level=9)
for (k, v) in list(self.ebqe.items()):
logEvent(str((k, v.shape)), level=9)
logEvent("Interpolation points for nonlinear diffusion potential (phi_ip)", level=9)
for (k, v) in list(self.phi_ip.items()):
logEvent(str((k, v.shape)), level=9)
#
# allocate residual and Jacobian storage
#
self.elementResidual = [numpy.zeros(
(self.mesh.nElements_global,
self.nDOF_test_element[ci]),
'd') for ci in range(self.nc)]
self.elementSpatialResidual = [numpy.zeros(
(self.mesh.nElements_global,
self.nDOF_test_element[ci]),
'd') for ci in range(self.nc)]
self.inflowBoundaryBC = {}
self.inflowBoundaryBC_values = {}
self.inflowFlux = {}
for cj in range(self.nc):
self.inflowBoundaryBC[cj] = numpy.zeros((self.mesh.nExteriorElementBoundaries_global,), 'i')
self.inflowBoundaryBC_values[cj] = numpy.zeros((self.mesh.nExteriorElementBoundaries_global, self.nDOF_trial_element[cj]), 'd')
self.inflowFlux[cj] = numpy.zeros((self.mesh.nExteriorElementBoundaries_global, self.nElementBoundaryQuadraturePoints_elementBoundary), 'd')
self.internalNodes = set(range(self.mesh.nNodes_global))
# identify the internal nodes this is ought to be in mesh
# \todo move this to mesh
for ebNE in range(self.mesh.nExteriorElementBoundaries_global):
ebN = self.mesh.exteriorElementBoundariesArray[ebNE]
eN_global = self.mesh.elementBoundaryElementsArray[ebN, 0]
ebN_element = self.mesh.elementBoundaryLocalElementBoundariesArray[ebN, 0]
for i in range(self.mesh.nNodes_element):
if i != ebN_element:
I = self.mesh.elementNodesArray[eN_global, i]
self.internalNodes -= set([I])
self.nNodes_internal = len(self.internalNodes)
self.internalNodesArray = numpy.zeros((self.nNodes_internal,), 'i')
for nI, n in enumerate(self.internalNodes):
self.internalNodesArray[nI] = n
#
del self.internalNodes
self.internalNodes = None
logEvent("Updating local to global mappings", 2)
self.updateLocal2Global()
logEvent("Building time integration object", 2)
logEvent(memory("inflowBC, internalNodes,updateLocal2Global", "OneLevelTransport"), level=4)
# mwf for interpolating subgrid error for gradients etc
if self.stabilization and self.stabilization.usesGradientStabilization:
self.timeIntegration = TimeIntegrationClass(self, integrateInterpolationPoints=True)
else:
self.timeIntegration = TimeIntegrationClass(self)
if options is not None:
self.timeIntegration.setFromOptions(options)
logEvent(memory("TimeIntegration", "OneLevelTransport"), level=4)
logEvent("Calculating numerical quadrature formulas", 2)
self.calculateQuadrature()
self.setupFieldStrides()
comm = Comm.get()
self.comm = comm
if comm.size() > 1:
assert numericalFluxType is not None and numericalFluxType.useWeakDirichletConditions, "You must use a numerical flux to apply weak boundary conditions for parallel runs"
logEvent(memory("stride+offset", "OneLevelTransport"), level=4)
if numericalFluxType is not None:
if options is None or options.periodicDirichletConditions is None:
self.numericalFlux = numericalFluxType(self,
dofBoundaryConditionsSetterDict,
advectiveFluxBoundaryConditionsSetterDict,
diffusiveFluxBoundaryConditionsSetterDictDict)
else:
self.numericalFlux = numericalFluxType(self,
dofBoundaryConditionsSetterDict,
advectiveFluxBoundaryConditionsSetterDict,
diffusiveFluxBoundaryConditionsSetterDictDict,
options.periodicDirichletConditions)
else:
self.numericalFlux = None
# set penalty terms
# cek todo move into numerical flux initialization
if 'penalty' in self.ebq_global:
for ebN in range(self.mesh.nElementBoundaries_global):
for k in range(self.nElementBoundaryQuadraturePoints_elementBoundary):
self.ebq_global['penalty'][ebN, k] = old_div(self.numericalFlux.penalty_constant, \
(self.mesh.elementBoundaryDiametersArray[ebN]**self.numericalFlux.penalty_power))
# penalty term
# cek move to Numerical flux initialization
if 'penalty' in self.ebqe:
for ebNE in range(self.mesh.nExteriorElementBoundaries_global):
ebN = self.mesh.exteriorElementBoundariesArray[ebNE]
for k in range(self.nElementBoundaryQuadraturePoints_elementBoundary):
self.ebqe['penalty'][ebNE, k] = old_div(self.numericalFlux.penalty_constant, \
self.mesh.elementBoundaryDiametersArray[ebN]**self.numericalFlux.penalty_power)
logEvent(memory("numericalFlux", "OneLevelTransport"), level=4)
self.elementEffectiveDiametersArray = self.mesh.elementInnerDiametersArray
# use post processing tools to get conservative fluxes, None by default
# helper for writing out data storage
import proteus.Archiver
self.elementQuadratureDictionaryWriter = Archiver.XdmfWriter()
self.elementBoundaryQuadratureDictionaryWriter = Archiver.XdmfWriter()
self.exteriorElementBoundaryQuadratureDictionaryWriter = Archiver.XdmfWriter()
for ci, sbcObject in list(self.stressFluxBoundaryConditionsObjectsDict.items()):
self.ebqe[('stressFlux_bc_flag', ci)] = numpy.zeros(self.ebqe[('stressFlux_bc', ci)].shape, 'i')
for t, g in list(sbcObject.stressFluxBoundaryConditionsDict.items()):
self.ebqe[('stressFlux_bc', ci)][t[0], t[1]] = g(self.ebqe[('x')][t[0], t[1]], self.timeIntegration.t)
self.ebqe[('stressFlux_bc_flag', ci)][t[0], t[1]] = 1
self.numericalFlux.setDirichletValues(self.ebqe)
if self.mesh.nodeVelocityArray is None:
self.mesh.nodeVelocityArray = numpy.zeros(self.mesh.nodeArray.shape, 'd')
compKernelFlag = 0
if self.nSpace_global == 2:
import copy
self.u[2] = self.u[1].copy()
self.u[2].name = 'hz'
self.offset.append(self.offset[1])
self.stride.append(self.stride[1])
self.numericalFlux.isDOFBoundary[2] = self.numericalFlux.isDOFBoundary[1].copy()
self.numericalFlux.ebqe[('u', 2)] = self.numericalFlux.ebqe[('u', 1)].copy()
logEvent("calling cMoveMesh2D_base ctor")
self.moveMesh = cMoveMesh2D_base(self.nSpace_global,
self.nQuadraturePoints_element,
self.u[0].femSpace.elementMaps.localFunctionSpace.dim,
self.u[0].femSpace.referenceFiniteElement.localFunctionSpace.dim,
self.testSpace[0].referenceFiniteElement.localFunctionSpace.dim,
self.nElementBoundaryQuadraturePoints_elementBoundary,
compKernelFlag)
else:
logEvent("calling cMoveMesh_base ctor")
self.moveMesh = cMoveMesh_base(self.nSpace_global,
self.nQuadraturePoints_element,
self.u[0].femSpace.elementMaps.localFunctionSpace.dim,
self.u[0].femSpace.referenceFiniteElement.localFunctionSpace.dim,
self.testSpace[0].referenceFiniteElement.localFunctionSpace.dim,
self.nElementBoundaryQuadraturePoints_elementBoundary,
compKernelFlag)
self.disp0 = numpy.zeros(self.nSpace_global, 'd')
self.disp1 = numpy.zeros(self.nSpace_global, 'd')
self.vel0 = numpy.zeros(self.nSpace_global, 'd')
self.vel1 = numpy.zeros(self.nSpace_global, 'd')
self.rot0 = numpy.eye(self.nSpace_global, dtype=float)
self.rot1 = numpy.eye(self.nSpace_global, dtype=float)
self.angVel0 = numpy.zeros(self.nSpace_global, 'd')
self.angVel1 = numpy.zeros(self.nSpace_global, 'd')
self.forceStrongConditions = True # False#True
self.dirichletConditionsForceDOF = {}
if self.forceStrongConditions:
for cj in range(self.nc):
self.dirichletConditionsForceDOF[cj] = DOFBoundaryConditions(
self.u[cj].femSpace, dofBoundaryConditionsSetterDict[cj], weakDirichletConditions=False)
from proteus import PostProcessingTools
self.velocityPostProcessor = PostProcessingTools.VelocityPostProcessingChooser(self)
logEvent(memory("velocity postprocessor", "OneLevelTransport"), level=4)
def getResidual(self, u, r):
# Load the unknowns into the finite element dof
self.timeIntegration.calculateCoefs()
self.timeIntegration.calculateU(u)
self.setUnknowns(self.timeIntegration.u)
if self.bcsTimeDependent or not self.bcsSet:
self.bcsSet = True
# Dirichlet boundary conditions
self.numericalFlux.setDirichletValues(self.ebqe)
# Flux boundary conditions
for ci, fbcObject in list(self.stressFluxBoundaryConditionsObjectsDict.items()):
for t, g in list(fbcObject.stressFluxBoundaryConditionsDict.items()):
self.ebqe[('stressFlux_bc', ci)][t[0], t[1]] = g(self.ebqe[('x')][t[0], t[1]], self.timeIntegration.t)
self.ebqe[('stressFlux_bc_flag', ci)][t[0], t[1]] = 1
r.fill(0.0)
self.elementResidual[0].fill(0.0)
self.elementResidual[1].fill(0.0)
if self.nSpace_global == 3:
self.elementResidual[2].fill(0.0)
if self.forceStrongConditions:
for cj in range(self.nc):
for dofN, g in list(self.dirichletConditionsForceDOF[cj].DOFBoundaryConditionsDict.items()):
self.u[cj].dof[dofN] = g(self.dirichletConditionsForceDOF[cj].DOFBoundaryPointDict[dofN], self.timeIntegration.t)
self.moveMesh.calculateResidual( # element
self.u[0].femSpace.elementMaps.psi,
self.u[0].femSpace.elementMaps.grad_psi,
self.mesh.nodeArray,
self.mesh.elementNodesArray,
self.elementQuadratureWeights[('u', 0)],
self.u[0].femSpace.psi,
self.u[0].femSpace.grad_psi,
self.u[0].femSpace.psi,
self.u[0].femSpace.grad_psi,
# element boundary
self.u[0].femSpace.elementMaps.psi_trace,
self.u[0].femSpace.elementMaps.grad_psi_trace,
self.elementBoundaryQuadratureWeights[('u', 0)],
self.u[0].femSpace.psi_trace,
self.u[0].femSpace.grad_psi_trace,
self.u[0].femSpace.psi_trace,
self.u[0].femSpace.grad_psi_trace,
self.u[0].femSpace.elementMaps.boundaryNormals,
self.u[0].femSpace.elementMaps.boundaryJacobians,
# physics
self.mesh.nElements_global,
self.mesh.elementMaterialTypes,
self.coefficients.nMaterialProperties,
self.coefficients.materialProperties,
self.u[0].femSpace.dofMap.l2g,
self.u[0].dof,
self.u[1].dof,
self.u[2].dof,
self.coefficients.bodyForce,
self.offset[0], self.offset[1], self.offset[2],
self.stride[0], self.stride[1], self.stride[2],
r,
self.mesh.nExteriorElementBoundaries_global,
self.mesh.exteriorElementBoundariesArray,
self.mesh.elementBoundaryElementsArray,
self.mesh.elementBoundaryLocalElementBoundariesArray,
self.numericalFlux.isDOFBoundary[0],
self.numericalFlux.isDOFBoundary[1],
self.numericalFlux.isDOFBoundary[2],
self.ebqe[('stressFlux_bc_flag', 0)],
self.ebqe[('stressFlux_bc_flag', 1)],
self.ebqe[('stressFlux_bc_flag', 2)],
self.numericalFlux.ebqe[('u', 0)],
self.numericalFlux.ebqe[('u', 1)],
self.numericalFlux.ebqe[('u', 2)],
self.ebqe[('stressFlux_bc', 0)],
self.ebqe[('stressFlux_bc', 1)],
self.ebqe[('stressFlux_bc', 2)])
if self.forceStrongConditions:
for cj in range(self.nc):
for dofN, g in list(self.dirichletConditionsForceDOF[cj].DOFBoundaryConditionsDict.items()):
r[self.offset[cj] + self.stride[cj] * dofN] = self.u[cj].dof[dofN] - \
g(self.dirichletConditionsForceDOF[cj].DOFBoundaryPointDict[dofN], self.timeIntegration.t)
logEvent("Global residual", level=9, data=r)
self.nonlinear_function_evaluations += 1
def getJacobian(self, jacobian):
cfemIntegrals.zeroJacobian_CSR(self.nNonzerosInJacobian,
jacobian)
if self.nSpace_global == 2:
self.csrRowIndeces[(0, 2)] = self.csrRowIndeces[(0, 1)]
self.csrColumnOffsets[(0, 2)] = self.csrColumnOffsets[(0, 1)]
self.csrRowIndeces[(1, 2)] = self.csrRowIndeces[(0, 1)]
self.csrColumnOffsets[(1, 2)] = self.csrColumnOffsets[(0, 1)]
self.csrRowIndeces[(2, 0)] = self.csrRowIndeces[(1, 0)]
self.csrColumnOffsets[(2, 0)] = self.csrColumnOffsets[(1, 0)]
self.csrRowIndeces[(2, 1)] = self.csrRowIndeces[(1, 0)]
self.csrColumnOffsets[(2, 1)] = self.csrColumnOffsets[(1, 0)]
self.csrRowIndeces[(2, 2)] = self.csrRowIndeces[(1, 0)]
self.csrColumnOffsets[(2, 2)] = self.csrColumnOffsets[(1, 0)]
self.csrColumnOffsets_eb[(0, 2)] = self.csrColumnOffsets[(0, 1)]
self.csrColumnOffsets_eb[(1, 2)] = self.csrColumnOffsets[(0, 1)]
self.csrColumnOffsets_eb[(2, 2)] = self.csrColumnOffsets[(0, 1)]
self.csrColumnOffsets_eb[(2, 0)] = self.csrColumnOffsets[(0, 1)]
self.csrColumnOffsets_eb[(2, 1)] = self.csrColumnOffsets[(0, 1)]
self.csrColumnOffsets_eb[(2, 2)] = self.csrColumnOffsets[(0, 1)]
self.moveMesh.calculateJacobian( # element
self.u[0].femSpace.elementMaps.psi,
self.u[0].femSpace.elementMaps.grad_psi,
self.mesh.nodeArray,
self.mesh.elementNodesArray,
self.elementQuadratureWeights[('u', 0)],
self.u[0].femSpace.psi,
self.u[0].femSpace.grad_psi,
self.u[0].femSpace.psi,
self.u[0].femSpace.grad_psi,
# element boundary
self.u[0].femSpace.elementMaps.psi_trace,
self.u[0].femSpace.elementMaps.grad_psi_trace,
self.elementBoundaryQuadratureWeights[('u', 0)],
self.u[0].femSpace.psi_trace,
self.u[0].femSpace.grad_psi_trace,
self.u[0].femSpace.psi_trace,
self.u[0].femSpace.grad_psi_trace,
self.u[0].femSpace.elementMaps.boundaryNormals,
self.u[0].femSpace.elementMaps.boundaryJacobians,
self.mesh.nElements_global,
self.mesh.elementMaterialTypes,
self.coefficients.nMaterialProperties,
self.coefficients.materialProperties,
self.u[0].femSpace.dofMap.l2g,
self.u[0].dof,
self.u[1].dof,
self.u[2].dof,
self.coefficients.bodyForce,
self.csrRowIndeces[(0, 0)], self.csrColumnOffsets[(0, 0)],
self.csrRowIndeces[(0, 1)], self.csrColumnOffsets[(0, 1)],
self.csrRowIndeces[(0, 2)], self.csrColumnOffsets[(0, 2)],
self.csrRowIndeces[(1, 0)], self.csrColumnOffsets[(1, 0)],
self.csrRowIndeces[(1, 1)], self.csrColumnOffsets[(1, 1)],
self.csrRowIndeces[(1, 2)], self.csrColumnOffsets[(1, 2)],
self.csrRowIndeces[(2, 0)], self.csrColumnOffsets[(2, 0)],
self.csrRowIndeces[(2, 1)], self.csrColumnOffsets[(2, 1)],
self.csrRowIndeces[(2, 2)], self.csrColumnOffsets[(2, 2)],
jacobian,
self.mesh.nExteriorElementBoundaries_global,
self.mesh.exteriorElementBoundariesArray,
self.mesh.elementBoundaryElementsArray,
self.mesh.elementBoundaryLocalElementBoundariesArray,
self.numericalFlux.isDOFBoundary[0],
self.numericalFlux.isDOFBoundary[1],
self.numericalFlux.isDOFBoundary[2],
self.ebqe[('stressFlux_bc_flag', 0)],
self.ebqe[('stressFlux_bc_flag', 1)],
self.ebqe[('stressFlux_bc_flag', 2)],
self.csrColumnOffsets_eb[(0, 0)],
self.csrColumnOffsets_eb[(0, 1)],
self.csrColumnOffsets_eb[(0, 2)],
self.csrColumnOffsets_eb[(1, 0)],
self.csrColumnOffsets_eb[(1, 1)],
self.csrColumnOffsets_eb[(1, 2)],
self.csrColumnOffsets_eb[(2, 0)],
self.csrColumnOffsets_eb[(2, 1)],
self.csrColumnOffsets_eb[(2, 2)])
# Load the Dirichlet conditions directly into residual
if self.forceStrongConditions:
scaling = 1.0 # probably want to add some scaling to match non-dirichlet diagonals in linear system
for cj in range(self.nc):
for dofN in list(self.dirichletConditionsForceDOF[cj].DOFBoundaryConditionsDict.keys()):
global_dofN = self.offset[cj] + self.stride[cj] * dofN
for i in range(self.rowptr[global_dofN], self.rowptr[global_dofN + 1]):
if (self.colind[i] == global_dofN):
self.nzval[i] = scaling
else:
self.nzval[i] = 0.0
logEvent("Jacobian ", level=10, data=jacobian)
# mwf decide if this is reasonable for solver statistics
self.nonlinear_function_jacobian_evaluations += 1
# jacobian.fwrite("jacobian_p"+`self.nonlinear_function_jacobian_evaluations`)
return jacobian
def calculateElementQuadrature(self):
self.u[0].femSpace.elementMaps.getBasisValuesRef(self.elementQuadraturePoints)
self.u[0].femSpace.elementMaps.getBasisGradientValuesRef(self.elementQuadraturePoints)
self.u[0].femSpace.getBasisValuesRef(self.elementQuadraturePoints)
self.u[0].femSpace.getBasisGradientValuesRef(self.elementQuadraturePoints)
self.coefficients.initializeElementQuadrature(self.timeIntegration.t, self.q)
def calculateElementBoundaryQuadrature(self):
pass
def calculateExteriorElementBoundaryQuadrature(self):
#
# get physical locations of element boundary quadrature points
#
# assume all components live on the same mesh
self.u[0].femSpace.elementMaps.getBasisValuesTraceRef(self.elementBoundaryQuadraturePoints)
self.u[0].femSpace.elementMaps.getBasisGradientValuesTraceRef(self.elementBoundaryQuadraturePoints)
self.u[0].femSpace.getBasisValuesTraceRef(self.elementBoundaryQuadraturePoints)
self.u[0].femSpace.getBasisGradientValuesTraceRef(self.elementBoundaryQuadraturePoints)
self.u[0].femSpace.elementMaps.getValuesGlobalExteriorTrace(self.elementBoundaryQuadraturePoints,
self.ebqe['x'])
self.stressFluxBoundaryConditionsObjectsDict = dict([(cj, FluxBoundaryConditions(self.mesh,
self.nElementBoundaryQuadraturePoints_elementBoundary,
self.ebqe[('x')],
self.stressFluxBoundaryConditionsSetterDict[cj]))
for cj in list(self.stressFluxBoundaryConditionsSetterDict.keys())])
self.coefficients.initializeGlobalExteriorElementBoundaryQuadrature(self.timeIntegration.t, self.ebqe)
def estimate_mt(self):
pass
def calculateSolutionAtQuadrature(self):
pass
def calculateAuxiliaryQuantitiesAfterStep(self):
OneLevelTransport.calculateAuxiliaryQuantitiesAfterStep(self)
def preStep(self):
pass
def postStep(self):
pass
def updateAfterMeshMotion(self):
# cek todo: this needs to be cleaned up and generalized for other models under moving conditions
# few models actually use the ebqe['x'] for boundary conditions, but we need to make it
# consistent (the physical coordinates and not the reference domain coordinates)
self.calculateElementQuadrature()
self.ebqe_old_x = self.ebqe['x'].copy()
self.calculateExteriorElementBoundaryQuadrature() # pass
for cj in range(self.nc):
self.u[cj].femSpace.updateInterpolationPoints()
for dofN, g in list(self.dirichletConditionsForceDOF[cj].DOFBoundaryConditionsDict.items()):
self.dirichletConditionsForceDOF[cj].DOFBoundaryPointDict[dofN] = self.mesh.nodeArray[dofN]
| true | true |
f7f75a96746e49407a881c06c1369b6bbd9f34e5 | 591 | py | Python | database_service.py | LizaGenke/dinner-at-lizas | 591841b807cc248d68139b6823ca2fb8fbad0452 | [
"MIT"
] | null | null | null | database_service.py | LizaGenke/dinner-at-lizas | 591841b807cc248d68139b6823ca2fb8fbad0452 | [
"MIT"
] | null | null | null | database_service.py | LizaGenke/dinner-at-lizas | 591841b807cc248d68139b6823ca2fb8fbad0452 | [
"MIT"
] | null | null | null | import pyrebase
import json
with open('env/database_config.json', 'r') as config_file: config = json.load(config_file)
firebase = pyrebase.initialize_app(config)
# import firebase_admin
# from firebase_admin import credentials
# cred = credentials.Certificate("path/to/serviceAccountKey.json")
# firebase_admin.initialize_app(cred)
# default_app = firebase_admin.initialize_app()
db = firebase.database()
# data to save
data = {
"user": {
"name": "Mortimer Smith"
}
}
# Pass the user's idToken to the push method
results = db.child("users").push(data)
print(results) | 21.888889 | 91 | 0.734349 | import pyrebase
import json
with open('env/database_config.json', 'r') as config_file: config = json.load(config_file)
firebase = pyrebase.initialize_app(config)
db = firebase.database()
data = {
"user": {
"name": "Mortimer Smith"
}
}
results = db.child("users").push(data)
print(results) | true | true |
f7f75bcb45ca3635c70b5e03ef40746b85a6857b | 21,603 | py | Python | python/ray/tests/test_actor_resources.py | AshHarvey/ray | f35339b5ff3d5e85c20720637e28bd5a380a545e | [
"Apache-2.0"
] | null | null | null | python/ray/tests/test_actor_resources.py | AshHarvey/ray | f35339b5ff3d5e85c20720637e28bd5a380a545e | [
"Apache-2.0"
] | null | null | null | python/ray/tests/test_actor_resources.py | AshHarvey/ray | f35339b5ff3d5e85c20720637e28bd5a380a545e | [
"Apache-2.0"
] | null | null | null | import collections
import os
import pytest
try:
import pytest_timeout
except ImportError:
pytest_timeout = None
import sys
import time
import ray
import ray.test_utils
import ray.cluster_utils
def test_actor_deletion_with_gpus(shutdown_only):
ray.init(
num_cpus=1, num_gpus=1, object_store_memory=int(150 * 1024 * 1024))
# When an actor that uses a GPU exits, make sure that the GPU resources
# are released.
@ray.remote(num_gpus=1)
class Actor:
def getpid(self):
return os.getpid()
for _ in range(5):
# If we can successfully create an actor, that means that enough
# GPU resources are available.
a = Actor.remote()
ray.get(a.getpid.remote())
def test_actor_state(ray_start_regular):
@ray.remote
class Counter:
def __init__(self):
self.value = 0
def increase(self):
self.value += 1
def value(self):
return self.value
c1 = Counter.remote()
c1.increase.remote()
assert ray.get(c1.value.remote()) == 1
c2 = Counter.remote()
c2.increase.remote()
c2.increase.remote()
assert ray.get(c2.value.remote()) == 2
def test_actor_class_methods(ray_start_regular):
class Foo:
x = 2
@classmethod
def as_remote(cls):
return ray.remote(cls)
@classmethod
def f(cls):
return cls.x
@classmethod
def g(cls, y):
return cls.x + y
def echo(self, value):
return value
a = Foo.as_remote().remote()
assert ray.get(a.echo.remote(2)) == 2
assert ray.get(a.f.remote()) == 2
assert ray.get(a.g.remote(2)) == 4
@pytest.mark.skipif(
os.environ.get("RAY_USE_NEW_GCS") == "on",
reason="Failing with new GCS API on Linux.")
@pytest.mark.skipif(sys.platform == "win32", reason="Failing on Windows.")
def test_actor_gpus(ray_start_cluster):
cluster = ray_start_cluster
num_nodes = 3
num_gpus_per_raylet = 4
for i in range(num_nodes):
cluster.add_node(
num_cpus=10 * num_gpus_per_raylet, num_gpus=num_gpus_per_raylet)
ray.init(address=cluster.address)
@ray.remote(num_gpus=1)
class Actor1:
def __init__(self):
self.gpu_ids = ray.get_gpu_ids(as_str=True)
def get_location_and_ids(self):
assert ray.get_gpu_ids(as_str=True) == self.gpu_ids
return (ray.worker.global_worker.node.unique_id,
tuple(self.gpu_ids))
# Create one actor per GPU.
actors = [Actor1.remote() for _ in range(num_nodes * num_gpus_per_raylet)]
# Make sure that no two actors are assigned to the same GPU.
locations_and_ids = ray.get(
[actor.get_location_and_ids.remote() for actor in actors])
node_names = {location for location, gpu_id in locations_and_ids}
assert len(node_names) == num_nodes
location_actor_combinations = []
for node_name in node_names:
for gpu_id in range(num_gpus_per_raylet):
location_actor_combinations.append((node_name, (gpu_id, )))
assert set(locations_and_ids) == set(location_actor_combinations)
# Creating a new actor should fail because all of the GPUs are being
# used.
a = Actor1.remote()
ready_ids, _ = ray.wait([a.get_location_and_ids.remote()], timeout=0.01)
assert ready_ids == []
def test_actor_multiple_gpus(ray_start_cluster):
cluster = ray_start_cluster
num_nodes = 3
num_gpus_per_raylet = 5
for i in range(num_nodes):
cluster.add_node(
num_cpus=10 * num_gpus_per_raylet, num_gpus=num_gpus_per_raylet)
ray.init(address=cluster.address)
@ray.remote(num_gpus=2)
class Actor1:
def __init__(self):
self.gpu_ids = ray.get_gpu_ids()
def get_location_and_ids(self):
assert ray.get_gpu_ids() == self.gpu_ids
return (ray.worker.global_worker.node.unique_id,
tuple(self.gpu_ids))
# Create some actors.
actors1 = [Actor1.remote() for _ in range(num_nodes * 2)]
# Make sure that no two actors are assigned to the same GPU.
locations_and_ids = ray.get(
[actor.get_location_and_ids.remote() for actor in actors1])
node_names = {location for location, gpu_id in locations_and_ids}
assert len(node_names) == num_nodes
# Keep track of which GPU IDs are being used for each location.
gpus_in_use = {node_name: [] for node_name in node_names}
for location, gpu_ids in locations_and_ids:
gpus_in_use[location].extend(gpu_ids)
for node_name in node_names:
assert len(set(gpus_in_use[node_name])) == 4
# Creating a new actor should fail because all of the GPUs are being
# used.
a = Actor1.remote()
ready_ids, _ = ray.wait([a.get_location_and_ids.remote()], timeout=0.01)
assert ready_ids == []
# We should be able to create more actors that use only a single GPU.
@ray.remote(num_gpus=1)
class Actor2:
def __init__(self):
self.gpu_ids = ray.get_gpu_ids()
def get_location_and_ids(self):
return (ray.worker.global_worker.node.unique_id,
tuple(self.gpu_ids))
# Create some actors.
actors2 = [Actor2.remote() for _ in range(num_nodes)]
# Make sure that no two actors are assigned to the same GPU.
locations_and_ids = ray.get(
[actor.get_location_and_ids.remote() for actor in actors2])
names = {location for location, gpu_id in locations_and_ids}
assert node_names == names
for location, gpu_ids in locations_and_ids:
gpus_in_use[location].extend(gpu_ids)
for node_name in node_names:
assert len(gpus_in_use[node_name]) == 5
assert set(gpus_in_use[node_name]) == set(range(5))
# Creating a new actor should fail because all of the GPUs are being
# used.
a = Actor2.remote()
ready_ids, _ = ray.wait([a.get_location_and_ids.remote()], timeout=0.01)
assert ready_ids == []
def test_actor_different_numbers_of_gpus(ray_start_cluster):
# Test that we can create actors on two nodes that have different
# numbers of GPUs.
cluster = ray_start_cluster
cluster.add_node(num_cpus=10, num_gpus=0)
cluster.add_node(num_cpus=10, num_gpus=5)
cluster.add_node(num_cpus=10, num_gpus=10)
ray.init(address=cluster.address)
@ray.remote(num_gpus=1)
class Actor1:
def __init__(self):
self.gpu_ids = ray.get_gpu_ids()
def get_location_and_ids(self):
return (ray.worker.global_worker.node.unique_id,
tuple(self.gpu_ids))
# Create some actors.
actors = [Actor1.remote() for _ in range(0 + 5 + 10)]
# Make sure that no two actors are assigned to the same GPU.
locations_and_ids = ray.get(
[actor.get_location_and_ids.remote() for actor in actors])
node_names = {location for location, gpu_id in locations_and_ids}
assert len(node_names) == 2
for node_name in node_names:
node_gpu_ids = [
gpu_id for location, gpu_id in locations_and_ids
if location == node_name
]
assert len(node_gpu_ids) in [5, 10]
assert set(node_gpu_ids) == {(i, ) for i in range(len(node_gpu_ids))}
# Creating a new actor should fail because all of the GPUs are being
# used.
a = Actor1.remote()
ready_ids, _ = ray.wait([a.get_location_and_ids.remote()], timeout=0.01)
assert ready_ids == []
def test_actor_multiple_gpus_from_multiple_tasks(ray_start_cluster):
cluster = ray_start_cluster
num_nodes = 5
num_gpus_per_raylet = 5
for i in range(num_nodes):
cluster.add_node(
num_cpus=10 * num_gpus_per_raylet,
num_gpus=num_gpus_per_raylet,
_system_config={"num_heartbeats_timeout": 1000} if i == 0 else {})
ray.init(address=cluster.address)
@ray.remote
def create_actors(i, n):
@ray.remote(num_gpus=1)
class Actor:
def __init__(self, i, j):
self.gpu_ids = ray.get_gpu_ids()
def get_location_and_ids(self):
return ((ray.worker.global_worker.node.unique_id),
tuple(self.gpu_ids))
def sleep(self):
time.sleep(100)
# Create n actors.
actors = []
for j in range(n):
actors.append(Actor.remote(i, j))
locations = ray.get(
[actor.get_location_and_ids.remote() for actor in actors])
# Put each actor to sleep for a long time to prevent them from getting
# terminated.
for actor in actors:
actor.sleep.remote()
return locations
all_locations = ray.get([
create_actors.remote(i, num_gpus_per_raylet) for i in range(num_nodes)
])
# Make sure that no two actors are assigned to the same GPU.
node_names = {
location
for locations in all_locations for location, gpu_id in locations
}
assert len(node_names) == num_nodes
# Keep track of which GPU IDs are being used for each location.
gpus_in_use = {node_name: [] for node_name in node_names}
for locations in all_locations:
for location, gpu_ids in locations:
gpus_in_use[location].extend(gpu_ids)
for node_name in node_names:
assert len(set(gpus_in_use[node_name])) == num_gpus_per_raylet
@ray.remote(num_gpus=1)
class Actor:
def __init__(self):
self.gpu_ids = ray.get_gpu_ids()
def get_location_and_ids(self):
return (ray.worker.global_worker.node.unique_id,
tuple(self.gpu_ids))
# All the GPUs should be used up now.
a = Actor.remote()
ready_ids, _ = ray.wait([a.get_location_and_ids.remote()], timeout=0.01)
assert ready_ids == []
def test_actors_and_tasks_with_gpus(ray_start_cluster):
cluster = ray_start_cluster
num_nodes = 3
num_gpus_per_raylet = 2
for i in range(num_nodes):
cluster.add_node(
num_cpus=num_gpus_per_raylet, num_gpus=num_gpus_per_raylet)
ray.init(address=cluster.address)
def check_intervals_non_overlapping(list_of_intervals):
for i in range(len(list_of_intervals)):
for j in range(i):
first_interval = list_of_intervals[i]
second_interval = list_of_intervals[j]
# Check that list_of_intervals[i] and list_of_intervals[j]
# don't overlap.
assert first_interval[0] < first_interval[1]
assert second_interval[0] < second_interval[1]
intervals_nonoverlapping = (
first_interval[1] <= second_interval[0]
or second_interval[1] <= first_interval[0])
assert intervals_nonoverlapping, (
"Intervals {} and {} are overlapping.".format(
first_interval, second_interval))
@ray.remote(num_gpus=1)
def f1():
t1 = time.monotonic()
time.sleep(0.1)
t2 = time.monotonic()
gpu_ids = ray.get_gpu_ids()
assert len(gpu_ids) == 1
assert gpu_ids[0] in range(num_gpus_per_raylet)
return (ray.worker.global_worker.node.unique_id, tuple(gpu_ids),
[t1, t2])
@ray.remote(num_gpus=2)
def f2():
t1 = time.monotonic()
time.sleep(0.1)
t2 = time.monotonic()
gpu_ids = ray.get_gpu_ids()
assert len(gpu_ids) == 2
assert gpu_ids[0] in range(num_gpus_per_raylet)
assert gpu_ids[1] in range(num_gpus_per_raylet)
return (ray.worker.global_worker.node.unique_id, tuple(gpu_ids),
[t1, t2])
@ray.remote(num_gpus=1)
class Actor1:
def __init__(self):
self.gpu_ids = ray.get_gpu_ids()
assert len(self.gpu_ids) == 1
assert self.gpu_ids[0] in range(num_gpus_per_raylet)
def get_location_and_ids(self):
assert ray.get_gpu_ids() == self.gpu_ids
return (ray.worker.global_worker.node.unique_id,
tuple(self.gpu_ids))
def locations_to_intervals_for_many_tasks():
# Launch a bunch of GPU tasks.
locations_ids_and_intervals = ray.get(
[f1.remote() for _ in range(5 * num_nodes * num_gpus_per_raylet)] +
[f2.remote() for _ in range(5 * num_nodes * num_gpus_per_raylet)] +
[f1.remote() for _ in range(5 * num_nodes * num_gpus_per_raylet)])
locations_to_intervals = collections.defaultdict(lambda: [])
for location, gpu_ids, interval in locations_ids_and_intervals:
for gpu_id in gpu_ids:
locations_to_intervals[(location, gpu_id)].append(interval)
return locations_to_intervals
# Run a bunch of GPU tasks.
locations_to_intervals = locations_to_intervals_for_many_tasks()
# For each GPU, verify that the set of tasks that used this specific
# GPU did not overlap in time.
for locations in locations_to_intervals:
check_intervals_non_overlapping(locations_to_intervals[locations])
# Create an actor that uses a GPU.
a = Actor1.remote()
actor_location = ray.get(a.get_location_and_ids.remote())
actor_location = (actor_location[0], actor_location[1][0])
# This check makes sure that actor_location is formatted the same way
# that the keys of locations_to_intervals are formatted.
assert actor_location in locations_to_intervals
# Run a bunch of GPU tasks.
locations_to_intervals = locations_to_intervals_for_many_tasks()
# For each GPU, verify that the set of tasks that used this specific
# GPU did not overlap in time.
for locations in locations_to_intervals:
check_intervals_non_overlapping(locations_to_intervals[locations])
# Make sure that the actor's GPU was not used.
assert actor_location not in locations_to_intervals
# Create more actors to fill up all the GPUs.
more_actors = [
Actor1.remote() for _ in range(num_nodes * num_gpus_per_raylet - 1)
]
# Wait for the actors to finish being created.
ray.get([actor.get_location_and_ids.remote() for actor in more_actors])
# Now if we run some GPU tasks, they should not be scheduled.
results = [f1.remote() for _ in range(30)]
ready_ids, remaining_ids = ray.wait(results, timeout=1.0)
assert len(ready_ids) == 0
def test_actors_and_tasks_with_gpus_version_two(shutdown_only):
# Create tasks and actors that both use GPUs and make sure that they
# are given different GPUs
num_gpus = 4
ray.init(
num_cpus=(num_gpus + 1),
num_gpus=num_gpus,
object_store_memory=int(150 * 1024 * 1024))
# The point of this actor is to record which GPU IDs have been seen. We
# can't just return them from the tasks, because the tasks don't return
# for a long time in order to make sure the GPU is not released
# prematurely.
@ray.remote
class RecordGPUs:
def __init__(self):
self.gpu_ids_seen = []
self.num_calls = 0
def add_ids(self, gpu_ids):
self.gpu_ids_seen += gpu_ids
self.num_calls += 1
def get_gpu_ids_and_calls(self):
return self.gpu_ids_seen, self.num_calls
@ray.remote(num_gpus=1)
def f(record_gpu_actor):
gpu_ids = ray.get_gpu_ids()
assert len(gpu_ids) == 1
record_gpu_actor.add_ids.remote(gpu_ids)
# Sleep for a long time so that the GPU never gets released. This task
# will be killed by ray.shutdown() before it actually finishes.
time.sleep(1000)
@ray.remote(num_gpus=1)
class Actor:
def __init__(self, record_gpu_actor):
self.gpu_ids = ray.get_gpu_ids()
assert len(self.gpu_ids) == 1
record_gpu_actor.add_ids.remote(self.gpu_ids)
def check_gpu_ids(self):
assert ray.get_gpu_ids() == self.gpu_ids
record_gpu_actor = RecordGPUs.remote()
actors = []
actor_results = []
for _ in range(num_gpus // 2):
f.remote(record_gpu_actor)
a = Actor.remote(record_gpu_actor)
actor_results.append(a.check_gpu_ids.remote())
# Prevent the actor handle from going out of scope so that its GPU
# resources don't get released.
actors.append(a)
# Make sure that the actor method calls succeeded.
ray.get(actor_results)
start_time = time.time()
while time.time() - start_time < 30:
seen_gpu_ids, num_calls = ray.get(
record_gpu_actor.get_gpu_ids_and_calls.remote())
if num_calls == num_gpus:
break
assert set(seen_gpu_ids) == set(range(num_gpus))
def test_blocking_actor_task(shutdown_only):
ray.init(
num_cpus=1, num_gpus=1, object_store_memory=int(150 * 1024 * 1024))
@ray.remote(num_gpus=1)
def f():
return 1
@ray.remote
class Foo:
def __init__(self):
pass
def blocking_method(self):
ray.get(f.remote())
# Make sure we can execute a blocking actor method even if there is
# only one CPU.
actor = Foo.remote()
ray.get(actor.blocking_method.remote())
@ray.remote(num_cpus=1)
class CPUFoo:
def __init__(self):
pass
def blocking_method(self):
ray.get(f.remote())
# Make sure that lifetime CPU resources are not released when actors
# block.
actor = CPUFoo.remote()
x_id = actor.blocking_method.remote()
ready_ids, remaining_ids = ray.wait([x_id], timeout=1.0)
assert ready_ids == []
assert remaining_ids == [x_id]
@ray.remote(num_gpus=1)
class GPUFoo:
def __init__(self):
pass
def blocking_method(self):
ray.get(f.remote())
# Make sure that GPU resources are not released when actors block.
actor = GPUFoo.remote()
x_id = actor.blocking_method.remote()
ready_ids, remaining_ids = ray.wait([x_id], timeout=1.0)
assert ready_ids == []
assert remaining_ids == [x_id]
def test_lifetime_and_transient_resources(ray_start_regular):
# This actor acquires resources only when running methods.
@ray.remote
class Actor1:
def method(self):
pass
# This actor acquires resources for its lifetime.
@ray.remote(num_cpus=1)
class Actor2:
def method(self):
pass
actor1s = [Actor1.remote() for _ in range(10)]
ray.get([a.method.remote() for a in actor1s])
actor2s = [Actor2.remote() for _ in range(2)]
results = [a.method.remote() for a in actor2s]
ready_ids, remaining_ids = ray.wait(
results, num_returns=len(results), timeout=5.0)
assert len(ready_ids) == 1
def test_custom_label_placement(ray_start_cluster):
cluster = ray_start_cluster
custom_resource1_node = cluster.add_node(
num_cpus=2, resources={"CustomResource1": 2})
custom_resource2_node = cluster.add_node(
num_cpus=2, resources={"CustomResource2": 2})
ray.init(address=cluster.address)
@ray.remote(resources={"CustomResource1": 1})
class ResourceActor1:
def get_location(self):
return ray.worker.global_worker.node.unique_id
@ray.remote(resources={"CustomResource2": 1})
class ResourceActor2:
def get_location(self):
return ray.worker.global_worker.node.unique_id
# Create some actors.
actors1 = [ResourceActor1.remote() for _ in range(2)]
actors2 = [ResourceActor2.remote() for _ in range(2)]
locations1 = ray.get([a.get_location.remote() for a in actors1])
locations2 = ray.get([a.get_location.remote() for a in actors2])
for location in locations1:
assert location == custom_resource1_node.unique_id
for location in locations2:
assert location == custom_resource2_node.unique_id
def test_creating_more_actors_than_resources(shutdown_only):
ray.init(num_cpus=10, num_gpus=2, resources={"CustomResource1": 1})
@ray.remote(num_gpus=1)
class ResourceActor1:
def method(self):
return ray.get_gpu_ids()[0]
@ray.remote(resources={"CustomResource1": 1})
class ResourceActor2:
def method(self):
pass
# Make sure the first two actors get created and the third one does
# not.
actor1 = ResourceActor1.remote()
result1 = actor1.method.remote()
ray.wait([result1])
actor2 = ResourceActor1.remote()
result2 = actor2.method.remote()
ray.wait([result2])
actor3 = ResourceActor1.remote()
result3 = actor3.method.remote()
ready_ids, _ = ray.wait([result3], timeout=0.2)
assert len(ready_ids) == 0
# By deleting actor1, we free up resources to create actor3.
del actor1
results = ray.get([result1, result2, result3])
assert results[0] == results[2]
assert set(results) == {0, 1}
# Make sure that when one actor goes out of scope a new actor is
# created because some resources have been freed up.
results = []
for _ in range(3):
actor = ResourceActor2.remote()
object_ref = actor.method.remote()
results.append(object_ref)
# Wait for the task to execute. We do this because otherwise it may
# be possible for the __ray_terminate__ task to execute before the
# method.
ray.wait([object_ref])
ray.get(results)
if __name__ == "__main__":
import pytest
sys.exit(pytest.main(["-v", __file__]))
| 33.493023 | 79 | 0.648336 | import collections
import os
import pytest
try:
import pytest_timeout
except ImportError:
pytest_timeout = None
import sys
import time
import ray
import ray.test_utils
import ray.cluster_utils
def test_actor_deletion_with_gpus(shutdown_only):
ray.init(
num_cpus=1, num_gpus=1, object_store_memory=int(150 * 1024 * 1024))
@ray.remote(num_gpus=1)
class Actor:
def getpid(self):
return os.getpid()
for _ in range(5):
a = Actor.remote()
ray.get(a.getpid.remote())
def test_actor_state(ray_start_regular):
@ray.remote
class Counter:
def __init__(self):
self.value = 0
def increase(self):
self.value += 1
def value(self):
return self.value
c1 = Counter.remote()
c1.increase.remote()
assert ray.get(c1.value.remote()) == 1
c2 = Counter.remote()
c2.increase.remote()
c2.increase.remote()
assert ray.get(c2.value.remote()) == 2
def test_actor_class_methods(ray_start_regular):
class Foo:
x = 2
@classmethod
def as_remote(cls):
return ray.remote(cls)
@classmethod
def f(cls):
return cls.x
@classmethod
def g(cls, y):
return cls.x + y
def echo(self, value):
return value
a = Foo.as_remote().remote()
assert ray.get(a.echo.remote(2)) == 2
assert ray.get(a.f.remote()) == 2
assert ray.get(a.g.remote(2)) == 4
@pytest.mark.skipif(
os.environ.get("RAY_USE_NEW_GCS") == "on",
reason="Failing with new GCS API on Linux.")
@pytest.mark.skipif(sys.platform == "win32", reason="Failing on Windows.")
def test_actor_gpus(ray_start_cluster):
cluster = ray_start_cluster
num_nodes = 3
num_gpus_per_raylet = 4
for i in range(num_nodes):
cluster.add_node(
num_cpus=10 * num_gpus_per_raylet, num_gpus=num_gpus_per_raylet)
ray.init(address=cluster.address)
@ray.remote(num_gpus=1)
class Actor1:
def __init__(self):
self.gpu_ids = ray.get_gpu_ids(as_str=True)
def get_location_and_ids(self):
assert ray.get_gpu_ids(as_str=True) == self.gpu_ids
return (ray.worker.global_worker.node.unique_id,
tuple(self.gpu_ids))
actors = [Actor1.remote() for _ in range(num_nodes * num_gpus_per_raylet)]
locations_and_ids = ray.get(
[actor.get_location_and_ids.remote() for actor in actors])
node_names = {location for location, gpu_id in locations_and_ids}
assert len(node_names) == num_nodes
location_actor_combinations = []
for node_name in node_names:
for gpu_id in range(num_gpus_per_raylet):
location_actor_combinations.append((node_name, (gpu_id, )))
assert set(locations_and_ids) == set(location_actor_combinations)
a = Actor1.remote()
ready_ids, _ = ray.wait([a.get_location_and_ids.remote()], timeout=0.01)
assert ready_ids == []
def test_actor_multiple_gpus(ray_start_cluster):
cluster = ray_start_cluster
num_nodes = 3
num_gpus_per_raylet = 5
for i in range(num_nodes):
cluster.add_node(
num_cpus=10 * num_gpus_per_raylet, num_gpus=num_gpus_per_raylet)
ray.init(address=cluster.address)
@ray.remote(num_gpus=2)
class Actor1:
def __init__(self):
self.gpu_ids = ray.get_gpu_ids()
def get_location_and_ids(self):
assert ray.get_gpu_ids() == self.gpu_ids
return (ray.worker.global_worker.node.unique_id,
tuple(self.gpu_ids))
actors1 = [Actor1.remote() for _ in range(num_nodes * 2)]
locations_and_ids = ray.get(
[actor.get_location_and_ids.remote() for actor in actors1])
node_names = {location for location, gpu_id in locations_and_ids}
assert len(node_names) == num_nodes
gpus_in_use = {node_name: [] for node_name in node_names}
for location, gpu_ids in locations_and_ids:
gpus_in_use[location].extend(gpu_ids)
for node_name in node_names:
assert len(set(gpus_in_use[node_name])) == 4
a = Actor1.remote()
ready_ids, _ = ray.wait([a.get_location_and_ids.remote()], timeout=0.01)
assert ready_ids == []
@ray.remote(num_gpus=1)
class Actor2:
def __init__(self):
self.gpu_ids = ray.get_gpu_ids()
def get_location_and_ids(self):
return (ray.worker.global_worker.node.unique_id,
tuple(self.gpu_ids))
actors2 = [Actor2.remote() for _ in range(num_nodes)]
locations_and_ids = ray.get(
[actor.get_location_and_ids.remote() for actor in actors2])
names = {location for location, gpu_id in locations_and_ids}
assert node_names == names
for location, gpu_ids in locations_and_ids:
gpus_in_use[location].extend(gpu_ids)
for node_name in node_names:
assert len(gpus_in_use[node_name]) == 5
assert set(gpus_in_use[node_name]) == set(range(5))
a = Actor2.remote()
ready_ids, _ = ray.wait([a.get_location_and_ids.remote()], timeout=0.01)
assert ready_ids == []
def test_actor_different_numbers_of_gpus(ray_start_cluster):
cluster = ray_start_cluster
cluster.add_node(num_cpus=10, num_gpus=0)
cluster.add_node(num_cpus=10, num_gpus=5)
cluster.add_node(num_cpus=10, num_gpus=10)
ray.init(address=cluster.address)
@ray.remote(num_gpus=1)
class Actor1:
def __init__(self):
self.gpu_ids = ray.get_gpu_ids()
def get_location_and_ids(self):
return (ray.worker.global_worker.node.unique_id,
tuple(self.gpu_ids))
actors = [Actor1.remote() for _ in range(0 + 5 + 10)]
locations_and_ids = ray.get(
[actor.get_location_and_ids.remote() for actor in actors])
node_names = {location for location, gpu_id in locations_and_ids}
assert len(node_names) == 2
for node_name in node_names:
node_gpu_ids = [
gpu_id for location, gpu_id in locations_and_ids
if location == node_name
]
assert len(node_gpu_ids) in [5, 10]
assert set(node_gpu_ids) == {(i, ) for i in range(len(node_gpu_ids))}
a = Actor1.remote()
ready_ids, _ = ray.wait([a.get_location_and_ids.remote()], timeout=0.01)
assert ready_ids == []
def test_actor_multiple_gpus_from_multiple_tasks(ray_start_cluster):
cluster = ray_start_cluster
num_nodes = 5
num_gpus_per_raylet = 5
for i in range(num_nodes):
cluster.add_node(
num_cpus=10 * num_gpus_per_raylet,
num_gpus=num_gpus_per_raylet,
_system_config={"num_heartbeats_timeout": 1000} if i == 0 else {})
ray.init(address=cluster.address)
@ray.remote
def create_actors(i, n):
@ray.remote(num_gpus=1)
class Actor:
def __init__(self, i, j):
self.gpu_ids = ray.get_gpu_ids()
def get_location_and_ids(self):
return ((ray.worker.global_worker.node.unique_id),
tuple(self.gpu_ids))
def sleep(self):
time.sleep(100)
actors = []
for j in range(n):
actors.append(Actor.remote(i, j))
locations = ray.get(
[actor.get_location_and_ids.remote() for actor in actors])
for actor in actors:
actor.sleep.remote()
return locations
all_locations = ray.get([
create_actors.remote(i, num_gpus_per_raylet) for i in range(num_nodes)
])
node_names = {
location
for locations in all_locations for location, gpu_id in locations
}
assert len(node_names) == num_nodes
gpus_in_use = {node_name: [] for node_name in node_names}
for locations in all_locations:
for location, gpu_ids in locations:
gpus_in_use[location].extend(gpu_ids)
for node_name in node_names:
assert len(set(gpus_in_use[node_name])) == num_gpus_per_raylet
@ray.remote(num_gpus=1)
class Actor:
def __init__(self):
self.gpu_ids = ray.get_gpu_ids()
def get_location_and_ids(self):
return (ray.worker.global_worker.node.unique_id,
tuple(self.gpu_ids))
a = Actor.remote()
ready_ids, _ = ray.wait([a.get_location_and_ids.remote()], timeout=0.01)
assert ready_ids == []
def test_actors_and_tasks_with_gpus(ray_start_cluster):
cluster = ray_start_cluster
num_nodes = 3
num_gpus_per_raylet = 2
for i in range(num_nodes):
cluster.add_node(
num_cpus=num_gpus_per_raylet, num_gpus=num_gpus_per_raylet)
ray.init(address=cluster.address)
def check_intervals_non_overlapping(list_of_intervals):
for i in range(len(list_of_intervals)):
for j in range(i):
first_interval = list_of_intervals[i]
second_interval = list_of_intervals[j]
assert first_interval[0] < first_interval[1]
assert second_interval[0] < second_interval[1]
intervals_nonoverlapping = (
first_interval[1] <= second_interval[0]
or second_interval[1] <= first_interval[0])
assert intervals_nonoverlapping, (
"Intervals {} and {} are overlapping.".format(
first_interval, second_interval))
@ray.remote(num_gpus=1)
def f1():
t1 = time.monotonic()
time.sleep(0.1)
t2 = time.monotonic()
gpu_ids = ray.get_gpu_ids()
assert len(gpu_ids) == 1
assert gpu_ids[0] in range(num_gpus_per_raylet)
return (ray.worker.global_worker.node.unique_id, tuple(gpu_ids),
[t1, t2])
@ray.remote(num_gpus=2)
def f2():
t1 = time.monotonic()
time.sleep(0.1)
t2 = time.monotonic()
gpu_ids = ray.get_gpu_ids()
assert len(gpu_ids) == 2
assert gpu_ids[0] in range(num_gpus_per_raylet)
assert gpu_ids[1] in range(num_gpus_per_raylet)
return (ray.worker.global_worker.node.unique_id, tuple(gpu_ids),
[t1, t2])
@ray.remote(num_gpus=1)
class Actor1:
def __init__(self):
self.gpu_ids = ray.get_gpu_ids()
assert len(self.gpu_ids) == 1
assert self.gpu_ids[0] in range(num_gpus_per_raylet)
def get_location_and_ids(self):
assert ray.get_gpu_ids() == self.gpu_ids
return (ray.worker.global_worker.node.unique_id,
tuple(self.gpu_ids))
def locations_to_intervals_for_many_tasks():
# Launch a bunch of GPU tasks.
locations_ids_and_intervals = ray.get(
[f1.remote() for _ in range(5 * num_nodes * num_gpus_per_raylet)] +
[f2.remote() for _ in range(5 * num_nodes * num_gpus_per_raylet)] +
[f1.remote() for _ in range(5 * num_nodes * num_gpus_per_raylet)])
locations_to_intervals = collections.defaultdict(lambda: [])
for location, gpu_ids, interval in locations_ids_and_intervals:
for gpu_id in gpu_ids:
locations_to_intervals[(location, gpu_id)].append(interval)
return locations_to_intervals
# Run a bunch of GPU tasks.
locations_to_intervals = locations_to_intervals_for_many_tasks()
# For each GPU, verify that the set of tasks that used this specific
# GPU did not overlap in time.
for locations in locations_to_intervals:
check_intervals_non_overlapping(locations_to_intervals[locations])
# Create an actor that uses a GPU.
a = Actor1.remote()
actor_location = ray.get(a.get_location_and_ids.remote())
actor_location = (actor_location[0], actor_location[1][0])
# This check makes sure that actor_location is formatted the same way
# that the keys of locations_to_intervals are formatted.
assert actor_location in locations_to_intervals
# Run a bunch of GPU tasks.
locations_to_intervals = locations_to_intervals_for_many_tasks()
# For each GPU, verify that the set of tasks that used this specific
# GPU did not overlap in time.
for locations in locations_to_intervals:
check_intervals_non_overlapping(locations_to_intervals[locations])
# Make sure that the actor's GPU was not used.
assert actor_location not in locations_to_intervals
more_actors = [
Actor1.remote() for _ in range(num_nodes * num_gpus_per_raylet - 1)
]
ray.get([actor.get_location_and_ids.remote() for actor in more_actors])
results = [f1.remote() for _ in range(30)]
ready_ids, remaining_ids = ray.wait(results, timeout=1.0)
assert len(ready_ids) == 0
def test_actors_and_tasks_with_gpus_version_two(shutdown_only):
num_gpus = 4
ray.init(
num_cpus=(num_gpus + 1),
num_gpus=num_gpus,
object_store_memory=int(150 * 1024 * 1024))
@ray.remote
class RecordGPUs:
def __init__(self):
self.gpu_ids_seen = []
self.num_calls = 0
def add_ids(self, gpu_ids):
self.gpu_ids_seen += gpu_ids
self.num_calls += 1
def get_gpu_ids_and_calls(self):
return self.gpu_ids_seen, self.num_calls
@ray.remote(num_gpus=1)
def f(record_gpu_actor):
gpu_ids = ray.get_gpu_ids()
assert len(gpu_ids) == 1
record_gpu_actor.add_ids.remote(gpu_ids)
time.sleep(1000)
@ray.remote(num_gpus=1)
class Actor:
def __init__(self, record_gpu_actor):
self.gpu_ids = ray.get_gpu_ids()
assert len(self.gpu_ids) == 1
record_gpu_actor.add_ids.remote(self.gpu_ids)
def check_gpu_ids(self):
assert ray.get_gpu_ids() == self.gpu_ids
record_gpu_actor = RecordGPUs.remote()
actors = []
actor_results = []
for _ in range(num_gpus // 2):
f.remote(record_gpu_actor)
a = Actor.remote(record_gpu_actor)
actor_results.append(a.check_gpu_ids.remote())
actors.append(a)
# Make sure that the actor method calls succeeded.
ray.get(actor_results)
start_time = time.time()
while time.time() - start_time < 30:
seen_gpu_ids, num_calls = ray.get(
record_gpu_actor.get_gpu_ids_and_calls.remote())
if num_calls == num_gpus:
break
assert set(seen_gpu_ids) == set(range(num_gpus))
def test_blocking_actor_task(shutdown_only):
ray.init(
num_cpus=1, num_gpus=1, object_store_memory=int(150 * 1024 * 1024))
@ray.remote(num_gpus=1)
def f():
return 1
@ray.remote
class Foo:
def __init__(self):
pass
def blocking_method(self):
ray.get(f.remote())
# Make sure we can execute a blocking actor method even if there is
# only one CPU.
actor = Foo.remote()
ray.get(actor.blocking_method.remote())
@ray.remote(num_cpus=1)
class CPUFoo:
def __init__(self):
pass
def blocking_method(self):
ray.get(f.remote())
# Make sure that lifetime CPU resources are not released when actors
# block.
actor = CPUFoo.remote()
x_id = actor.blocking_method.remote()
ready_ids, remaining_ids = ray.wait([x_id], timeout=1.0)
assert ready_ids == []
assert remaining_ids == [x_id]
@ray.remote(num_gpus=1)
class GPUFoo:
def __init__(self):
pass
def blocking_method(self):
ray.get(f.remote())
# Make sure that GPU resources are not released when actors block.
actor = GPUFoo.remote()
x_id = actor.blocking_method.remote()
ready_ids, remaining_ids = ray.wait([x_id], timeout=1.0)
assert ready_ids == []
assert remaining_ids == [x_id]
def test_lifetime_and_transient_resources(ray_start_regular):
# This actor acquires resources only when running methods.
@ray.remote
class Actor1:
def method(self):
pass
# This actor acquires resources for its lifetime.
@ray.remote(num_cpus=1)
class Actor2:
def method(self):
pass
actor1s = [Actor1.remote() for _ in range(10)]
ray.get([a.method.remote() for a in actor1s])
actor2s = [Actor2.remote() for _ in range(2)]
results = [a.method.remote() for a in actor2s]
ready_ids, remaining_ids = ray.wait(
results, num_returns=len(results), timeout=5.0)
assert len(ready_ids) == 1
def test_custom_label_placement(ray_start_cluster):
cluster = ray_start_cluster
custom_resource1_node = cluster.add_node(
num_cpus=2, resources={"CustomResource1": 2})
custom_resource2_node = cluster.add_node(
num_cpus=2, resources={"CustomResource2": 2})
ray.init(address=cluster.address)
@ray.remote(resources={"CustomResource1": 1})
class ResourceActor1:
def get_location(self):
return ray.worker.global_worker.node.unique_id
@ray.remote(resources={"CustomResource2": 1})
class ResourceActor2:
def get_location(self):
return ray.worker.global_worker.node.unique_id
# Create some actors.
actors1 = [ResourceActor1.remote() for _ in range(2)]
actors2 = [ResourceActor2.remote() for _ in range(2)]
locations1 = ray.get([a.get_location.remote() for a in actors1])
locations2 = ray.get([a.get_location.remote() for a in actors2])
for location in locations1:
assert location == custom_resource1_node.unique_id
for location in locations2:
assert location == custom_resource2_node.unique_id
def test_creating_more_actors_than_resources(shutdown_only):
ray.init(num_cpus=10, num_gpus=2, resources={"CustomResource1": 1})
@ray.remote(num_gpus=1)
class ResourceActor1:
def method(self):
return ray.get_gpu_ids()[0]
@ray.remote(resources={"CustomResource1": 1})
class ResourceActor2:
def method(self):
pass
# Make sure the first two actors get created and the third one does
# not.
actor1 = ResourceActor1.remote()
result1 = actor1.method.remote()
ray.wait([result1])
actor2 = ResourceActor1.remote()
result2 = actor2.method.remote()
ray.wait([result2])
actor3 = ResourceActor1.remote()
result3 = actor3.method.remote()
ready_ids, _ = ray.wait([result3], timeout=0.2)
assert len(ready_ids) == 0
# By deleting actor1, we free up resources to create actor3.
del actor1
results = ray.get([result1, result2, result3])
assert results[0] == results[2]
assert set(results) == {0, 1}
# Make sure that when one actor goes out of scope a new actor is
# created because some resources have been freed up.
results = []
for _ in range(3):
actor = ResourceActor2.remote()
object_ref = actor.method.remote()
results.append(object_ref)
# Wait for the task to execute. We do this because otherwise it may
# be possible for the __ray_terminate__ task to execute before the
# method.
ray.wait([object_ref])
ray.get(results)
if __name__ == "__main__":
import pytest
sys.exit(pytest.main(["-v", __file__]))
| true | true |
f7f75c32bc1653963cbbab84ee7282e0d0063ffe | 8,078 | py | Python | core/admin/mailu/ui/views/users.py | Nebukadneza/Mailu | c25c646909823dc4250636bb73167c6a2ea8b43c | [
"MIT"
] | null | null | null | core/admin/mailu/ui/views/users.py | Nebukadneza/Mailu | c25c646909823dc4250636bb73167c6a2ea8b43c | [
"MIT"
] | null | null | null | core/admin/mailu/ui/views/users.py | Nebukadneza/Mailu | c25c646909823dc4250636bb73167c6a2ea8b43c | [
"MIT"
] | null | null | null | from mailu import db, models, app
from mailu.ui import ui, access, forms
import flask
import flask_login
import wtforms
import wtforms_components
@ui.route('/user/list/<domain_name>', methods=['GET'])
@access.domain_admin(models.Domain, 'domain_name')
def user_list(domain_name):
domain = models.Domain.query.get(domain_name) or flask.abort(404)
return flask.render_template('user/list.html', domain=domain)
@ui.route('/user/create/<domain_name>', methods=['GET', 'POST'])
@access.domain_admin(models.Domain, 'domain_name')
def user_create(domain_name):
domain = models.Domain.query.get(domain_name) or flask.abort(404)
if domain.max_users and len(domain.users) >= domain.max_users:
flask.flash('Too many users for domain %s' % domain, 'error')
return flask.redirect(
flask.url_for('.user_list', domain_name=domain.name))
form = forms.UserForm()
if domain.max_quota_bytes:
form.quota_bytes.validators = [
wtforms.validators.NumberRange(max=domain.max_quota_bytes)]
if form.validate_on_submit():
if domain.has_email(form.localpart.data):
flask.flash('Email is already used', 'error')
else:
user = models.User(domain=domain)
form.populate_obj(user)
user.set_password(form.pw.data)
db.session.add(user)
db.session.commit()
user.send_welcome()
flask.flash('User %s created' % user)
return flask.redirect(
flask.url_for('.user_list', domain_name=domain.name))
return flask.render_template('user/create.html',
domain=domain, form=form)
@ui.route('/user/edit/<user_email>', methods=['GET', 'POST'])
@access.domain_admin(models.User, 'user_email')
def user_edit(user_email):
user = models.User.query.get(user_email) or flask.abort(404)
# Handle the case where user quota is more than allowed
max_quota_bytes = user.domain.max_quota_bytes
if max_quota_bytes and user.quota_bytes > max_quota_bytes:
max_quota_bytes = user.quota_bytes
# Create the form
form = forms.UserForm(obj=user)
wtforms_components.read_only(form.localpart)
form.pw.validators = []
form.localpart.validators = []
if max_quota_bytes:
form.quota_bytes.validators = [
wtforms.validators.NumberRange(max=max_quota_bytes)]
if form.validate_on_submit():
form.populate_obj(user)
if form.pw.data:
user.set_password(form.pw.data)
db.session.commit()
flask.flash('User %s updated' % user)
return flask.redirect(
flask.url_for('.user_list', domain_name=user.domain.name))
return flask.render_template('user/edit.html', form=form, user=user,
domain=user.domain, max_quota_bytes=max_quota_bytes)
@ui.route('/user/delete/<user_email>', methods=['GET', 'POST'])
@access.domain_admin(models.User, 'user_email')
@access.confirmation_required("delete {user_email}")
def user_delete(user_email):
user = models.User.query.get(user_email) or flask.abort(404)
domain = user.domain
db.session.delete(user)
db.session.commit()
flask.flash('User %s deleted' % user)
return flask.redirect(
flask.url_for('.user_list', domain_name=domain.name))
@ui.route('/user/settings', methods=['GET', 'POST'], defaults={'user_email': None})
@ui.route('/user/usersettings/<user_email>', methods=['GET', 'POST'])
@access.owner(models.User, 'user_email')
def user_settings(user_email):
user_email_or_current = user_email or flask_login.current_user.email
user = models.User.query.get(user_email_or_current) or flask.abort(404)
form = forms.UserSettingsForm(obj=user)
if form.validate_on_submit():
form.populate_obj(user)
db.session.commit()
flask.flash('Settings updated for %s' % user)
if user_email:
return flask.redirect(
flask.url_for('.user_list', domain_name=user.domain.name))
return flask.render_template('user/settings.html', form=form, user=user)
@ui.route('/user/password', methods=['GET', 'POST'], defaults={'user_email': None})
@ui.route('/user/password/<user_email>', methods=['GET', 'POST'])
@access.owner(models.User, 'user_email')
def user_password(user_email):
user_email_or_current = user_email or flask_login.current_user.email
user = models.User.query.get(user_email_or_current) or flask.abort(404)
form = forms.UserPasswordForm()
if form.validate_on_submit():
if form.pw.data != form.pw2.data:
flask.flash('Passwords do not match', 'error')
else:
user.set_password(form.pw.data)
db.session.commit()
flask.flash('Password updated for %s' % user)
if user_email:
return flask.redirect(flask.url_for('.user_list',
domain_name=user.domain.name))
return flask.render_template('user/password.html', form=form, user=user)
@ui.route('/user/forward', methods=['GET', 'POST'], defaults={'user_email': None})
@ui.route('/user/forward/<user_email>', methods=['GET', 'POST'])
@access.owner(models.User, 'user_email')
def user_forward(user_email):
user_email_or_current = user_email or flask_login.current_user.email
user = models.User.query.get(user_email_or_current) or flask.abort(404)
form = forms.UserForwardForm(obj=user)
if form.validate_on_submit():
form.populate_obj(user)
db.session.commit()
flask.flash('Forward destination updated for %s' % user)
if user_email:
return flask.redirect(
flask.url_for('.user_list', domain_name=user.domain.name))
return flask.render_template('user/forward.html', form=form, user=user)
@ui.route('/user/reply', methods=['GET', 'POST'], defaults={'user_email': None})
@ui.route('/user/reply/<user_email>', methods=['GET', 'POST'])
@access.owner(models.User, 'user_email')
def user_reply(user_email):
user_email_or_current = user_email or flask_login.current_user.email
user = models.User.query.get(user_email_or_current) or flask.abort(404)
form = forms.UserReplyForm(obj=user)
if form.validate_on_submit():
form.populate_obj(user)
db.session.commit()
flask.flash('Auto-reply message updated for %s' % user)
if user_email:
return flask.redirect(
flask.url_for('.user_list', domain_name=user.domain.name))
return flask.render_template('user/reply.html', form=form, user=user)
@ui.route('/user/signup', methods=['GET', 'POST'])
@ui.route('/user/signup/<domain_name>', methods=['GET', 'POST'])
def user_signup(domain_name=None):
available_domains = {
domain.name: domain
for domain in models.Domain.query.filter_by(signup_enabled=True).all()
if not domain.max_users or len(domain.users) < domain.max_users
}
if not available_domains:
flask.flash('No domain available for registration')
if not domain_name:
return flask.render_template('user/signup_domain.html',
available_domains=available_domains)
domain = available_domains.get(domain_name) or flask.abort(404)
quota_bytes = domain.max_quota_bytes or app.config['DEFAULT_QUOTA']
if app.config['RECAPTCHA_PUBLIC_KEY'] == "" or app.config['RECAPTCHA_PRIVATE_KEY'] == "":
form = forms.UserSignupForm()
else:
form = forms.UserSignupFormCaptcha()
if form.validate_on_submit():
if domain.has_email(form.localpart.data):
flask.flash('Email is already used', 'error')
else:
user = models.User(domain=domain)
form.populate_obj(user)
user.set_password(form.pw.data)
user.quota_bytes = quota_bytes
db.session.add(user)
db.session.commit()
user.send_welcome()
flask.flash('Successfully signed up %s' % user)
return flask.redirect(flask.url_for('.index'))
return flask.render_template('user/signup.html', domain=domain, form=form)
| 42.072917 | 93 | 0.673929 | from mailu import db, models, app
from mailu.ui import ui, access, forms
import flask
import flask_login
import wtforms
import wtforms_components
@ui.route('/user/list/<domain_name>', methods=['GET'])
@access.domain_admin(models.Domain, 'domain_name')
def user_list(domain_name):
domain = models.Domain.query.get(domain_name) or flask.abort(404)
return flask.render_template('user/list.html', domain=domain)
@ui.route('/user/create/<domain_name>', methods=['GET', 'POST'])
@access.domain_admin(models.Domain, 'domain_name')
def user_create(domain_name):
domain = models.Domain.query.get(domain_name) or flask.abort(404)
if domain.max_users and len(domain.users) >= domain.max_users:
flask.flash('Too many users for domain %s' % domain, 'error')
return flask.redirect(
flask.url_for('.user_list', domain_name=domain.name))
form = forms.UserForm()
if domain.max_quota_bytes:
form.quota_bytes.validators = [
wtforms.validators.NumberRange(max=domain.max_quota_bytes)]
if form.validate_on_submit():
if domain.has_email(form.localpart.data):
flask.flash('Email is already used', 'error')
else:
user = models.User(domain=domain)
form.populate_obj(user)
user.set_password(form.pw.data)
db.session.add(user)
db.session.commit()
user.send_welcome()
flask.flash('User %s created' % user)
return flask.redirect(
flask.url_for('.user_list', domain_name=domain.name))
return flask.render_template('user/create.html',
domain=domain, form=form)
@ui.route('/user/edit/<user_email>', methods=['GET', 'POST'])
@access.domain_admin(models.User, 'user_email')
def user_edit(user_email):
user = models.User.query.get(user_email) or flask.abort(404)
max_quota_bytes = user.domain.max_quota_bytes
if max_quota_bytes and user.quota_bytes > max_quota_bytes:
max_quota_bytes = user.quota_bytes
form = forms.UserForm(obj=user)
wtforms_components.read_only(form.localpart)
form.pw.validators = []
form.localpart.validators = []
if max_quota_bytes:
form.quota_bytes.validators = [
wtforms.validators.NumberRange(max=max_quota_bytes)]
if form.validate_on_submit():
form.populate_obj(user)
if form.pw.data:
user.set_password(form.pw.data)
db.session.commit()
flask.flash('User %s updated' % user)
return flask.redirect(
flask.url_for('.user_list', domain_name=user.domain.name))
return flask.render_template('user/edit.html', form=form, user=user,
domain=user.domain, max_quota_bytes=max_quota_bytes)
@ui.route('/user/delete/<user_email>', methods=['GET', 'POST'])
@access.domain_admin(models.User, 'user_email')
@access.confirmation_required("delete {user_email}")
def user_delete(user_email):
user = models.User.query.get(user_email) or flask.abort(404)
domain = user.domain
db.session.delete(user)
db.session.commit()
flask.flash('User %s deleted' % user)
return flask.redirect(
flask.url_for('.user_list', domain_name=domain.name))
@ui.route('/user/settings', methods=['GET', 'POST'], defaults={'user_email': None})
@ui.route('/user/usersettings/<user_email>', methods=['GET', 'POST'])
@access.owner(models.User, 'user_email')
def user_settings(user_email):
user_email_or_current = user_email or flask_login.current_user.email
user = models.User.query.get(user_email_or_current) or flask.abort(404)
form = forms.UserSettingsForm(obj=user)
if form.validate_on_submit():
form.populate_obj(user)
db.session.commit()
flask.flash('Settings updated for %s' % user)
if user_email:
return flask.redirect(
flask.url_for('.user_list', domain_name=user.domain.name))
return flask.render_template('user/settings.html', form=form, user=user)
@ui.route('/user/password', methods=['GET', 'POST'], defaults={'user_email': None})
@ui.route('/user/password/<user_email>', methods=['GET', 'POST'])
@access.owner(models.User, 'user_email')
def user_password(user_email):
user_email_or_current = user_email or flask_login.current_user.email
user = models.User.query.get(user_email_or_current) or flask.abort(404)
form = forms.UserPasswordForm()
if form.validate_on_submit():
if form.pw.data != form.pw2.data:
flask.flash('Passwords do not match', 'error')
else:
user.set_password(form.pw.data)
db.session.commit()
flask.flash('Password updated for %s' % user)
if user_email:
return flask.redirect(flask.url_for('.user_list',
domain_name=user.domain.name))
return flask.render_template('user/password.html', form=form, user=user)
@ui.route('/user/forward', methods=['GET', 'POST'], defaults={'user_email': None})
@ui.route('/user/forward/<user_email>', methods=['GET', 'POST'])
@access.owner(models.User, 'user_email')
def user_forward(user_email):
user_email_or_current = user_email or flask_login.current_user.email
user = models.User.query.get(user_email_or_current) or flask.abort(404)
form = forms.UserForwardForm(obj=user)
if form.validate_on_submit():
form.populate_obj(user)
db.session.commit()
flask.flash('Forward destination updated for %s' % user)
if user_email:
return flask.redirect(
flask.url_for('.user_list', domain_name=user.domain.name))
return flask.render_template('user/forward.html', form=form, user=user)
@ui.route('/user/reply', methods=['GET', 'POST'], defaults={'user_email': None})
@ui.route('/user/reply/<user_email>', methods=['GET', 'POST'])
@access.owner(models.User, 'user_email')
def user_reply(user_email):
user_email_or_current = user_email or flask_login.current_user.email
user = models.User.query.get(user_email_or_current) or flask.abort(404)
form = forms.UserReplyForm(obj=user)
if form.validate_on_submit():
form.populate_obj(user)
db.session.commit()
flask.flash('Auto-reply message updated for %s' % user)
if user_email:
return flask.redirect(
flask.url_for('.user_list', domain_name=user.domain.name))
return flask.render_template('user/reply.html', form=form, user=user)
@ui.route('/user/signup', methods=['GET', 'POST'])
@ui.route('/user/signup/<domain_name>', methods=['GET', 'POST'])
def user_signup(domain_name=None):
available_domains = {
domain.name: domain
for domain in models.Domain.query.filter_by(signup_enabled=True).all()
if not domain.max_users or len(domain.users) < domain.max_users
}
if not available_domains:
flask.flash('No domain available for registration')
if not domain_name:
return flask.render_template('user/signup_domain.html',
available_domains=available_domains)
domain = available_domains.get(domain_name) or flask.abort(404)
quota_bytes = domain.max_quota_bytes or app.config['DEFAULT_QUOTA']
if app.config['RECAPTCHA_PUBLIC_KEY'] == "" or app.config['RECAPTCHA_PRIVATE_KEY'] == "":
form = forms.UserSignupForm()
else:
form = forms.UserSignupFormCaptcha()
if form.validate_on_submit():
if domain.has_email(form.localpart.data):
flask.flash('Email is already used', 'error')
else:
user = models.User(domain=domain)
form.populate_obj(user)
user.set_password(form.pw.data)
user.quota_bytes = quota_bytes
db.session.add(user)
db.session.commit()
user.send_welcome()
flask.flash('Successfully signed up %s' % user)
return flask.redirect(flask.url_for('.index'))
return flask.render_template('user/signup.html', domain=domain, form=form)
| true | true |
f7f75dd62613ec944a98de990b49820e4b4fb528 | 95,865 | py | Python | testsuite.py | weety/Kconfiglib | ef5358e8b8174716470b00691fba9946b7d307ce | [
"ISC"
] | null | null | null | testsuite.py | weety/Kconfiglib | ef5358e8b8174716470b00691fba9946b7d307ce | [
"ISC"
] | null | null | null | testsuite.py | weety/Kconfiglib | ef5358e8b8174716470b00691fba9946b7d307ce | [
"ISC"
] | null | null | null | # Copyright (c) 2011-2018, Ulf Magnusson
# SPDX-License-Identifier: ISC
# This is the Kconfiglib test suite. It runs selftests on Kconfigs provided by
# us and tests compatibility with the C Kconfig implementation by comparing the
# output of Kconfiglib with the output of the scripts/kconfig/*conf utilities
# for different targets and defconfigs. It should be run from the top-level
# kernel directory with
#
# $ python Kconfiglib/testsuite.py
#
# Some additional options can be turned on by passing them as arguments. They
# default to off.
#
# - obsessive:
# By default, only valid arch/defconfig pairs are tested. In obsessive mode,
# every arch will be tested with every defconfig. Increases the testing time
# by an order of magnitude. Occasionally finds (usually obscure) bugs, and I
# make sure everything passes with it.
#
# - obsessive-min-config:
# Like obsessive, for the minimal configuation (defconfig) tests.
#
# - log:
# Log timestamped defconfig test failures to the file test_defconfig_fails.
# Handy in obsessive mode.
#
# For example, this commands runs the test suite in obsessive mode with logging
# enabled:
#
# $ python(3) Kconfiglib/testsuite.py obsessive log
#
# pypy works too, and runs most tests much faster than CPython.
#
# All tests should pass. Report regressions to ulfalizer a.t Google's email
# service.
from kconfiglib import Kconfig, Symbol, Choice, COMMENT, MENU, MenuNode, \
BOOL, TRISTATE, HEX, STRING, \
TRI_TO_STR, \
escape, unescape, \
expr_str, expr_value, expr_items, split_expr, \
_ordered_unique, \
OR, AND, \
KconfigError
import difflib
import errno
import os
import platform
import re
import shutil
import subprocess
import sys
import tempfile
import textwrap
def shell(cmd):
with open(os.devnull, "w") as devnull:
subprocess.call(cmd, shell=True, stdout=devnull, stderr=devnull)
all_passed = True
def fail(msg=None):
global all_passed
all_passed = False
if msg is not None:
print("fail: " + msg)
def verify(cond, msg):
if not cond:
fail(msg)
def verify_equal(x, y):
if x != y:
fail("'{}' does not equal '{}'".format(x, y))
# Prevent accidental loading of configuration files by removing
# KCONFIG_ALLCONFIG from the environment
os.environ.pop("KCONFIG_ALLCONFIG", None)
obsessive = False
obsessive_min_config = False
log = False
def run_tests():
global obsessive, log
for s in sys.argv[1:]:
if s == "obsessive":
obsessive = True
print("Obsessive mode enabled")
elif s == "obsessive-min-config":
obsessive_min_config = True
print("Obsessive minimal config mode enabled")
elif s == "log":
log = True
print("Log mode enabled")
else:
print("Unrecognized option '{}'".format(s))
return
run_selftests()
run_compatibility_tests()
def run_selftests():
#
# Common helper functions. These all expect 'c' to hold the current
# configuration.
#
def verify_value(sym_name, val):
"""
Verifies that a symbol has a particular value.
"""
if isinstance(val, int):
val = TRI_TO_STR[val]
sym = c.syms[sym_name]
verify(sym.str_value == val,
'expected {} to have the value "{}", had the value "{}"'
.format(sym_name, val, sym.str_value))
def assign_and_verify_value(sym_name, val, new_val):
"""
Assigns 'val' to a symbol and verifies that its value becomes
'new_val'. Assumes (and tests) that 'val' is valid for the
symbol type.
"""
if isinstance(new_val, int):
new_val = TRI_TO_STR[new_val]
sym = c.syms[sym_name]
old_val = sym.str_value
verify(sym.set_value(val),
"assigning '{}' to {} unexpectedly failed"
.format(val, sym_name))
verify(sym.str_value == new_val,
"expected {} to have the value '{}' after being assigned the "
"value '{}'. Instead, the value is '{}'. The old value was "
"'{}'."
.format(sym_name, new_val, val, sym.str_value, old_val))
def assign_and_verify(sym_name, user_val):
"""
Like assign_and_verify_value(), with the expected value being the
value just set.
"""
assign_and_verify_value(sym_name, user_val, user_val)
def assign_and_verify_user_value(sym_name, val, user_val, valid):
"""
Assigns a user value to the symbol and verifies the new user value. If
valid is True, the user value is valid for the type, otherwise not.
This is used to test the set_value() return value.
"""
sym = c.syms[sym_name]
sym_old_user_val = sym.user_value
verify(sym.set_value(val) == valid,
"expected the user value '{}' to be {} for {}, was not"
.format(val, "valid" if valid else "invalid", sym_name))
verify(sym.user_value == user_val,
"the assigned user value '{}' wasn't reflected in user_value "
"on the symbol {}. Instead, the new user_value was '{}'. The "
"old user value was '{}'."
.format(user_val, sym_name, sym.user_value, sym_old_user_val))
#
# Selftests
#
print("Testing string literal lexing")
# Dummy empty configuration just to get a Kconfig object
c = Kconfig("Kconfiglib/tests/empty")
def verify_string_lex(s, expected):
"""
Verifies that a constant symbol with the name 'res' is produced from
lexing 's'
"""
res = c._tokenize("if " + s)[1].name
verify(res == expected,
"expected <{}> to produced the constant symbol <{}>, "
'produced <{}>'.format(s[1:-1], expected, res))
verify_string_lex(r""" "" """, "")
verify_string_lex(r""" '' """, "")
verify_string_lex(r""" "a" """, "a")
verify_string_lex(r""" 'a' """, "a")
verify_string_lex(r""" "ab" """, "ab")
verify_string_lex(r""" 'ab' """, "ab")
verify_string_lex(r""" "abc" """, "abc")
verify_string_lex(r""" 'abc' """, "abc")
verify_string_lex(r""" "'" """, "'")
verify_string_lex(r""" '"' """, '"')
verify_string_lex(r""" "\"" """, '"')
verify_string_lex(r""" '\'' """, "'")
verify_string_lex(r""" "\"\"" """, '""')
verify_string_lex(r""" '\'\'' """, "''")
verify_string_lex(r""" "\'" """, "'")
verify_string_lex(r""" '\"' """, '"')
verify_string_lex(r""" "\\" """, "\\")
verify_string_lex(r""" '\\' """, "\\")
verify_string_lex(r""" "\a\\'\b\c\"'d" """, 'a\\\'bc"\'d')
verify_string_lex(r""" '\a\\"\b\c\'"d' """, "a\\\"bc'\"d")
def verify_string_bad(s):
"""
Verifies that tokenizing 's' throws a KconfigError. Strips the first
and last characters from 's' so we can use readable raw strings as
input.
"""
try:
c.eval_string(s)
except KconfigError:
pass
else:
fail("expected tokenization of {} to fail, didn't".format(s[1:-1]))
verify_string_bad(r""" " """)
verify_string_bad(r""" ' """)
verify_string_bad(r""" "' """)
verify_string_bad(r""" '" """)
verify_string_bad(r""" "\" """)
verify_string_bad(r""" '\' """)
verify_string_bad(r""" "foo """)
verify_string_bad(r""" 'foo """)
print("Testing escape() and unescape()")
def verify_escape_unescape(s, sesc):
# Verify that 's' escapes to 'sesc' and that 'sesc' unescapes to 's'
verify_equal(escape(s), sesc)
verify_equal(unescape(sesc), s)
verify_escape_unescape(r'' , r'' )
verify_escape_unescape(r'foo' , r'foo' )
verify_escape_unescape(r'"' , r'\"' )
verify_escape_unescape(r'""' , r'\"\"' )
verify_escape_unescape('\\' , r'\\' )
verify_escape_unescape(r'\\' , r'\\\\' )
verify_escape_unescape(r'\"' , r'\\\"' )
verify_escape_unescape(r'"ab\cd"ef"', r'\"ab\\cd\"ef\"')
# Backslashes before any character should be unescaped, not just before "
# and \
verify_equal(unescape(r"\afoo\b\c\\d\\\e\\\\f"), r"afoobc\d\e\\f")
print("Testing _ordered_unique()")
verify_equal(_ordered_unique([]), [])
verify_equal(_ordered_unique([1]), [1])
verify_equal(_ordered_unique([1, 2]), [1, 2])
verify_equal(_ordered_unique([1, 1]), [1])
verify_equal(_ordered_unique([1, 1, 2]), [1, 2])
verify_equal(_ordered_unique([1, 2, 1]), [1, 2])
verify_equal(_ordered_unique([1, 2, 2]), [1, 2])
verify_equal(_ordered_unique([1, 2, 3, 2, 1, 2, 3, 4, 3, 2, 1, 0]),
[1, 2, 3, 4, 0])
print("Testing expression evaluation")
c = Kconfig("Kconfiglib/tests/Keval", warn=False)
def verify_eval(expr, val):
res = c.eval_string(expr)
verify(res == val,
"'{}' evaluated to {}, expected {}".format(expr, res, val))
# No modules
verify_eval("n", 0)
verify_eval("m", 0)
verify_eval("y", 2)
verify_eval("'n'", 0)
verify_eval("'m'", 0)
verify_eval("'y'", 2)
verify_eval("M", 2)
# Modules
c.modules.set_value(2)
verify_eval("n", 0)
verify_eval("m", 1)
verify_eval("y", 2)
verify_eval("'n'", 0)
verify_eval("'m'", 1)
verify_eval("'y'", 2)
verify_eval("M", 1)
verify_eval("(Y || N) && (m && y)", 1)
# Non-bool/non-tristate symbols are always n in a tristate sense
verify_eval("Y_STRING", 0)
verify_eval("Y_STRING || m", 1)
# As are all constants besides y and m
verify_eval('"foo"', 0)
verify_eval('"foo" || "bar"', 0)
verify_eval('"foo" || m', 1)
# Test equality for symbols
verify_eval("N = N", 2)
verify_eval("N = n", 2)
verify_eval("N = 'n'", 2)
verify_eval("N != N", 0)
verify_eval("N != n", 0)
verify_eval("N != 'n'", 0)
verify_eval("M = M", 2)
verify_eval("M = m", 2)
verify_eval("M = 'm'", 2)
verify_eval("M != M", 0)
verify_eval("M != m", 0)
verify_eval("M != 'm'", 0)
verify_eval("Y = Y", 2)
verify_eval("Y = y", 2)
verify_eval("Y = 'y'", 2)
verify_eval("Y != Y", 0)
verify_eval("Y != y", 0)
verify_eval("Y != 'y'", 0)
verify_eval("N != M", 2)
verify_eval("N != Y", 2)
verify_eval("M != Y", 2)
verify_eval("Y_STRING = y", 2)
verify_eval("Y_STRING = 'y'", 2)
verify_eval('FOO_BAR_STRING = "foo bar"', 2)
verify_eval('FOO_BAR_STRING != "foo bar baz"', 2)
verify_eval('INT_37 = 37', 2)
verify_eval("INT_37 = '37'", 2)
verify_eval('HEX_0X37 = 0x37', 2)
verify_eval("HEX_0X37 = '0x37'", 2)
# These should also hold after 31847b67 (kconfig: allow use of relations
# other than (in)equality)
verify_eval("HEX_0X37 = '0x037'", 2)
verify_eval("HEX_0X37 = '0x0037'", 2)
# Constant symbol comparisons
verify_eval('"foo" != "bar"', 2)
verify_eval('"foo" = "bar"', 0)
verify_eval('"foo" = "foo"', 2)
# Undefined symbols get their name as their value
c.disable_warnings()
verify_eval("'not_defined' = not_defined", 2)
verify_eval("not_defined_2 = not_defined_2", 2)
verify_eval("not_defined_1 != not_defined_2", 2)
# Test less than/greater than
# Basic evaluation
verify_eval("INT_37 < 38", 2)
verify_eval("38 < INT_37", 0)
verify_eval("INT_37 < '38'", 2)
verify_eval("'38' < INT_37", 0)
verify_eval("INT_37 < 138", 2)
verify_eval("138 < INT_37", 0)
verify_eval("INT_37 < '138'", 2)
verify_eval("'138' < INT_37", 0)
verify_eval("INT_37 < -138", 0)
verify_eval("-138 < INT_37", 2)
verify_eval("INT_37 < '-138'", 0)
verify_eval("'-138' < INT_37", 2)
verify_eval("INT_37 < 37", 0)
verify_eval("37 < INT_37", 0)
verify_eval("INT_37 < 36", 0)
verify_eval("36 < INT_37", 2)
# Different formats in comparison
verify_eval("INT_37 < 0x26", 2) # 38
verify_eval("INT_37 < 0x25", 0) # 37
verify_eval("INT_37 < 0x24", 0) # 36
verify_eval("HEX_0X37 < 56", 2) # 0x38
verify_eval("HEX_0X37 < 55", 0) # 0x37
verify_eval("HEX_0X37 < 54", 0) # 0x36
# Other int comparisons
verify_eval("INT_37 <= 38", 2)
verify_eval("INT_37 <= 37", 2)
verify_eval("INT_37 <= 36", 0)
verify_eval("INT_37 > 38", 0)
verify_eval("INT_37 > 37", 0)
verify_eval("INT_37 > 36", 2)
verify_eval("INT_37 >= 38", 0)
verify_eval("INT_37 >= 37", 2)
verify_eval("INT_37 >= 36", 2)
# Other hex comparisons
verify_eval("HEX_0X37 <= 0x38", 2)
verify_eval("HEX_0X37 <= 0x37", 2)
verify_eval("HEX_0X37 <= 0x36", 0)
verify_eval("HEX_0X37 > 0x38", 0)
verify_eval("HEX_0X37 > 0x37", 0)
verify_eval("HEX_0X37 > 0x36", 2)
verify_eval("HEX_0X37 >= 0x38", 0)
verify_eval("HEX_0X37 >= 0x37", 2)
verify_eval("HEX_0X37 >= 0x36", 2)
# A hex holding a value without a "0x" prefix should still be treated as
# hexadecimal
verify_eval("HEX_37 < 0x38", 2)
verify_eval("HEX_37 < 0x37", 0)
verify_eval("HEX_37 < 0x36", 0)
# Symbol comparisons
verify_eval("INT_37 < HEX_0X37", 2)
verify_eval("INT_37 > HEX_0X37", 0)
verify_eval("HEX_0X37 < INT_37 ", 0)
verify_eval("HEX_0X37 > INT_37 ", 2)
verify_eval("INT_37 < INT_37 ", 0)
verify_eval("INT_37 <= INT_37 ", 2)
verify_eval("INT_37 > INT_37 ", 0)
verify_eval("INT_37 <= INT_37 ", 2)
# Tristate value comparisons
verify_eval("n < n", 0)
verify_eval("n < m", 2)
verify_eval("n < y", 2)
verify_eval("n < N", 0)
verify_eval("n < M", 2)
verify_eval("n < Y", 2)
verify_eval("0 > n", 0)
verify_eval("1 > n", 2)
verify_eval("2 > n", 2)
verify_eval("m < n", 0)
verify_eval("m < m", 0)
verify_eval("m < y", 2)
# Strings compare lexicographically
verify_eval("'aa' < 'ab'", 2)
verify_eval("'aa' > 'ab'", 0)
verify_eval("'ab' < 'aa'", 0)
verify_eval("'ab' > 'aa'", 2)
# Comparisons where one of the operands doesn't parse as a number also give
# a lexicographic comparison
verify_eval("INT_37 < '37a' ", 2)
verify_eval("'37a' > INT_37", 2)
verify_eval("INT_37 <= '37a' ", 2)
verify_eval("'37a' >= INT_37", 2)
verify_eval("INT_37 >= '37a' ", 0)
verify_eval("INT_37 > '37a' ", 0)
verify_eval("'37a' < INT_37", 0)
verify_eval("'37a' <= INT_37", 0)
def verify_eval_bad(expr):
try:
c.eval_string(expr)
except KconfigError:
pass
else:
fail('expected eval_string("{}") to throw KconfigError, '
"didn't".format(expr))
# Verify that some bad stuff throws KconfigError's
verify_eval_bad("")
verify_eval_bad("&")
verify_eval_bad("|")
verify_eval_bad("!")
verify_eval_bad("(")
verify_eval_bad(")")
verify_eval_bad("=")
verify_eval_bad("(X")
verify_eval_bad("X)")
verify_eval_bad("X X")
verify_eval_bad("!X X")
verify_eval_bad("X !X")
verify_eval_bad("(X) X")
verify_eval_bad("X &&")
verify_eval_bad("&& X")
verify_eval_bad("X && && X")
verify_eval_bad("X && !&&")
verify_eval_bad("X ||")
verify_eval_bad("|| X")
print("Testing Symbol.__str__()/custom_str() and def_{int,hex,string}")
def verify_str(item, s):
verify_equal(str(item), s[1:])
def verify_custom_str(item, s):
verify_equal(item.custom_str(lambda sc: "[{}]".format(sc.name)), s[1:])
c = Kconfig("Kconfiglib/tests/Kstr", warn=False)
c.modules.set_value(2)
verify_str(c.syms["UNDEFINED"], """
""")
verify_str(c.syms["BASIC_NO_PROMPT"], """
config BASIC_NO_PROMPT
bool
help
blah blah
blah blah blah
blah
""")
verify_str(c.syms["BASIC_PROMPT"], """
config BASIC_PROMPT
bool
prompt "basic"
""")
verify_str(c.syms["ADVANCED"], """
config ADVANCED
tristate
prompt "prompt" if DEP
default DEFAULT_1
default DEFAULT_2 if DEP
select SELECTED_1
select SELECTED_2 if DEP
imply IMPLIED_1
imply IMPLIED_2 if DEP
help
first help text
config ADVANCED
tristate
prompt "prompt 2"
menuconfig ADVANCED
tristate
prompt "prompt 3"
config ADVANCED
tristate
depends on (A || !B || (C && D) || !(E && F) || G = H || (I && !J && (K || L) && !(M || N) && O = P)) && DEP4 && DEP3
help
second help text
""")
verify_custom_str(c.syms["ADVANCED"], """
config ADVANCED
tristate
prompt "prompt" if [DEP]
default [DEFAULT_1]
default [DEFAULT_2] if [DEP]
select [SELECTED_1]
select [SELECTED_2] if [DEP]
imply [IMPLIED_1]
imply [IMPLIED_2] if [DEP]
help
first help text
config ADVANCED
tristate
prompt "prompt 2"
menuconfig ADVANCED
tristate
prompt "prompt 3"
config ADVANCED
tristate
depends on ([A] || ![B] || ([C] && [D]) || !([E] && [F]) || [G] = [H] || ([I] && ![J] && ([K] || [L]) && !([M] || [N]) && [O] = [P])) && [DEP4] && [DEP3]
help
second help text
""")
verify_str(c.syms["ONLY_DIRECT_DEPS"], """
config ONLY_DIRECT_DEPS
int
depends on DEP1 && DEP2
""")
verify_str(c.syms["STRING"], """
config STRING
string
default "foo"
default "bar" if DEP
default STRING2
default STRING3 if DEP
""")
verify_str(c.syms["INT"], """
config INT
int
range 1 2
range FOO BAR
range BAZ QAZ if DEP
default 7 if DEP
""")
verify_str(c.syms["HEX"], """
config HEX
hex
range 0x100 0x200
range FOO BAR
range BAZ QAZ if DEP
default 0x123
""")
verify_str(c.modules, """
config MODULES
bool
prompt "MODULES"
option modules
""")
verify_str(c.syms["OPTIONS"], """
config OPTIONS
option allnoconfig_y
option defconfig_list
option env="ENV"
""")
verify_str(c.syms["CORRECT_PROP_LOCS_BOOL"], """
config CORRECT_PROP_LOCS_BOOL
bool
prompt "prompt 1" if LOC_1
default DEFAULT_1 if LOC_1
default DEFAULT_2 if LOC_1
select SELECT_1 if LOC_1
select SELECT_2 if LOC_1
imply IMPLY_1 if LOC_1
imply IMPLY_2 if LOC_1
depends on LOC_1
help
help 1
menuconfig CORRECT_PROP_LOCS_BOOL
bool
prompt "prompt 2" if LOC_2
default DEFAULT_3 if LOC_2
default DEFAULT_4 if LOC_2
select SELECT_3 if LOC_2
select SELECT_4 if LOC_2
imply IMPLY_3 if LOC_2
imply IMPLY_4 if LOC_2
depends on LOC_2
help
help 2
config CORRECT_PROP_LOCS_BOOL
bool
prompt "prompt 3" if LOC_3
default DEFAULT_5 if LOC_3
default DEFAULT_6 if LOC_3
select SELECT_5 if LOC_3
select SELECT_6 if LOC_3
imply IMPLY_5 if LOC_3
imply IMPLY_6 if LOC_3
depends on LOC_3
help
help 2
""")
verify_str(c.syms["CORRECT_PROP_LOCS_INT"], """
config CORRECT_PROP_LOCS_INT
int
range 1 2 if LOC_1
range 3 4 if LOC_1
depends on LOC_1
config CORRECT_PROP_LOCS_INT
int
range 5 6 if LOC_2
range 7 8 if LOC_2
depends on LOC_2
""")
verify_custom_str(c.syms["CORRECT_PROP_LOCS_INT"], """
config CORRECT_PROP_LOCS_INT
int
range [1] [2] if [LOC_1]
range [3] [4] if [LOC_1]
depends on [LOC_1]
config CORRECT_PROP_LOCS_INT
int
range [5] [6] if [LOC_2]
range [7] [8] if [LOC_2]
depends on [LOC_2]
""")
print("Testing Choice.__str__()/custom_str()")
verify_str(c.named_choices["CHOICE"], """
choice CHOICE
tristate
prompt "foo"
default CHOICE_1
default CHOICE_2 if dep
""")
verify_str(c.named_choices["CHOICE"].nodes[0].next.item, """
choice
tristate
prompt "no name"
optional
""")
verify_str(c.named_choices["CORRECT_PROP_LOCS_CHOICE"], """
choice CORRECT_PROP_LOCS_CHOICE
bool
default CHOICE_3 if LOC_1
depends on LOC_1
choice CORRECT_PROP_LOCS_CHOICE
bool
default CHOICE_4 if LOC_2
depends on LOC_2
choice CORRECT_PROP_LOCS_CHOICE
bool
default CHOICE_5 if LOC_3
depends on LOC_3
""")
verify_custom_str(c.named_choices["CORRECT_PROP_LOCS_CHOICE"], """
choice CORRECT_PROP_LOCS_CHOICE
bool
default [CHOICE_3] if [LOC_1]
depends on [LOC_1]
choice CORRECT_PROP_LOCS_CHOICE
bool
default [CHOICE_4] if [LOC_2]
depends on [LOC_2]
choice CORRECT_PROP_LOCS_CHOICE
bool
default [CHOICE_5] if [LOC_3]
depends on [LOC_3]
""")
print("Testing MenuNode.__str__()/custom_str() for menus and comments")
verify_str(c.syms["SIMPLE_MENU_HOOK"].nodes[0].next, """
menu "simple menu"
""")
verify_str(c.syms["ADVANCED_MENU_HOOK"].nodes[0].next, """
menu "advanced menu"
depends on A
visible if B && (C || D)
""")
verify_custom_str(c.syms["ADVANCED_MENU_HOOK"].nodes[0].next, """
menu "advanced menu"
depends on [A]
visible if [B] && ([C] || [D])
""")
verify_str(c.syms["SIMPLE_COMMENT_HOOK"].nodes[0].next, """
comment "simple comment"
""")
verify_str(c.syms["ADVANCED_COMMENT_HOOK"].nodes[0].next, """
comment "advanced comment"
depends on A && B
""")
verify_custom_str(c.syms["ADVANCED_COMMENT_HOOK"].nodes[0].next, """
comment "advanced comment"
depends on [A] && [B]
""")
print("Testing Symbol.__repr__()")
def verify_repr(item, s):
verify_equal(repr(item) + "\n", s[1:])
c = Kconfig("Kconfiglib/tests/Krepr", warn=False)
verify_repr(c.n, """
<symbol n, tristate, value n, constant>
""")
verify_repr(c.m, """
<symbol m, tristate, value m, constant>
""")
verify_repr(c.y, """
<symbol y, tristate, value y, constant>
""")
verify_repr(c.syms["UNDEFINED"], """
<symbol UNDEFINED, unknown, value "UNDEFINED", visibility n, direct deps n, undefined>
""")
verify_repr(c.syms["BASIC"], """
<symbol BASIC, bool, value y, visibility n, direct deps y, Kconfiglib/tests/Krepr:9>
""")
verify_repr(c.syms["VISIBLE"], """
<symbol VISIBLE, bool, "visible", value n, visibility y, direct deps y, Kconfiglib/tests/Krepr:14>
""")
c.syms["VISIBLE"].set_value(2)
verify_repr(c.syms["VISIBLE"], """
<symbol VISIBLE, bool, "visible", value y, user value y, visibility y, direct deps y, Kconfiglib/tests/Krepr:14>
""")
verify_repr(c.syms["DIR_DEP_N"], """
<symbol DIR_DEP_N, unknown, value "DIR_DEP_N", visibility n, direct deps n, Kconfiglib/tests/Krepr:17>
""")
verify_repr(c.syms["OPTIONS"], """
<symbol OPTIONS, unknown, value "OPTIONS", visibility n, allnoconfig_y, is the defconfig_list symbol, from environment variable ENV, direct deps y, Kconfiglib/tests/Krepr:20>
""")
verify_repr(c.syms["MULTI_DEF"], """
<symbol MULTI_DEF, unknown, value "MULTI_DEF", visibility n, direct deps y, Kconfiglib/tests/Krepr:25, Kconfiglib/tests/Krepr:26>
""")
verify_repr(c.syms["CHOICE_1"], """
<symbol CHOICE_1, tristate, "choice sym", value n, visibility m, choice symbol, direct deps m, Kconfiglib/tests/Krepr:33>
""")
verify_repr(c.modules, """
<symbol MODULES, bool, value y, visibility n, is the modules symbol, direct deps y, Kconfiglib/tests/Krepr:1>
""")
print("Testing Choice.__repr__()")
verify_repr(c.named_choices["CHOICE"], """
<choice CHOICE, tristate, "choice", mode m, visibility y, Kconfiglib/tests/Krepr:30>
""")
c.named_choices["CHOICE"].set_value(2)
verify_repr(c.named_choices["CHOICE"], """
<choice CHOICE, tristate, "choice", mode y, user mode y, CHOICE_1 selected, visibility y, Kconfiglib/tests/Krepr:30>
""")
c.syms["CHOICE_2"].set_value(2)
verify_repr(c.named_choices["CHOICE"], """
<choice CHOICE, tristate, "choice", mode y, user mode y, CHOICE_2 selected, CHOICE_2 selected by user, visibility y, Kconfiglib/tests/Krepr:30>
""")
c.named_choices["CHOICE"].set_value(1)
verify_repr(c.named_choices["CHOICE"], """
<choice CHOICE, tristate, "choice", mode m, user mode m, CHOICE_2 selected by user (overridden), visibility y, Kconfiglib/tests/Krepr:30>
""")
verify_repr(c.syms["CHOICE_HOOK"].nodes[0].next.item, """
<choice, tristate, "optional choice", mode n, visibility n, optional, Kconfiglib/tests/Krepr:43>
""")
print("Testing MenuNode.__repr__()")
verify_repr(c.syms["BASIC"].nodes[0], """
<menu node for symbol BASIC, deps y, has help, has next, Kconfiglib/tests/Krepr:9>
""")
verify_repr(c.syms["DIR_DEP_N"].nodes[0], """
<menu node for symbol DIR_DEP_N, deps n, has next, Kconfiglib/tests/Krepr:17>
""")
verify_repr(c.syms["MULTI_DEF"].nodes[0], """
<menu node for symbol MULTI_DEF, deps y, has next, Kconfiglib/tests/Krepr:25>
""")
verify_repr(c.syms["MULTI_DEF"].nodes[1], """
<menu node for symbol MULTI_DEF, deps y, has next, Kconfiglib/tests/Krepr:26>
""")
verify_repr(c.syms["MENUCONFIG"].nodes[0], """
<menu node for symbol MENUCONFIG, is menuconfig, deps y, has next, Kconfiglib/tests/Krepr:28>
""")
verify_repr(c.named_choices["CHOICE"].nodes[0], """
<menu node for choice CHOICE, prompt "choice" (visibility y), deps y, has child, has next, Kconfiglib/tests/Krepr:30>
""")
verify_repr(c.syms["CHOICE_HOOK"].nodes[0].next, """
<menu node for choice, prompt "optional choice" (visibility n), deps y, has next, Kconfiglib/tests/Krepr:43>
""")
verify_repr(c.syms["NO_VISIBLE_IF_HOOK"].nodes[0].next, """
<menu node for menu, prompt "no visible if" (visibility y), deps y, 'visible if' deps y, has next, Kconfiglib/tests/Krepr:50>
""")
verify_repr(c.syms["VISIBLE_IF_HOOK"].nodes[0].next, """
<menu node for menu, prompt "visible if" (visibility y), deps y, 'visible if' deps m, has next, Kconfiglib/tests/Krepr:55>
""")
verify_repr(c.syms["COMMENT_HOOK"].nodes[0].next, """
<menu node for comment, prompt "comment" (visibility y), deps y, Kconfiglib/tests/Krepr:61>
""")
print("Testing Kconfig.__repr__()")
verify_repr(c, """
<configuration with 14 symbols, main menu prompt "Main menu", srctree is current directory, config symbol prefix "CONFIG_", warnings disabled, printing of warnings to stderr enabled, undef. symbol assignment warnings disabled, redundant symbol assignment warnings enabled>
""")
os.environ["srctree"] = "Kconfiglib"
os.environ["CONFIG_"] = "CONFIG_ value"
c = Kconfig("tests/Krepr", warn=False)
c.enable_warnings()
c.disable_stderr_warnings()
c.disable_redun_warnings()
c.enable_undef_warnings()
verify_repr(c, """
<configuration with 14 symbols, main menu prompt "Main menu", srctree "Kconfiglib", config symbol prefix "CONFIG_ value", warnings enabled, printing of warnings to stderr disabled, undef. symbol assignment warnings enabled, redundant symbol assignment warnings disabled>
""")
os.environ.pop("srctree", None)
os.environ.pop("CONFIG_", None)
print("Testing tricky help strings")
c = Kconfig("Kconfiglib/tests/Khelp")
def verify_help(node, s):
verify_equal(node.help, s[1:])
verify_help(c.syms["TWO_HELP_STRINGS"].nodes[0], """
first help string
""")
verify_help(c.syms["TWO_HELP_STRINGS"].nodes[1], """
second help string
""")
verify_help(c.syms["NO_BLANK_AFTER_HELP"].nodes[0], """
help for
NO_BLANK_AFTER_HELP
""")
verify_help(c.named_choices["CHOICE_HELP"].nodes[0], """
help for
CHOICE_HELP
""")
verify_help(c.syms["HELP_TERMINATED_BY_COMMENT"].nodes[0], """
a
b
c
""")
verify_help(c.syms["TRICKY_HELP"].nodes[0], """
a
b
c
d
e
f
g
h
i
""")
print("Testing locations, source/rsource/gsource/grsource, and "
"Kconfig.kconfig_filenames")
def verify_locations(nodes, *expected_locs):
verify(len(nodes) == len(expected_locs),
"Wrong number of locations for " + repr(nodes))
for node, expected_loc in zip(nodes, expected_locs):
node_loc = "{}:{}".format(node.filename, node.linenr)
verify(node_loc == expected_loc,
"expected {} to have the location {}, had the location {}"
.format(repr(node), expected_loc, node_loc))
# Expanded in the 'source' statement in Klocation
os.environ["TESTS_DIR_FROM_ENV"] = "tests"
os.environ["SUB_DIR_FROM_ENV"] = "sub"
os.environ["_SOURCED"] = "_sourced"
os.environ["_RSOURCED"] = "_rsourced"
os.environ["_GSOURCED"] = "_gsourced"
os.environ["_GRSOURCED"] = "_grsourced"
# Test twice, with $srctree as a relative and an absolute path,
# respectively
for srctree in "Kconfiglib", os.path.abspath("Kconfiglib"):
os.environ["srctree"] = srctree
# Has symbol with empty help text, so disable warnings
c = Kconfig("tests/Klocation", warn=False)
verify_locations(c.syms["SINGLE_DEF"].nodes, "tests/Klocation:4")
verify_locations(c.syms["MULTI_DEF"].nodes,
"tests/Klocation:7",
"tests/Klocation:37",
"tests/Klocation_sourced:3",
"tests/sub/Klocation_rsourced:2",
"tests/sub/Klocation_gsourced1:1",
"tests/sub/Klocation_gsourced2:1",
"tests/sub/Klocation_gsourced1:1",
"tests/sub/Klocation_gsourced2:1",
"tests/sub/Klocation_grsourced1:1",
"tests/sub/Klocation_grsourced2:1",
"tests/sub/Klocation_grsourced1:1",
"tests/sub/Klocation_grsourced2:1",
"tests/Klocation:70")
verify_locations(c.named_choices["CHOICE"].nodes,
"tests/Klocation_sourced:5")
verify_locations([c.syms["MENU_HOOK"].nodes[0].next],
"tests/Klocation_sourced:12")
verify_locations([c.syms["COMMENT_HOOK"].nodes[0].next],
"tests/Klocation_sourced:18")
# Test Kconfig.kconfig_filenames
verify_equal(c.kconfig_filenames, [
"tests/Klocation",
"tests/Klocation_sourced",
"tests/sub/Klocation_rsourced",
"tests/sub/Klocation_gsourced1",
"tests/sub/Klocation_gsourced2",
"tests/sub/Klocation_gsourced1",
"tests/sub/Klocation_gsourced2",
"tests/sub/Klocation_grsourced1",
"tests/sub/Klocation_grsourced2",
"tests/sub/Klocation_grsourced1",
"tests/sub/Klocation_grsourced2"
])
# Test recursive 'source' detection
try:
Kconfig("tests/Krecursive1")
except KconfigError as e:
verify_equal(str(e), """
tests/Krecursive2:1: Recursive 'source' of 'tests/Krecursive1' detected. Check that environment variables are set correctly.
Include path:
tests/Krecursive1:1
tests/Krecursive2:1
"""[:-1])
except:
fail("recursive 'source' raised wrong exception")
else:
fail("recursive 'source' did not raise exception")
# Verify that source and rsource throw exceptions for missing files
# TODO: Make an exception test helper
try:
Kconfig("tests/Kmissingsource")
except KconfigError as e:
if "does not exist" not in str(e):
fail("'source' with missing file raised wrong KconfigError")
except:
fail("'source' with missing file raised wrong exception")
else:
fail("'source' with missing file did not raise exception")
try:
Kconfig("tests/Kmissingrsource")
except KconfigError as e:
if "does not exist" not in str(e):
fail("'rsource' with missing file raised wrong KconfigError")
except:
fail("'rsource' with missing file raised wrong exception")
else:
fail("'rsource' with missing file did not raise exception")
print("Testing Kconfig.node_iter()")
# Reuse tests/Klocation. The node_iter(unique_syms=True) case already gets
# plenty of testing from write_config() as well.
c = Kconfig("tests/Klocation", warn=False)
verify_equal(
[node.item.name for node in c.node_iter()
if isinstance(node.item, Symbol)],
["SINGLE_DEF", "MULTI_DEF", "HELP_1", "HELP_2", "HELP_3", "MULTI_DEF",
"MULTI_DEF", "MENU_HOOK", "COMMENT_HOOK"] + 10*["MULTI_DEF"])
verify_equal(
[node.item.name for node in c.node_iter(True)
if isinstance(node.item, Symbol)],
["SINGLE_DEF", "MULTI_DEF", "HELP_1", "HELP_2", "HELP_3", "MENU_HOOK",
"COMMENT_HOOK"])
verify_equal(
[node.prompt[0] for node in c.node_iter()
if not isinstance(node.item, Symbol)],
["choice", "menu", "comment"])
verify_equal(
[node.prompt[0] for node in c.node_iter(True)
if not isinstance(node.item, Symbol)],
["choice", "menu", "comment"])
# Get rid of custom 'srctree' from Klocation test
os.environ.pop("srctree", None)
print("Testing MenuNode.include_path")
os.environ["srctree"] = "Kconfiglib/tests"
c = Kconfig("Kinclude_path")
def verify_node_path(node, *expected):
if node.include_path != expected:
fail("Wrong include path for node {!r}. Got {}, expected {}."
.format(node, node.include_path, expected))
def verify_sym_path(sym_name, node_i, *expected):
verify_node_path(c.syms[sym_name].nodes[node_i], *expected)
verify_sym_path("TOP", 0)
verify_sym_path("TOP", 1)
verify_sym_path("TOP", 2)
verify_sym_path("ONE_DOWN", 0, ("Kinclude_path", 4))
verify_sym_path("ONE_DOWN", 1, ("Kinclude_path", 4))
verify_sym_path("ONE_DOWN", 2, ("Kinclude_path", 4))
verify_sym_path("ONE_DOWN", 3, ("Kinclude_path", 9))
verify_sym_path("ONE_DOWN", 4, ("Kinclude_path", 9))
verify_sym_path("ONE_DOWN", 5, ("Kinclude_path", 9))
verify_sym_path("TWO_DOWN", 0,
("Kinclude_path", 4), ("Kinclude_path_sourced_1", 4))
verify_sym_path("TWO_DOWN", 1,
("Kinclude_path", 4), ("Kinclude_path_sourced_1", 9))
verify_sym_path("TWO_DOWN", 2,
("Kinclude_path", 9), ("Kinclude_path_sourced_1", 4))
verify_sym_path("TWO_DOWN", 3,
("Kinclude_path", 9), ("Kinclude_path_sourced_1", 9))
verify_node_path(c.top_node)
verify_node_path(c.menus[0], ("Kinclude_path", 4), ("Kinclude_path_sourced_1", 4))
verify_node_path(c.comments[0], ("Kinclude_path", 4), ("Kinclude_path_sourced_1", 4))
verify_node_path(c.choices[0].nodes[0], ("Kinclude_path", 4), ("Kinclude_path_sourced_1", 4))
os.environ.pop("srctree", None)
print("Testing Kconfig.choices/menus/comments")
c = Kconfig("Kconfiglib/tests/Kitemlists")
def verify_prompts(items, *expected_prompts):
verify(len(items) == len(expected_prompts),
"Wrong number of prompts for {}".format(items))
for item, expected_prompt in zip(items, expected_prompts):
if not isinstance(item, MenuNode):
item = item.nodes[0]
verify(item.prompt[0] == expected_prompt,
"Wrong prompt for {}, expected '{}'"
.format(repr(item), expected_prompt))
verify_prompts(c.choices, "choice 1", "choice 2", "choice 3")
verify_prompts(c.menus, "menu 1", "menu 2", "menu 3", "menu 4", "menu 5")
verify_prompts(c.comments, "comment 1", "comment 2", "comment 3")
print("Testing Symbol/Choice.direct_dep")
c = Kconfig("Kconfiglib/tests/Kdirdep")
verify_equal(expr_str(c.syms["NO_DEP_SYM"].direct_dep), '"y"')
verify_equal(expr_str(c.syms["DEP_SYM"].direct_dep), "A || (B && C) || !D")
verify_equal(expr_str(c.named_choices["NO_DEP_CHOICE"].direct_dep), '"y"')
verify_equal(expr_str(c.named_choices["DEP_CHOICE"].direct_dep),
"A || B || C")
print("Testing expr_items()")
c = Kconfig("Kconfiglib/tests/Kexpr_items")
def verify_expr_items(expr, *sym_names):
verify_equal(tuple(sorted(item.name for item in expr_items(expr))),
sym_names)
verify_expr_items(
c.syms["TEST"].defaults[0][0],
"A", "B", "C", "D", "E", "F", "G", "H"
)
verify_expr_items(
c.syms["TEST_CHOICE"].nodes[0].prompt[1],
"A", "CHOICE"
)
print("Testing MenuNode/Symbol/Choice.referenced")
c = Kconfig("Kconfiglib/tests/Kreferenced", warn=False)
def verify_deps(item, *dep_names):
verify_equal(tuple(sorted(item.name for item in item.referenced)),
dep_names)
verify_deps(c.top_node, "y")
verify_deps(c.syms["NO_REFS"].nodes[0], "y")
verify_deps(c.syms["JUST_DEPENDS_ON_REFS"].nodes[0], "A", "B")
verify_deps(c.syms["LOTS_OF_REFS"].nodes[0],
*(chr(n) for n in range(ord("A"), ord("Z") + 1)))
verify_deps(c.syms["INT_REFS"].nodes[0],
"A", "B", "C", "D", "E", "F", "G", "H", "y")
verify_deps(c.syms["CHOICE_REF"].nodes[0], "CHOICE")
verify_deps(c.menus[0], "A", "B", "C", "D")
verify_deps(c.comments[0], "A", "B")
verify_deps(c.syms["MULTI_DEF_SYM"], "A", "B", "C", "y")
verify_deps(c.named_choices["MULTI_DEF_CHOICE"], "A", "B", "C")
print("Testing split_expr()")
c = Kconfig("Kconfiglib/tests/empty")
c.disable_warnings()
def verify_split(to_split, op, operand_strs):
# The same hackage as in Kconfig.eval_string()
c._tokens = c._tokenize("if " + to_split)[1:]
c._tokens_i = -1
operands = split_expr(c._parse_expr(False), op)
verify(len(operands) == len(operand_strs),
"Wrong number of operands when {} was split by {}"
.format(to_split, "OR" if op == OR else "AND"))
for operand, operand_str in zip(operands, operand_strs):
verify_equal(expr_str(operand), operand_str)
verify_split("A", OR, ("A", ))
verify_split("!A", OR, ("!A", ))
verify_split("A = B", OR, ("A = B", ))
verify_split("A && B", OR, ("A && B", ))
verify_split("A || B", OR, ("A", "B" ))
verify_split("(A || B) || C", OR, ("A", "B", "C" ))
verify_split("A || (B || C)", OR, ("A", "B", "C" ))
verify_split("A || !(B || C)", OR, ("A", "!(B || C)" ))
verify_split("A || (B && (C || D))", OR, ("A", "B && (C || D)"))
verify_split("(A && (B || C)) || D", OR, ("A && (B || C)", "D"))
verify_split("A", AND, ("A", ))
verify_split("!A", AND, ("!A", ))
verify_split("A = B", AND, ("A = B", ))
verify_split("A || B", AND, ("A || B", ))
verify_split("A && B", AND, ("A", "B" ))
verify_split("(A && B) && C", AND, ("A", "B", "C" ))
verify_split("A && (B && C)", AND, ("A", "B", "C" ))
verify_split("A && !(B && C)", AND, ("A", "!(B && C)" ))
verify_split("A && (B || (C && D))", AND, ("A", "B || (C && D)"))
verify_split("(A || (B && C)) && D", AND, ("A || (B && C)", "D"))
print("Testing visibility")
c = Kconfig("Kconfiglib/tests/Kvisibility")
def verify_visibility(item, no_module_vis, module_vis):
c.modules.set_value(0)
verify(item.visibility == no_module_vis,
"expected {} to have visibility {} without modules, had "
"visibility {}".
format(repr(item), no_module_vis, item.visibility))
c.modules.set_value(2)
verify(item.visibility == module_vis,
"expected {} to have visibility {} with modules, had "
"visibility {}".
format(repr(item), module_vis, item.visibility))
# Symbol visibility
verify_visibility(c.syms["NO_PROMPT"], 0, 0)
verify_visibility(c.syms["BOOL_N"], 0, 0)
verify_visibility(c.syms["BOOL_M"], 0, 2)
verify_visibility(c.syms["BOOL_MOD"], 2, 2)
verify_visibility(c.syms["BOOL_Y"], 2, 2)
verify_visibility(c.syms["TRISTATE_M"], 0, 1)
verify_visibility(c.syms["TRISTATE_MOD"], 2, 1)
verify_visibility(c.syms["TRISTATE_Y"], 2, 2)
verify_visibility(c.syms["BOOL_IF_N"], 0, 0)
verify_visibility(c.syms["BOOL_IF_M"], 0, 2)
verify_visibility(c.syms["BOOL_IF_Y"], 2, 2)
verify_visibility(c.syms["BOOL_MENU_N"], 0, 0)
verify_visibility(c.syms["BOOL_MENU_M"], 0, 2)
verify_visibility(c.syms["BOOL_MENU_Y"], 2, 2)
verify_visibility(c.syms["BOOL_CHOICE_N"], 0, 0)
# Non-tristate symbols in tristate choices are only visible if the choice
# is in y mode
# The choice can't be brought to y mode because of the 'if m'
verify_visibility(c.syms["BOOL_CHOICE_M"], 0, 0)
c.syms["BOOL_CHOICE_M"].choice.set_value(2)
verify_visibility(c.syms["BOOL_CHOICE_M"], 0, 0)
# The choice gets y mode only when running without modules, because it
# defaults to m mode
verify_visibility(c.syms["BOOL_CHOICE_Y"], 2, 0)
c.syms["BOOL_CHOICE_Y"].choice.set_value(2)
# When set to y mode, the choice symbol becomes visible both with and
# without modules
verify_visibility(c.syms["BOOL_CHOICE_Y"], 2, 2)
verify_visibility(c.syms["TRISTATE_IF_N"], 0, 0)
verify_visibility(c.syms["TRISTATE_IF_M"], 0, 1)
verify_visibility(c.syms["TRISTATE_IF_Y"], 2, 2)
verify_visibility(c.syms["TRISTATE_MENU_N"], 0, 0)
verify_visibility(c.syms["TRISTATE_MENU_M"], 0, 1)
verify_visibility(c.syms["TRISTATE_MENU_Y"], 2, 2)
verify_visibility(c.syms["TRISTATE_CHOICE_N"], 0, 0)
verify_visibility(c.syms["TRISTATE_CHOICE_M"], 0, 1)
verify_visibility(c.syms["TRISTATE_CHOICE_Y"], 2, 2)
verify_visibility(c.named_choices["BOOL_CHOICE_N"], 0, 0)
verify_visibility(c.named_choices["BOOL_CHOICE_M"], 0, 2)
verify_visibility(c.named_choices["BOOL_CHOICE_Y"], 2, 2)
verify_visibility(c.named_choices["TRISTATE_CHOICE_N"], 0, 0)
verify_visibility(c.named_choices["TRISTATE_CHOICE_M"], 0, 1)
verify_visibility(c.named_choices["TRISTATE_CHOICE_Y"], 2, 2)
verify_visibility(c.named_choices["TRISTATE_CHOICE_IF_M_AND_Y"], 0, 1)
verify_visibility(c.named_choices["TRISTATE_CHOICE_MENU_N_AND_Y"], 0, 0)
# Verify that 'visible if' visibility gets propagated to prompts
verify_visibility(c.syms["VISIBLE_IF_N"], 0, 0)
verify_visibility(c.syms["VISIBLE_IF_M"], 0, 1)
verify_visibility(c.syms["VISIBLE_IF_Y"], 2, 2)
verify_visibility(c.syms["VISIBLE_IF_M_2"], 0, 1)
# Verify that string/int/hex symbols with m visibility accept a user value
assign_and_verify("STRING_m", "foo bar")
assign_and_verify("INT_m", "123")
assign_and_verify("HEX_m", "0x123")
print("Testing .assignable")
c = Kconfig("Kconfiglib/tests/Kassignable")
def verify_assignable_imp(item, assignable_no_modules, assignable_modules):
"""
Verifies the assignable values for 'item', with and without modules.
"""
for modules_val, assignable in (0, assignable_no_modules), \
(2, assignable_modules):
c.modules.set_value(modules_val)
module_msg = "without modules" if modules_val == 0 else \
"with modules"
verify(item.assignable == assignable,
"Incorrect assignable values for {} {}. Should be {}, "
"was {}."
.format(item.name, module_msg, assignable, item.assignable))
# Verify that the values can actually be assigned too
for val in item.assignable:
item.set_value(val)
verify(item.tri_value == val,
"Unable to set {} to {} {}, even though it was in "
".assignable".format(item.name, val, module_msg))
def verify_assignable(sym_name, assignable_no_modules, assignable_modules):
verify_assignable_imp(c.syms[sym_name],
assignable_no_modules,
assignable_modules)
def verify_const_unassignable(sym_name):
verify_assignable_imp(c.const_syms[sym_name], (), ())
# Things that shouldn't be .assignable
verify_const_unassignable("n")
verify_const_unassignable("m")
verify_const_unassignable("y")
verify_const_unassignable("const")
verify_assignable("UNDEFINED", (), ())
verify_assignable("NO_PROMPT", (), ())
verify_assignable("STRING", (), ())
verify_assignable("INT", (), ())
verify_assignable("HEX", (), ())
# Non-selected symbols
verify_assignable("Y_VIS_BOOL", (0, 2), (0, 2))
verify_assignable("M_VIS_BOOL", ( ), (0, 2)) # Vis. promoted
verify_assignable("N_VIS_BOOL", ( ), ( ))
verify_assignable("Y_VIS_TRI", (0, 2), (0, 1, 2))
verify_assignable("M_VIS_TRI", ( ), (0, 1 ))
verify_assignable("N_VIS_TRI", ( ), ( ))
# Symbols selected to y
verify_assignable("Y_SEL_Y_VIS_BOOL", (2,), (2,))
verify_assignable("Y_SEL_M_VIS_BOOL", ( ), (2,)) # Vis. promoted
verify_assignable("Y_SEL_N_VIS_BOOL", ( ), ( ))
verify_assignable("Y_SEL_Y_VIS_TRI", (2,), (2,))
verify_assignable("Y_SEL_M_VIS_TRI", ( ), (2,))
verify_assignable("Y_SEL_N_VIS_TRI", ( ), ( ))
# Symbols selected to m
verify_assignable("M_SEL_Y_VIS_BOOL", (2,), ( 2,)) # Value promoted
verify_assignable("M_SEL_M_VIS_BOOL", ( ), ( 2,)) # Vis./value promoted
verify_assignable("M_SEL_N_VIS_BOOL", ( ), ( ))
verify_assignable("M_SEL_Y_VIS_TRI", (2,), (1, 2 ))
verify_assignable("M_SEL_M_VIS_TRI", ( ), (1, ))
verify_assignable("M_SEL_N_VIS_TRI", ( ), ( ))
# Symbols implied to y
verify_assignable("Y_IMP_Y_VIS_BOOL", (0, 2), (0, 2))
verify_assignable("Y_IMP_M_VIS_BOOL", ( ), (0, 2)) # Vis. promoted
verify_assignable("Y_IMP_N_VIS_BOOL", ( ), ( ))
verify_assignable("Y_IMP_Y_VIS_TRI", (0, 2), (0, 2)) # m removed by imply
verify_assignable("Y_IMP_M_VIS_TRI", ( ), (0, 2)) # m promoted to y by imply
verify_assignable("Y_IMP_N_VIS_TRI", ( ), ( ))
# Symbols implied to m (never affects assignable values)
verify_assignable("M_IMP_Y_VIS_BOOL", (0, 2), (0, 2))
verify_assignable("M_IMP_M_VIS_BOOL", ( ), (0, 2)) # Vis. promoted
verify_assignable("M_IMP_N_VIS_BOOL", ( ), ( ))
verify_assignable("M_IMP_Y_VIS_TRI", (0, 2), (0, 1, 2))
verify_assignable("M_IMP_M_VIS_TRI", ( ), (0, 1 ))
verify_assignable("M_IMP_N_VIS_TRI", ( ), ( ))
# Symbols in y-mode choice
verify_assignable("Y_CHOICE_BOOL", (2,), (2,))
verify_assignable("Y_CHOICE_TRISTATE", (2,), (2,))
verify_assignable("Y_CHOICE_N_VIS_TRISTATE", ( ), ( ))
# Symbols in m/y-mode choice, starting out in m mode, or y mode when
# running without modules
verify_assignable("MY_CHOICE_BOOL", (2,), ( ))
verify_assignable("MY_CHOICE_TRISTATE", (2,), (0, 1))
verify_assignable("MY_CHOICE_N_VIS_TRISTATE", ( ), ( ))
c.named_choices["MY_CHOICE"].set_value(2)
# Symbols in m/y-mode choice, now in y mode
verify_assignable("MY_CHOICE_BOOL", (2,), (2,))
verify_assignable("MY_CHOICE_TRISTATE", (2,), (2,))
verify_assignable("MY_CHOICE_N_VIS_TRISTATE", ( ), ( ))
def verify_choice_assignable(choice_name, assignable_no_modules,
assignable_modules):
verify_assignable_imp(c.named_choices[choice_name],
assignable_no_modules,
assignable_modules)
# Choices with various possible modes
verify_choice_assignable("Y_CHOICE", (2, ), ( 2,))
verify_choice_assignable("MY_CHOICE", (2, ), ( 1, 2 ))
verify_choice_assignable("NMY_CHOICE", (0, 2), (0, 1, 2 ))
verify_choice_assignable("NY_CHOICE", (0, 2), (0, 2 ))
verify_choice_assignable("NM_CHOICE", ( ), (0, 1 ))
verify_choice_assignable("M_CHOICE", ( ), ( 1, ))
verify_choice_assignable("N_CHOICE", ( ), ( ))
print("Testing object relations")
c = Kconfig("Kconfiglib/tests/Krelation")
verify(c.syms["A"].nodes[0].parent is c.top_node,
"A's parent should be the top node")
verify(c.syms["B"].nodes[0].parent.item is c.named_choices["CHOICE_1"],
"B's parent should be the first choice")
verify(c.syms["C"].nodes[0].parent.item is c.syms["B"],
"C's parent should be B (due to auto menus)")
verify(c.syms["E"].nodes[0].parent.item == MENU,
"E's parent should be a menu")
verify(c.syms["E"].nodes[0].parent.parent is c.top_node,
"E's grandparent should be the top node")
verify(c.syms["G"].nodes[0].parent.item is c.named_choices["CHOICE_2"],
"G's parent should be the second choice")
verify(c.syms["G"].nodes[0].parent.parent.item == MENU,
"G's grandparent should be a menu")
print("Testing hex/int ranges")
c = Kconfig("Kconfiglib/tests/Krange", warn=False)
for sym_name in "HEX_NO_RANGE", "INT_NO_RANGE", "HEX_40", "INT_40":
sym = c.syms[sym_name]
verify(not sym.ranges,
"{} should not have ranges".format(sym_name))
for sym_name in "HEX_ALL_RANGES_DISABLED", "INT_ALL_RANGES_DISABLED", \
"HEX_RANGE_10_20_LOW_DEFAULT", \
"INT_RANGE_10_20_LOW_DEFAULT":
sym = c.syms[sym_name]
verify(sym.ranges, "{} should have ranges".format(sym_name))
# hex/int symbols without defaults should get no default value
verify_value("HEX_NO_RANGE", "")
verify_value("INT_NO_RANGE", "")
# And neither if all ranges are disabled
verify_value("HEX_ALL_RANGES_DISABLED", "")
verify_value("INT_ALL_RANGES_DISABLED", "")
# Make sure they are assignable though, and test that the form of the user
# value is reflected in the value for hex symbols
assign_and_verify("HEX_NO_RANGE", "0x123")
assign_and_verify("HEX_NO_RANGE", "123")
assign_and_verify("INT_NO_RANGE", "123")
# Defaults outside of the valid range should be clamped
verify_value("HEX_RANGE_10_20_LOW_DEFAULT", "0x10")
verify_value("HEX_RANGE_10_20_HIGH_DEFAULT", "0x20")
verify_value("INT_RANGE_10_20_LOW_DEFAULT", "10")
verify_value("INT_RANGE_10_20_HIGH_DEFAULT", "20")
# Defaults inside the valid range should be preserved. For hex symbols,
# they should additionally use the same form as in the assignment.
verify_value("HEX_RANGE_10_20_OK_DEFAULT", "0x15")
verify_value("HEX_RANGE_10_20_OK_DEFAULT_ALTERNATE", "15")
verify_value("INT_RANGE_10_20_OK_DEFAULT", "15")
# hex/int symbols with no defaults but valid ranges should default to the
# lower end of the range if it's > 0
verify_value("HEX_RANGE_10_20", "0x10")
verify_value("HEX_RANGE_0_10", "")
verify_value("INT_RANGE_10_20", "10")
verify_value("INT_RANGE_0_10", "")
verify_value("INT_RANGE_NEG_10_10", "")
# User values and dependent ranges
# Avoid warnings for assigning values outside the active range
c.disable_warnings()
def verify_range(sym_name, low, high, default):
"""
Tests that the values in the range 'low'-'high' can be assigned, and
that assigning values outside this range reverts the value back to
'default' (None if it should revert back to "").
"""
is_hex = (c.syms[sym_name].type == HEX)
for i in range(low, high + 1):
assign_and_verify_user_value(sym_name, str(i), str(i), True)
if is_hex:
# The form of the user value should be preserved for hex
# symbols
assign_and_verify_user_value(sym_name, hex(i), hex(i), True)
# Verify that assigning a user value just outside the range causes
# defaults to be used
if default is None:
default_str = ""
else:
default_str = hex(default) if is_hex else str(default)
if is_hex:
too_low_str = hex(low - 1)
too_high_str = hex(high + 1)
else:
too_low_str = str(low - 1)
too_high_str = str(high + 1)
assign_and_verify_value(sym_name, too_low_str, default_str)
assign_and_verify_value(sym_name, too_high_str, default_str)
verify_range("HEX_RANGE_10_20_LOW_DEFAULT", 0x10, 0x20, 0x10)
verify_range("HEX_RANGE_10_20_HIGH_DEFAULT", 0x10, 0x20, 0x20)
verify_range("HEX_RANGE_10_20_OK_DEFAULT", 0x10, 0x20, 0x15)
verify_range("INT_RANGE_10_20_LOW_DEFAULT", 10, 20, 10)
verify_range("INT_RANGE_10_20_HIGH_DEFAULT", 10, 20, 20)
verify_range("INT_RANGE_10_20_OK_DEFAULT", 10, 20, 15)
verify_range("HEX_RANGE_10_20", 0x10, 0x20, 0x10)
verify_range("INT_RANGE_10_20", 10, 20, 10)
verify_range("INT_RANGE_0_10", 0, 10, None)
verify_range("INT_RANGE_NEG_10_10", -10, 10, None)
# Dependent ranges
verify_value("HEX_40", "40")
verify_value("INT_40", "40")
c.syms["HEX_RANGE_10_20"].unset_value()
c.syms["INT_RANGE_10_20"].unset_value()
verify_value("HEX_RANGE_10_40_DEPENDENT", "0x10")
verify_value("INT_RANGE_10_40_DEPENDENT", "10")
c.syms["HEX_RANGE_10_20"].set_value("15")
c.syms["INT_RANGE_10_20"].set_value("15")
verify_value("HEX_RANGE_10_40_DEPENDENT", "0x15")
verify_value("INT_RANGE_10_40_DEPENDENT", "15")
c.unset_values()
verify_range("HEX_RANGE_10_40_DEPENDENT", 0x10, 0x40, 0x10)
verify_range("INT_RANGE_10_40_DEPENDENT", 10, 40, 10)
# Ranges and symbols defined in multiple locations
verify_value("INACTIVE_RANGE", "2")
verify_value("ACTIVE_RANGE", "1")
print("Testing defconfig_filename")
c = Kconfig("Kconfiglib/tests/empty")
verify(c.defconfig_filename is None,
"defconfig_filename should be None with no defconfig_list symbol")
c = Kconfig("Kconfiglib/tests/Kdefconfig_nonexistent")
verify(c.defconfig_filename is None,
"defconfig_filename should be None when none of the files in the "
"defconfig_list symbol exist")
# Referenced in Kdefconfig_existent(_but_n)
os.environ["FOO"] = "defconfig_2"
c = Kconfig("Kconfiglib/tests/Kdefconfig_existent_but_n")
verify(c.defconfig_filename is None,
"defconfig_filename should be None when the condition is n for all "
"the defaults")
c = Kconfig("Kconfiglib/tests/Kdefconfig_existent")
verify(c.defconfig_filename == "Kconfiglib/tests/defconfig_2",
"defconfig_filename should return the existing file "
"Kconfiglib/tests/defconfig_2")
# Should also look relative to $srctree if the specified defconfig is a
# relative path and can't be opened
c = Kconfig("Kconfiglib/tests/Kdefconfig_srctree")
verify(c.defconfig_filename == "Kconfiglib/tests/defconfig_2",
"defconfig_filename gave wrong file with $srctree unset")
os.environ["srctree"] = "Kconfiglib/tests"
c = Kconfig("Kdefconfig_srctree")
verify(c.defconfig_filename == "Kconfiglib/tests/sub/defconfig_in_sub",
"defconfig_filename gave wrong file with $srctree set")
os.environ.pop("srctree", None)
print("Testing mainmenu_text")
c = Kconfig("Kconfiglib/tests/empty")
verify(c.mainmenu_text == "Main menu",
"An empty Kconfig should get a default main menu prompt")
# Expanded in the mainmenu text
os.environ["FOO"] = "bar baz"
c = Kconfig("Kconfiglib/tests/Kmainmenu")
verify(c.mainmenu_text == "---bar baz---",
"Wrong mainmenu text")
print("Testing user_value")
# References undefined env. var. Disable warnings.
c = Kconfig("Kconfiglib/tests/Kmisc", warn=False)
# Avoid warnings from assigning invalid user values and assigning user
# values to symbols without prompts
c.disable_warnings()
syms = [c.syms[name] for name in
("BOOL", "TRISTATE", "STRING", "INT", "HEX")]
for sym in syms:
verify(sym.user_value is None,
"{} should not have a user value to begin with")
# Assign valid values for the types
assign_and_verify_user_value("BOOL", 0, 0, True)
assign_and_verify_user_value("BOOL", 2, 2, True)
assign_and_verify_user_value("TRISTATE", 0, 0, True)
assign_and_verify_user_value("TRISTATE", 1, 1, True)
assign_and_verify_user_value("TRISTATE", 2, 2, True)
assign_and_verify_user_value("STRING", "foo bar", "foo bar", True)
assign_and_verify_user_value("INT", "123", "123", True)
assign_and_verify_user_value("HEX", "0x123", "0x123", True)
# Assign invalid values for the types. They should retain their old user
# value.
assign_and_verify_user_value("BOOL", 1, 2, False)
assign_and_verify_user_value("BOOL", "foo", 2, False)
assign_and_verify_user_value("BOOL", "1", 2, False)
assign_and_verify_user_value("TRISTATE", "foo", 2, False)
assign_and_verify_user_value("TRISTATE", "1", 2, False)
assign_and_verify_user_value("STRING", 0, "foo bar", False)
assign_and_verify_user_value("INT", "foo", "123", False)
assign_and_verify_user_value("INT", 0, "123", False)
assign_and_verify_user_value("HEX", "foo", "0x123", False)
assign_and_verify_user_value("HEX", 0, "0x123", False)
assign_and_verify_user_value("HEX", "-0x1", "0x123", False)
for s in syms:
s.unset_value()
verify(s.user_value is None,
"{} should not have a user value after being reset".
format(s.name))
print("Testing is_menuconfig")
c = Kconfig("Kconfiglib/tests/Kmenuconfig")
for not_menuconfig in c.syms["NOT_MENUCONFIG_1"].nodes[0], \
c.syms["NOT_MENUCONFIG_2"].nodes[0], \
c.syms["MENUCONFIG_MULTI_DEF"].nodes[0], \
c.syms["COMMENT_HOOK"].nodes[0].next:
verify(not not_menuconfig.is_menuconfig,
"'{}' should have is_menuconfig False".format(not_menuconfig))
for menuconfig in c.top_node, \
c.syms["MENUCONFIG_1"].nodes[0], \
c.syms["MENUCONFIG_MULTI_DEF"].nodes[1], \
c.syms["MENU_HOOK"].nodes[0].next, \
c.syms["CHOICE_HOOK"].nodes[0].next:
verify(menuconfig.is_menuconfig,
"'{}' should have is_menuconfig True".format(menuconfig))
print("Testing 'option env' semantics")
os.environ["ENV_VAR"] = "ENV_VAR value"
# References undefined env. var., so disable warnings
c = Kconfig("Kconfiglib/tests/Kmisc", warn=False)
# Verify that 'option env' is treated like a default
verify_value("FROM_ENV", "ENV_VAR value")
verify_value("FROM_ENV_MISSING", "missing")
verify_value("FROM_ENV_WEIRD", "weird")
print("Testing defined vs undefined symbols")
for name in "A", "B", "C", "D", "BOOL", "TRISTATE", "STRING", "INT", "HEX":
verify(c.syms[name].nodes,
"{} should be defined".format(name))
for name in "NOT_DEFINED_1", "NOT_DEFINED_2", "NOT_DEFINED_3", \
"NOT_DEFINED_4":
sym = c.syms[name]
verify(not c.syms[name].nodes,
"{} should not be defined".format(name))
print("Testing Symbol.choice")
for name in "A", "B", "C", "D":
verify(c.syms[name].choice is not None,
"{} should be a choice symbol".format(name))
for name in "Q1", "Q2", "Q3", "BOOL", "TRISTATE", "STRING", "INT", "HEX", \
"FROM_ENV", "FROM_ENV_MISSING", "NOT_DEFINED_1", \
"NOT_DEFINED_2", "NOT_DEFINED_3", "NOT_DEFINED_4":
verify(c.syms[name].choice is None,
"{} should not be a choice symbol".format(name))
print("Testing is_allnoconfig_y")
verify(not c.syms["NOT_ALLNOCONFIG_Y"].is_allnoconfig_y,
"NOT_ALLNOCONFIG_Y should not be allnoconfig_y")
verify(c.syms["ALLNOCONFIG_Y"].is_allnoconfig_y,
"ALLNOCONFIG_Y should be allnoconfig_y")
print("Testing .config reading and writing")
config_test_file = "Kconfiglib/tests/config_test"
def verify_file_contents(fname, contents):
with open(fname, "r") as f:
file_contents = f.read()
verify(file_contents == contents,
"{} contains '{}'. Expected '{}'."
.format(fname, file_contents, contents))
# Writing/reading strings with characters that need to be escaped
c = Kconfig("Kconfiglib/tests/Kescape")
# Test the default value
c.write_config(config_test_file + "_from_def", header="")
verify_file_contents(config_test_file + "_from_def",
r'''CONFIG_STRING="\"\\"''' "\n")
# Write our own value
c.syms["STRING"].set_value(r'''\"a'\\''')
c.write_config(config_test_file + "_from_user", header="")
verify_file_contents(config_test_file + "_from_user",
r'''CONFIG_STRING="\\\"a'\\\\"''' "\n")
# Read back the two configs and verify the respective values
c.load_config(config_test_file + "_from_def")
verify_value("STRING", '"\\')
c.load_config(config_test_file + "_from_user")
verify_value("STRING", r'''\"a'\\''')
# Appending values from a .config
c = Kconfig("Kconfiglib/tests/Kappend")
# Values before assigning
verify_value("BOOL", "n")
verify_value("STRING", "")
# Assign BOOL
c.load_config("Kconfiglib/tests/config_set_bool", replace=False)
verify_value("BOOL", "y")
verify_value("STRING", "")
# Assign STRING
c.load_config("Kconfiglib/tests/config_set_string", replace=False)
verify_value("BOOL", "y")
verify_value("STRING", "foo bar")
# Reset BOOL
c.load_config("Kconfiglib/tests/config_set_string")
verify_value("BOOL", "n")
verify_value("STRING", "foo bar")
# Loading a completely empty .config should reset values
c.load_config("Kconfiglib/tests/empty")
verify_value("STRING", "")
# An indented assignment in a .config should be ignored
c.load_config("Kconfiglib/tests/config_indented")
verify_value("IGNOREME", "y")
# Symbol order in headers and minimal configuration files should match
# definition order, like in .config files
c = Kconfig("Kconfiglib/tests/Korder")
c.write_autoconf(config_test_file, header="")
verify_file_contents(config_test_file, """
#define CONFIG_O 0
#define CONFIG_R 1
#define CONFIG_D 2
#define CONFIG_E 3
#define CONFIG_R2 4
#define CONFIG_I 5
#define CONFIG_N 6
#define CONFIG_G 7
"""[1:])
# Differs from defaults
c.syms["O"].set_value("-1")
c.syms["R"].set_value("-1")
c.syms["E"].set_value("-1")
c.syms["R2"].set_value("-1")
c.syms["N"].set_value("-1")
c.syms["G"].set_value("-1")
c.write_min_config(config_test_file, header="")
verify_file_contents(config_test_file, """
CONFIG_O=-1
CONFIG_R=-1
CONFIG_E=-1
CONFIG_R2=-1
CONFIG_N=-1
CONFIG_G=-1
"""[1:])
print("Testing Kconfig fetching and separation")
for c in Kconfig("Kconfiglib/tests/Kmisc", warn=False), \
Kconfig("Kconfiglib/tests/Kmisc", warn=False):
for item in c.syms["BOOL"], \
c.syms["BOOL"].nodes[0], \
c.named_choices["OPTIONAL"], \
c.named_choices["OPTIONAL"].nodes[0], \
c.syms["MENU_HOOK"].nodes[0].next, \
c.syms["COMMENT_HOOK"].nodes[0].next:
verify(item.kconfig is c,
".kconfig not properly set for " + repr(item))
print("Testing imply semantics")
c = Kconfig("Kconfiglib/tests/Kimply")
verify_value("IMPLY_DIRECT_DEPS", "y")
verify_value("UNMET_DIRECT_1", "n")
verify_value("UNMET_DIRECT_2", "n")
verify_value("UNMET_DIRECT_3", "n")
verify_value("MET_DIRECT_1", "y")
verify_value("MET_DIRECT_2", "y")
verify_value("MET_DIRECT_3", "y")
verify_value("MET_DIRECT_4", "y")
verify_value("IMPLY_COND", "y")
verify_value("IMPLIED_N_COND", "n")
verify_value("IMPLIED_M_COND", "m")
verify_value("IMPLIED_Y_COND", "y")
verify_value("IMPLY_N_1", "n")
verify_value("IMPLY_N_2", "n")
verify_value("IMPLIED_FROM_N_1", "n")
verify_value("IMPLIED_FROM_N_2", "n")
verify_value("IMPLY_M", "m")
verify_value("IMPLIED_M", "m")
verify_value("IMPLIED_M_BOOL", "y")
verify_value("IMPLY_M_TO_Y", "y")
verify_value("IMPLIED_M_TO_Y", "y")
# Test user value semantics
# Verify that IMPLIED_TRISTATE is invalidated if the direct
# dependencies change
assign_and_verify("IMPLY", 2)
assign_and_verify("DIRECT_DEP", 2)
verify_value("IMPLIED_TRISTATE", 2)
assign_and_verify("DIRECT_DEP", 0)
verify_value("IMPLIED_TRISTATE", 0)
# Set back for later tests
assign_and_verify("DIRECT_DEP", 2)
# Verify that IMPLIED_TRISTATE can be set to anything when IMPLY has value
# n, and that it gets the value n by default (for non-imply-related
# reasons)
assign_and_verify("IMPLY", 0)
assign_and_verify("IMPLIED_TRISTATE", 0)
assign_and_verify("IMPLIED_TRISTATE", 1)
assign_and_verify("IMPLIED_TRISTATE", 2)
c.syms["IMPLIED_TRISTATE"].unset_value()
verify_value("IMPLIED_TRISTATE", "n")
# Same as above for m. Anything still goes, but m by default now.
assign_and_verify("IMPLY", 1)
assign_and_verify("IMPLIED_TRISTATE", 0)
assign_and_verify("IMPLIED_TRISTATE", 1)
assign_and_verify("IMPLIED_TRISTATE", 2)
c.syms["IMPLIED_TRISTATE"].unset_value()
verify_value("IMPLIED_TRISTATE", 1)
# Same as above for y. Only n and y should be accepted. m gets promoted to
# y. Default should be y.
assign_and_verify("IMPLY", 2)
assign_and_verify("IMPLIED_TRISTATE", 0)
assign_and_verify_value("IMPLIED_TRISTATE", 1, 2)
assign_and_verify("IMPLIED_TRISTATE", 2)
c.syms["IMPLIED_TRISTATE"].unset_value()
verify_value("IMPLIED_TRISTATE", 2)
# Being implied to either m or y should give a bool the value y
c.syms["IMPLY"].unset_value()
verify_value("IMPLIED_BOOL", 0)
assign_and_verify("IMPLY", 0)
verify_value("IMPLIED_BOOL", 0)
assign_and_verify("IMPLY", 1)
verify_value("IMPLIED_BOOL", 2)
assign_and_verify("IMPLY", 2)
verify_value("IMPLIED_BOOL", 2)
# A bool implied to m or y can take the values n and y
c.syms["IMPLY"].set_value(1)
assign_and_verify("IMPLIED_BOOL", 0)
assign_and_verify("IMPLIED_BOOL", 2)
c.syms["IMPLY"].set_value(2)
assign_and_verify("IMPLIED_BOOL", 0)
assign_and_verify("IMPLIED_BOOL", 2)
print("Testing choice semantics")
# Would warn for choice value symbols defined without a type, even
# though the type is automatically derived. This is probably more
# helpful than ignoring those cases, as this feature isn't used
# deliberately anywhere from what I've seen.
c = Kconfig("Kconfiglib/tests/Kchoice", warn=False)
for name in "BOOL", "BOOL_OPT", "BOOL_M", "DEFAULTS":
verify(c.named_choices[name].orig_type == BOOL,
"choice {} should have type bool".format(name))
for name in "TRISTATE", "TRISTATE_OPT", "TRISTATE_M":
verify(c.named_choices[name].orig_type == TRISTATE,
"choice {} should have type tristate".format(name))
def select_and_verify(sym):
choice = sym.nodes[0].parent.item
choice.set_value(2)
sym.set_value(2)
verify(sym.choice.selection is sym,
sym.name + " should be the selected symbol")
verify(choice.user_selection is sym,
sym.name + " should be the user selection of the choice")
verify(sym.tri_value == 2,
sym.name + " should have value y when selected")
verify(sym.user_value == 2,
sym.name + " should have user value y when selected")
for sibling in choice.syms:
if sibling is not sym:
verify(sibling.tri_value == 0,
sibling.name + " should be n when not selected")
def select_and_verify_all(choice_name):
choice = c.named_choices[choice_name]
# Select in forward order
for sym in choice.syms:
select_and_verify(sym)
# Select in reverse order
for sym in reversed(choice.syms):
select_and_verify(sym)
def verify_mode(choice_name, no_modules_mode, modules_mode):
choice = c.named_choices[choice_name]
c.modules.set_value(0)
verify(choice.tri_value == no_modules_mode,
'Wrong mode for choice {} with no modules. Expected {}, got {}.'
.format(choice.name, no_modules_mode, choice.tri_value))
c.modules.set_value(2)
verify(choice.tri_value == modules_mode,
'Wrong mode for choice {} with modules. Expected {}, got {}.'
.format(choice.name, modules_mode, choice.tri_value))
verify_mode("BOOL", 2, 2)
verify_mode("BOOL_OPT", 0, 0)
verify_mode("TRISTATE", 2, 1)
verify_mode("TRISTATE_OPT", 0, 0)
verify_mode("BOOL_M", 0, 2)
verify_mode("TRISTATE_M", 0, 1)
# Test defaults
choice = c.named_choices["DEFAULTS"]
c.syms["TRISTATE_SYM"].set_value(0)
verify(choice.selection is c.syms["OPT_4"],
"Wrong choice default with TRISTATE_SYM = n")
c.syms["TRISTATE_SYM"].set_value(2)
verify(choice.selection is c.syms["OPT_2"],
"Wrong choice default with TRISTATE_SYM = y")
c.syms["OPT_1"].set_value(2)
verify(choice.selection is c.syms["OPT_1"],
"User selection should override defaults")
verify(c.named_choices["DEFAULTS_NOT_VISIBLE"].selection
is c.syms["OPT_8"],
"Non-visible choice symbols should cause the next default to be "
"considered")
# Test y mode selection
c.modules.set_value(2)
select_and_verify_all("BOOL")
select_and_verify_all("BOOL_OPT")
select_and_verify_all("TRISTATE")
select_and_verify_all("TRISTATE_OPT")
# For BOOL_M, the mode should have been promoted
select_and_verify_all("BOOL_M")
# Test m mode selection
c.named_choices["TRISTATE"].set_value(1)
verify(c.named_choices["TRISTATE"].tri_value == 1,
"TRISTATE choice should have mode m after explicit mode assignment")
assign_and_verify_value("T_1", 0, 0)
assign_and_verify_value("T_2", 0, 0)
assign_and_verify_value("T_1", 1, 1)
assign_and_verify_value("T_2", 1, 1)
assign_and_verify_value("T_1", 2, 1)
assign_and_verify_value("T_2", 2, 1)
# Switching to y mode should cause T_2 to become selected
c.named_choices["TRISTATE"].set_value(2)
verify_value("T_1", 0)
verify_value("T_2", 2)
# Verify that choices with no explicitly specified type get the type of the
# first contained symbol with a type
verify(c.named_choices["NO_TYPE_BOOL"].orig_type == BOOL,
"Expected first choice without explicit type to have type bool")
verify(c.named_choices["NO_TYPE_TRISTATE"].orig_type == TRISTATE,
"Expected second choice without explicit type to have type "
"tristate")
# Verify that symbols without a type in the choice get the type of the
# choice
for name in "MMT_1", "MMT_2", "MMT_4", "MMT_5":
verify(c.syms[name].orig_type == BOOL,
"Expected {} to get type bool".format(name))
verify(c.syms["MMT_3"].orig_type == TRISTATE,
"Expected MMT_3 to have type tristate")
# Verify that the default selection can change depending on the
# visibility of the choice symbols
default_with_dep_choice = c.named_choices["DEFAULT_WITH_DEP"]
verify(default_with_dep_choice.selection is c.syms["B"],
"Wrong choice default with unsatisfied deps on default")
c.syms["DEP"].set_value("y")
verify(default_with_dep_choice.selection is c.syms["A"],
"Wrong choice default with satisfied deps on default")
c.syms["DEP"].set_value("n")
verify(default_with_dep_choice.selection is c.syms["B"],
"Wrong choice default with unsatisfied deps on default (round two)")
# Verify that symbols in choices that depend on the preceding symbol aren't
# considered choice symbols
weird_choice = c.named_choices["WEIRD_SYMS"]
def verify_is_normal_choice_symbol(name):
sym = c.syms[name]
verify(sym.choice is not None and
sym in weird_choice.syms and
sym.nodes[0].parent.item is weird_choice,
"{} should be a normal choice symbol".format(sym.name))
def verify_is_weird_choice_symbol(name):
sym = c.syms[name]
verify(sym.choice is None and
sym not in weird_choice.syms,
"{} should be a weird (non-)choice symbol"
.format(sym.name))
verify_is_normal_choice_symbol("WS1")
verify_is_weird_choice_symbol("WS2")
verify_is_weird_choice_symbol("WS3")
verify_is_weird_choice_symbol("WS4")
verify_is_weird_choice_symbol("WS5")
verify_is_normal_choice_symbol("WS6")
verify_is_weird_choice_symbol("WS7")
verify_is_weird_choice_symbol("WS8")
verify_is_normal_choice_symbol("WS9")
print("Testing multi.def. property copying")
c = Kconfig("Kconfiglib/tests/Kdepcopy", warn=False)
def verify_props(desc, props, prop_names):
actual = [prop[0].name for prop in props]
expected = prop_names.split()
verify(actual == expected,
"Wrong {} properties, expected '{}', got '{}'"
.format(desc, expected, actual))
verify_props("default", c.syms["MULTIDEF"].defaults,
"A B C D E F G H I J K L M N O P Q R")
verify_props("select", c.syms["MULTIDEF"].selects,
"AA BB CC DD EE FF GG HH II JJ")
verify_props("imply", c.syms["MULTIDEF"].selects,
"AA BB CC DD EE FF GG HH II JJ")
verify_props("select", c.syms["MULTIDEF_CHOICE"].selects,
"A B C")
verify_props("range", c.syms["MULTIDEF_RANGE"].ranges,
"A B C D E F")
verify_props("default", c.choices[1].defaults,
"A B C D E")
print("Testing dependency loop detection")
# These are all expected to raise dependency loop errors
for i in range(11):
filename = "Kconfiglib/tests/Kdeploop" + str(i)
try:
Kconfig(filename)
except KconfigError as e:
if "Dependency loop" not in str(e):
fail("dependency loop in {} raised wrong KconfigError"
.format(filename))
except:
fail("dependency loop in {} raised wrong exception"
.format(filename))
else:
fail("dependency loop in {} not detected".format(filename))
# Check the most complicated message completely
try:
Kconfig("Kconfiglib/tests/Kdeploop10")
except KconfigError as e:
verify_equal(str(e), """
Dependency loop
===============
A (defined at Kconfiglib/tests/Kdeploop10:1), with definition...
config A
bool
depends on B
...depends on B (defined at Kconfiglib/tests/Kdeploop10:5), with definition...
config B
bool
depends on C = 7
...depends on C (defined at Kconfiglib/tests/Kdeploop10:9), with definition...
config C
int
range D 8
...depends on D (defined at Kconfiglib/tests/Kdeploop10:13), with definition...
config D
int
default 3 if E
default 8
...depends on E (defined at Kconfiglib/tests/Kdeploop10:18), with definition...
config E
bool
(select-related dependencies: F && G)
...depends on G (defined at Kconfiglib/tests/Kdeploop10:25), with definition...
config G
bool
depends on H
...depends on the choice symbol H (defined at Kconfiglib/tests/Kdeploop10:32), with definition...
config H
bool
prompt "H" if I && <choice>
depends on I && <choice>
...depends on the choice symbol I (defined at Kconfiglib/tests/Kdeploop10:41), with definition...
config I
bool
prompt "I" if <choice>
depends on <choice>
...depends on <choice> (defined at Kconfiglib/tests/Kdeploop10:38), with definition...
choice
bool
prompt "choice" if J
...depends on J (defined at Kconfiglib/tests/Kdeploop10:46), with definition...
config J
bool
depends on A
...depends again on A (defined at Kconfiglib/tests/Kdeploop10:1)
"""[:-1])
except:
fail("Loop detection message check raised wrong exception")
else:
fail("Loop detection message check did not raise exception")
print("Testing preprocessor")
os.environ["ENV_1"] = "env_1"
os.environ["ENV_2"] = "env_2"
os.environ["ENV_3"] = "env_3"
os.environ["ENV_4"] = "env_4"
os.environ["ENV_5"] = "n"
os.environ["ENV_6"] = "Kconfiglib/tests/empty"
os.environ["ENV_7"] = "env_7"
# We verify warnings manually
c = Kconfig("Kconfiglib/tests/Kpreprocess", warn_to_stderr=False)
def verify_variable(name, unexp_value, exp_value, recursive):
var = c.variables[name]
verify(var.value == unexp_value,
"expected variable '{}' to have the unexpanded value '{}', had "
"the value '{}'".format(name, unexp_value, var.value))
verify(var.expanded_value == exp_value,
"expected variable '{}' to have the expanded value '{}', had "
"the value '{}'".format(name, exp_value, var.expanded_value))
verify(var.is_recursive == recursive,
"{} was {}, shouldn't be"
.format(name, "recursive" if var.is_recursive else "simple"))
verify_variable("simple-recursive", "foo", "foo", True)
verify_variable("simple-immediate", "bar", "bar", False)
verify_variable("simple-recursive-2", "baz", "baz", True)
verify_variable("whitespaced", "foo", "foo", True)
verify_variable("preserve-recursive", "foo bar", "foo bar", True)
verify_variable("preserve-immediate", "foo bar", "foo bar", False)
verify_variable("recursive",
"$(foo) $(bar) $($(b-char)a$(z-char)) $(indir)",
"abc def ghi jkl mno",
True)
verify_variable("immediate", "foofoo", "foofoo", False)
verify_variable("messy-fn-res",
"$($(fn-indir)-unused-arg, a b , c d )",
'surround-rev-quote " c d " " a b " surround-rev-quote ',
True)
verify_variable("special-chars-fn-res",
"$(fn,$(comma)$(dollar)$(left-paren)foo$(right-paren))",
'",$(foo)"',
True)
verify_str(c.syms["PRINT_ME"], r"""
config PRINT_ME
string
prompt "env_1" if (FOO && BAR) || !BAZ || !QAZ
default "\"foo\"" if "foo \"bar\" baz" = ""
""")
def verify_recursive(name):
try:
c.variables[name].expanded_value
except KconfigError:
pass
else:
fail("Expected '{}' expansion to flag recursive expansion, didn't"
.format(name))
verify_recursive("rec-1")
# Indirectly verifies that it's not recursive
verify_variable("safe-fn-rec-res",
"$(safe-fn-rec,safe-fn-rec-2)",
"foo",
True)
verify_recursive("unsafe-fn-rec")
verify_variable("foo-bar-baz", "$(rhs)", "value", True)
verify_variable("space-var-res", "$(foo bar)", "value", True)
verify_variable("shell-res",
"$(shell,false && echo foo bar || echo baz qaz)",
"baz qaz",
True)
verify_variable("shell-stderr-res", "", "", False)
verify_variable("location-res",
"Kconfiglib/tests/Kpreprocess:119",
"Kconfiglib/tests/Kpreprocess:119",
False)
verify_variable("warning-res", "", "", False)
verify_variable("error-n-res", "", "", False)
try:
c.variables["error-y-res"].expanded_value
except KconfigError:
pass
else:
fail("expanding error-y-res didn't raise an exception")
# Check Kconfig.env_vars
verify_equal(c.env_vars,
set(("ENV_1", "ENV_2", "ENV_3", "ENV_4", "ENV_5", "ENV_6")))
# Check that the expected warnings were generated
verify_equal(c.warnings, [
"Kconfiglib/tests/Kpreprocess:116: warning: 'echo message on stderr >&2' wrote to stderr: message on stderr",
"Kconfiglib/tests/Kpreprocess:124: warning: a warning"
])
print("Testing KCONFIG_STRICT")
os.environ["KCONFIG_STRICT"] = "y"
c = Kconfig("Kconfiglib/tests/Kstrict", warn_to_stderr=False)
verify_equal("\n".join(c.warnings), """
warning: the int symbol INT (defined at Kconfiglib/tests/Kstrict:8) has a non-int range [UNDEF_2 (undefined), 8 (undefined)]
warning: undefined symbol UNDEF_1:
- Referenced at Kconfiglib/tests/Kstrict:4:
config BOOL
bool
prompt "foo" if DEF || !UNDEF_1
default UNDEF_2
- Referenced at Kconfiglib/tests/Kstrict:19:
menu "menu"
depends on UNDEF_1
visible if UNDEF_3
warning: undefined symbol UNDEF_2:
- Referenced at Kconfiglib/tests/Kstrict:4:
config BOOL
bool
prompt "foo" if DEF || !UNDEF_1
default UNDEF_2
- Referenced at Kconfiglib/tests/Kstrict:8:
config INT
int
range UNDEF_2 8
range 5 15
default 10
warning: undefined symbol UNDEF_3:
- Referenced at Kconfiglib/tests/Kstrict:19:
menu "menu"
depends on UNDEF_1
visible if UNDEF_3
"""[1:])
os.environ.pop("KCONFIG_STRICT")
print("\nAll selftests passed\n" if all_passed else
"\nSome selftests failed\n")
def run_compatibility_tests():
"""
Runs tests on configurations from the kernel. Tests compability with the
C implementation by comparing outputs.
"""
# Referenced inside the kernel Kconfig files.
#
# The str() makes the type of the value 'str' on both Python 2 and Python 3,
# which is nice for some later dictionary key sanity checks.
os.environ["KERNELVERSION"] = str(
subprocess.check_output("make kernelversion", shell=True)
.decode("utf-8").rstrip()
)
os.environ["CC_VERSION_TEXT"] = str(
subprocess.check_output("gcc --version | head -n1", shell=True)
.decode("utf-8").rstrip()
)
os.environ["srctree"] = "."
os.environ["CC"] = "gcc"
if not os.path.exists("scripts/kconfig/conf"):
print("\nscripts/kconfig/conf does not exist -- running "
"'make allnoconfig' to build it...")
shell("make allnoconfig")
print("Running compatibility tests...\n")
test_fns = (test_defconfig,
# Fails for a few defconfigs due to a bug in the C tools. Will
# be enabled once patches get in.
#test_min_config,
test_alldefconfig,
test_allnoconfig,
test_allnoconfig_walk,
test_allmodconfig,
test_allyesconfig,
test_sanity)
for test_fn in test_fns:
# The test description is taken from the docstring of the corresponding
# function
print(textwrap.dedent(test_fn.__doc__))
for arch, srcarch in all_arch_srcarch():
# Referenced inside the Kconfig files
os.environ["ARCH"] = arch
os.environ["SRCARCH"] = srcarch
rm_configs()
test_fn(arch, srcarch)
if all_passed:
print("All selftests and compatibility tests passed")
else:
sys.exit("Some tests failed")
def all_arch_srcarch():
for srcarch in os.listdir("arch"):
# arc and h8300 are currently broken with the C tools on linux-next as
# well. Perhaps they require cross-compilers to be installed.
#
# User-mode Linux has an unorthodox Kconfig setup that would require a
# different testing setup. Skip it too.
if srcarch in ("arc", "h8300", "um"):
continue
if os.path.exists(os.path.join("arch", srcarch, "Kconfig")):
yield (srcarch, srcarch)
# Some arches define additional ARCH settings with ARCH != SRCARCH
# (search for "Additional ARCH settings for" in the top-level Makefile)
yield ("i386", "x86")
yield ("x86_64", "x86")
yield ("sparc32", "sparc")
yield ("sparc64", "sparc")
yield ("sh64", "sh")
def test_allnoconfig(arch, srcarch):
"""
Verify that allnoconfig.py generates the same .config as
'make allnoconfig', for each architecture. Runs the script via
'make scriptconfig'.
"""
shell("make scriptconfig SCRIPT=Kconfiglib/allnoconfig.py "
"PYTHONCMD='{}'".format(sys.executable))
shell("mv .config ._config")
shell("scripts/kconfig/conf --allnoconfig Kconfig")
compare_configs(arch)
def test_allnoconfig_walk(arch, srcarch):
"""
Verify that examples/allnoconfig_walk.py generates the same .config as
'make allnoconfig', for each architecture. Runs the script via
'make scriptconfig'.
"""
shell("make scriptconfig SCRIPT=Kconfiglib/examples/allnoconfig_walk.py "
"PYTHONCMD='{}'".format(sys.executable))
shell("mv .config ._config")
shell("scripts/kconfig/conf --allnoconfig Kconfig")
compare_configs(arch)
def test_allmodconfig(arch, srcarch):
"""
Verify that allmodconfig.py generates the same .config as
'make allmodconfig', for each architecture. Runs the script via
'make scriptconfig'.
"""
shell("make scriptconfig SCRIPT=Kconfiglib/allmodconfig.py "
"PYTHONCMD='{}'".format(sys.executable))
shell("mv .config ._config")
shell("scripts/kconfig/conf --allmodconfig Kconfig")
compare_configs(arch)
def test_allyesconfig(arch, srcarch):
"""
Verify that allyesconfig.py generates the same .config as
'make allyesconfig', for each architecture. Runs the script via
'make scriptconfig'.
"""
shell("make scriptconfig SCRIPT=Kconfiglib/allyesconfig.py "
"PYTHONCMD='{}'".format(sys.executable))
shell("mv .config ._config")
shell("scripts/kconfig/conf --allyesconfig Kconfig")
compare_configs(arch)
def test_sanity(arch, srcarch):
"""
Do sanity checks on each configuration and call all public methods on all
symbols, choices, and menu nodes for all architectures to make sure we
never crash or hang.
"""
print("For {}...".format(arch))
kconf = Kconfig()
for sym in kconf.defined_syms:
verify(sym._visited == 2,
"{} has broken dependency loop detection (_visited = {})"
.format(sym.name, sym._visited))
kconf.modules
kconf.defconfig_list
kconf.defconfig_filename
kconf.enable_redun_warnings()
kconf.disable_redun_warnings()
kconf.enable_undef_warnings()
kconf.disable_undef_warnings()
kconf.enable_warnings()
kconf.disable_warnings()
kconf.enable_stderr_warnings()
kconf.disable_stderr_warnings()
kconf.mainmenu_text
kconf.unset_values()
kconf.write_autoconf("/dev/null")
# No tempfile.TemporaryDirectory in Python 2
tmpdir = tempfile.mkdtemp()
kconf.sync_deps(os.path.join(tmpdir, "deps")) # Create
kconf.sync_deps(os.path.join(tmpdir, "deps")) # Update
shutil.rmtree(tmpdir)
# Python 2/3 compatible
for key, sym in kconf.syms.items():
verify(isinstance(key, str), "weird key '{}' in syms dict".format(key))
verify(not sym.is_constant, sym.name + " in 'syms' and constant")
verify(sym not in kconf.const_syms,
sym.name + " in both 'syms' and 'const_syms'")
for dep in sym._dependents:
verify(not dep.is_constant,
"the constant symbol {} depends on {}"
.format(dep.name, sym.name))
sym.__repr__()
sym.__str__()
sym.assignable
kconf.disable_warnings()
sym.set_value(2)
sym.set_value("foo")
sym.unset_value()
kconf.enable_warnings()
sym.str_value
sym.tri_value
sym.type
sym.user_value
sym.visibility
for sym in kconf.defined_syms:
verify(sym.nodes, sym.name + " is defined but lacks menu nodes")
verify(not (sym.orig_type not in (BOOL, TRISTATE) and sym.choice),
sym.name + " is a choice symbol but not bool/tristate")
for key, sym in kconf.const_syms.items():
verify(isinstance(key, str),
"weird key '{}' in const_syms dict".format(key))
verify(sym.is_constant,
'"{}" is in const_syms but not marked constant'
.format(sym.name))
verify(not sym.nodes,
'"{}" is constant but has menu nodes'.format(sym.name))
verify(not sym._dependents,
'"{}" is constant but is a dependency of some symbol'
.format(sym.name))
verify(not sym.choice,
'"{}" is constant and a choice symbol'.format(sym.name))
sym.__repr__()
sym.__str__()
sym.assignable
kconf.disable_warnings()
sym.set_value(2)
sym.set_value("foo")
sym.unset_value()
kconf.enable_warnings()
sym.str_value
sym.tri_value
sym.type
sym.visibility
for choice in kconf.choices:
for sym in choice.syms:
verify(sym.choice is choice,
"{0} is in choice.syms but 'sym.choice' is not the choice"
.format(sym.name))
verify(sym.type in (BOOL, TRISTATE),
"{} is a choice symbol but is not a bool/tristate"
.format(sym.name))
choice.__str__()
choice.__repr__()
choice.str_value
choice.tri_value
choice.user_value
choice.assignable
choice.selection
choice.type
choice.visibility
# Menu nodes
node = kconf.top_node
while 1:
# Everything else should be well exercised elsewhere
node.__repr__()
node.__str__()
verify(isinstance(node.item, (Symbol, Choice)) or \
node.item in (MENU, COMMENT),
"'{}' appeared as a menu item".format(node.item))
if node.list is not None:
node = node.list
elif node.next is not None:
node = node.next
else:
while node.parent is not None:
node = node.parent
if node.next is not None:
node = node.next
break
else:
break
def test_alldefconfig(arch, srcarch):
"""
Verify that alldefconfig.py generates the same .config as
'make alldefconfig', for each architecture. Runs the script via
'make scriptconfig'.
"""
shell("make scriptconfig SCRIPT=Kconfiglib/alldefconfig.py "
"PYTHONCMD='{}'".format(sys.executable))
shell("mv .config ._config")
shell("scripts/kconfig/conf --alldefconfig Kconfig")
compare_configs(arch)
def test_defconfig(arch, srcarch):
"""
Verify that Kconfiglib generates the same .config as scripts/kconfig/conf,
for each architecture/defconfig pair. In obsessive mode, this test includes
nonsensical groupings of arches with defconfigs from other arches (every
arch/defconfig combination) and takes an order of magnitude longer time to
run.
With logging enabled, this test appends any failures to a file
test_defconfig_fails in the root.
"""
kconf = Kconfig()
if obsessive:
defconfigs = []
# Collect all defconfigs. This could be done once instead, but it's
# a speedy operation comparatively.
for srcarch_ in os.listdir("arch"):
defconfigs.extend(defconfig_files(srcarch_))
else:
defconfigs = defconfig_files(srcarch)
# Test architecture for each defconfig
for defconfig in defconfigs:
rm_configs()
kconf.load_config(defconfig)
kconf.write_config("._config")
shell("scripts/kconfig/conf --defconfig='{}' Kconfig".
format(defconfig))
arch_defconfig_str = " {:14}with {:60} ".format(arch, defconfig)
if equal_configs():
print(arch_defconfig_str + "OK")
else:
print(arch_defconfig_str + "FAIL")
fail()
if log:
with open("test_defconfig_fails", "a") as fail_log:
fail_log.write("{} with {} did not match\n"
.format(arch, defconfig))
def test_min_config(arch, srcarch):
"""
Verify that Kconfiglib generates the same .config as 'make savedefconfig'
for each architecture/defconfig pair.
"""
kconf = Kconfig()
if obsessive_min_config:
defconfigs = []
for srcarch_ in os.listdir("arch"):
defconfigs.extend(defconfig_files(srcarch_))
else:
defconfigs = defconfig_files(srcarch)
for defconfig in defconfigs:
rm_configs()
kconf.load_config(defconfig)
kconf.write_min_config("._config")
shell("cp {} .config".format(defconfig))
shell("scripts/kconfig/conf --savedefconfig=.config Kconfig")
arch_defconfig_str = " {:14}with {:60} ".format(arch, defconfig)
if equal_configs():
print(arch_defconfig_str + "OK")
else:
print(arch_defconfig_str + "FAIL")
#
# Helper functions
#
def defconfig_files(srcarch):
# Yields a list of defconfig file filenames for a particular srcarch
# subdirectory (arch/<srcarch>/)
srcarch_dir = os.path.join("arch", srcarch)
# Some arches have a defconfig in the root of their arch/<arch>/ directory
root_defconfig = os.path.join(srcarch_dir, "defconfig")
if os.path.exists(root_defconfig):
yield root_defconfig
# Assume all files in the arch/<arch>/configs/ directory (if it exists) are
# configurations
defconfigs_dir = os.path.join(srcarch_dir, "configs")
if not os.path.isdir(defconfigs_dir):
return
for dirpath, _, filenames in os.walk(defconfigs_dir):
for filename in filenames:
yield os.path.join(dirpath, filename)
def rm_configs():
"""
Delete any old ".config" (generated by the C implementation) and
"._config" (generated by us), if present.
"""
def rm_if_exists(f):
if os.path.exists(f):
os.remove(f)
rm_if_exists(".config")
rm_if_exists("._config")
def compare_configs(arch):
if equal_configs():
print("{:14}OK".format(arch))
else:
print("{:14}FAIL".format(arch))
fail()
def equal_configs():
with open(".config") as f:
their = f.readlines()
# Strip the header generated by 'conf'
i = 0
for line in their:
if not line.startswith("#") or \
re.match(r"# CONFIG_(\w+) is not set", line):
break
i += 1
their = their[i:]
try:
f = open("._config")
except IOError as e:
if e.errno != errno.ENOENT:
raise
print("._config not found. Did you forget to apply the Makefile patch?")
return False
else:
with f:
# [1:] strips the default header
our = f.readlines()[1:]
if their == our:
return True
# Print a unified diff to help debugging
print("Mismatched .config's! Unified diff:")
sys.stdout.writelines(difflib.unified_diff(their, our, fromfile="their",
tofile="our"))
return False
if __name__ == "__main__":
run_tests()
| 32.277778 | 272 | 0.62105 |
# service.
from kconfiglib import Kconfig, Symbol, Choice, COMMENT, MENU, MenuNode, \
BOOL, TRISTATE, HEX, STRING, \
TRI_TO_STR, \
escape, unescape, \
expr_str, expr_value, expr_items, split_expr, \
_ordered_unique, \
OR, AND, \
KconfigError
import difflib
import errno
import os
import platform
import re
import shutil
import subprocess
import sys
import tempfile
import textwrap
def shell(cmd):
with open(os.devnull, "w") as devnull:
subprocess.call(cmd, shell=True, stdout=devnull, stderr=devnull)
all_passed = True
def fail(msg=None):
global all_passed
all_passed = False
if msg is not None:
print("fail: " + msg)
def verify(cond, msg):
if not cond:
fail(msg)
def verify_equal(x, y):
if x != y:
fail("'{}' does not equal '{}'".format(x, y))
# Prevent accidental loading of configuration files by removing
# KCONFIG_ALLCONFIG from the environment
os.environ.pop("KCONFIG_ALLCONFIG", None)
obsessive = False
obsessive_min_config = False
log = False
def run_tests():
global obsessive, log
for s in sys.argv[1:]:
if s == "obsessive":
obsessive = True
print("Obsessive mode enabled")
elif s == "obsessive-min-config":
obsessive_min_config = True
print("Obsessive minimal config mode enabled")
elif s == "log":
log = True
print("Log mode enabled")
else:
print("Unrecognized option '{}'".format(s))
return
run_selftests()
run_compatibility_tests()
def run_selftests():
#
# Common helper functions. These all expect 'c' to hold the current
# configuration.
#
def verify_value(sym_name, val):
if isinstance(val, int):
val = TRI_TO_STR[val]
sym = c.syms[sym_name]
verify(sym.str_value == val,
'expected {} to have the value "{}", had the value "{}"'
.format(sym_name, val, sym.str_value))
def assign_and_verify_value(sym_name, val, new_val):
if isinstance(new_val, int):
new_val = TRI_TO_STR[new_val]
sym = c.syms[sym_name]
old_val = sym.str_value
verify(sym.set_value(val),
"assigning '{}' to {} unexpectedly failed"
.format(val, sym_name))
verify(sym.str_value == new_val,
"expected {} to have the value '{}' after being assigned the "
"value '{}'. Instead, the value is '{}'. The old value was "
"'{}'."
.format(sym_name, new_val, val, sym.str_value, old_val))
def assign_and_verify(sym_name, user_val):
assign_and_verify_value(sym_name, user_val, user_val)
def assign_and_verify_user_value(sym_name, val, user_val, valid):
sym = c.syms[sym_name]
sym_old_user_val = sym.user_value
verify(sym.set_value(val) == valid,
"expected the user value '{}' to be {} for {}, was not"
.format(val, "valid" if valid else "invalid", sym_name))
verify(sym.user_value == user_val,
"the assigned user value '{}' wasn't reflected in user_value "
"on the symbol {}. Instead, the new user_value was '{}'. The "
"old user value was '{}'."
.format(user_val, sym_name, sym.user_value, sym_old_user_val))
print("Testing string literal lexing")
c = Kconfig("Kconfiglib/tests/empty")
def verify_string_lex(s, expected):
res = c._tokenize("if " + s)[1].name
verify(res == expected,
"expected <{}> to produced the constant symbol <{}>, "
'produced <{}>'.format(s[1:-1], expected, res))
verify_string_lex(r""" "" """, "")
verify_string_lex(r""" '' """, "")
verify_string_lex(r""" "a" """, "a")
verify_string_lex(r""" 'a' """, "a")
verify_string_lex(r""" "ab" """, "ab")
verify_string_lex(r""" 'ab' """, "ab")
verify_string_lex(r""" "abc" """, "abc")
verify_string_lex(r""" 'abc' """, "abc")
verify_string_lex(r""" "'" """, "'")
verify_string_lex(r""" '"' """, '"')
verify_string_lex(r""" "\"" """, '"')
verify_string_lex(r""" '\'' """, "'")
verify_string_lex(r""" "\"\"" """, '""')
verify_string_lex(r""" '\'\'' """, "''")
verify_string_lex(r""" "\'" """, "'")
verify_string_lex(r""" '\"' """, '"')
verify_string_lex(r""" "\\" """, "\\")
verify_string_lex(r""" '\\' """, "\\")
verify_string_lex(r""" "\a\\'\b\c\"'d" """, 'a\\\'bc"\'d')
verify_string_lex(r""" '\a\\"\b\c\'"d' """, "a\\\"bc'\"d")
def verify_string_bad(s):
try:
c.eval_string(s)
except KconfigError:
pass
else:
fail("expected tokenization of {} to fail, didn't".format(s[1:-1]))
verify_string_bad(r""" " """)
verify_string_bad(r""" ' """)
verify_string_bad(r""" "' """)
verify_string_bad(r""" '" """)
verify_string_bad(r""" "\" """)
verify_string_bad(r""" '\' """)
verify_string_bad(r""" "foo """)
verify_string_bad(r""" 'foo """)
print("Testing escape() and unescape()")
def verify_escape_unescape(s, sesc):
# Verify that 's' escapes to 'sesc' and that 'sesc' unescapes to 's'
verify_equal(escape(s), sesc)
verify_equal(unescape(sesc), s)
verify_escape_unescape(r'' , r'' )
verify_escape_unescape(r'foo' , r'foo' )
verify_escape_unescape(r'"' , r'\"' )
verify_escape_unescape(r'""' , r'\"\"' )
verify_escape_unescape('\\' , r'\\' )
verify_escape_unescape(r'\\' , r'\\\\' )
verify_escape_unescape(r'\"' , r'\\\"' )
verify_escape_unescape(r'"ab\cd"ef"', r'\"ab\\cd\"ef\"')
# Backslashes before any character should be unescaped, not just before "
# and \
verify_equal(unescape(r"\afoo\b\c\\d\\\e\\\\f"), r"afoobc\d\e\\f")
print("Testing _ordered_unique()")
verify_equal(_ordered_unique([]), [])
verify_equal(_ordered_unique([1]), [1])
verify_equal(_ordered_unique([1, 2]), [1, 2])
verify_equal(_ordered_unique([1, 1]), [1])
verify_equal(_ordered_unique([1, 1, 2]), [1, 2])
verify_equal(_ordered_unique([1, 2, 1]), [1, 2])
verify_equal(_ordered_unique([1, 2, 2]), [1, 2])
verify_equal(_ordered_unique([1, 2, 3, 2, 1, 2, 3, 4, 3, 2, 1, 0]),
[1, 2, 3, 4, 0])
print("Testing expression evaluation")
c = Kconfig("Kconfiglib/tests/Keval", warn=False)
def verify_eval(expr, val):
res = c.eval_string(expr)
verify(res == val,
"'{}' evaluated to {}, expected {}".format(expr, res, val))
# No modules
verify_eval("n", 0)
verify_eval("m", 0)
verify_eval("y", 2)
verify_eval("'n'", 0)
verify_eval("'m'", 0)
verify_eval("'y'", 2)
verify_eval("M", 2)
# Modules
c.modules.set_value(2)
verify_eval("n", 0)
verify_eval("m", 1)
verify_eval("y", 2)
verify_eval("'n'", 0)
verify_eval("'m'", 1)
verify_eval("'y'", 2)
verify_eval("M", 1)
verify_eval("(Y || N) && (m && y)", 1)
# Non-bool/non-tristate symbols are always n in a tristate sense
verify_eval("Y_STRING", 0)
verify_eval("Y_STRING || m", 1)
# As are all constants besides y and m
verify_eval('"foo"', 0)
verify_eval('"foo" || "bar"', 0)
verify_eval('"foo" || m', 1)
# Test equality for symbols
verify_eval("N = N", 2)
verify_eval("N = n", 2)
verify_eval("N = 'n'", 2)
verify_eval("N != N", 0)
verify_eval("N != n", 0)
verify_eval("N != 'n'", 0)
verify_eval("M = M", 2)
verify_eval("M = m", 2)
verify_eval("M = 'm'", 2)
verify_eval("M != M", 0)
verify_eval("M != m", 0)
verify_eval("M != 'm'", 0)
verify_eval("Y = Y", 2)
verify_eval("Y = y", 2)
verify_eval("Y = 'y'", 2)
verify_eval("Y != Y", 0)
verify_eval("Y != y", 0)
verify_eval("Y != 'y'", 0)
verify_eval("N != M", 2)
verify_eval("N != Y", 2)
verify_eval("M != Y", 2)
verify_eval("Y_STRING = y", 2)
verify_eval("Y_STRING = 'y'", 2)
verify_eval('FOO_BAR_STRING = "foo bar"', 2)
verify_eval('FOO_BAR_STRING != "foo bar baz"', 2)
verify_eval('INT_37 = 37', 2)
verify_eval("INT_37 = '37'", 2)
verify_eval('HEX_0X37 = 0x37', 2)
verify_eval("HEX_0X37 = '0x37'", 2)
# These should also hold after 31847b67 (kconfig: allow use of relations
# other than (in)equality)
verify_eval("HEX_0X37 = '0x037'", 2)
verify_eval("HEX_0X37 = '0x0037'", 2)
# Constant symbol comparisons
verify_eval('"foo" != "bar"', 2)
verify_eval('"foo" = "bar"', 0)
verify_eval('"foo" = "foo"', 2)
# Undefined symbols get their name as their value
c.disable_warnings()
verify_eval("'not_defined' = not_defined", 2)
verify_eval("not_defined_2 = not_defined_2", 2)
verify_eval("not_defined_1 != not_defined_2", 2)
# Test less than/greater than
# Basic evaluation
verify_eval("INT_37 < 38", 2)
verify_eval("38 < INT_37", 0)
verify_eval("INT_37 < '38'", 2)
verify_eval("'38' < INT_37", 0)
verify_eval("INT_37 < 138", 2)
verify_eval("138 < INT_37", 0)
verify_eval("INT_37 < '138'", 2)
verify_eval("'138' < INT_37", 0)
verify_eval("INT_37 < -138", 0)
verify_eval("-138 < INT_37", 2)
verify_eval("INT_37 < '-138'", 0)
verify_eval("'-138' < INT_37", 2)
verify_eval("INT_37 < 37", 0)
verify_eval("37 < INT_37", 0)
verify_eval("INT_37 < 36", 0)
verify_eval("36 < INT_37", 2)
# Different formats in comparison
verify_eval("INT_37 < 0x26", 2) # 38
verify_eval("INT_37 < 0x25", 0) # 37
verify_eval("INT_37 < 0x24", 0) # 36
verify_eval("HEX_0X37 < 56", 2) # 0x38
verify_eval("HEX_0X37 < 55", 0) # 0x37
verify_eval("HEX_0X37 < 54", 0) # 0x36
# Other int comparisons
verify_eval("INT_37 <= 38", 2)
verify_eval("INT_37 <= 37", 2)
verify_eval("INT_37 <= 36", 0)
verify_eval("INT_37 > 38", 0)
verify_eval("INT_37 > 37", 0)
verify_eval("INT_37 > 36", 2)
verify_eval("INT_37 >= 38", 0)
verify_eval("INT_37 >= 37", 2)
verify_eval("INT_37 >= 36", 2)
# Other hex comparisons
verify_eval("HEX_0X37 <= 0x38", 2)
verify_eval("HEX_0X37 <= 0x37", 2)
verify_eval("HEX_0X37 <= 0x36", 0)
verify_eval("HEX_0X37 > 0x38", 0)
verify_eval("HEX_0X37 > 0x37", 0)
verify_eval("HEX_0X37 > 0x36", 2)
verify_eval("HEX_0X37 >= 0x38", 0)
verify_eval("HEX_0X37 >= 0x37", 2)
verify_eval("HEX_0X37 >= 0x36", 2)
# A hex holding a value without a "0x" prefix should still be treated as
# hexadecimal
verify_eval("HEX_37 < 0x38", 2)
verify_eval("HEX_37 < 0x37", 0)
verify_eval("HEX_37 < 0x36", 0)
# Symbol comparisons
verify_eval("INT_37 < HEX_0X37", 2)
verify_eval("INT_37 > HEX_0X37", 0)
verify_eval("HEX_0X37 < INT_37 ", 0)
verify_eval("HEX_0X37 > INT_37 ", 2)
verify_eval("INT_37 < INT_37 ", 0)
verify_eval("INT_37 <= INT_37 ", 2)
verify_eval("INT_37 > INT_37 ", 0)
verify_eval("INT_37 <= INT_37 ", 2)
# Tristate value comparisons
verify_eval("n < n", 0)
verify_eval("n < m", 2)
verify_eval("n < y", 2)
verify_eval("n < N", 0)
verify_eval("n < M", 2)
verify_eval("n < Y", 2)
verify_eval("0 > n", 0)
verify_eval("1 > n", 2)
verify_eval("2 > n", 2)
verify_eval("m < n", 0)
verify_eval("m < m", 0)
verify_eval("m < y", 2)
# Strings compare lexicographically
verify_eval("'aa' < 'ab'", 2)
verify_eval("'aa' > 'ab'", 0)
verify_eval("'ab' < 'aa'", 0)
verify_eval("'ab' > 'aa'", 2)
# Comparisons where one of the operands doesn't parse as a number also give
# a lexicographic comparison
verify_eval("INT_37 < '37a' ", 2)
verify_eval("'37a' > INT_37", 2)
verify_eval("INT_37 <= '37a' ", 2)
verify_eval("'37a' >= INT_37", 2)
verify_eval("INT_37 >= '37a' ", 0)
verify_eval("INT_37 > '37a' ", 0)
verify_eval("'37a' < INT_37", 0)
verify_eval("'37a' <= INT_37", 0)
def verify_eval_bad(expr):
try:
c.eval_string(expr)
except KconfigError:
pass
else:
fail('expected eval_string("{}") to throw KconfigError, '
"didn't".format(expr))
# Verify that some bad stuff throws KconfigError's
verify_eval_bad("")
verify_eval_bad("&")
verify_eval_bad("|")
verify_eval_bad("!")
verify_eval_bad("(")
verify_eval_bad(")")
verify_eval_bad("=")
verify_eval_bad("(X")
verify_eval_bad("X)")
verify_eval_bad("X X")
verify_eval_bad("!X X")
verify_eval_bad("X !X")
verify_eval_bad("(X) X")
verify_eval_bad("X &&")
verify_eval_bad("&& X")
verify_eval_bad("X && && X")
verify_eval_bad("X && !&&")
verify_eval_bad("X ||")
verify_eval_bad("|| X")
print("Testing Symbol.__str__()/custom_str() and def_{int,hex,string}")
def verify_str(item, s):
verify_equal(str(item), s[1:])
def verify_custom_str(item, s):
verify_equal(item.custom_str(lambda sc: "[{}]".format(sc.name)), s[1:])
c = Kconfig("Kconfiglib/tests/Kstr", warn=False)
c.modules.set_value(2)
verify_str(c.syms["UNDEFINED"], """
""")
verify_str(c.syms["BASIC_NO_PROMPT"], """
config BASIC_NO_PROMPT
bool
help
blah blah
blah blah blah
blah
""")
verify_str(c.syms["BASIC_PROMPT"], """
config BASIC_PROMPT
bool
prompt "basic"
""")
verify_str(c.syms["ADVANCED"], """
config ADVANCED
tristate
prompt "prompt" if DEP
default DEFAULT_1
default DEFAULT_2 if DEP
select SELECTED_1
select SELECTED_2 if DEP
imply IMPLIED_1
imply IMPLIED_2 if DEP
help
first help text
config ADVANCED
tristate
prompt "prompt 2"
menuconfig ADVANCED
tristate
prompt "prompt 3"
config ADVANCED
tristate
depends on (A || !B || (C && D) || !(E && F) || G = H || (I && !J && (K || L) && !(M || N) && O = P)) && DEP4 && DEP3
help
second help text
""")
verify_custom_str(c.syms["ADVANCED"], """
config ADVANCED
tristate
prompt "prompt" if [DEP]
default [DEFAULT_1]
default [DEFAULT_2] if [DEP]
select [SELECTED_1]
select [SELECTED_2] if [DEP]
imply [IMPLIED_1]
imply [IMPLIED_2] if [DEP]
help
first help text
config ADVANCED
tristate
prompt "prompt 2"
menuconfig ADVANCED
tristate
prompt "prompt 3"
config ADVANCED
tristate
depends on ([A] || ![B] || ([C] && [D]) || !([E] && [F]) || [G] = [H] || ([I] && ![J] && ([K] || [L]) && !([M] || [N]) && [O] = [P])) && [DEP4] && [DEP3]
help
second help text
""")
verify_str(c.syms["ONLY_DIRECT_DEPS"], """
config ONLY_DIRECT_DEPS
int
depends on DEP1 && DEP2
""")
verify_str(c.syms["STRING"], """
config STRING
string
default "foo"
default "bar" if DEP
default STRING2
default STRING3 if DEP
""")
verify_str(c.syms["INT"], """
config INT
int
range 1 2
range FOO BAR
range BAZ QAZ if DEP
default 7 if DEP
""")
verify_str(c.syms["HEX"], """
config HEX
hex
range 0x100 0x200
range FOO BAR
range BAZ QAZ if DEP
default 0x123
""")
verify_str(c.modules, """
config MODULES
bool
prompt "MODULES"
option modules
""")
verify_str(c.syms["OPTIONS"], """
config OPTIONS
option allnoconfig_y
option defconfig_list
option env="ENV"
""")
verify_str(c.syms["CORRECT_PROP_LOCS_BOOL"], """
config CORRECT_PROP_LOCS_BOOL
bool
prompt "prompt 1" if LOC_1
default DEFAULT_1 if LOC_1
default DEFAULT_2 if LOC_1
select SELECT_1 if LOC_1
select SELECT_2 if LOC_1
imply IMPLY_1 if LOC_1
imply IMPLY_2 if LOC_1
depends on LOC_1
help
help 1
menuconfig CORRECT_PROP_LOCS_BOOL
bool
prompt "prompt 2" if LOC_2
default DEFAULT_3 if LOC_2
default DEFAULT_4 if LOC_2
select SELECT_3 if LOC_2
select SELECT_4 if LOC_2
imply IMPLY_3 if LOC_2
imply IMPLY_4 if LOC_2
depends on LOC_2
help
help 2
config CORRECT_PROP_LOCS_BOOL
bool
prompt "prompt 3" if LOC_3
default DEFAULT_5 if LOC_3
default DEFAULT_6 if LOC_3
select SELECT_5 if LOC_3
select SELECT_6 if LOC_3
imply IMPLY_5 if LOC_3
imply IMPLY_6 if LOC_3
depends on LOC_3
help
help 2
""")
verify_str(c.syms["CORRECT_PROP_LOCS_INT"], """
config CORRECT_PROP_LOCS_INT
int
range 1 2 if LOC_1
range 3 4 if LOC_1
depends on LOC_1
config CORRECT_PROP_LOCS_INT
int
range 5 6 if LOC_2
range 7 8 if LOC_2
depends on LOC_2
""")
verify_custom_str(c.syms["CORRECT_PROP_LOCS_INT"], """
config CORRECT_PROP_LOCS_INT
int
range [1] [2] if [LOC_1]
range [3] [4] if [LOC_1]
depends on [LOC_1]
config CORRECT_PROP_LOCS_INT
int
range [5] [6] if [LOC_2]
range [7] [8] if [LOC_2]
depends on [LOC_2]
""")
print("Testing Choice.__str__()/custom_str()")
verify_str(c.named_choices["CHOICE"], """
choice CHOICE
tristate
prompt "foo"
default CHOICE_1
default CHOICE_2 if dep
""")
verify_str(c.named_choices["CHOICE"].nodes[0].next.item, """
choice
tristate
prompt "no name"
optional
""")
verify_str(c.named_choices["CORRECT_PROP_LOCS_CHOICE"], """
choice CORRECT_PROP_LOCS_CHOICE
bool
default CHOICE_3 if LOC_1
depends on LOC_1
choice CORRECT_PROP_LOCS_CHOICE
bool
default CHOICE_4 if LOC_2
depends on LOC_2
choice CORRECT_PROP_LOCS_CHOICE
bool
default CHOICE_5 if LOC_3
depends on LOC_3
""")
verify_custom_str(c.named_choices["CORRECT_PROP_LOCS_CHOICE"], """
choice CORRECT_PROP_LOCS_CHOICE
bool
default [CHOICE_3] if [LOC_1]
depends on [LOC_1]
choice CORRECT_PROP_LOCS_CHOICE
bool
default [CHOICE_4] if [LOC_2]
depends on [LOC_2]
choice CORRECT_PROP_LOCS_CHOICE
bool
default [CHOICE_5] if [LOC_3]
depends on [LOC_3]
""")
print("Testing MenuNode.__str__()/custom_str() for menus and comments")
verify_str(c.syms["SIMPLE_MENU_HOOK"].nodes[0].next, """
menu "simple menu"
""")
verify_str(c.syms["ADVANCED_MENU_HOOK"].nodes[0].next, """
menu "advanced menu"
depends on A
visible if B && (C || D)
""")
verify_custom_str(c.syms["ADVANCED_MENU_HOOK"].nodes[0].next, """
menu "advanced menu"
depends on [A]
visible if [B] && ([C] || [D])
""")
verify_str(c.syms["SIMPLE_COMMENT_HOOK"].nodes[0].next, """
comment "simple comment"
""")
verify_str(c.syms["ADVANCED_COMMENT_HOOK"].nodes[0].next, """
comment "advanced comment"
depends on A && B
""")
verify_custom_str(c.syms["ADVANCED_COMMENT_HOOK"].nodes[0].next, """
comment "advanced comment"
depends on [A] && [B]
""")
print("Testing Symbol.__repr__()")
def verify_repr(item, s):
verify_equal(repr(item) + "\n", s[1:])
c = Kconfig("Kconfiglib/tests/Krepr", warn=False)
verify_repr(c.n, """
<symbol n, tristate, value n, constant>
""")
verify_repr(c.m, """
<symbol m, tristate, value m, constant>
""")
verify_repr(c.y, """
<symbol y, tristate, value y, constant>
""")
verify_repr(c.syms["UNDEFINED"], """
<symbol UNDEFINED, unknown, value "UNDEFINED", visibility n, direct deps n, undefined>
""")
verify_repr(c.syms["BASIC"], """
<symbol BASIC, bool, value y, visibility n, direct deps y, Kconfiglib/tests/Krepr:9>
""")
verify_repr(c.syms["VISIBLE"], """
<symbol VISIBLE, bool, "visible", value n, visibility y, direct deps y, Kconfiglib/tests/Krepr:14>
""")
c.syms["VISIBLE"].set_value(2)
verify_repr(c.syms["VISIBLE"], """
<symbol VISIBLE, bool, "visible", value y, user value y, visibility y, direct deps y, Kconfiglib/tests/Krepr:14>
""")
verify_repr(c.syms["DIR_DEP_N"], """
<symbol DIR_DEP_N, unknown, value "DIR_DEP_N", visibility n, direct deps n, Kconfiglib/tests/Krepr:17>
""")
verify_repr(c.syms["OPTIONS"], """
<symbol OPTIONS, unknown, value "OPTIONS", visibility n, allnoconfig_y, is the defconfig_list symbol, from environment variable ENV, direct deps y, Kconfiglib/tests/Krepr:20>
""")
verify_repr(c.syms["MULTI_DEF"], """
<symbol MULTI_DEF, unknown, value "MULTI_DEF", visibility n, direct deps y, Kconfiglib/tests/Krepr:25, Kconfiglib/tests/Krepr:26>
""")
verify_repr(c.syms["CHOICE_1"], """
<symbol CHOICE_1, tristate, "choice sym", value n, visibility m, choice symbol, direct deps m, Kconfiglib/tests/Krepr:33>
""")
verify_repr(c.modules, """
<symbol MODULES, bool, value y, visibility n, is the modules symbol, direct deps y, Kconfiglib/tests/Krepr:1>
""")
print("Testing Choice.__repr__()")
verify_repr(c.named_choices["CHOICE"], """
<choice CHOICE, tristate, "choice", mode m, visibility y, Kconfiglib/tests/Krepr:30>
""")
c.named_choices["CHOICE"].set_value(2)
verify_repr(c.named_choices["CHOICE"], """
<choice CHOICE, tristate, "choice", mode y, user mode y, CHOICE_1 selected, visibility y, Kconfiglib/tests/Krepr:30>
""")
c.syms["CHOICE_2"].set_value(2)
verify_repr(c.named_choices["CHOICE"], """
<choice CHOICE, tristate, "choice", mode y, user mode y, CHOICE_2 selected, CHOICE_2 selected by user, visibility y, Kconfiglib/tests/Krepr:30>
""")
c.named_choices["CHOICE"].set_value(1)
verify_repr(c.named_choices["CHOICE"], """
<choice CHOICE, tristate, "choice", mode m, user mode m, CHOICE_2 selected by user (overridden), visibility y, Kconfiglib/tests/Krepr:30>
""")
verify_repr(c.syms["CHOICE_HOOK"].nodes[0].next.item, """
<choice, tristate, "optional choice", mode n, visibility n, optional, Kconfiglib/tests/Krepr:43>
""")
print("Testing MenuNode.__repr__()")
verify_repr(c.syms["BASIC"].nodes[0], """
<menu node for symbol BASIC, deps y, has help, has next, Kconfiglib/tests/Krepr:9>
""")
verify_repr(c.syms["DIR_DEP_N"].nodes[0], """
<menu node for symbol DIR_DEP_N, deps n, has next, Kconfiglib/tests/Krepr:17>
""")
verify_repr(c.syms["MULTI_DEF"].nodes[0], """
<menu node for symbol MULTI_DEF, deps y, has next, Kconfiglib/tests/Krepr:25>
""")
verify_repr(c.syms["MULTI_DEF"].nodes[1], """
<menu node for symbol MULTI_DEF, deps y, has next, Kconfiglib/tests/Krepr:26>
""")
verify_repr(c.syms["MENUCONFIG"].nodes[0], """
<menu node for symbol MENUCONFIG, is menuconfig, deps y, has next, Kconfiglib/tests/Krepr:28>
""")
verify_repr(c.named_choices["CHOICE"].nodes[0], """
<menu node for choice CHOICE, prompt "choice" (visibility y), deps y, has child, has next, Kconfiglib/tests/Krepr:30>
""")
verify_repr(c.syms["CHOICE_HOOK"].nodes[0].next, """
<menu node for choice, prompt "optional choice" (visibility n), deps y, has next, Kconfiglib/tests/Krepr:43>
""")
verify_repr(c.syms["NO_VISIBLE_IF_HOOK"].nodes[0].next, """
<menu node for menu, prompt "no visible if" (visibility y), deps y, 'visible if' deps y, has next, Kconfiglib/tests/Krepr:50>
""")
verify_repr(c.syms["VISIBLE_IF_HOOK"].nodes[0].next, """
<menu node for menu, prompt "visible if" (visibility y), deps y, 'visible if' deps m, has next, Kconfiglib/tests/Krepr:55>
""")
verify_repr(c.syms["COMMENT_HOOK"].nodes[0].next, """
<menu node for comment, prompt "comment" (visibility y), deps y, Kconfiglib/tests/Krepr:61>
""")
print("Testing Kconfig.__repr__()")
verify_repr(c, """
<configuration with 14 symbols, main menu prompt "Main menu", srctree is current directory, config symbol prefix "CONFIG_", warnings disabled, printing of warnings to stderr enabled, undef. symbol assignment warnings disabled, redundant symbol assignment warnings enabled>
""")
os.environ["srctree"] = "Kconfiglib"
os.environ["CONFIG_"] = "CONFIG_ value"
c = Kconfig("tests/Krepr", warn=False)
c.enable_warnings()
c.disable_stderr_warnings()
c.disable_redun_warnings()
c.enable_undef_warnings()
verify_repr(c, """
<configuration with 14 symbols, main menu prompt "Main menu", srctree "Kconfiglib", config symbol prefix "CONFIG_ value", warnings enabled, printing of warnings to stderr disabled, undef. symbol assignment warnings enabled, redundant symbol assignment warnings disabled>
""")
os.environ.pop("srctree", None)
os.environ.pop("CONFIG_", None)
print("Testing tricky help strings")
c = Kconfig("Kconfiglib/tests/Khelp")
def verify_help(node, s):
verify_equal(node.help, s[1:])
verify_help(c.syms["TWO_HELP_STRINGS"].nodes[0], """
first help string
""")
verify_help(c.syms["TWO_HELP_STRINGS"].nodes[1], """
second help string
""")
verify_help(c.syms["NO_BLANK_AFTER_HELP"].nodes[0], """
help for
NO_BLANK_AFTER_HELP
""")
verify_help(c.named_choices["CHOICE_HELP"].nodes[0], """
help for
CHOICE_HELP
""")
verify_help(c.syms["HELP_TERMINATED_BY_COMMENT"].nodes[0], """
a
b
c
""")
verify_help(c.syms["TRICKY_HELP"].nodes[0], """
a
b
c
d
e
f
g
h
i
""")
print("Testing locations, source/rsource/gsource/grsource, and "
"Kconfig.kconfig_filenames")
def verify_locations(nodes, *expected_locs):
verify(len(nodes) == len(expected_locs),
"Wrong number of locations for " + repr(nodes))
for node, expected_loc in zip(nodes, expected_locs):
node_loc = "{}:{}".format(node.filename, node.linenr)
verify(node_loc == expected_loc,
"expected {} to have the location {}, had the location {}"
.format(repr(node), expected_loc, node_loc))
# Expanded in the 'source' statement in Klocation
os.environ["TESTS_DIR_FROM_ENV"] = "tests"
os.environ["SUB_DIR_FROM_ENV"] = "sub"
os.environ["_SOURCED"] = "_sourced"
os.environ["_RSOURCED"] = "_rsourced"
os.environ["_GSOURCED"] = "_gsourced"
os.environ["_GRSOURCED"] = "_grsourced"
# Test twice, with $srctree as a relative and an absolute path,
# respectively
for srctree in "Kconfiglib", os.path.abspath("Kconfiglib"):
os.environ["srctree"] = srctree
# Has symbol with empty help text, so disable warnings
c = Kconfig("tests/Klocation", warn=False)
verify_locations(c.syms["SINGLE_DEF"].nodes, "tests/Klocation:4")
verify_locations(c.syms["MULTI_DEF"].nodes,
"tests/Klocation:7",
"tests/Klocation:37",
"tests/Klocation_sourced:3",
"tests/sub/Klocation_rsourced:2",
"tests/sub/Klocation_gsourced1:1",
"tests/sub/Klocation_gsourced2:1",
"tests/sub/Klocation_gsourced1:1",
"tests/sub/Klocation_gsourced2:1",
"tests/sub/Klocation_grsourced1:1",
"tests/sub/Klocation_grsourced2:1",
"tests/sub/Klocation_grsourced1:1",
"tests/sub/Klocation_grsourced2:1",
"tests/Klocation:70")
verify_locations(c.named_choices["CHOICE"].nodes,
"tests/Klocation_sourced:5")
verify_locations([c.syms["MENU_HOOK"].nodes[0].next],
"tests/Klocation_sourced:12")
verify_locations([c.syms["COMMENT_HOOK"].nodes[0].next],
"tests/Klocation_sourced:18")
# Test Kconfig.kconfig_filenames
verify_equal(c.kconfig_filenames, [
"tests/Klocation",
"tests/Klocation_sourced",
"tests/sub/Klocation_rsourced",
"tests/sub/Klocation_gsourced1",
"tests/sub/Klocation_gsourced2",
"tests/sub/Klocation_gsourced1",
"tests/sub/Klocation_gsourced2",
"tests/sub/Klocation_grsourced1",
"tests/sub/Klocation_grsourced2",
"tests/sub/Klocation_grsourced1",
"tests/sub/Klocation_grsourced2"
])
# Test recursive 'source' detection
try:
Kconfig("tests/Krecursive1")
except KconfigError as e:
verify_equal(str(e), """
tests/Krecursive2:1: Recursive 'source' of 'tests/Krecursive1' detected. Check that environment variables are set correctly.
Include path:
tests/Krecursive1:1
tests/Krecursive2:1
"""[:-1])
except:
fail("recursive 'source' raised wrong exception")
else:
fail("recursive 'source' did not raise exception")
# Verify that source and rsource throw exceptions for missing files
# TODO: Make an exception test helper
try:
Kconfig("tests/Kmissingsource")
except KconfigError as e:
if "does not exist" not in str(e):
fail("'source' with missing file raised wrong KconfigError")
except:
fail("'source' with missing file raised wrong exception")
else:
fail("'source' with missing file did not raise exception")
try:
Kconfig("tests/Kmissingrsource")
except KconfigError as e:
if "does not exist" not in str(e):
fail("'rsource' with missing file raised wrong KconfigError")
except:
fail("'rsource' with missing file raised wrong exception")
else:
fail("'rsource' with missing file did not raise exception")
print("Testing Kconfig.node_iter()")
# Reuse tests/Klocation. The node_iter(unique_syms=True) case already gets
# plenty of testing from write_config() as well.
c = Kconfig("tests/Klocation", warn=False)
verify_equal(
[node.item.name for node in c.node_iter()
if isinstance(node.item, Symbol)],
["SINGLE_DEF", "MULTI_DEF", "HELP_1", "HELP_2", "HELP_3", "MULTI_DEF",
"MULTI_DEF", "MENU_HOOK", "COMMENT_HOOK"] + 10*["MULTI_DEF"])
verify_equal(
[node.item.name for node in c.node_iter(True)
if isinstance(node.item, Symbol)],
["SINGLE_DEF", "MULTI_DEF", "HELP_1", "HELP_2", "HELP_3", "MENU_HOOK",
"COMMENT_HOOK"])
verify_equal(
[node.prompt[0] for node in c.node_iter()
if not isinstance(node.item, Symbol)],
["choice", "menu", "comment"])
verify_equal(
[node.prompt[0] for node in c.node_iter(True)
if not isinstance(node.item, Symbol)],
["choice", "menu", "comment"])
# Get rid of custom 'srctree' from Klocation test
os.environ.pop("srctree", None)
print("Testing MenuNode.include_path")
os.environ["srctree"] = "Kconfiglib/tests"
c = Kconfig("Kinclude_path")
def verify_node_path(node, *expected):
if node.include_path != expected:
fail("Wrong include path for node {!r}. Got {}, expected {}."
.format(node, node.include_path, expected))
def verify_sym_path(sym_name, node_i, *expected):
verify_node_path(c.syms[sym_name].nodes[node_i], *expected)
verify_sym_path("TOP", 0)
verify_sym_path("TOP", 1)
verify_sym_path("TOP", 2)
verify_sym_path("ONE_DOWN", 0, ("Kinclude_path", 4))
verify_sym_path("ONE_DOWN", 1, ("Kinclude_path", 4))
verify_sym_path("ONE_DOWN", 2, ("Kinclude_path", 4))
verify_sym_path("ONE_DOWN", 3, ("Kinclude_path", 9))
verify_sym_path("ONE_DOWN", 4, ("Kinclude_path", 9))
verify_sym_path("ONE_DOWN", 5, ("Kinclude_path", 9))
verify_sym_path("TWO_DOWN", 0,
("Kinclude_path", 4), ("Kinclude_path_sourced_1", 4))
verify_sym_path("TWO_DOWN", 1,
("Kinclude_path", 4), ("Kinclude_path_sourced_1", 9))
verify_sym_path("TWO_DOWN", 2,
("Kinclude_path", 9), ("Kinclude_path_sourced_1", 4))
verify_sym_path("TWO_DOWN", 3,
("Kinclude_path", 9), ("Kinclude_path_sourced_1", 9))
verify_node_path(c.top_node)
verify_node_path(c.menus[0], ("Kinclude_path", 4), ("Kinclude_path_sourced_1", 4))
verify_node_path(c.comments[0], ("Kinclude_path", 4), ("Kinclude_path_sourced_1", 4))
verify_node_path(c.choices[0].nodes[0], ("Kinclude_path", 4), ("Kinclude_path_sourced_1", 4))
os.environ.pop("srctree", None)
print("Testing Kconfig.choices/menus/comments")
c = Kconfig("Kconfiglib/tests/Kitemlists")
def verify_prompts(items, *expected_prompts):
verify(len(items) == len(expected_prompts),
"Wrong number of prompts for {}".format(items))
for item, expected_prompt in zip(items, expected_prompts):
if not isinstance(item, MenuNode):
item = item.nodes[0]
verify(item.prompt[0] == expected_prompt,
"Wrong prompt for {}, expected '{}'"
.format(repr(item), expected_prompt))
verify_prompts(c.choices, "choice 1", "choice 2", "choice 3")
verify_prompts(c.menus, "menu 1", "menu 2", "menu 3", "menu 4", "menu 5")
verify_prompts(c.comments, "comment 1", "comment 2", "comment 3")
print("Testing Symbol/Choice.direct_dep")
c = Kconfig("Kconfiglib/tests/Kdirdep")
verify_equal(expr_str(c.syms["NO_DEP_SYM"].direct_dep), '"y"')
verify_equal(expr_str(c.syms["DEP_SYM"].direct_dep), "A || (B && C) || !D")
verify_equal(expr_str(c.named_choices["NO_DEP_CHOICE"].direct_dep), '"y"')
verify_equal(expr_str(c.named_choices["DEP_CHOICE"].direct_dep),
"A || B || C")
print("Testing expr_items()")
c = Kconfig("Kconfiglib/tests/Kexpr_items")
def verify_expr_items(expr, *sym_names):
verify_equal(tuple(sorted(item.name for item in expr_items(expr))),
sym_names)
verify_expr_items(
c.syms["TEST"].defaults[0][0],
"A", "B", "C", "D", "E", "F", "G", "H"
)
verify_expr_items(
c.syms["TEST_CHOICE"].nodes[0].prompt[1],
"A", "CHOICE"
)
print("Testing MenuNode/Symbol/Choice.referenced")
c = Kconfig("Kconfiglib/tests/Kreferenced", warn=False)
def verify_deps(item, *dep_names):
verify_equal(tuple(sorted(item.name for item in item.referenced)),
dep_names)
verify_deps(c.top_node, "y")
verify_deps(c.syms["NO_REFS"].nodes[0], "y")
verify_deps(c.syms["JUST_DEPENDS_ON_REFS"].nodes[0], "A", "B")
verify_deps(c.syms["LOTS_OF_REFS"].nodes[0],
*(chr(n) for n in range(ord("A"), ord("Z") + 1)))
verify_deps(c.syms["INT_REFS"].nodes[0],
"A", "B", "C", "D", "E", "F", "G", "H", "y")
verify_deps(c.syms["CHOICE_REF"].nodes[0], "CHOICE")
verify_deps(c.menus[0], "A", "B", "C", "D")
verify_deps(c.comments[0], "A", "B")
verify_deps(c.syms["MULTI_DEF_SYM"], "A", "B", "C", "y")
verify_deps(c.named_choices["MULTI_DEF_CHOICE"], "A", "B", "C")
print("Testing split_expr()")
c = Kconfig("Kconfiglib/tests/empty")
c.disable_warnings()
def verify_split(to_split, op, operand_strs):
# The same hackage as in Kconfig.eval_string()
c._tokens = c._tokenize("if " + to_split)[1:]
c._tokens_i = -1
operands = split_expr(c._parse_expr(False), op)
verify(len(operands) == len(operand_strs),
"Wrong number of operands when {} was split by {}"
.format(to_split, "OR" if op == OR else "AND"))
for operand, operand_str in zip(operands, operand_strs):
verify_equal(expr_str(operand), operand_str)
verify_split("A", OR, ("A", ))
verify_split("!A", OR, ("!A", ))
verify_split("A = B", OR, ("A = B", ))
verify_split("A && B", OR, ("A && B", ))
verify_split("A || B", OR, ("A", "B" ))
verify_split("(A || B) || C", OR, ("A", "B", "C" ))
verify_split("A || (B || C)", OR, ("A", "B", "C" ))
verify_split("A || !(B || C)", OR, ("A", "!(B || C)" ))
verify_split("A || (B && (C || D))", OR, ("A", "B && (C || D)"))
verify_split("(A && (B || C)) || D", OR, ("A && (B || C)", "D"))
verify_split("A", AND, ("A", ))
verify_split("!A", AND, ("!A", ))
verify_split("A = B", AND, ("A = B", ))
verify_split("A || B", AND, ("A || B", ))
verify_split("A && B", AND, ("A", "B" ))
verify_split("(A && B) && C", AND, ("A", "B", "C" ))
verify_split("A && (B && C)", AND, ("A", "B", "C" ))
verify_split("A && !(B && C)", AND, ("A", "!(B && C)" ))
verify_split("A && (B || (C && D))", AND, ("A", "B || (C && D)"))
verify_split("(A || (B && C)) && D", AND, ("A || (B && C)", "D"))
print("Testing visibility")
c = Kconfig("Kconfiglib/tests/Kvisibility")
def verify_visibility(item, no_module_vis, module_vis):
c.modules.set_value(0)
verify(item.visibility == no_module_vis,
"expected {} to have visibility {} without modules, had "
"visibility {}".
format(repr(item), no_module_vis, item.visibility))
c.modules.set_value(2)
verify(item.visibility == module_vis,
"expected {} to have visibility {} with modules, had "
"visibility {}".
format(repr(item), module_vis, item.visibility))
# Symbol visibility
verify_visibility(c.syms["NO_PROMPT"], 0, 0)
verify_visibility(c.syms["BOOL_N"], 0, 0)
verify_visibility(c.syms["BOOL_M"], 0, 2)
verify_visibility(c.syms["BOOL_MOD"], 2, 2)
verify_visibility(c.syms["BOOL_Y"], 2, 2)
verify_visibility(c.syms["TRISTATE_M"], 0, 1)
verify_visibility(c.syms["TRISTATE_MOD"], 2, 1)
verify_visibility(c.syms["TRISTATE_Y"], 2, 2)
verify_visibility(c.syms["BOOL_IF_N"], 0, 0)
verify_visibility(c.syms["BOOL_IF_M"], 0, 2)
verify_visibility(c.syms["BOOL_IF_Y"], 2, 2)
verify_visibility(c.syms["BOOL_MENU_N"], 0, 0)
verify_visibility(c.syms["BOOL_MENU_M"], 0, 2)
verify_visibility(c.syms["BOOL_MENU_Y"], 2, 2)
verify_visibility(c.syms["BOOL_CHOICE_N"], 0, 0)
# Non-tristate symbols in tristate choices are only visible if the choice
# is in y mode
# The choice can't be brought to y mode because of the 'if m'
verify_visibility(c.syms["BOOL_CHOICE_M"], 0, 0)
c.syms["BOOL_CHOICE_M"].choice.set_value(2)
verify_visibility(c.syms["BOOL_CHOICE_M"], 0, 0)
# The choice gets y mode only when running without modules, because it
# defaults to m mode
verify_visibility(c.syms["BOOL_CHOICE_Y"], 2, 0)
c.syms["BOOL_CHOICE_Y"].choice.set_value(2)
# When set to y mode, the choice symbol becomes visible both with and
# without modules
verify_visibility(c.syms["BOOL_CHOICE_Y"], 2, 2)
verify_visibility(c.syms["TRISTATE_IF_N"], 0, 0)
verify_visibility(c.syms["TRISTATE_IF_M"], 0, 1)
verify_visibility(c.syms["TRISTATE_IF_Y"], 2, 2)
verify_visibility(c.syms["TRISTATE_MENU_N"], 0, 0)
verify_visibility(c.syms["TRISTATE_MENU_M"], 0, 1)
verify_visibility(c.syms["TRISTATE_MENU_Y"], 2, 2)
verify_visibility(c.syms["TRISTATE_CHOICE_N"], 0, 0)
verify_visibility(c.syms["TRISTATE_CHOICE_M"], 0, 1)
verify_visibility(c.syms["TRISTATE_CHOICE_Y"], 2, 2)
verify_visibility(c.named_choices["BOOL_CHOICE_N"], 0, 0)
verify_visibility(c.named_choices["BOOL_CHOICE_M"], 0, 2)
verify_visibility(c.named_choices["BOOL_CHOICE_Y"], 2, 2)
verify_visibility(c.named_choices["TRISTATE_CHOICE_N"], 0, 0)
verify_visibility(c.named_choices["TRISTATE_CHOICE_M"], 0, 1)
verify_visibility(c.named_choices["TRISTATE_CHOICE_Y"], 2, 2)
verify_visibility(c.named_choices["TRISTATE_CHOICE_IF_M_AND_Y"], 0, 1)
verify_visibility(c.named_choices["TRISTATE_CHOICE_MENU_N_AND_Y"], 0, 0)
# Verify that 'visible if' visibility gets propagated to prompts
verify_visibility(c.syms["VISIBLE_IF_N"], 0, 0)
verify_visibility(c.syms["VISIBLE_IF_M"], 0, 1)
verify_visibility(c.syms["VISIBLE_IF_Y"], 2, 2)
verify_visibility(c.syms["VISIBLE_IF_M_2"], 0, 1)
# Verify that string/int/hex symbols with m visibility accept a user value
assign_and_verify("STRING_m", "foo bar")
assign_and_verify("INT_m", "123")
assign_and_verify("HEX_m", "0x123")
print("Testing .assignable")
c = Kconfig("Kconfiglib/tests/Kassignable")
def verify_assignable_imp(item, assignable_no_modules, assignable_modules):
for modules_val, assignable in (0, assignable_no_modules), \
(2, assignable_modules):
c.modules.set_value(modules_val)
module_msg = "without modules" if modules_val == 0 else \
"with modules"
verify(item.assignable == assignable,
"Incorrect assignable values for {} {}. Should be {}, "
"was {}."
.format(item.name, module_msg, assignable, item.assignable))
# Verify that the values can actually be assigned too
for val in item.assignable:
item.set_value(val)
verify(item.tri_value == val,
"Unable to set {} to {} {}, even though it was in "
".assignable".format(item.name, val, module_msg))
def verify_assignable(sym_name, assignable_no_modules, assignable_modules):
verify_assignable_imp(c.syms[sym_name],
assignable_no_modules,
assignable_modules)
def verify_const_unassignable(sym_name):
verify_assignable_imp(c.const_syms[sym_name], (), ())
# Things that shouldn't be .assignable
verify_const_unassignable("n")
verify_const_unassignable("m")
verify_const_unassignable("y")
verify_const_unassignable("const")
verify_assignable("UNDEFINED", (), ())
verify_assignable("NO_PROMPT", (), ())
verify_assignable("STRING", (), ())
verify_assignable("INT", (), ())
verify_assignable("HEX", (), ())
# Non-selected symbols
verify_assignable("Y_VIS_BOOL", (0, 2), (0, 2))
verify_assignable("M_VIS_BOOL", ( ), (0, 2)) # Vis. promoted
verify_assignable("N_VIS_BOOL", ( ), ( ))
verify_assignable("Y_VIS_TRI", (0, 2), (0, 1, 2))
verify_assignable("M_VIS_TRI", ( ), (0, 1 ))
verify_assignable("N_VIS_TRI", ( ), ( ))
# Symbols selected to y
verify_assignable("Y_SEL_Y_VIS_BOOL", (2,), (2,))
verify_assignable("Y_SEL_M_VIS_BOOL", ( ), (2,)) # Vis. promoted
verify_assignable("Y_SEL_N_VIS_BOOL", ( ), ( ))
verify_assignable("Y_SEL_Y_VIS_TRI", (2,), (2,))
verify_assignable("Y_SEL_M_VIS_TRI", ( ), (2,))
verify_assignable("Y_SEL_N_VIS_TRI", ( ), ( ))
# Symbols selected to m
verify_assignable("M_SEL_Y_VIS_BOOL", (2,), ( 2,)) # Value promoted
verify_assignable("M_SEL_M_VIS_BOOL", ( ), ( 2,)) # Vis./value promoted
verify_assignable("M_SEL_N_VIS_BOOL", ( ), ( ))
verify_assignable("M_SEL_Y_VIS_TRI", (2,), (1, 2 ))
verify_assignable("M_SEL_M_VIS_TRI", ( ), (1, ))
verify_assignable("M_SEL_N_VIS_TRI", ( ), ( ))
# Symbols implied to y
verify_assignable("Y_IMP_Y_VIS_BOOL", (0, 2), (0, 2))
verify_assignable("Y_IMP_M_VIS_BOOL", ( ), (0, 2)) # Vis. promoted
verify_assignable("Y_IMP_N_VIS_BOOL", ( ), ( ))
verify_assignable("Y_IMP_Y_VIS_TRI", (0, 2), (0, 2)) # m removed by imply
verify_assignable("Y_IMP_M_VIS_TRI", ( ), (0, 2)) # m promoted to y by imply
verify_assignable("Y_IMP_N_VIS_TRI", ( ), ( ))
# Symbols implied to m (never affects assignable values)
verify_assignable("M_IMP_Y_VIS_BOOL", (0, 2), (0, 2))
verify_assignable("M_IMP_M_VIS_BOOL", ( ), (0, 2)) # Vis. promoted
verify_assignable("M_IMP_N_VIS_BOOL", ( ), ( ))
verify_assignable("M_IMP_Y_VIS_TRI", (0, 2), (0, 1, 2))
verify_assignable("M_IMP_M_VIS_TRI", ( ), (0, 1 ))
verify_assignable("M_IMP_N_VIS_TRI", ( ), ( ))
# Symbols in y-mode choice
verify_assignable("Y_CHOICE_BOOL", (2,), (2,))
verify_assignable("Y_CHOICE_TRISTATE", (2,), (2,))
verify_assignable("Y_CHOICE_N_VIS_TRISTATE", ( ), ( ))
# Symbols in m/y-mode choice, starting out in m mode, or y mode when
# running without modules
verify_assignable("MY_CHOICE_BOOL", (2,), ( ))
verify_assignable("MY_CHOICE_TRISTATE", (2,), (0, 1))
verify_assignable("MY_CHOICE_N_VIS_TRISTATE", ( ), ( ))
c.named_choices["MY_CHOICE"].set_value(2)
# Symbols in m/y-mode choice, now in y mode
verify_assignable("MY_CHOICE_BOOL", (2,), (2,))
verify_assignable("MY_CHOICE_TRISTATE", (2,), (2,))
verify_assignable("MY_CHOICE_N_VIS_TRISTATE", ( ), ( ))
def verify_choice_assignable(choice_name, assignable_no_modules,
assignable_modules):
verify_assignable_imp(c.named_choices[choice_name],
assignable_no_modules,
assignable_modules)
# Choices with various possible modes
verify_choice_assignable("Y_CHOICE", (2, ), ( 2,))
verify_choice_assignable("MY_CHOICE", (2, ), ( 1, 2 ))
verify_choice_assignable("NMY_CHOICE", (0, 2), (0, 1, 2 ))
verify_choice_assignable("NY_CHOICE", (0, 2), (0, 2 ))
verify_choice_assignable("NM_CHOICE", ( ), (0, 1 ))
verify_choice_assignable("M_CHOICE", ( ), ( 1, ))
verify_choice_assignable("N_CHOICE", ( ), ( ))
print("Testing object relations")
c = Kconfig("Kconfiglib/tests/Krelation")
verify(c.syms["A"].nodes[0].parent is c.top_node,
"A's parent should be the top node")
verify(c.syms["B"].nodes[0].parent.item is c.named_choices["CHOICE_1"],
"B's parent should be the first choice")
verify(c.syms["C"].nodes[0].parent.item is c.syms["B"],
"C's parent should be B (due to auto menus)")
verify(c.syms["E"].nodes[0].parent.item == MENU,
"E's parent should be a menu")
verify(c.syms["E"].nodes[0].parent.parent is c.top_node,
"E's grandparent should be the top node")
verify(c.syms["G"].nodes[0].parent.item is c.named_choices["CHOICE_2"],
"G's parent should be the second choice")
verify(c.syms["G"].nodes[0].parent.parent.item == MENU,
"G's grandparent should be a menu")
print("Testing hex/int ranges")
c = Kconfig("Kconfiglib/tests/Krange", warn=False)
for sym_name in "HEX_NO_RANGE", "INT_NO_RANGE", "HEX_40", "INT_40":
sym = c.syms[sym_name]
verify(not sym.ranges,
"{} should not have ranges".format(sym_name))
for sym_name in "HEX_ALL_RANGES_DISABLED", "INT_ALL_RANGES_DISABLED", \
"HEX_RANGE_10_20_LOW_DEFAULT", \
"INT_RANGE_10_20_LOW_DEFAULT":
sym = c.syms[sym_name]
verify(sym.ranges, "{} should have ranges".format(sym_name))
# hex/int symbols without defaults should get no default value
verify_value("HEX_NO_RANGE", "")
verify_value("INT_NO_RANGE", "")
# And neither if all ranges are disabled
verify_value("HEX_ALL_RANGES_DISABLED", "")
verify_value("INT_ALL_RANGES_DISABLED", "")
# Make sure they are assignable though, and test that the form of the user
# value is reflected in the value for hex symbols
assign_and_verify("HEX_NO_RANGE", "0x123")
assign_and_verify("HEX_NO_RANGE", "123")
assign_and_verify("INT_NO_RANGE", "123")
# Defaults outside of the valid range should be clamped
verify_value("HEX_RANGE_10_20_LOW_DEFAULT", "0x10")
verify_value("HEX_RANGE_10_20_HIGH_DEFAULT", "0x20")
verify_value("INT_RANGE_10_20_LOW_DEFAULT", "10")
verify_value("INT_RANGE_10_20_HIGH_DEFAULT", "20")
# Defaults inside the valid range should be preserved. For hex symbols,
# they should additionally use the same form as in the assignment.
verify_value("HEX_RANGE_10_20_OK_DEFAULT", "0x15")
verify_value("HEX_RANGE_10_20_OK_DEFAULT_ALTERNATE", "15")
verify_value("INT_RANGE_10_20_OK_DEFAULT", "15")
# hex/int symbols with no defaults but valid ranges should default to the
# lower end of the range if it's > 0
verify_value("HEX_RANGE_10_20", "0x10")
verify_value("HEX_RANGE_0_10", "")
verify_value("INT_RANGE_10_20", "10")
verify_value("INT_RANGE_0_10", "")
verify_value("INT_RANGE_NEG_10_10", "")
# User values and dependent ranges
# Avoid warnings for assigning values outside the active range
c.disable_warnings()
def verify_range(sym_name, low, high, default):
is_hex = (c.syms[sym_name].type == HEX)
for i in range(low, high + 1):
assign_and_verify_user_value(sym_name, str(i), str(i), True)
if is_hex:
# The form of the user value should be preserved for hex
# symbols
assign_and_verify_user_value(sym_name, hex(i), hex(i), True)
# Verify that assigning a user value just outside the range causes
# defaults to be used
if default is None:
default_str = ""
else:
default_str = hex(default) if is_hex else str(default)
if is_hex:
too_low_str = hex(low - 1)
too_high_str = hex(high + 1)
else:
too_low_str = str(low - 1)
too_high_str = str(high + 1)
assign_and_verify_value(sym_name, too_low_str, default_str)
assign_and_verify_value(sym_name, too_high_str, default_str)
verify_range("HEX_RANGE_10_20_LOW_DEFAULT", 0x10, 0x20, 0x10)
verify_range("HEX_RANGE_10_20_HIGH_DEFAULT", 0x10, 0x20, 0x20)
verify_range("HEX_RANGE_10_20_OK_DEFAULT", 0x10, 0x20, 0x15)
verify_range("INT_RANGE_10_20_LOW_DEFAULT", 10, 20, 10)
verify_range("INT_RANGE_10_20_HIGH_DEFAULT", 10, 20, 20)
verify_range("INT_RANGE_10_20_OK_DEFAULT", 10, 20, 15)
verify_range("HEX_RANGE_10_20", 0x10, 0x20, 0x10)
verify_range("INT_RANGE_10_20", 10, 20, 10)
verify_range("INT_RANGE_0_10", 0, 10, None)
verify_range("INT_RANGE_NEG_10_10", -10, 10, None)
# Dependent ranges
verify_value("HEX_40", "40")
verify_value("INT_40", "40")
c.syms["HEX_RANGE_10_20"].unset_value()
c.syms["INT_RANGE_10_20"].unset_value()
verify_value("HEX_RANGE_10_40_DEPENDENT", "0x10")
verify_value("INT_RANGE_10_40_DEPENDENT", "10")
c.syms["HEX_RANGE_10_20"].set_value("15")
c.syms["INT_RANGE_10_20"].set_value("15")
verify_value("HEX_RANGE_10_40_DEPENDENT", "0x15")
verify_value("INT_RANGE_10_40_DEPENDENT", "15")
c.unset_values()
verify_range("HEX_RANGE_10_40_DEPENDENT", 0x10, 0x40, 0x10)
verify_range("INT_RANGE_10_40_DEPENDENT", 10, 40, 10)
# Ranges and symbols defined in multiple locations
verify_value("INACTIVE_RANGE", "2")
verify_value("ACTIVE_RANGE", "1")
print("Testing defconfig_filename")
c = Kconfig("Kconfiglib/tests/empty")
verify(c.defconfig_filename is None,
"defconfig_filename should be None with no defconfig_list symbol")
c = Kconfig("Kconfiglib/tests/Kdefconfig_nonexistent")
verify(c.defconfig_filename is None,
"defconfig_filename should be None when none of the files in the "
"defconfig_list symbol exist")
# Referenced in Kdefconfig_existent(_but_n)
os.environ["FOO"] = "defconfig_2"
c = Kconfig("Kconfiglib/tests/Kdefconfig_existent_but_n")
verify(c.defconfig_filename is None,
"defconfig_filename should be None when the condition is n for all "
"the defaults")
c = Kconfig("Kconfiglib/tests/Kdefconfig_existent")
verify(c.defconfig_filename == "Kconfiglib/tests/defconfig_2",
"defconfig_filename should return the existing file "
"Kconfiglib/tests/defconfig_2")
# Should also look relative to $srctree if the specified defconfig is a
# relative path and can't be opened
c = Kconfig("Kconfiglib/tests/Kdefconfig_srctree")
verify(c.defconfig_filename == "Kconfiglib/tests/defconfig_2",
"defconfig_filename gave wrong file with $srctree unset")
os.environ["srctree"] = "Kconfiglib/tests"
c = Kconfig("Kdefconfig_srctree")
verify(c.defconfig_filename == "Kconfiglib/tests/sub/defconfig_in_sub",
"defconfig_filename gave wrong file with $srctree set")
os.environ.pop("srctree", None)
print("Testing mainmenu_text")
c = Kconfig("Kconfiglib/tests/empty")
verify(c.mainmenu_text == "Main menu",
"An empty Kconfig should get a default main menu prompt")
# Expanded in the mainmenu text
os.environ["FOO"] = "bar baz"
c = Kconfig("Kconfiglib/tests/Kmainmenu")
verify(c.mainmenu_text == "---bar baz---",
"Wrong mainmenu text")
print("Testing user_value")
# References undefined env. var. Disable warnings.
c = Kconfig("Kconfiglib/tests/Kmisc", warn=False)
# Avoid warnings from assigning invalid user values and assigning user
# values to symbols without prompts
c.disable_warnings()
syms = [c.syms[name] for name in
("BOOL", "TRISTATE", "STRING", "INT", "HEX")]
for sym in syms:
verify(sym.user_value is None,
"{} should not have a user value to begin with")
# Assign valid values for the types
assign_and_verify_user_value("BOOL", 0, 0, True)
assign_and_verify_user_value("BOOL", 2, 2, True)
assign_and_verify_user_value("TRISTATE", 0, 0, True)
assign_and_verify_user_value("TRISTATE", 1, 1, True)
assign_and_verify_user_value("TRISTATE", 2, 2, True)
assign_and_verify_user_value("STRING", "foo bar", "foo bar", True)
assign_and_verify_user_value("INT", "123", "123", True)
assign_and_verify_user_value("HEX", "0x123", "0x123", True)
# Assign invalid values for the types. They should retain their old user
# value.
assign_and_verify_user_value("BOOL", 1, 2, False)
assign_and_verify_user_value("BOOL", "foo", 2, False)
assign_and_verify_user_value("BOOL", "1", 2, False)
assign_and_verify_user_value("TRISTATE", "foo", 2, False)
assign_and_verify_user_value("TRISTATE", "1", 2, False)
assign_and_verify_user_value("STRING", 0, "foo bar", False)
assign_and_verify_user_value("INT", "foo", "123", False)
assign_and_verify_user_value("INT", 0, "123", False)
assign_and_verify_user_value("HEX", "foo", "0x123", False)
assign_and_verify_user_value("HEX", 0, "0x123", False)
assign_and_verify_user_value("HEX", "-0x1", "0x123", False)
for s in syms:
s.unset_value()
verify(s.user_value is None,
"{} should not have a user value after being reset".
format(s.name))
print("Testing is_menuconfig")
c = Kconfig("Kconfiglib/tests/Kmenuconfig")
for not_menuconfig in c.syms["NOT_MENUCONFIG_1"].nodes[0], \
c.syms["NOT_MENUCONFIG_2"].nodes[0], \
c.syms["MENUCONFIG_MULTI_DEF"].nodes[0], \
c.syms["COMMENT_HOOK"].nodes[0].next:
verify(not not_menuconfig.is_menuconfig,
"'{}' should have is_menuconfig False".format(not_menuconfig))
for menuconfig in c.top_node, \
c.syms["MENUCONFIG_1"].nodes[0], \
c.syms["MENUCONFIG_MULTI_DEF"].nodes[1], \
c.syms["MENU_HOOK"].nodes[0].next, \
c.syms["CHOICE_HOOK"].nodes[0].next:
verify(menuconfig.is_menuconfig,
"'{}' should have is_menuconfig True".format(menuconfig))
print("Testing 'option env' semantics")
os.environ["ENV_VAR"] = "ENV_VAR value"
# References undefined env. var., so disable warnings
c = Kconfig("Kconfiglib/tests/Kmisc", warn=False)
# Verify that 'option env' is treated like a default
verify_value("FROM_ENV", "ENV_VAR value")
verify_value("FROM_ENV_MISSING", "missing")
verify_value("FROM_ENV_WEIRD", "weird")
print("Testing defined vs undefined symbols")
for name in "A", "B", "C", "D", "BOOL", "TRISTATE", "STRING", "INT", "HEX":
verify(c.syms[name].nodes,
"{} should be defined".format(name))
for name in "NOT_DEFINED_1", "NOT_DEFINED_2", "NOT_DEFINED_3", \
"NOT_DEFINED_4":
sym = c.syms[name]
verify(not c.syms[name].nodes,
"{} should not be defined".format(name))
print("Testing Symbol.choice")
for name in "A", "B", "C", "D":
verify(c.syms[name].choice is not None,
"{} should be a choice symbol".format(name))
for name in "Q1", "Q2", "Q3", "BOOL", "TRISTATE", "STRING", "INT", "HEX", \
"FROM_ENV", "FROM_ENV_MISSING", "NOT_DEFINED_1", \
"NOT_DEFINED_2", "NOT_DEFINED_3", "NOT_DEFINED_4":
verify(c.syms[name].choice is None,
"{} should not be a choice symbol".format(name))
print("Testing is_allnoconfig_y")
verify(not c.syms["NOT_ALLNOCONFIG_Y"].is_allnoconfig_y,
"NOT_ALLNOCONFIG_Y should not be allnoconfig_y")
verify(c.syms["ALLNOCONFIG_Y"].is_allnoconfig_y,
"ALLNOCONFIG_Y should be allnoconfig_y")
print("Testing .config reading and writing")
config_test_file = "Kconfiglib/tests/config_test"
def verify_file_contents(fname, contents):
with open(fname, "r") as f:
file_contents = f.read()
verify(file_contents == contents,
"{} contains '{}'. Expected '{}'."
.format(fname, file_contents, contents))
# Writing/reading strings with characters that need to be escaped
c = Kconfig("Kconfiglib/tests/Kescape")
# Test the default value
c.write_config(config_test_file + "_from_def", header="")
verify_file_contents(config_test_file + "_from_def",
r'''CONFIG_STRING="\"\\"''' "\n")
# Write our own value
c.syms["STRING"].set_value(r'''\"a'\\''')
c.write_config(config_test_file + "_from_user", header="")
verify_file_contents(config_test_file + "_from_user",
r'''CONFIG_STRING="\\\"a'\\\\"''' "\n")
# Read back the two configs and verify the respective values
c.load_config(config_test_file + "_from_def")
verify_value("STRING", '"\\')
c.load_config(config_test_file + "_from_user")
verify_value("STRING", r'''\"a'\\''')
c = Kconfig("Kconfiglib/tests/Kappend")
verify_value("BOOL", "n")
verify_value("STRING", "")
c.load_config("Kconfiglib/tests/config_set_bool", replace=False)
verify_value("BOOL", "y")
verify_value("STRING", "")
c.load_config("Kconfiglib/tests/config_set_string", replace=False)
verify_value("BOOL", "y")
verify_value("STRING", "foo bar")
c.load_config("Kconfiglib/tests/config_set_string")
verify_value("BOOL", "n")
verify_value("STRING", "foo bar")
c.load_config("Kconfiglib/tests/empty")
verify_value("STRING", "")
c.load_config("Kconfiglib/tests/config_indented")
verify_value("IGNOREME", "y")
c = Kconfig("Kconfiglib/tests/Korder")
c.write_autoconf(config_test_file, header="")
verify_file_contents(config_test_file, """
#define CONFIG_O 0
#define CONFIG_R 1
#define CONFIG_D 2
#define CONFIG_E 3
#define CONFIG_R2 4
#define CONFIG_I 5
#define CONFIG_N 6
#define CONFIG_G 7
"""[1:])
c.syms["O"].set_value("-1")
c.syms["R"].set_value("-1")
c.syms["E"].set_value("-1")
c.syms["R2"].set_value("-1")
c.syms["N"].set_value("-1")
c.syms["G"].set_value("-1")
c.write_min_config(config_test_file, header="")
verify_file_contents(config_test_file, """
CONFIG_O=-1
CONFIG_R=-1
CONFIG_E=-1
CONFIG_R2=-1
CONFIG_N=-1
CONFIG_G=-1
"""[1:])
print("Testing Kconfig fetching and separation")
for c in Kconfig("Kconfiglib/tests/Kmisc", warn=False), \
Kconfig("Kconfiglib/tests/Kmisc", warn=False):
for item in c.syms["BOOL"], \
c.syms["BOOL"].nodes[0], \
c.named_choices["OPTIONAL"], \
c.named_choices["OPTIONAL"].nodes[0], \
c.syms["MENU_HOOK"].nodes[0].next, \
c.syms["COMMENT_HOOK"].nodes[0].next:
verify(item.kconfig is c,
".kconfig not properly set for " + repr(item))
print("Testing imply semantics")
c = Kconfig("Kconfiglib/tests/Kimply")
verify_value("IMPLY_DIRECT_DEPS", "y")
verify_value("UNMET_DIRECT_1", "n")
verify_value("UNMET_DIRECT_2", "n")
verify_value("UNMET_DIRECT_3", "n")
verify_value("MET_DIRECT_1", "y")
verify_value("MET_DIRECT_2", "y")
verify_value("MET_DIRECT_3", "y")
verify_value("MET_DIRECT_4", "y")
verify_value("IMPLY_COND", "y")
verify_value("IMPLIED_N_COND", "n")
verify_value("IMPLIED_M_COND", "m")
verify_value("IMPLIED_Y_COND", "y")
verify_value("IMPLY_N_1", "n")
verify_value("IMPLY_N_2", "n")
verify_value("IMPLIED_FROM_N_1", "n")
verify_value("IMPLIED_FROM_N_2", "n")
verify_value("IMPLY_M", "m")
verify_value("IMPLIED_M", "m")
verify_value("IMPLIED_M_BOOL", "y")
verify_value("IMPLY_M_TO_Y", "y")
verify_value("IMPLIED_M_TO_Y", "y")
assign_and_verify("IMPLY", 2)
assign_and_verify("DIRECT_DEP", 2)
verify_value("IMPLIED_TRISTATE", 2)
assign_and_verify("DIRECT_DEP", 0)
verify_value("IMPLIED_TRISTATE", 0)
assign_and_verify("DIRECT_DEP", 2)
assign_and_verify("IMPLY", 0)
assign_and_verify("IMPLIED_TRISTATE", 0)
assign_and_verify("IMPLIED_TRISTATE", 1)
assign_and_verify("IMPLIED_TRISTATE", 2)
c.syms["IMPLIED_TRISTATE"].unset_value()
verify_value("IMPLIED_TRISTATE", "n")
assign_and_verify("IMPLY", 1)
assign_and_verify("IMPLIED_TRISTATE", 0)
assign_and_verify("IMPLIED_TRISTATE", 1)
assign_and_verify("IMPLIED_TRISTATE", 2)
c.syms["IMPLIED_TRISTATE"].unset_value()
verify_value("IMPLIED_TRISTATE", 1)
assign_and_verify("IMPLY", 2)
assign_and_verify("IMPLIED_TRISTATE", 0)
assign_and_verify_value("IMPLIED_TRISTATE", 1, 2)
assign_and_verify("IMPLIED_TRISTATE", 2)
c.syms["IMPLIED_TRISTATE"].unset_value()
verify_value("IMPLIED_TRISTATE", 2)
c.syms["IMPLY"].unset_value()
verify_value("IMPLIED_BOOL", 0)
assign_and_verify("IMPLY", 0)
verify_value("IMPLIED_BOOL", 0)
assign_and_verify("IMPLY", 1)
verify_value("IMPLIED_BOOL", 2)
assign_and_verify("IMPLY", 2)
verify_value("IMPLIED_BOOL", 2)
c.syms["IMPLY"].set_value(1)
assign_and_verify("IMPLIED_BOOL", 0)
assign_and_verify("IMPLIED_BOOL", 2)
c.syms["IMPLY"].set_value(2)
assign_and_verify("IMPLIED_BOOL", 0)
assign_and_verify("IMPLIED_BOOL", 2)
print("Testing choice semantics")
# deliberately anywhere from what I've seen.
c = Kconfig("Kconfiglib/tests/Kchoice", warn=False)
for name in "BOOL", "BOOL_OPT", "BOOL_M", "DEFAULTS":
verify(c.named_choices[name].orig_type == BOOL,
"choice {} should have type bool".format(name))
for name in "TRISTATE", "TRISTATE_OPT", "TRISTATE_M":
verify(c.named_choices[name].orig_type == TRISTATE,
"choice {} should have type tristate".format(name))
def select_and_verify(sym):
choice = sym.nodes[0].parent.item
choice.set_value(2)
sym.set_value(2)
verify(sym.choice.selection is sym,
sym.name + " should be the selected symbol")
verify(choice.user_selection is sym,
sym.name + " should be the user selection of the choice")
verify(sym.tri_value == 2,
sym.name + " should have value y when selected")
verify(sym.user_value == 2,
sym.name + " should have user value y when selected")
for sibling in choice.syms:
if sibling is not sym:
verify(sibling.tri_value == 0,
sibling.name + " should be n when not selected")
def select_and_verify_all(choice_name):
choice = c.named_choices[choice_name]
for sym in choice.syms:
select_and_verify(sym)
for sym in reversed(choice.syms):
select_and_verify(sym)
def verify_mode(choice_name, no_modules_mode, modules_mode):
choice = c.named_choices[choice_name]
c.modules.set_value(0)
verify(choice.tri_value == no_modules_mode,
'Wrong mode for choice {} with no modules. Expected {}, got {}.'
.format(choice.name, no_modules_mode, choice.tri_value))
c.modules.set_value(2)
verify(choice.tri_value == modules_mode,
'Wrong mode for choice {} with modules. Expected {}, got {}.'
.format(choice.name, modules_mode, choice.tri_value))
verify_mode("BOOL", 2, 2)
verify_mode("BOOL_OPT", 0, 0)
verify_mode("TRISTATE", 2, 1)
verify_mode("TRISTATE_OPT", 0, 0)
verify_mode("BOOL_M", 0, 2)
verify_mode("TRISTATE_M", 0, 1)
choice = c.named_choices["DEFAULTS"]
c.syms["TRISTATE_SYM"].set_value(0)
verify(choice.selection is c.syms["OPT_4"],
"Wrong choice default with TRISTATE_SYM = n")
c.syms["TRISTATE_SYM"].set_value(2)
verify(choice.selection is c.syms["OPT_2"],
"Wrong choice default with TRISTATE_SYM = y")
c.syms["OPT_1"].set_value(2)
verify(choice.selection is c.syms["OPT_1"],
"User selection should override defaults")
verify(c.named_choices["DEFAULTS_NOT_VISIBLE"].selection
is c.syms["OPT_8"],
"Non-visible choice symbols should cause the next default to be "
"considered")
c.modules.set_value(2)
select_and_verify_all("BOOL")
select_and_verify_all("BOOL_OPT")
select_and_verify_all("TRISTATE")
select_and_verify_all("TRISTATE_OPT")
select_and_verify_all("BOOL_M")
c.named_choices["TRISTATE"].set_value(1)
verify(c.named_choices["TRISTATE"].tri_value == 1,
"TRISTATE choice should have mode m after explicit mode assignment")
assign_and_verify_value("T_1", 0, 0)
assign_and_verify_value("T_2", 0, 0)
assign_and_verify_value("T_1", 1, 1)
assign_and_verify_value("T_2", 1, 1)
assign_and_verify_value("T_1", 2, 1)
assign_and_verify_value("T_2", 2, 1)
c.named_choices["TRISTATE"].set_value(2)
verify_value("T_1", 0)
verify_value("T_2", 2)
verify(c.named_choices["NO_TYPE_BOOL"].orig_type == BOOL,
"Expected first choice without explicit type to have type bool")
verify(c.named_choices["NO_TYPE_TRISTATE"].orig_type == TRISTATE,
"Expected second choice without explicit type to have type "
"tristate")
for name in "MMT_1", "MMT_2", "MMT_4", "MMT_5":
verify(c.syms[name].orig_type == BOOL,
"Expected {} to get type bool".format(name))
verify(c.syms["MMT_3"].orig_type == TRISTATE,
"Expected MMT_3 to have type tristate")
default_with_dep_choice = c.named_choices["DEFAULT_WITH_DEP"]
verify(default_with_dep_choice.selection is c.syms["B"],
"Wrong choice default with unsatisfied deps on default")
c.syms["DEP"].set_value("y")
verify(default_with_dep_choice.selection is c.syms["A"],
"Wrong choice default with satisfied deps on default")
c.syms["DEP"].set_value("n")
verify(default_with_dep_choice.selection is c.syms["B"],
"Wrong choice default with unsatisfied deps on default (round two)")
# considered choice symbols
weird_choice = c.named_choices["WEIRD_SYMS"]
def verify_is_normal_choice_symbol(name):
sym = c.syms[name]
verify(sym.choice is not None and
sym in weird_choice.syms and
sym.nodes[0].parent.item is weird_choice,
"{} should be a normal choice symbol".format(sym.name))
def verify_is_weird_choice_symbol(name):
sym = c.syms[name]
verify(sym.choice is None and
sym not in weird_choice.syms,
"{} should be a weird (non-)choice symbol"
.format(sym.name))
verify_is_normal_choice_symbol("WS1")
verify_is_weird_choice_symbol("WS2")
verify_is_weird_choice_symbol("WS3")
verify_is_weird_choice_symbol("WS4")
verify_is_weird_choice_symbol("WS5")
verify_is_normal_choice_symbol("WS6")
verify_is_weird_choice_symbol("WS7")
verify_is_weird_choice_symbol("WS8")
verify_is_normal_choice_symbol("WS9")
print("Testing multi.def. property copying")
c = Kconfig("Kconfiglib/tests/Kdepcopy", warn=False)
def verify_props(desc, props, prop_names):
actual = [prop[0].name for prop in props]
expected = prop_names.split()
verify(actual == expected,
"Wrong {} properties, expected '{}', got '{}'"
.format(desc, expected, actual))
verify_props("default", c.syms["MULTIDEF"].defaults,
"A B C D E F G H I J K L M N O P Q R")
verify_props("select", c.syms["MULTIDEF"].selects,
"AA BB CC DD EE FF GG HH II JJ")
verify_props("imply", c.syms["MULTIDEF"].selects,
"AA BB CC DD EE FF GG HH II JJ")
verify_props("select", c.syms["MULTIDEF_CHOICE"].selects,
"A B C")
verify_props("range", c.syms["MULTIDEF_RANGE"].ranges,
"A B C D E F")
verify_props("default", c.choices[1].defaults,
"A B C D E")
print("Testing dependency loop detection")
# These are all expected to raise dependency loop errors
for i in range(11):
filename = "Kconfiglib/tests/Kdeploop" + str(i)
try:
Kconfig(filename)
except KconfigError as e:
if "Dependency loop" not in str(e):
fail("dependency loop in {} raised wrong KconfigError"
.format(filename))
except:
fail("dependency loop in {} raised wrong exception"
.format(filename))
else:
fail("dependency loop in {} not detected".format(filename))
# Check the most complicated message completely
try:
Kconfig("Kconfiglib/tests/Kdeploop10")
except KconfigError as e:
verify_equal(str(e), """
Dependency loop
===============
A (defined at Kconfiglib/tests/Kdeploop10:1), with definition...
config A
bool
depends on B
...depends on B (defined at Kconfiglib/tests/Kdeploop10:5), with definition...
config B
bool
depends on C = 7
...depends on C (defined at Kconfiglib/tests/Kdeploop10:9), with definition...
config C
int
range D 8
...depends on D (defined at Kconfiglib/tests/Kdeploop10:13), with definition...
config D
int
default 3 if E
default 8
...depends on E (defined at Kconfiglib/tests/Kdeploop10:18), with definition...
config E
bool
(select-related dependencies: F && G)
...depends on G (defined at Kconfiglib/tests/Kdeploop10:25), with definition...
config G
bool
depends on H
...depends on the choice symbol H (defined at Kconfiglib/tests/Kdeploop10:32), with definition...
config H
bool
prompt "H" if I && <choice>
depends on I && <choice>
...depends on the choice symbol I (defined at Kconfiglib/tests/Kdeploop10:41), with definition...
config I
bool
prompt "I" if <choice>
depends on <choice>
...depends on <choice> (defined at Kconfiglib/tests/Kdeploop10:38), with definition...
choice
bool
prompt "choice" if J
...depends on J (defined at Kconfiglib/tests/Kdeploop10:46), with definition...
config J
bool
depends on A
...depends again on A (defined at Kconfiglib/tests/Kdeploop10:1)
"""[:-1])
except:
fail("Loop detection message check raised wrong exception")
else:
fail("Loop detection message check did not raise exception")
print("Testing preprocessor")
os.environ["ENV_1"] = "env_1"
os.environ["ENV_2"] = "env_2"
os.environ["ENV_3"] = "env_3"
os.environ["ENV_4"] = "env_4"
os.environ["ENV_5"] = "n"
os.environ["ENV_6"] = "Kconfiglib/tests/empty"
os.environ["ENV_7"] = "env_7"
# We verify warnings manually
c = Kconfig("Kconfiglib/tests/Kpreprocess", warn_to_stderr=False)
def verify_variable(name, unexp_value, exp_value, recursive):
var = c.variables[name]
verify(var.value == unexp_value,
"expected variable '{}' to have the unexpanded value '{}', had "
"the value '{}'".format(name, unexp_value, var.value))
verify(var.expanded_value == exp_value,
"expected variable '{}' to have the expanded value '{}', had "
"the value '{}'".format(name, exp_value, var.expanded_value))
verify(var.is_recursive == recursive,
"{} was {}, shouldn't be"
.format(name, "recursive" if var.is_recursive else "simple"))
verify_variable("simple-recursive", "foo", "foo", True)
verify_variable("simple-immediate", "bar", "bar", False)
verify_variable("simple-recursive-2", "baz", "baz", True)
verify_variable("whitespaced", "foo", "foo", True)
verify_variable("preserve-recursive", "foo bar", "foo bar", True)
verify_variable("preserve-immediate", "foo bar", "foo bar", False)
verify_variable("recursive",
"$(foo) $(bar) $($(b-char)a$(z-char)) $(indir)",
"abc def ghi jkl mno",
True)
verify_variable("immediate", "foofoo", "foofoo", False)
verify_variable("messy-fn-res",
"$($(fn-indir)-unused-arg, a b , c d )",
'surround-rev-quote " c d " " a b " surround-rev-quote ',
True)
verify_variable("special-chars-fn-res",
"$(fn,$(comma)$(dollar)$(left-paren)foo$(right-paren))",
'",$(foo)"',
True)
verify_str(c.syms["PRINT_ME"], r"""
config PRINT_ME
string
prompt "env_1" if (FOO && BAR) || !BAZ || !QAZ
default "\"foo\"" if "foo \"bar\" baz" = ""
""")
def verify_recursive(name):
try:
c.variables[name].expanded_value
except KconfigError:
pass
else:
fail("Expected '{}' expansion to flag recursive expansion, didn't"
.format(name))
verify_recursive("rec-1")
# Indirectly verifies that it's not recursive
verify_variable("safe-fn-rec-res",
"$(safe-fn-rec,safe-fn-rec-2)",
"foo",
True)
verify_recursive("unsafe-fn-rec")
verify_variable("foo-bar-baz", "$(rhs)", "value", True)
verify_variable("space-var-res", "$(foo bar)", "value", True)
verify_variable("shell-res",
"$(shell,false && echo foo bar || echo baz qaz)",
"baz qaz",
True)
verify_variable("shell-stderr-res", "", "", False)
verify_variable("location-res",
"Kconfiglib/tests/Kpreprocess:119",
"Kconfiglib/tests/Kpreprocess:119",
False)
verify_variable("warning-res", "", "", False)
verify_variable("error-n-res", "", "", False)
try:
c.variables["error-y-res"].expanded_value
except KconfigError:
pass
else:
fail("expanding error-y-res didn't raise an exception")
# Check Kconfig.env_vars
verify_equal(c.env_vars,
set(("ENV_1", "ENV_2", "ENV_3", "ENV_4", "ENV_5", "ENV_6")))
# Check that the expected warnings were generated
verify_equal(c.warnings, [
"Kconfiglib/tests/Kpreprocess:116: warning: 'echo message on stderr >&2' wrote to stderr: message on stderr",
"Kconfiglib/tests/Kpreprocess:124: warning: a warning"
])
print("Testing KCONFIG_STRICT")
os.environ["KCONFIG_STRICT"] = "y"
c = Kconfig("Kconfiglib/tests/Kstrict", warn_to_stderr=False)
verify_equal("\n".join(c.warnings), """
warning: the int symbol INT (defined at Kconfiglib/tests/Kstrict:8) has a non-int range [UNDEF_2 (undefined), 8 (undefined)]
warning: undefined symbol UNDEF_1:
- Referenced at Kconfiglib/tests/Kstrict:4:
config BOOL
bool
prompt "foo" if DEF || !UNDEF_1
default UNDEF_2
- Referenced at Kconfiglib/tests/Kstrict:19:
menu "menu"
depends on UNDEF_1
visible if UNDEF_3
warning: undefined symbol UNDEF_2:
- Referenced at Kconfiglib/tests/Kstrict:4:
config BOOL
bool
prompt "foo" if DEF || !UNDEF_1
default UNDEF_2
- Referenced at Kconfiglib/tests/Kstrict:8:
config INT
int
range UNDEF_2 8
range 5 15
default 10
warning: undefined symbol UNDEF_3:
- Referenced at Kconfiglib/tests/Kstrict:19:
menu "menu"
depends on UNDEF_1
visible if UNDEF_3
"""[1:])
os.environ.pop("KCONFIG_STRICT")
print("\nAll selftests passed\n" if all_passed else
"\nSome selftests failed\n")
def run_compatibility_tests():
# Referenced inside the kernel Kconfig files.
#
# The str() makes the type of the value 'str' on both Python 2 and Python 3,
# which is nice for some later dictionary key sanity checks.
os.environ["KERNELVERSION"] = str(
subprocess.check_output("make kernelversion", shell=True)
.decode("utf-8").rstrip()
)
os.environ["CC_VERSION_TEXT"] = str(
subprocess.check_output("gcc --version | head -n1", shell=True)
.decode("utf-8").rstrip()
)
os.environ["srctree"] = "."
os.environ["CC"] = "gcc"
if not os.path.exists("scripts/kconfig/conf"):
print("\nscripts/kconfig/conf does not exist -- running "
"'make allnoconfig' to build it...")
shell("make allnoconfig")
print("Running compatibility tests...\n")
test_fns = (test_defconfig,
# Fails for a few defconfigs due to a bug in the C tools. Will
# be enabled once patches get in.
#test_min_config,
test_alldefconfig,
test_allnoconfig,
test_allnoconfig_walk,
test_allmodconfig,
test_allyesconfig,
test_sanity)
for test_fn in test_fns:
# The test description is taken from the docstring of the corresponding
# function
print(textwrap.dedent(test_fn.__doc__))
for arch, srcarch in all_arch_srcarch():
# Referenced inside the Kconfig files
os.environ["ARCH"] = arch
os.environ["SRCARCH"] = srcarch
rm_configs()
test_fn(arch, srcarch)
if all_passed:
print("All selftests and compatibility tests passed")
else:
sys.exit("Some tests failed")
def all_arch_srcarch():
for srcarch in os.listdir("arch"):
# arc and h8300 are currently broken with the C tools on linux-next as
# well. Perhaps they require cross-compilers to be installed.
#
# User-mode Linux has an unorthodox Kconfig setup that would require a
# different testing setup. Skip it too.
if srcarch in ("arc", "h8300", "um"):
continue
if os.path.exists(os.path.join("arch", srcarch, "Kconfig")):
yield (srcarch, srcarch)
# Some arches define additional ARCH settings with ARCH != SRCARCH
# (search for "Additional ARCH settings for" in the top-level Makefile)
yield ("i386", "x86")
yield ("x86_64", "x86")
yield ("sparc32", "sparc")
yield ("sparc64", "sparc")
yield ("sh64", "sh")
def test_allnoconfig(arch, srcarch):
shell("make scriptconfig SCRIPT=Kconfiglib/allnoconfig.py "
"PYTHONCMD='{}'".format(sys.executable))
shell("mv .config ._config")
shell("scripts/kconfig/conf --allnoconfig Kconfig")
compare_configs(arch)
def test_allnoconfig_walk(arch, srcarch):
shell("make scriptconfig SCRIPT=Kconfiglib/examples/allnoconfig_walk.py "
"PYTHONCMD='{}'".format(sys.executable))
shell("mv .config ._config")
shell("scripts/kconfig/conf --allnoconfig Kconfig")
compare_configs(arch)
def test_allmodconfig(arch, srcarch):
shell("make scriptconfig SCRIPT=Kconfiglib/allmodconfig.py "
"PYTHONCMD='{}'".format(sys.executable))
shell("mv .config ._config")
shell("scripts/kconfig/conf --allmodconfig Kconfig")
compare_configs(arch)
def test_allyesconfig(arch, srcarch):
shell("make scriptconfig SCRIPT=Kconfiglib/allyesconfig.py "
"PYTHONCMD='{}'".format(sys.executable))
shell("mv .config ._config")
shell("scripts/kconfig/conf --allyesconfig Kconfig")
compare_configs(arch)
def test_sanity(arch, srcarch):
print("For {}...".format(arch))
kconf = Kconfig()
for sym in kconf.defined_syms:
verify(sym._visited == 2,
"{} has broken dependency loop detection (_visited = {})"
.format(sym.name, sym._visited))
kconf.modules
kconf.defconfig_list
kconf.defconfig_filename
kconf.enable_redun_warnings()
kconf.disable_redun_warnings()
kconf.enable_undef_warnings()
kconf.disable_undef_warnings()
kconf.enable_warnings()
kconf.disable_warnings()
kconf.enable_stderr_warnings()
kconf.disable_stderr_warnings()
kconf.mainmenu_text
kconf.unset_values()
kconf.write_autoconf("/dev/null")
# No tempfile.TemporaryDirectory in Python 2
tmpdir = tempfile.mkdtemp()
kconf.sync_deps(os.path.join(tmpdir, "deps")) # Create
kconf.sync_deps(os.path.join(tmpdir, "deps")) # Update
shutil.rmtree(tmpdir)
# Python 2/3 compatible
for key, sym in kconf.syms.items():
verify(isinstance(key, str), "weird key '{}' in syms dict".format(key))
verify(not sym.is_constant, sym.name + " in 'syms' and constant")
verify(sym not in kconf.const_syms,
sym.name + " in both 'syms' and 'const_syms'")
for dep in sym._dependents:
verify(not dep.is_constant,
"the constant symbol {} depends on {}"
.format(dep.name, sym.name))
sym.__repr__()
sym.__str__()
sym.assignable
kconf.disable_warnings()
sym.set_value(2)
sym.set_value("foo")
sym.unset_value()
kconf.enable_warnings()
sym.str_value
sym.tri_value
sym.type
sym.user_value
sym.visibility
for sym in kconf.defined_syms:
verify(sym.nodes, sym.name + " is defined but lacks menu nodes")
verify(not (sym.orig_type not in (BOOL, TRISTATE) and sym.choice),
sym.name + " is a choice symbol but not bool/tristate")
for key, sym in kconf.const_syms.items():
verify(isinstance(key, str),
"weird key '{}' in const_syms dict".format(key))
verify(sym.is_constant,
'"{}" is in const_syms but not marked constant'
.format(sym.name))
verify(not sym.nodes,
'"{}" is constant but has menu nodes'.format(sym.name))
verify(not sym._dependents,
'"{}" is constant but is a dependency of some symbol'
.format(sym.name))
verify(not sym.choice,
'"{}" is constant and a choice symbol'.format(sym.name))
sym.__repr__()
sym.__str__()
sym.assignable
kconf.disable_warnings()
sym.set_value(2)
sym.set_value("foo")
sym.unset_value()
kconf.enable_warnings()
sym.str_value
sym.tri_value
sym.type
sym.visibility
for choice in kconf.choices:
for sym in choice.syms:
verify(sym.choice is choice,
"{0} is in choice.syms but 'sym.choice' is not the choice"
.format(sym.name))
verify(sym.type in (BOOL, TRISTATE),
"{} is a choice symbol but is not a bool/tristate"
.format(sym.name))
choice.__str__()
choice.__repr__()
choice.str_value
choice.tri_value
choice.user_value
choice.assignable
choice.selection
choice.type
choice.visibility
# Menu nodes
node = kconf.top_node
while 1:
# Everything else should be well exercised elsewhere
node.__repr__()
node.__str__()
verify(isinstance(node.item, (Symbol, Choice)) or \
node.item in (MENU, COMMENT),
"'{}' appeared as a menu item".format(node.item))
if node.list is not None:
node = node.list
elif node.next is not None:
node = node.next
else:
while node.parent is not None:
node = node.parent
if node.next is not None:
node = node.next
break
else:
break
def test_alldefconfig(arch, srcarch):
shell("make scriptconfig SCRIPT=Kconfiglib/alldefconfig.py "
"PYTHONCMD='{}'".format(sys.executable))
shell("mv .config ._config")
shell("scripts/kconfig/conf --alldefconfig Kconfig")
compare_configs(arch)
def test_defconfig(arch, srcarch):
kconf = Kconfig()
if obsessive:
defconfigs = []
# Collect all defconfigs. This could be done once instead, but it's
for srcarch_ in os.listdir("arch"):
defconfigs.extend(defconfig_files(srcarch_))
else:
defconfigs = defconfig_files(srcarch)
for defconfig in defconfigs:
rm_configs()
kconf.load_config(defconfig)
kconf.write_config("._config")
shell("scripts/kconfig/conf --defconfig='{}' Kconfig".
format(defconfig))
arch_defconfig_str = " {:14}with {:60} ".format(arch, defconfig)
if equal_configs():
print(arch_defconfig_str + "OK")
else:
print(arch_defconfig_str + "FAIL")
fail()
if log:
with open("test_defconfig_fails", "a") as fail_log:
fail_log.write("{} with {} did not match\n"
.format(arch, defconfig))
def test_min_config(arch, srcarch):
kconf = Kconfig()
if obsessive_min_config:
defconfigs = []
for srcarch_ in os.listdir("arch"):
defconfigs.extend(defconfig_files(srcarch_))
else:
defconfigs = defconfig_files(srcarch)
for defconfig in defconfigs:
rm_configs()
kconf.load_config(defconfig)
kconf.write_min_config("._config")
shell("cp {} .config".format(defconfig))
shell("scripts/kconfig/conf --savedefconfig=.config Kconfig")
arch_defconfig_str = " {:14}with {:60} ".format(arch, defconfig)
if equal_configs():
print(arch_defconfig_str + "OK")
else:
print(arch_defconfig_str + "FAIL")
def defconfig_files(srcarch):
srcarch_dir = os.path.join("arch", srcarch)
root_defconfig = os.path.join(srcarch_dir, "defconfig")
if os.path.exists(root_defconfig):
yield root_defconfig
defconfigs_dir = os.path.join(srcarch_dir, "configs")
if not os.path.isdir(defconfigs_dir):
return
for dirpath, _, filenames in os.walk(defconfigs_dir):
for filename in filenames:
yield os.path.join(dirpath, filename)
def rm_configs():
def rm_if_exists(f):
if os.path.exists(f):
os.remove(f)
rm_if_exists(".config")
rm_if_exists("._config")
def compare_configs(arch):
if equal_configs():
print("{:14}OK".format(arch))
else:
print("{:14}FAIL".format(arch))
fail()
def equal_configs():
with open(".config") as f:
their = f.readlines()
i = 0
for line in their:
if not line.startswith("#") or \
re.match(r"# CONFIG_(\w+) is not set", line):
break
i += 1
their = their[i:]
try:
f = open("._config")
except IOError as e:
if e.errno != errno.ENOENT:
raise
print("._config not found. Did you forget to apply the Makefile patch?")
return False
else:
with f:
our = f.readlines()[1:]
if their == our:
return True
print("Mismatched .config's! Unified diff:")
sys.stdout.writelines(difflib.unified_diff(their, our, fromfile="their",
tofile="our"))
return False
if __name__ == "__main__":
run_tests()
| true | true |
f7f75ebe5411c610c2b0d4c422d7d98754dee352 | 3,839 | py | Python | build_dictionaries.py | spallas/wsd | 97154b7c1ba5baa68e6336d709f188f416fe2f4c | [
"MIT"
] | 4 | 2020-01-07T15:45:37.000Z | 2020-09-11T08:25:14.000Z | build_dictionaries.py | spallas/wsd | 97154b7c1ba5baa68e6336d709f188f416fe2f4c | [
"MIT"
] | 1 | 2020-06-08T21:15:22.000Z | 2020-06-09T21:56:03.000Z | build_dictionaries.py | spallas/wsd | 97154b7c1ba5baa68e6336d709f188f416fe2f4c | [
"MIT"
] | 1 | 2020-11-19T06:06:31.000Z | 2020-11-19T06:06:31.000Z | import argparse
from collections import OrderedDict
from nltk.corpus import wordnet as wn
def _get_dicts(syn_lemma_vocab='res/dictionaries/syn_lemma_vocab.txt',
senses_vocab='res/dictionaries/senses.txt'):
with open(senses_vocab) as f:
sense2id = {line.strip().split()[0]: int(line.strip().split()[1]) for line in f}
wn_lemmas = OrderedDict()
with open(syn_lemma_vocab) as f:
for i, line in enumerate(f):
wn_lemmas[line.strip()] = i
return sense2id, wn_lemmas
def build_1hop(dest_path='res/dictionaries/sense_lemmas_1hop.txt',
syn_lemma_vocab='res/dictionaries/syn_lemma_vocab.txt',
senses_vocab='res/dictionaries/senses.txt'):
sense2id, wn_lemmas = _get_dicts(syn_lemma_vocab, senses_vocab)
with open(dest_path, 'w') as f:
for S in sorted(sense2id.keys()):
synset = wn.synset(S)
hyper_list = synset.hypernyms()
hypo_list = synset.hyponyms()
synset_lemmas = synset.lemma_names()
for h_s in hyper_list + hypo_list:
synset_lemmas += h_s.lemma_names()
syn_lemma_ids = [wn_lemmas[l] for l in synset_lemmas if l in wn_lemmas]
print(f"{sense2id[S]}\t{syn_lemma_ids}", file=f)
#
# def build_blc(dest_path='res/dictionaries/sense_lemmas_blc.txt',
# syn_lemma_vocab='res/dictionaries/syn_lemma_vocab.txt',
# senses_vocab='res/dictionaries/senses.txt'):
# sense2id, wn_lemmas = _get_dicts(syn_lemma_vocab, senses_vocab)
# smap = SynsetMap('blc', 'res/blc/???')
# with open(dest_path, 'w') as f:
# for S in sorted(sense2id.keys()):
# actual_synset = smap.map_synset(S)
# syn_lemma_ids = [wn_lemmas[l] for l in actual_synset.lemma_names() if l in wn_lemmas]
# print(f"{sense2id[S]}\t{syn_lemma_ids}", file=f)
#
#
# def build_macro(dest_path='res/dictionaries/sense_lemmas_macro.txt',
# syn_lemma_vocab='res/dictionaries/syn_lemma_vocab.txt',
# senses_vocab='res/dictionaries/senses.txt'):
# sense2id, wn_lemmas = _get_dicts(syn_lemma_vocab, senses_vocab)
# smap = SynsetMap('macro', 'res/macrosenses/???')
# with open(dest_path, 'w') as f:
# for S in sorted(sense2id.keys()):
# actual_synset = smap.map_synset(S)
# syn_lemma_ids = [wn_lemmas[l] for l in actual_synset.lemma_names() if l in wn_lemmas]
# print(f"{sense2id[S]}\t{syn_lemma_ids}", file=f)
def build_hyper(dest_path='res/dictionaries/sense_lemmas_hyper.txt',
syn_lemma_vocab='res/dictionaries/syn_lemma_vocab.txt',
senses_vocab='res/dictionaries/senses.txt'):
sense2id, wn_lemmas = _get_dicts(syn_lemma_vocab, senses_vocab)
with open(dest_path, 'w') as f:
for S in sorted(sense2id.keys()):
synset = wn.synset(S)
hyper_list = synset.hypernyms()
synset_lemmas = synset.lemma_names()
for h_s in hyper_list:
synset_lemmas += h_s.lemma_names()
syn_lemma_ids = [wn_lemmas[l] for l in synset_lemmas if l in wn_lemmas]
print(f"{sense2id[S]}\t{syn_lemma_ids}", file=f)
def build_synset(dest_path='res/dictionaries/sense_lemmas_synset_.txt',
syn_lemma_vocab='res/dictionaries/syn_lemma_vocab.txt',
senses_vocab='res/dictionaries/senses.txt'):
sense2id, wn_lemmas = _get_dicts(syn_lemma_vocab, senses_vocab)
with open(dest_path, 'w') as f:
for S in sorted(sense2id.keys()):
synset_lemmas = wn.synset(S).lemma_names()
syn_lemma_ids = [wn_lemmas[l] for l in synset_lemmas]
print(f"{sense2id[S]}\t{syn_lemma_ids}", file=f)
def main():
build_hyper()
if __name__ == '__main__':
main()
| 43.134831 | 99 | 0.642355 | import argparse
from collections import OrderedDict
from nltk.corpus import wordnet as wn
def _get_dicts(syn_lemma_vocab='res/dictionaries/syn_lemma_vocab.txt',
senses_vocab='res/dictionaries/senses.txt'):
with open(senses_vocab) as f:
sense2id = {line.strip().split()[0]: int(line.strip().split()[1]) for line in f}
wn_lemmas = OrderedDict()
with open(syn_lemma_vocab) as f:
for i, line in enumerate(f):
wn_lemmas[line.strip()] = i
return sense2id, wn_lemmas
def build_1hop(dest_path='res/dictionaries/sense_lemmas_1hop.txt',
syn_lemma_vocab='res/dictionaries/syn_lemma_vocab.txt',
senses_vocab='res/dictionaries/senses.txt'):
sense2id, wn_lemmas = _get_dicts(syn_lemma_vocab, senses_vocab)
with open(dest_path, 'w') as f:
for S in sorted(sense2id.keys()):
synset = wn.synset(S)
hyper_list = synset.hypernyms()
hypo_list = synset.hyponyms()
synset_lemmas = synset.lemma_names()
for h_s in hyper_list + hypo_list:
synset_lemmas += h_s.lemma_names()
syn_lemma_ids = [wn_lemmas[l] for l in synset_lemmas if l in wn_lemmas]
print(f"{sense2id[S]}\t{syn_lemma_ids}", file=f)
def build_hyper(dest_path='res/dictionaries/sense_lemmas_hyper.txt',
syn_lemma_vocab='res/dictionaries/syn_lemma_vocab.txt',
senses_vocab='res/dictionaries/senses.txt'):
sense2id, wn_lemmas = _get_dicts(syn_lemma_vocab, senses_vocab)
with open(dest_path, 'w') as f:
for S in sorted(sense2id.keys()):
synset = wn.synset(S)
hyper_list = synset.hypernyms()
synset_lemmas = synset.lemma_names()
for h_s in hyper_list:
synset_lemmas += h_s.lemma_names()
syn_lemma_ids = [wn_lemmas[l] for l in synset_lemmas if l in wn_lemmas]
print(f"{sense2id[S]}\t{syn_lemma_ids}", file=f)
def build_synset(dest_path='res/dictionaries/sense_lemmas_synset_.txt',
syn_lemma_vocab='res/dictionaries/syn_lemma_vocab.txt',
senses_vocab='res/dictionaries/senses.txt'):
sense2id, wn_lemmas = _get_dicts(syn_lemma_vocab, senses_vocab)
with open(dest_path, 'w') as f:
for S in sorted(sense2id.keys()):
synset_lemmas = wn.synset(S).lemma_names()
syn_lemma_ids = [wn_lemmas[l] for l in synset_lemmas]
print(f"{sense2id[S]}\t{syn_lemma_ids}", file=f)
def main():
build_hyper()
if __name__ == '__main__':
main()
| true | true |
f7f75fa6812685470f7d045729a7a77b6d6e0f56 | 12,299 | py | Python | xgcm/test/test_autogenerate.py | IvanaEscobar/xgcm | 2ecc59cbd0af9ac1d21eee9c2b18a639cf0e02b4 | [
"MIT"
] | 174 | 2015-09-19T16:40:29.000Z | 2022-03-25T13:25:45.000Z | xgcm/test/test_autogenerate.py | IvanaEscobar/xgcm | 2ecc59cbd0af9ac1d21eee9c2b18a639cf0e02b4 | [
"MIT"
] | 384 | 2015-10-27T18:55:28.000Z | 2022-03-31T21:33:04.000Z | xgcm/test/test_autogenerate.py | andersy005/xgcm | 95f4f33d72d2add00136e27f6b3bedecb97d4d77 | [
"MIT"
] | 74 | 2015-08-30T23:19:19.000Z | 2021-07-29T00:41:49.000Z | import numpy as np
import pytest
import xarray as xr
from xarray.testing import assert_allclose, assert_equal
from xgcm.autogenerate import (
_fill_attrs,
_parse_boundary_params,
_parse_position,
_position_to_relative,
generate_axis,
generate_grid_ds,
)
# create test datasets
pad_value = 1000
dx = 5.0
dy = 2.5
dz = 0.5
a = np.random.rand(int(180 / dy), int(360 / dx), int(10 / dz))
x = np.arange(-180 + dx, 180 + dx, dx)
y = np.arange(-90 + dy, 90 + dy, dy)
z = np.arange(0 + dz, 10 + dz, dz)
x_outer = np.arange(-180 + dx / 2, 180 + dx, dx)
y_outer = np.arange(-90 + dy / 2, 90 + dy, dy)
z_outer = np.arange(0 + dz / 2, 10 + dz, dz)
z_1D = z[0:3]
z_1D_padded = np.hstack([z[0:2] + (dz / 2.0), (z[2] + pad_value) / 2])
xx, yy = np.meshgrid(x, y)
_, _, zz = np.meshgrid(x, y, z)
xx_outer, _ = np.meshgrid(x_outer, y)
_, yy_outer = np.meshgrid(x, y_outer)
_, _, zz_outer = np.meshgrid(x, y, z_outer)
ds_original = xr.Dataset(
{"somedata": (["lat", "lon", "z"], a)},
coords={
"lon": (["lon"], x + (dx / 2.0)),
"lat": (["lat"], y + (dy / 2.0)),
"z": (["z"], z + (dz / 2.0)),
"llon": (["lat", "lon"], xx + (dx / 2.0)),
"llat": (["lat", "lon"], yy + (dy / 2.0)),
"zz": (["lat", "lon", "z"], zz + (dz / 2.0)),
},
)
ds_original_left = xr.Dataset(
{"somedata": (["lat", "lon", "z"], a)},
coords={
"lon": (["lon"], x),
"lat": (["lat"], y),
"z": (["z"], z),
"llon": (["lat", "lon"], xx),
"llat": (["lat", "lon"], yy),
"zz": (["lat", "lon", "z"], zz),
},
)
ds_original_1D = xr.Dataset(
{"somedata": (["z"], np.array([1, 2, 3]))}, coords={"z": (["z"], z_1D)}
)
ds_original_1D_padded = xr.Dataset(
{"somedata": (["z"], np.array([1, 2, 3]))},
coords={"z": (["z"], z[0:3]), "test": (["test"], z_1D_padded)},
)
ds_out_left = xr.Dataset(
{"somedata": (["lat", "lon", "z"], a)},
coords={
"lon": (["lon"], x + (dx / 2.0), {"axis": "X"}),
"lat": (["lat"], y + (dy / 2.0), {"axis": "Y"}),
"z": (["z"], z + (dz / 2.0), {"axis": "Z"}),
"llon": (["lat", "lon"], xx + (dx / 2.0), {"axis": "X"}),
"llat": (["lat", "lon"], yy + (dy / 2.0), {"axis": "Y"}),
"zz": (["lat", "lon", "z"], zz + (dz / 2.0), {"axis": "Z"}),
"lon_left": (["lon_left"], x, {"axis": "X", "c_grid_axis_shift": -0.5}),
"lat_left": (["lat_left"], y, {"axis": "Y", "c_grid_axis_shift": -0.5}),
"z_left": (["z_left"], z, {"axis": "Z", "c_grid_axis_shift": -0.5}),
"llon_left": (
["lat", "lon_left"],
xx,
{"axis": "X", "c_grid_axis_shift": -0.5},
),
"llat_left": (
["lat_left", "lon"],
yy,
{"axis": "Y", "c_grid_axis_shift": -0.5},
),
"zz_left": (
["lat", "lon", "z_left"],
zz,
{"axis": "Z", "c_grid_axis_shift": -0.5},
),
},
)
ds_out_right = xr.Dataset(
{"somedata": (["lat", "lon", "z"], a)},
coords={
"lon": (["lon"], x + (dx / 2.0), {"axis": "X", "c_grid_axis_shift": -0.5}),
"lat": (["lat"], y + (dy / 2.0), {"axis": "Y", "c_grid_axis_shift": -0.5}),
"z": (["z"], z + (dz / 2.0), {"axis": "Z", "c_grid_axis_shift": -0.5}),
"llon": (
["lat", "lon"],
xx + (dx / 2.0),
{"axis": "X", "c_grid_axis_shift": -0.5},
),
"llat": (
["lat", "lon"],
yy + (dy / 2.0),
{"axis": "Y", "c_grid_axis_shift": -0.5},
),
"zz": (
["lat", "lon", "z"],
zz + (dz / 2.0),
{"axis": "Z", "c_grid_axis_shift": -0.5},
),
"lon_right": (["lon_right"], x + dx, {"axis": "X"}),
"lat_right": (["lat_right"], y + dy, {"axis": "Y"}),
"z_right": (["z_right"], z + dz, {"axis": "Z"}),
"llon_right": (["lat", "lon_right"], xx + dx, {"axis": "X"}),
"llat_right": (["lat_right", "lon"], yy + dy, {"axis": "Y"}),
"zz_right": (["lat", "lon", "z_right"], zz + dz, {"axis": "Z"}),
},
)
ds_out_center = xr.Dataset(
{"somedata": (["lat", "lon", "z"], a)},
coords={
"lon": (["lon"], x, {"axis": "X", "c_grid_axis_shift": -0.5}),
"lat": (["lat"], y, {"axis": "Y", "c_grid_axis_shift": -0.5}),
"z": (["z"], z, {"axis": "Z", "c_grid_axis_shift": -0.5}),
"llon": (["lat", "lon"], xx, {"axis": "X", "c_grid_axis_shift": -0.5}),
"llat": (["lat", "lon"], yy, {"axis": "Y", "c_grid_axis_shift": -0.5}),
"zz": (["lat", "lon", "z"], zz, {"axis": "Z", "c_grid_axis_shift": -0.5}),
"lon_center": (["lon_center"], x + (dx / 2.0), {"axis": "X"}),
"lat_center": (["lat_center"], y + (dy / 2.0), {"axis": "Y"}),
"z_center": (["z_center"], z + (dz / 2.0), {"axis": "Z"}),
"llon_center": (["lat", "lon_center"], xx + (dx / 2.0), {"axis": "X"}),
"llat_center": (["lat_center", "lon"], yy + (dy / 2.0), {"axis": "Y"}),
"zz_center": (["lat", "lon", "z_center"], zz + (dz / 2.0), {"axis": "Z"}),
},
)
ds_out_outer = xr.Dataset(
{"somedata": (["lat", "lon", "z"], a)},
coords={
"lon": (["lon"], x, {"axis": "X"}),
"lat": (["lat"], y, {"axis": "Y"}),
"z": (["z"], z, {"axis": "Z"}),
"llon": (["lat", "lon"], xx, {"axis": "X"}),
"llat": (["lat", "lon"], yy, {"axis": "Y"}),
"zz": (["lat", "lon", "z"], zz, {"axis": "Z"}),
"lon_outer": (["lon_outer"], x_outer, {"axis": "X", "c_grid_axis_shift": -0.5}),
"lat_outer": (["lat_outer"], y_outer, {"axis": "Y", "c_grid_axis_shift": -0.5}),
"z_outer": (["z_outer"], z_outer, {"axis": "Z", "c_grid_axis_shift": -0.5}),
"llon_outer": (
["lat", "lon_outer"],
xx_outer,
{"axis": "X", "c_grid_axis_shift": -0.5},
),
"llat_outer": (
["lat_outer", "lon"],
yy_outer,
{"axis": "Y", "c_grid_axis_shift": -0.5},
),
"zz_outer": (
["lat", "lon", "z_outer"],
zz_outer,
{"axis": "Z", "c_grid_axis_shift": -0.5},
),
},
)
def test_generate_axis():
a = generate_axis(
ds_original,
"X",
"lon",
"lon",
pos_from="center",
pos_to="right",
pad=None,
boundary_discontinuity=360,
)
b = generate_axis(
ds_original,
"Y",
"lat",
"lat",
pos_from="center",
pos_to="left",
pad=None,
boundary_discontinuity=180,
)
c = generate_axis(
ds_original, "Z", "z", "z", pos_from="center", pos_to="left", pad="auto"
)
d = generate_axis(
ds_original_1D,
"Z",
"z",
"z",
pos_from="left",
pos_to="center",
pad=pad_value,
new_name="test",
)
e = generate_axis(
ds_original_left, "Z", "z", "z", pos_from="left", pos_to="center", pad="auto"
)
f = generate_axis(
ds_original_left, "Z", "z", "z", pos_from="center", pos_to="outer", pad="auto"
)
g = generate_axis(
ds_original_left,
"X",
"lon",
"lon",
pos_from="center",
pos_to="outer",
pad=None,
boundary_discontinuity=360,
)
assert_allclose(a["lon_right"], ds_out_right["lon_right"])
assert_allclose(b["lat_left"], ds_out_left["lat_left"])
assert_allclose(c["z_left"], ds_out_left["z_left"])
assert_allclose(d["test"], ds_original_1D_padded["test"])
assert_allclose(e["z_center"], ds_out_center["z_center"])
assert_allclose(f["z_outer"], ds_out_outer["z_outer"])
assert_allclose(g["lon_outer"], ds_out_outer["lon_outer"])
# Mulitdim cases
aa = generate_axis(
a,
"X",
"llon",
"lon",
pos_from="center",
pos_to="right",
pad=None,
boundary_discontinuity=360,
attrs_from_scratch=False,
)
bb = generate_axis(
b,
"Y",
"llat",
"lat",
pos_from="center",
pos_to="left",
pad=None,
boundary_discontinuity=180,
attrs_from_scratch=False,
)
ee = generate_axis(
e,
"Z",
"zz",
"z",
pos_from="left",
pos_to="center",
pad="auto",
attrs_from_scratch=False,
)
ff = generate_axis(
f,
"Z",
"zz",
"z",
pos_from="center",
pos_to="outer",
pad="auto",
attrs_from_scratch=False,
)
gg = generate_axis(
g,
"X",
"llon",
"lon",
pos_from="center",
pos_to="outer",
pad=None,
boundary_discontinuity=360,
attrs_from_scratch=False,
)
assert_allclose(aa["llon_right"], ds_out_right["llon_right"])
assert_allclose(bb["llat_left"], ds_out_left["llat_left"])
assert_allclose(ee["zz_center"], ds_out_center["zz_center"])
assert_allclose(ff["zz_outer"], ds_out_outer["zz_outer"])
assert_allclose(gg["llon_outer"], ds_out_outer["llon_outer"])
with pytest.raises(ValueError):
# Check if generate axis fails when a DataArray is passed instead of
# Dataset
generate_axis(
c["somedata"],
"Z",
"zz",
"z",
pos_from="left",
pos_to="center",
pad="auto",
attrs_from_scratch=False,
)
with pytest.raises(ValueError):
generate_axis(c, "Z", "zz", "z", pad="auto", boundary_discontinuity=360)
with pytest.raises(ValueError):
generate_axis(c, "Z", "zz", "z", pad=None, boundary_discontinuity=None)
def test_generate_grid_ds():
# This needs more cases
axis_dims = {"X": "lon", "Y": "lat", "Z": "z"}
axis_coords = {"X": "llon", "Y": "llat", "Z": "zz"}
position = ("center", "outer")
boundary_discontinuity = {"lon": 360, "llon": 360, "lat": 180, "llat": 180}
pad = {"z": "auto", "zz": "auto"}
ds = generate_grid_ds(
ds_original_left, axis_dims, axis_coords, position, boundary_discontinuity, pad
)
assert_equal(ds, ds_out_outer)
def test_parse_boundary_params():
assert _parse_boundary_params(360, "anything") == 360
assert _parse_boundary_params({"something": 360}, "something") == 360
assert _parse_boundary_params({"something": 360}, "something_else") is None
@pytest.mark.parametrize(
"p_f, p_t",
[("left", "center"), ("center", "left"), ("center", "right"), ("right", "center")],
)
def test_parse_position(p_f, p_t):
default = ("center", "left")
assert _parse_position((p_f, p_t), "anything") == (p_f, p_t)
assert _parse_position({"a": (p_f, p_t)}, "a") == (p_f, p_t)
assert _parse_position({"a": (p_f, p_t)}, "b") == default
assert _parse_position({"a": (p_f, p_t), "b": (p_t, p_f)}, "a") == (p_f, p_t)
assert _parse_position({"a": (p_f, p_t), "b": (p_t, p_f)}, "b") == (p_t, p_f)
@pytest.mark.parametrize(
"p, relative",
[
(("left", "center"), "right"),
(("center", "left"), "left"),
(("center", "right"), "right"),
(("right", "center"), "left"),
(("center", "outer"), "outer"),
(("center", "inner"), "inner"),
],
)
def test_position_to_relative(p, relative):
assert _position_to_relative(p[0], p[1]) == relative
error_test = [
("left", "right"),
("inner", "outer"),
("left", "outer"),
("right", "outer"),
("left", "inner"),
("right", "inner"),
]
for et in error_test:
with pytest.raises(RuntimeError):
_position_to_relative(et[0], et[1])
with pytest.raises(RuntimeError):
_position_to_relative(et[1], et[0])
def test_fill_attrs():
a = _fill_attrs(ds_out_right["lon"], "right", "X")
assert a.attrs["axis"] == "X"
assert a.attrs["c_grid_axis_shift"] == 0.5
a = _fill_attrs(ds_out_right["lon"], "left", "Z")
assert a.attrs["axis"] == "Z"
assert a.attrs["c_grid_axis_shift"] == -0.5
a = _fill_attrs(ds_out_right["lon"], "center", "Y")
assert a.attrs["axis"] == "Y"
assert "c_grid_axis_shift" not in a.attrs.keys()
| 31.616967 | 88 | 0.484917 | import numpy as np
import pytest
import xarray as xr
from xarray.testing import assert_allclose, assert_equal
from xgcm.autogenerate import (
_fill_attrs,
_parse_boundary_params,
_parse_position,
_position_to_relative,
generate_axis,
generate_grid_ds,
)
pad_value = 1000
dx = 5.0
dy = 2.5
dz = 0.5
a = np.random.rand(int(180 / dy), int(360 / dx), int(10 / dz))
x = np.arange(-180 + dx, 180 + dx, dx)
y = np.arange(-90 + dy, 90 + dy, dy)
z = np.arange(0 + dz, 10 + dz, dz)
x_outer = np.arange(-180 + dx / 2, 180 + dx, dx)
y_outer = np.arange(-90 + dy / 2, 90 + dy, dy)
z_outer = np.arange(0 + dz / 2, 10 + dz, dz)
z_1D = z[0:3]
z_1D_padded = np.hstack([z[0:2] + (dz / 2.0), (z[2] + pad_value) / 2])
xx, yy = np.meshgrid(x, y)
_, _, zz = np.meshgrid(x, y, z)
xx_outer, _ = np.meshgrid(x_outer, y)
_, yy_outer = np.meshgrid(x, y_outer)
_, _, zz_outer = np.meshgrid(x, y, z_outer)
ds_original = xr.Dataset(
{"somedata": (["lat", "lon", "z"], a)},
coords={
"lon": (["lon"], x + (dx / 2.0)),
"lat": (["lat"], y + (dy / 2.0)),
"z": (["z"], z + (dz / 2.0)),
"llon": (["lat", "lon"], xx + (dx / 2.0)),
"llat": (["lat", "lon"], yy + (dy / 2.0)),
"zz": (["lat", "lon", "z"], zz + (dz / 2.0)),
},
)
ds_original_left = xr.Dataset(
{"somedata": (["lat", "lon", "z"], a)},
coords={
"lon": (["lon"], x),
"lat": (["lat"], y),
"z": (["z"], z),
"llon": (["lat", "lon"], xx),
"llat": (["lat", "lon"], yy),
"zz": (["lat", "lon", "z"], zz),
},
)
ds_original_1D = xr.Dataset(
{"somedata": (["z"], np.array([1, 2, 3]))}, coords={"z": (["z"], z_1D)}
)
ds_original_1D_padded = xr.Dataset(
{"somedata": (["z"], np.array([1, 2, 3]))},
coords={"z": (["z"], z[0:3]), "test": (["test"], z_1D_padded)},
)
ds_out_left = xr.Dataset(
{"somedata": (["lat", "lon", "z"], a)},
coords={
"lon": (["lon"], x + (dx / 2.0), {"axis": "X"}),
"lat": (["lat"], y + (dy / 2.0), {"axis": "Y"}),
"z": (["z"], z + (dz / 2.0), {"axis": "Z"}),
"llon": (["lat", "lon"], xx + (dx / 2.0), {"axis": "X"}),
"llat": (["lat", "lon"], yy + (dy / 2.0), {"axis": "Y"}),
"zz": (["lat", "lon", "z"], zz + (dz / 2.0), {"axis": "Z"}),
"lon_left": (["lon_left"], x, {"axis": "X", "c_grid_axis_shift": -0.5}),
"lat_left": (["lat_left"], y, {"axis": "Y", "c_grid_axis_shift": -0.5}),
"z_left": (["z_left"], z, {"axis": "Z", "c_grid_axis_shift": -0.5}),
"llon_left": (
["lat", "lon_left"],
xx,
{"axis": "X", "c_grid_axis_shift": -0.5},
),
"llat_left": (
["lat_left", "lon"],
yy,
{"axis": "Y", "c_grid_axis_shift": -0.5},
),
"zz_left": (
["lat", "lon", "z_left"],
zz,
{"axis": "Z", "c_grid_axis_shift": -0.5},
),
},
)
ds_out_right = xr.Dataset(
{"somedata": (["lat", "lon", "z"], a)},
coords={
"lon": (["lon"], x + (dx / 2.0), {"axis": "X", "c_grid_axis_shift": -0.5}),
"lat": (["lat"], y + (dy / 2.0), {"axis": "Y", "c_grid_axis_shift": -0.5}),
"z": (["z"], z + (dz / 2.0), {"axis": "Z", "c_grid_axis_shift": -0.5}),
"llon": (
["lat", "lon"],
xx + (dx / 2.0),
{"axis": "X", "c_grid_axis_shift": -0.5},
),
"llat": (
["lat", "lon"],
yy + (dy / 2.0),
{"axis": "Y", "c_grid_axis_shift": -0.5},
),
"zz": (
["lat", "lon", "z"],
zz + (dz / 2.0),
{"axis": "Z", "c_grid_axis_shift": -0.5},
),
"lon_right": (["lon_right"], x + dx, {"axis": "X"}),
"lat_right": (["lat_right"], y + dy, {"axis": "Y"}),
"z_right": (["z_right"], z + dz, {"axis": "Z"}),
"llon_right": (["lat", "lon_right"], xx + dx, {"axis": "X"}),
"llat_right": (["lat_right", "lon"], yy + dy, {"axis": "Y"}),
"zz_right": (["lat", "lon", "z_right"], zz + dz, {"axis": "Z"}),
},
)
ds_out_center = xr.Dataset(
{"somedata": (["lat", "lon", "z"], a)},
coords={
"lon": (["lon"], x, {"axis": "X", "c_grid_axis_shift": -0.5}),
"lat": (["lat"], y, {"axis": "Y", "c_grid_axis_shift": -0.5}),
"z": (["z"], z, {"axis": "Z", "c_grid_axis_shift": -0.5}),
"llon": (["lat", "lon"], xx, {"axis": "X", "c_grid_axis_shift": -0.5}),
"llat": (["lat", "lon"], yy, {"axis": "Y", "c_grid_axis_shift": -0.5}),
"zz": (["lat", "lon", "z"], zz, {"axis": "Z", "c_grid_axis_shift": -0.5}),
"lon_center": (["lon_center"], x + (dx / 2.0), {"axis": "X"}),
"lat_center": (["lat_center"], y + (dy / 2.0), {"axis": "Y"}),
"z_center": (["z_center"], z + (dz / 2.0), {"axis": "Z"}),
"llon_center": (["lat", "lon_center"], xx + (dx / 2.0), {"axis": "X"}),
"llat_center": (["lat_center", "lon"], yy + (dy / 2.0), {"axis": "Y"}),
"zz_center": (["lat", "lon", "z_center"], zz + (dz / 2.0), {"axis": "Z"}),
},
)
ds_out_outer = xr.Dataset(
{"somedata": (["lat", "lon", "z"], a)},
coords={
"lon": (["lon"], x, {"axis": "X"}),
"lat": (["lat"], y, {"axis": "Y"}),
"z": (["z"], z, {"axis": "Z"}),
"llon": (["lat", "lon"], xx, {"axis": "X"}),
"llat": (["lat", "lon"], yy, {"axis": "Y"}),
"zz": (["lat", "lon", "z"], zz, {"axis": "Z"}),
"lon_outer": (["lon_outer"], x_outer, {"axis": "X", "c_grid_axis_shift": -0.5}),
"lat_outer": (["lat_outer"], y_outer, {"axis": "Y", "c_grid_axis_shift": -0.5}),
"z_outer": (["z_outer"], z_outer, {"axis": "Z", "c_grid_axis_shift": -0.5}),
"llon_outer": (
["lat", "lon_outer"],
xx_outer,
{"axis": "X", "c_grid_axis_shift": -0.5},
),
"llat_outer": (
["lat_outer", "lon"],
yy_outer,
{"axis": "Y", "c_grid_axis_shift": -0.5},
),
"zz_outer": (
["lat", "lon", "z_outer"],
zz_outer,
{"axis": "Z", "c_grid_axis_shift": -0.5},
),
},
)
def test_generate_axis():
a = generate_axis(
ds_original,
"X",
"lon",
"lon",
pos_from="center",
pos_to="right",
pad=None,
boundary_discontinuity=360,
)
b = generate_axis(
ds_original,
"Y",
"lat",
"lat",
pos_from="center",
pos_to="left",
pad=None,
boundary_discontinuity=180,
)
c = generate_axis(
ds_original, "Z", "z", "z", pos_from="center", pos_to="left", pad="auto"
)
d = generate_axis(
ds_original_1D,
"Z",
"z",
"z",
pos_from="left",
pos_to="center",
pad=pad_value,
new_name="test",
)
e = generate_axis(
ds_original_left, "Z", "z", "z", pos_from="left", pos_to="center", pad="auto"
)
f = generate_axis(
ds_original_left, "Z", "z", "z", pos_from="center", pos_to="outer", pad="auto"
)
g = generate_axis(
ds_original_left,
"X",
"lon",
"lon",
pos_from="center",
pos_to="outer",
pad=None,
boundary_discontinuity=360,
)
assert_allclose(a["lon_right"], ds_out_right["lon_right"])
assert_allclose(b["lat_left"], ds_out_left["lat_left"])
assert_allclose(c["z_left"], ds_out_left["z_left"])
assert_allclose(d["test"], ds_original_1D_padded["test"])
assert_allclose(e["z_center"], ds_out_center["z_center"])
assert_allclose(f["z_outer"], ds_out_outer["z_outer"])
assert_allclose(g["lon_outer"], ds_out_outer["lon_outer"])
aa = generate_axis(
a,
"X",
"llon",
"lon",
pos_from="center",
pos_to="right",
pad=None,
boundary_discontinuity=360,
attrs_from_scratch=False,
)
bb = generate_axis(
b,
"Y",
"llat",
"lat",
pos_from="center",
pos_to="left",
pad=None,
boundary_discontinuity=180,
attrs_from_scratch=False,
)
ee = generate_axis(
e,
"Z",
"zz",
"z",
pos_from="left",
pos_to="center",
pad="auto",
attrs_from_scratch=False,
)
ff = generate_axis(
f,
"Z",
"zz",
"z",
pos_from="center",
pos_to="outer",
pad="auto",
attrs_from_scratch=False,
)
gg = generate_axis(
g,
"X",
"llon",
"lon",
pos_from="center",
pos_to="outer",
pad=None,
boundary_discontinuity=360,
attrs_from_scratch=False,
)
assert_allclose(aa["llon_right"], ds_out_right["llon_right"])
assert_allclose(bb["llat_left"], ds_out_left["llat_left"])
assert_allclose(ee["zz_center"], ds_out_center["zz_center"])
assert_allclose(ff["zz_outer"], ds_out_outer["zz_outer"])
assert_allclose(gg["llon_outer"], ds_out_outer["llon_outer"])
with pytest.raises(ValueError):
generate_axis(
c["somedata"],
"Z",
"zz",
"z",
pos_from="left",
pos_to="center",
pad="auto",
attrs_from_scratch=False,
)
with pytest.raises(ValueError):
generate_axis(c, "Z", "zz", "z", pad="auto", boundary_discontinuity=360)
with pytest.raises(ValueError):
generate_axis(c, "Z", "zz", "z", pad=None, boundary_discontinuity=None)
def test_generate_grid_ds():
axis_dims = {"X": "lon", "Y": "lat", "Z": "z"}
axis_coords = {"X": "llon", "Y": "llat", "Z": "zz"}
position = ("center", "outer")
boundary_discontinuity = {"lon": 360, "llon": 360, "lat": 180, "llat": 180}
pad = {"z": "auto", "zz": "auto"}
ds = generate_grid_ds(
ds_original_left, axis_dims, axis_coords, position, boundary_discontinuity, pad
)
assert_equal(ds, ds_out_outer)
def test_parse_boundary_params():
assert _parse_boundary_params(360, "anything") == 360
assert _parse_boundary_params({"something": 360}, "something") == 360
assert _parse_boundary_params({"something": 360}, "something_else") is None
@pytest.mark.parametrize(
"p_f, p_t",
[("left", "center"), ("center", "left"), ("center", "right"), ("right", "center")],
)
def test_parse_position(p_f, p_t):
default = ("center", "left")
assert _parse_position((p_f, p_t), "anything") == (p_f, p_t)
assert _parse_position({"a": (p_f, p_t)}, "a") == (p_f, p_t)
assert _parse_position({"a": (p_f, p_t)}, "b") == default
assert _parse_position({"a": (p_f, p_t), "b": (p_t, p_f)}, "a") == (p_f, p_t)
assert _parse_position({"a": (p_f, p_t), "b": (p_t, p_f)}, "b") == (p_t, p_f)
@pytest.mark.parametrize(
"p, relative",
[
(("left", "center"), "right"),
(("center", "left"), "left"),
(("center", "right"), "right"),
(("right", "center"), "left"),
(("center", "outer"), "outer"),
(("center", "inner"), "inner"),
],
)
def test_position_to_relative(p, relative):
assert _position_to_relative(p[0], p[1]) == relative
error_test = [
("left", "right"),
("inner", "outer"),
("left", "outer"),
("right", "outer"),
("left", "inner"),
("right", "inner"),
]
for et in error_test:
with pytest.raises(RuntimeError):
_position_to_relative(et[0], et[1])
with pytest.raises(RuntimeError):
_position_to_relative(et[1], et[0])
def test_fill_attrs():
a = _fill_attrs(ds_out_right["lon"], "right", "X")
assert a.attrs["axis"] == "X"
assert a.attrs["c_grid_axis_shift"] == 0.5
a = _fill_attrs(ds_out_right["lon"], "left", "Z")
assert a.attrs["axis"] == "Z"
assert a.attrs["c_grid_axis_shift"] == -0.5
a = _fill_attrs(ds_out_right["lon"], "center", "Y")
assert a.attrs["axis"] == "Y"
assert "c_grid_axis_shift" not in a.attrs.keys()
| true | true |
f7f75fc521da9a6159324701bc2b50c00bb27f08 | 1,644 | py | Python | Week 08/id_475/LeetCode_198_475.py | sekishi/algorithm004-05 | 1f1508c03edb94db96a7642e0c746233184a60d3 | [
"Apache-2.0"
] | 1 | 2019-10-12T06:48:45.000Z | 2019-10-12T06:48:45.000Z | Week 08/id_475/LeetCode_198_475.py | sekishi/algorithm004-05 | 1f1508c03edb94db96a7642e0c746233184a60d3 | [
"Apache-2.0"
] | null | null | null | Week 08/id_475/LeetCode_198_475.py | sekishi/algorithm004-05 | 1f1508c03edb94db96a7642e0c746233184a60d3 | [
"Apache-2.0"
] | null | null | null | # 打家劫舍
# DP
# 法一:一维数组
class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) == 0:
return 0
if len(nums) == 1:
return nums[0]
# 创建数组
dp = [0] * len(nums)
# 初始化数组
dp[0] = nums[0]
dp[1] = max(nums[0],nums[1])
# 填充剩余位置
for i in range(2,len(nums)):
dp[i] = max(dp[i-1], dp[i-2] + nums[i]) # DP方程
return dp[-1]
# 法二:二维数组
# 自己写的
class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) == 0:
return 0
if len(nums) == 1:
return nums[0]
# 创建数组
dp = [ [0] * 2 for _ in range(len(nums))]
# 初始化数组
dp[0][1] = nums[0]
dp[1][0] = nums[0]
dp[1][1] = nums[1]
# 填充剩余位置
for i in range(2,len(nums)):
dp[i][0] = max(dp[i-1][1],dp[i-1][0])
dp[i][1] = max(dp[i-2][1],dp[i-2][0]) + nums[i]
return max(dp[-1])
# 别人写的
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums: # 空时直接返回 0
return 0
if len(nums) <= 2: # 元素个数小于 2 时的最基本情况
return max(nums)
dp = [[None]*2 for _ in nums] # 初始化数组
dp[0][0] = 0 # 第 1 天未抢
dp[0][1] = nums[0] # 第 1 天抢劫了
for i in range(1, len(nums)): # 从第二天开始择优
dp[i][0] = max(dp[i-1][0], dp[i-1][1])
dp[i][1] = dp[i-1][0] + nums[i]
n = len(nums) - 1
return max(dp[n][0], dp[n][1]) # 从最后一天选择出 抢了最后一天 和 没抢最后一天 最大的
| 27.864407 | 70 | 0.414234 |
class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) == 0:
return 0
if len(nums) == 1:
return nums[0]
dp = [0] * len(nums)
dp[0] = nums[0]
dp[1] = max(nums[0],nums[1])
for i in range(2,len(nums)):
dp[i] = max(dp[i-1], dp[i-2] + nums[i])
return dp[-1]
class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) == 0:
return 0
if len(nums) == 1:
return nums[0]
dp = [ [0] * 2 for _ in range(len(nums))]
dp[0][1] = nums[0]
dp[1][0] = nums[0]
dp[1][1] = nums[1]
for i in range(2,len(nums)):
dp[i][0] = max(dp[i-1][1],dp[i-1][0])
dp[i][1] = max(dp[i-2][1],dp[i-2][0]) + nums[i]
return max(dp[-1])
class Solution(object):
def rob(self, nums):
if not nums:
return 0
if len(nums) <= 2:
return max(nums)
dp = [[None]*2 for _ in nums]
dp[0][0] = 0
dp[0][1] = nums[0]
for i in range(1, len(nums)):
dp[i][0] = max(dp[i-1][0], dp[i-1][1])
dp[i][1] = dp[i-1][0] + nums[i]
n = len(nums) - 1
return max(dp[n][0], dp[n][1])
| true | true |
f7f75fec0375333f03591fba930dbd99b228e1fc | 458 | py | Python | data/scripts/templates/object/draft_schematic/weapon/component/shared_scope_weapon.py | obi-two/GameServer | 7d37024e2291a97d49522610cd8f1dbe5666afc2 | [
"MIT"
] | 20 | 2015-02-23T15:11:56.000Z | 2022-03-18T20:56:48.000Z | data/scripts/templates/object/draft_schematic/weapon/component/shared_scope_weapon.py | apathyboy/swganh | 665128efe9154611dec4cb5efc61d246dd095984 | [
"MIT"
] | null | null | null | data/scripts/templates/object/draft_schematic/weapon/component/shared_scope_weapon.py | apathyboy/swganh | 665128efe9154611dec4cb5efc61d246dd095984 | [
"MIT"
] | 20 | 2015-04-04T16:35:59.000Z | 2022-03-24T14:54:37.000Z | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Intangible()
result.template = "object/draft_schematic/weapon/component/shared_scope_weapon.iff"
result.attribute_template_id = -1
result.stfName("string_id_table","")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result | 26.941176 | 84 | 0.731441 | true | true | |
f7f762a365ccaf1e254982cb24ffeb96db2bb8ae | 6,318 | py | Python | grpclib/health/check.py | artificial-aidan/grpclib | 948e32a29a4ad82ebbfdbb681f7a797f6233bff3 | [
"BSD-3-Clause"
] | 754 | 2017-08-01T23:41:24.000Z | 2022-03-31T09:03:24.000Z | grpclib/health/check.py | artificial-aidan/grpclib | 948e32a29a4ad82ebbfdbb681f7a797f6233bff3 | [
"BSD-3-Clause"
] | 154 | 2017-09-17T21:58:38.000Z | 2022-03-10T20:58:39.000Z | grpclib/health/check.py | artificial-aidan/grpclib | 948e32a29a4ad82ebbfdbb681f7a797f6233bff3 | [
"BSD-3-Clause"
] | 86 | 2017-09-17T12:53:23.000Z | 2022-02-16T21:59:24.000Z | import abc
import time
import asyncio
import logging
import warnings
from typing import Optional, Set, Callable, Awaitable
from ..utils import DeadlineWrapper
from ..metadata import Deadline
log = logging.getLogger(__name__)
DEFAULT_CHECK_TTL = 30
DEFAULT_CHECK_TIMEOUT = 10
_Status = Optional[bool]
class CheckBase(abc.ABC):
@abc.abstractmethod
def __status__(self) -> _Status:
pass
@abc.abstractmethod
async def __check__(self) -> _Status:
pass
@abc.abstractmethod
async def __subscribe__(self) -> asyncio.Event:
pass
@abc.abstractmethod
async def __unsubscribe__(self, event: asyncio.Event) -> None:
pass
class ServiceCheck(CheckBase):
"""Performs periodic checks
Example:
.. code-block:: python3
async def db_test():
# raised exceptions are the same as returning False,
# except that exceptions will be logged
await db.execute('SELECT 1;')
return True
db_check = ServiceCheck(db_test)
"""
_value = None
_poll_task = None
_last_check = None
def __init__(
self,
func: Callable[[], Awaitable[_Status]],
*,
loop: Optional[asyncio.AbstractEventLoop] = None,
check_ttl: float = DEFAULT_CHECK_TTL,
check_timeout: float = DEFAULT_CHECK_TIMEOUT,
) -> None:
"""
:param func: callable object which returns awaitable object, where
result is one of: ``True`` (healthy), ``False`` (unhealthy), or
``None`` (unknown)
:param loop: (deprecated) asyncio-compatible event loop
:param check_ttl: how long we can cache result of the previous check
:param check_timeout: timeout for this check
"""
self._func = func
self._check_ttl = check_ttl
self._check_timeout = check_timeout
self._events: Set[asyncio.Event] = set()
if loop:
warnings.warn("The loop argument is deprecated and scheduled "
"for removal in grpclib 0.5",
DeprecationWarning, stacklevel=2)
self._check_lock = asyncio.Event()
self._check_lock.set()
self._check_wrapper = DeadlineWrapper()
def __status__(self) -> _Status:
return self._value
async def __check__(self) -> _Status:
if (
self._last_check is not None
and time.monotonic() - self._last_check < self._check_ttl
):
return self._value
if not self._check_lock.is_set():
# wait until concurrent check succeed
await self._check_lock.wait()
return self._value
prev_value = self._value
self._check_lock.clear()
try:
deadline = Deadline.from_timeout(self._check_timeout)
with self._check_wrapper.start(deadline):
value = await self._func()
if value is not None and not isinstance(value, bool):
raise TypeError('Invalid status type: {!r}'.format(value))
self._value = value
except asyncio.CancelledError:
raise
except Exception:
log.exception('Health check failed')
self._value = False
finally:
self._check_lock.set()
self._last_check = time.monotonic()
if self._value != prev_value:
log_level = log.info if self._value else log.warning
log_level('Health check %r status changed to %r',
self._func, self._value)
# notify all watchers that this check was changed
for event in self._events:
event.set()
return self._value
async def _poll(self) -> None:
while True:
status = await self.__check__()
if status:
await asyncio.sleep(self._check_ttl)
else:
await asyncio.sleep(self._check_ttl) # TODO: change interval?
async def __subscribe__(self) -> asyncio.Event:
if self._poll_task is None:
loop = asyncio.get_event_loop()
self._poll_task = loop.create_task(self._poll())
event = asyncio.Event()
self._events.add(event)
return event
async def __unsubscribe__(self, event: asyncio.Event) -> None:
self._events.discard(event)
if not self._events:
assert self._poll_task is not None
task = self._poll_task
self._poll_task = None
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
class ServiceStatus(CheckBase):
"""Contains status of a proactive check
Example:
.. code-block:: python3
redis_status = ServiceStatus()
# detected that Redis is available
redis_status.set(True)
# detected that Redis is unavailable
redis_status.set(False)
"""
def __init__(
self,
*,
loop: Optional[asyncio.AbstractEventLoop] = None,
) -> None:
"""
:param loop: (deprecated) asyncio-compatible event loop
"""
if loop:
warnings.warn("The loop argument is deprecated and scheduled "
"for removal in grpclib 0.5",
DeprecationWarning, stacklevel=2)
self._value: _Status = None
self._events: Set[asyncio.Event] = set()
def set(self, value: _Status) -> None:
"""Sets current status of a check
:param value: ``True`` (healthy), ``False`` (unhealthy), or ``None``
(unknown)
"""
prev_value = self._value
self._value = value
if self._value != prev_value:
# notify all watchers that this check was changed
for event in self._events:
event.set()
def __status__(self) -> _Status:
return self._value
async def __check__(self) -> _Status:
return self._value
async def __subscribe__(self) -> asyncio.Event:
event = asyncio.Event()
self._events.add(event)
return event
async def __unsubscribe__(self, event: asyncio.Event) -> None:
self._events.discard(event)
| 28.588235 | 78 | 0.588319 | import abc
import time
import asyncio
import logging
import warnings
from typing import Optional, Set, Callable, Awaitable
from ..utils import DeadlineWrapper
from ..metadata import Deadline
log = logging.getLogger(__name__)
DEFAULT_CHECK_TTL = 30
DEFAULT_CHECK_TIMEOUT = 10
_Status = Optional[bool]
class CheckBase(abc.ABC):
@abc.abstractmethod
def __status__(self) -> _Status:
pass
@abc.abstractmethod
async def __check__(self) -> _Status:
pass
@abc.abstractmethod
async def __subscribe__(self) -> asyncio.Event:
pass
@abc.abstractmethod
async def __unsubscribe__(self, event: asyncio.Event) -> None:
pass
class ServiceCheck(CheckBase):
_value = None
_poll_task = None
_last_check = None
def __init__(
self,
func: Callable[[], Awaitable[_Status]],
*,
loop: Optional[asyncio.AbstractEventLoop] = None,
check_ttl: float = DEFAULT_CHECK_TTL,
check_timeout: float = DEFAULT_CHECK_TIMEOUT,
) -> None:
self._func = func
self._check_ttl = check_ttl
self._check_timeout = check_timeout
self._events: Set[asyncio.Event] = set()
if loop:
warnings.warn("The loop argument is deprecated and scheduled "
"for removal in grpclib 0.5",
DeprecationWarning, stacklevel=2)
self._check_lock = asyncio.Event()
self._check_lock.set()
self._check_wrapper = DeadlineWrapper()
def __status__(self) -> _Status:
return self._value
async def __check__(self) -> _Status:
if (
self._last_check is not None
and time.monotonic() - self._last_check < self._check_ttl
):
return self._value
if not self._check_lock.is_set():
await self._check_lock.wait()
return self._value
prev_value = self._value
self._check_lock.clear()
try:
deadline = Deadline.from_timeout(self._check_timeout)
with self._check_wrapper.start(deadline):
value = await self._func()
if value is not None and not isinstance(value, bool):
raise TypeError('Invalid status type: {!r}'.format(value))
self._value = value
except asyncio.CancelledError:
raise
except Exception:
log.exception('Health check failed')
self._value = False
finally:
self._check_lock.set()
self._last_check = time.monotonic()
if self._value != prev_value:
log_level = log.info if self._value else log.warning
log_level('Health check %r status changed to %r',
self._func, self._value)
for event in self._events:
event.set()
return self._value
async def _poll(self) -> None:
while True:
status = await self.__check__()
if status:
await asyncio.sleep(self._check_ttl)
else:
await asyncio.sleep(self._check_ttl)
async def __subscribe__(self) -> asyncio.Event:
if self._poll_task is None:
loop = asyncio.get_event_loop()
self._poll_task = loop.create_task(self._poll())
event = asyncio.Event()
self._events.add(event)
return event
async def __unsubscribe__(self, event: asyncio.Event) -> None:
self._events.discard(event)
if not self._events:
assert self._poll_task is not None
task = self._poll_task
self._poll_task = None
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
class ServiceStatus(CheckBase):
def __init__(
self,
*,
loop: Optional[asyncio.AbstractEventLoop] = None,
) -> None:
if loop:
warnings.warn("The loop argument is deprecated and scheduled "
"for removal in grpclib 0.5",
DeprecationWarning, stacklevel=2)
self._value: _Status = None
self._events: Set[asyncio.Event] = set()
def set(self, value: _Status) -> None:
prev_value = self._value
self._value = value
if self._value != prev_value:
for event in self._events:
event.set()
def __status__(self) -> _Status:
return self._value
async def __check__(self) -> _Status:
return self._value
async def __subscribe__(self) -> asyncio.Event:
event = asyncio.Event()
self._events.add(event)
return event
async def __unsubscribe__(self, event: asyncio.Event) -> None:
self._events.discard(event)
| true | true |
f7f7644ca49e57dd1a6bdb0cc8f2811b6bb5c356 | 4,641 | py | Python | bempp/api/external/fenicsx.py | ignacia-fp/bempp-cl | a65232558826e51e624b1a4f649b6a0ed5a7f551 | [
"MIT"
] | null | null | null | bempp/api/external/fenicsx.py | ignacia-fp/bempp-cl | a65232558826e51e624b1a4f649b6a0ed5a7f551 | [
"MIT"
] | null | null | null | bempp/api/external/fenicsx.py | ignacia-fp/bempp-cl | a65232558826e51e624b1a4f649b6a0ed5a7f551 | [
"MIT"
] | null | null | null | """Interface to DOLFINX for FEM-BEM coupling."""
def boundary_grid_from_fenics_mesh(fenics_mesh):
"""
Create a Bempp boundary grid from a FEniCS Mesh.
Return the Bempp grid and a map from the node numberings of the FEniCS
mesh to the node numbers of the boundary grid.
"""
import bempp.api
import numpy as np
from dolfinx.cpp.mesh import entities_to_geometry, exterior_facet_indices
boundary = entities_to_geometry(
fenics_mesh,
fenics_mesh.topology.dim - 1,
exterior_facet_indices(fenics_mesh),
True,
)
bm_nodes = set()
for tri in boundary:
for node in tri:
bm_nodes.add(node)
bm_nodes = list(bm_nodes)
bm_cells = np.array([[bm_nodes.index(i) for i in tri] for tri in boundary])
bm_coords = fenics_mesh.geometry.x[bm_nodes]
bempp_boundary_grid = bempp.api.Grid(bm_coords.transpose(), bm_cells.transpose())
return bempp_boundary_grid, bm_nodes
def fenics_to_bempp_trace_data(fenics_space):
"""Return tuple (space,trace_matrix)."""
family, degree = fenics_space_info(fenics_space)
if family == "Lagrange":
if degree == 1:
return p1_trace(fenics_space)
else:
raise NotImplementedError()
def fenics_space_info(fenics_space):
"""Return tuple (family,degree) containing information about a FEniCS space."""
element = fenics_space.ufl_element()
family = element.family()
degree = element.degree()
return (family, degree)
# pylint: disable=too-many-locals
def p1_trace(fenics_space):
"""
Return the P1 trace operator.
This function returns a pair (space, trace_matrix),
where space is a Bempp space object and trace_matrix is the corresponding
matrix that maps the coefficients of a FEniCS function to its boundary
trace coefficients in the corresponding Bempp space.
"""
import bempp.api
from scipy.sparse import coo_matrix
import numpy as np
family, degree = fenics_space_info(fenics_space)
if not (family == "Lagrange" and degree == 1):
raise ValueError("fenics_space must be a p1 Lagrange space")
fenics_mesh = fenics_space.mesh
bempp_boundary_grid, bm_nodes = boundary_grid_from_fenics_mesh(fenics_mesh)
# First get trace space
space = bempp.api.function_space(bempp_boundary_grid, "P", 1)
num_fenics_vertices = fenics_mesh.topology.connectivity(0, 0).num_nodes
# FEniCS vertices to bempp dofs
b_vertices_from_vertices = coo_matrix(
(np.ones(len(bm_nodes)), (np.arange(len(bm_nodes)), bm_nodes)),
shape=(len(bm_nodes), num_fenics_vertices),
dtype="float64",
).tocsc()
# Finally FEniCS dofs to vertices.
dof_to_vertex_map = np.zeros(num_fenics_vertices, dtype=np.int64)
tets = fenics_mesh.geometry.dofmap
for tet in range(tets.num_nodes):
cell_dofs = fenics_space.dofmap.cell_dofs(tet)
cell_verts = tets.links(tet)
for v in range(4):
vertex_n = cell_verts[v]
dof = cell_dofs[fenics_space.dofmap.dof_layout.entity_dofs(0, v)[0]]
dof_to_vertex_map[dof] = vertex_n
vertices_from_fenics_dofs = coo_matrix(
(
np.ones(num_fenics_vertices),
(dof_to_vertex_map, np.arange(num_fenics_vertices)),
),
shape=(num_fenics_vertices, num_fenics_vertices),
dtype="float64",
).tocsc()
# Get trace matrix by multiplication
trace_matrix = b_vertices_from_vertices @ vertices_from_fenics_dofs
# Now return everything
return space, trace_matrix
class FenicsOperator(object):
"""Wrap a FEniCS-X Operator into a Bempp operator."""
def __init__(self, fenics_weak_form):
"""Construct an operator from a weak form in FEniCS."""
self._fenics_weak_form = fenics_weak_form
self._sparse_mat = None
def weak_form(self):
"""Return the weak form."""
from bempp.api.assembly.discrete_boundary_operator import (
SparseDiscreteBoundaryOperator,
)
from dolfinx.fem import assemble_matrix, form
from scipy.sparse import csr_matrix
if self._sparse_mat is None:
mat = assemble_matrix(form(self._fenics_weak_form))
mat.finalize()
shape = tuple(
i._ufl_function_space.dofmap.index_map.size_global
for i in self._fenics_weak_form.arguments()
)
self._sparse_mat = csr_matrix(
(mat.data, mat.indices, mat.indptr), shape=shape
)
return SparseDiscreteBoundaryOperator(self._sparse_mat)
| 32.683099 | 85 | 0.676147 |
def boundary_grid_from_fenics_mesh(fenics_mesh):
import bempp.api
import numpy as np
from dolfinx.cpp.mesh import entities_to_geometry, exterior_facet_indices
boundary = entities_to_geometry(
fenics_mesh,
fenics_mesh.topology.dim - 1,
exterior_facet_indices(fenics_mesh),
True,
)
bm_nodes = set()
for tri in boundary:
for node in tri:
bm_nodes.add(node)
bm_nodes = list(bm_nodes)
bm_cells = np.array([[bm_nodes.index(i) for i in tri] for tri in boundary])
bm_coords = fenics_mesh.geometry.x[bm_nodes]
bempp_boundary_grid = bempp.api.Grid(bm_coords.transpose(), bm_cells.transpose())
return bempp_boundary_grid, bm_nodes
def fenics_to_bempp_trace_data(fenics_space):
family, degree = fenics_space_info(fenics_space)
if family == "Lagrange":
if degree == 1:
return p1_trace(fenics_space)
else:
raise NotImplementedError()
def fenics_space_info(fenics_space):
element = fenics_space.ufl_element()
family = element.family()
degree = element.degree()
return (family, degree)
def p1_trace(fenics_space):
import bempp.api
from scipy.sparse import coo_matrix
import numpy as np
family, degree = fenics_space_info(fenics_space)
if not (family == "Lagrange" and degree == 1):
raise ValueError("fenics_space must be a p1 Lagrange space")
fenics_mesh = fenics_space.mesh
bempp_boundary_grid, bm_nodes = boundary_grid_from_fenics_mesh(fenics_mesh)
space = bempp.api.function_space(bempp_boundary_grid, "P", 1)
num_fenics_vertices = fenics_mesh.topology.connectivity(0, 0).num_nodes
b_vertices_from_vertices = coo_matrix(
(np.ones(len(bm_nodes)), (np.arange(len(bm_nodes)), bm_nodes)),
shape=(len(bm_nodes), num_fenics_vertices),
dtype="float64",
).tocsc()
dof_to_vertex_map = np.zeros(num_fenics_vertices, dtype=np.int64)
tets = fenics_mesh.geometry.dofmap
for tet in range(tets.num_nodes):
cell_dofs = fenics_space.dofmap.cell_dofs(tet)
cell_verts = tets.links(tet)
for v in range(4):
vertex_n = cell_verts[v]
dof = cell_dofs[fenics_space.dofmap.dof_layout.entity_dofs(0, v)[0]]
dof_to_vertex_map[dof] = vertex_n
vertices_from_fenics_dofs = coo_matrix(
(
np.ones(num_fenics_vertices),
(dof_to_vertex_map, np.arange(num_fenics_vertices)),
),
shape=(num_fenics_vertices, num_fenics_vertices),
dtype="float64",
).tocsc()
trace_matrix = b_vertices_from_vertices @ vertices_from_fenics_dofs
return space, trace_matrix
class FenicsOperator(object):
def __init__(self, fenics_weak_form):
self._fenics_weak_form = fenics_weak_form
self._sparse_mat = None
def weak_form(self):
from bempp.api.assembly.discrete_boundary_operator import (
SparseDiscreteBoundaryOperator,
)
from dolfinx.fem import assemble_matrix, form
from scipy.sparse import csr_matrix
if self._sparse_mat is None:
mat = assemble_matrix(form(self._fenics_weak_form))
mat.finalize()
shape = tuple(
i._ufl_function_space.dofmap.index_map.size_global
for i in self._fenics_weak_form.arguments()
)
self._sparse_mat = csr_matrix(
(mat.data, mat.indices, mat.indptr), shape=shape
)
return SparseDiscreteBoundaryOperator(self._sparse_mat)
| true | true |
f7f7652849187a87b9a4981eb7e2055a91bd9c9e | 3,301 | py | Python | example/example.py | twhiteaker/arc_panimate | b68f8ff43f2b9b665852c09124d35885ab4685b7 | [
"MIT"
] | null | null | null | example/example.py | twhiteaker/arc_panimate | b68f8ff43f2b9b665852c09124d35885ab4685b7 | [
"MIT"
] | null | null | null | example/example.py | twhiteaker/arc_panimate | b68f8ff43f2b9b665852c09124d35885ab4685b7 | [
"MIT"
] | null | null | null | import inspect
import json
import os
import sys
import arcpy
sys.path.append('../arc_panimate')
import arc_panimate
def _demo_follow_line():
"""Demonstrate follow_line function.
Requires data/demo.mxd next to this script. The map has a single dataframe
with a line layer named Paths with an attribute named Path_Name.
"""
outfolder = os.path.abspath('demo_follow_line')
if not os.path.exists(outfolder):
os.makedirs(outfolder)
mxd = arcpy.mapping.MapDocument('data/test.mxd')
try:
df = arcpy.mapping.ListDataFrames(mxd)[0]
lyr = arcpy.mapping.ListLayers(mxd, 'Paths', df)[0]
with arcpy.da.SearchCursor(lyr, ['SHAPE@', 'Path_Name']) as cursor:
for row in cursor:
path_name = row[1]
print 'Path: {}'.format(path_name)
extents = arc_panimate.follow_line(
df, row[0], accelerate_steps=3, cruise_steps=3,
max_scale=10000000, target_scale=3000000)
for i, ext in enumerate(extents):
print ' ', i
png_file = os.path.join(outfolder,
path_name + '_{0:03d}'.format(i))
df.extent = ext
arcpy.mapping.ExportToPNG(mxd, png_file)
raw_input('Images exported to:\n{}\n'
'Press Enter to continue.\n'.format(outfolder))
except Exception as e:
print e
finally:
del mxd
def _demo_save_extents():
"""Demonstrate save_extents function.
Requires data/test.mxd next to this script.
"""
outfolder = os.path.abspath('demo_save_extents')
if not os.path.exists(outfolder):
os.makedirs(outfolder)
outfile = os.path.join(outfolder, 'saved_extents.json')
extents = []
try:
mxd = arcpy.mapping.MapDocument('data/test.mxd')
df = arcpy.mapping.ListDataFrames(mxd)[0]
extents.append(df.extent)
df.scale = df.scale * 1.5
extents.append(df.extent)
arc_panimate.save_extents(extents, outfile)
raw_input('Extents saved to:\n{}\n'
'Press Enter to continue.\n'.format(outfile))
except Exception as e:
print e
finally:
del mxd
def _demo_load_extents():
"""Demonstrate load_extents function.
Requires data/test.mxd and demo_save_extents/save_extents.json next to this
script.
"""
outfolder = os.path.abspath('demo_load_extents')
if not os.path.exists(outfolder):
os.makedirs(outfolder)
infile = 'demo_load_extents/saved_extents.json'
extents = arc_panimate.load_extents(infile)
try:
mxd = arcpy.mapping.MapDocument('data/test.mxd')
df = arcpy.mapping.ListDataFrames(mxd)[0]
for i, ext in enumerate(extents):
df.extent = ext
png_file = os.path.join(outfolder, 'extent_{0}'.format(i))
arcpy.mapping.ExportToPNG(mxd, png_file)
raw_input('Extents loaded and images exported to:\n{}\n'
'Press Enter to continue.\n'.format(outfolder))
except Exception as e:
print e
finally:
del mxd
if __name__ == '__main__':
_demo_follow_line()
_demo_save_extents()
_demo_load_extents()
| 31.141509 | 79 | 0.609815 | import inspect
import json
import os
import sys
import arcpy
sys.path.append('../arc_panimate')
import arc_panimate
def _demo_follow_line():
"""Demonstrate follow_line function.
Requires data/demo.mxd next to this script. The map has a single dataframe
with a line layer named Paths with an attribute named Path_Name.
"""
outfolder = os.path.abspath('demo_follow_line')
if not os.path.exists(outfolder):
os.makedirs(outfolder)
mxd = arcpy.mapping.MapDocument('data/test.mxd')
try:
df = arcpy.mapping.ListDataFrames(mxd)[0]
lyr = arcpy.mapping.ListLayers(mxd, 'Paths', df)[0]
with arcpy.da.SearchCursor(lyr, ['SHAPE@', 'Path_Name']) as cursor:
for row in cursor:
path_name = row[1]
print 'Path: {}'.format(path_name)
extents = arc_panimate.follow_line(
df, row[0], accelerate_steps=3, cruise_steps=3,
max_scale=10000000, target_scale=3000000)
for i, ext in enumerate(extents):
print ' ', i
png_file = os.path.join(outfolder,
path_name + '_{0:03d}'.format(i))
df.extent = ext
arcpy.mapping.ExportToPNG(mxd, png_file)
raw_input('Images exported to:\n{}\n'
'Press Enter to continue.\n'.format(outfolder))
except Exception as e:
print e
finally:
del mxd
def _demo_save_extents():
"""Demonstrate save_extents function.
Requires data/test.mxd next to this script.
"""
outfolder = os.path.abspath('demo_save_extents')
if not os.path.exists(outfolder):
os.makedirs(outfolder)
outfile = os.path.join(outfolder, 'saved_extents.json')
extents = []
try:
mxd = arcpy.mapping.MapDocument('data/test.mxd')
df = arcpy.mapping.ListDataFrames(mxd)[0]
extents.append(df.extent)
df.scale = df.scale * 1.5
extents.append(df.extent)
arc_panimate.save_extents(extents, outfile)
raw_input('Extents saved to:\n{}\n'
'Press Enter to continue.\n'.format(outfile))
except Exception as e:
print e
finally:
del mxd
def _demo_load_extents():
"""Demonstrate load_extents function.
Requires data/test.mxd and demo_save_extents/save_extents.json next to this
script.
"""
outfolder = os.path.abspath('demo_load_extents')
if not os.path.exists(outfolder):
os.makedirs(outfolder)
infile = 'demo_load_extents/saved_extents.json'
extents = arc_panimate.load_extents(infile)
try:
mxd = arcpy.mapping.MapDocument('data/test.mxd')
df = arcpy.mapping.ListDataFrames(mxd)[0]
for i, ext in enumerate(extents):
df.extent = ext
png_file = os.path.join(outfolder, 'extent_{0}'.format(i))
arcpy.mapping.ExportToPNG(mxd, png_file)
raw_input('Extents loaded and images exported to:\n{}\n'
'Press Enter to continue.\n'.format(outfolder))
except Exception as e:
print e
finally:
del mxd
if __name__ == '__main__':
_demo_follow_line()
_demo_save_extents()
_demo_load_extents()
| false | true |
f7f765410c70a6bac214f9982212e2721a78b766 | 2,225 | py | Python | port_scan_threading.py | michaelmdresser/neteng2017-ddos | 78abbcac2bc9fc461e8f61307202f04a9d7b883d | [
"MIT"
] | null | null | null | port_scan_threading.py | michaelmdresser/neteng2017-ddos | 78abbcac2bc9fc461e8f61307202f04a9d7b883d | [
"MIT"
] | null | null | null | port_scan_threading.py | michaelmdresser/neteng2017-ddos | 78abbcac2bc9fc461e8f61307202f04a9d7b883d | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# https://securitylair.wordpress.com/2014/02/21/simple-port-scanner-in-python-with-scapy-2/
import time
import Queue
import threading
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
closed = 0
class Scanner(threading.Thread):
""" Scanner Thread class """
def __init__(self, ip, test_port_queue, open_port_queue, lock):
super(Scanner, self).__init__()
self.test_port_queue = test_port_queue
self.open_port_queue = open_port_queue
self.lock = lock
self.ip = ip
def run(self):
global closed
src_port = RandShort()
port = self.test_port_queue.get()
p = IP(dst=self.ip)/TCP(sport=src_port, dport=port, flags='S')
resp = sr1(p, timeout=2)
if str(type(resp)) == "<type 'NoneType'>":
with self.lock:
closed += 1
elif resp.haslayer(TCP):
if resp.getlayer(TCP).flags == 0x12:
send_rst = sr(IP(dst=self.ip)/TCP(sport=src_port, dport=port, flags='AR'), timeout=1)
with self.lock:
# print "[*] %d open" % port
self.open_port_queue.put(port)
elif resp.getlayer(TCP).flags == 0x14:
with self.lock:
closed += 1
self.test_port_queue.task_done()
def is_up(ip):
p = IP(dst=ip)/ICMP()
resp = sr1(p, timeout=10)
if resp == None:
return False
elif resp.haslayer(ICMP):
return True
def get_open_ports(ip, max_port=1024):
conf.verb = 0
lock = threading.Lock()
test_port_queue = Queue.Queue()
open_port_queue = Queue.Queue()
if is_up(ip):
print "Host %s is up, start scanning" % ip
for port in range(0, max_port):
test_port_queue.put(port)
scan = Scanner(ip, test_port_queue, open_port_queue, lock)
scan.start()
test_port_queue.join()
else:
print "IP %s not up" % ip
return list(open_port_queue.queue)
# just for testing
if __name__ == '__main__':
open_ports = get_open_ports("34.237.72.89", max_port=90)
print "Open ports: %s" % open_ports
| 28.896104 | 101 | 0.594157 |
import time
import Queue
import threading
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
closed = 0
class Scanner(threading.Thread):
""" Scanner Thread class """
def __init__(self, ip, test_port_queue, open_port_queue, lock):
super(Scanner, self).__init__()
self.test_port_queue = test_port_queue
self.open_port_queue = open_port_queue
self.lock = lock
self.ip = ip
def run(self):
global closed
src_port = RandShort()
port = self.test_port_queue.get()
p = IP(dst=self.ip)/TCP(sport=src_port, dport=port, flags='S')
resp = sr1(p, timeout=2)
if str(type(resp)) == "<type 'NoneType'>":
with self.lock:
closed += 1
elif resp.haslayer(TCP):
if resp.getlayer(TCP).flags == 0x12:
send_rst = sr(IP(dst=self.ip)/TCP(sport=src_port, dport=port, flags='AR'), timeout=1)
with self.lock:
self.open_port_queue.put(port)
elif resp.getlayer(TCP).flags == 0x14:
with self.lock:
closed += 1
self.test_port_queue.task_done()
def is_up(ip):
p = IP(dst=ip)/ICMP()
resp = sr1(p, timeout=10)
if resp == None:
return False
elif resp.haslayer(ICMP):
return True
def get_open_ports(ip, max_port=1024):
conf.verb = 0
lock = threading.Lock()
test_port_queue = Queue.Queue()
open_port_queue = Queue.Queue()
if is_up(ip):
print "Host %s is up, start scanning" % ip
for port in range(0, max_port):
test_port_queue.put(port)
scan = Scanner(ip, test_port_queue, open_port_queue, lock)
scan.start()
test_port_queue.join()
else:
print "IP %s not up" % ip
return list(open_port_queue.queue)
if __name__ == '__main__':
open_ports = get_open_ports("34.237.72.89", max_port=90)
print "Open ports: %s" % open_ports
| false | true |
f7f765ad3a913c16cf6675d0ff79879c15b3b651 | 982 | py | Python | iwpt2020/package_for_submit.py | attardi/iwpt-shared-task-2020 | 3a70c42d53716678776afcccf02d896655777353 | [
"Apache-2.0"
] | 3 | 2020-06-16T12:58:57.000Z | 2021-06-07T21:07:37.000Z | iwpt2020/package_for_submit.py | attardi/iwpt-shared-task-2020 | 3a70c42d53716678776afcccf02d896655777353 | [
"Apache-2.0"
] | 6 | 2020-06-22T07:46:49.000Z | 2022-02-10T02:22:14.000Z | iwpt2020/package_for_submit.py | attardi/iwpt-shared-task-2020 | 3a70c42d53716678776afcccf02d896655777353 | [
"Apache-2.0"
] | 2 | 2020-06-27T07:32:43.000Z | 2020-11-10T07:21:03.000Z | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-04-22 21:09
import glob
import os
from shutil import copyfile
from edparser.metrics.parsing.iwpt20_eval import conllu_quick_fix, remove_complete_edges, remove_collapse_edges
from iwpt2020 import cdroot
def main():
cdroot()
submission = 'data/model/iwpt2020/emorynlp-submission'
os.makedirs(submission, exist_ok=True)
fs = sorted(glob.glob('data/iwpt2020/test-blind/*.txt'))
for idx, txt in enumerate(fs):
basename = os.path.basename(txt)
langcode = basename.split('.')[0]
print(f'{idx + 1:02d}/{len(fs)} {basename}')
src = f'data/model/iwpt2020/{langcode}/{langcode}.conllu'
dst = f'{submission}/{langcode}.conllu'
tmp = f'/home/hhe43/tmp/{langcode}.conllu'
copyfile(src, tmp)
remove_complete_edges(tmp, tmp)
remove_collapse_edges(tmp, tmp)
src = tmp
conllu_quick_fix(src, dst)
if __name__ == '__main__':
main()
| 29.757576 | 111 | 0.660896 |
import glob
import os
from shutil import copyfile
from edparser.metrics.parsing.iwpt20_eval import conllu_quick_fix, remove_complete_edges, remove_collapse_edges
from iwpt2020 import cdroot
def main():
cdroot()
submission = 'data/model/iwpt2020/emorynlp-submission'
os.makedirs(submission, exist_ok=True)
fs = sorted(glob.glob('data/iwpt2020/test-blind/*.txt'))
for idx, txt in enumerate(fs):
basename = os.path.basename(txt)
langcode = basename.split('.')[0]
print(f'{idx + 1:02d}/{len(fs)} {basename}')
src = f'data/model/iwpt2020/{langcode}/{langcode}.conllu'
dst = f'{submission}/{langcode}.conllu'
tmp = f'/home/hhe43/tmp/{langcode}.conllu'
copyfile(src, tmp)
remove_complete_edges(tmp, tmp)
remove_collapse_edges(tmp, tmp)
src = tmp
conllu_quick_fix(src, dst)
if __name__ == '__main__':
main()
| true | true |
f7f765b4aa77a2955b43e1e082ddda90d7050f46 | 63,678 | py | Python | salt/utils/network.py | ContextLogic/salt | f98839c72df2294cdd1670835d10904b12089622 | [
"Apache-2.0"
] | null | null | null | salt/utils/network.py | ContextLogic/salt | f98839c72df2294cdd1670835d10904b12089622 | [
"Apache-2.0"
] | null | null | null | salt/utils/network.py | ContextLogic/salt | f98839c72df2294cdd1670835d10904b12089622 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
'''
Define some generic socket functions for network modules
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import itertools
import os
import re
import types
import socket
import logging
import platform
import random
import subprocess
from string import ascii_letters, digits
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin
# Attempt to import wmi
try:
import wmi
import salt.utils.winapi
except ImportError:
pass
# Import salt libs
import salt.utils.args
import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.zeromq
from salt._compat import ipaddress
from salt.exceptions import SaltClientError, SaltSystemExit
from salt.utils.decorators.jinja import jinja_filter
from salt.utils.versions import LooseVersion
# inet_pton does not exist in Windows, this is a workaround
if salt.utils.platform.is_windows():
from salt.ext import win_inet_pton # pylint: disable=unused-import
log = logging.getLogger(__name__)
try:
import ctypes
import ctypes.util
libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c"))
res_init = libc.__res_init
except (ImportError, OSError, AttributeError, TypeError):
pass
# pylint: disable=C0103
def sanitize_host(host):
'''
Sanitize host string.
'''
return ''.join([
c for c in host[0:255] if c in (ascii_letters + digits + '.-')
])
def isportopen(host, port):
'''
Return status of a port
'''
if not 1 <= int(port) <= 65535:
return False
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
out = sock.connect_ex((sanitize_host(host), int(port)))
return out
def host_to_ips(host):
'''
Returns a list of IP addresses of a given hostname or None if not found.
'''
ips = []
try:
for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo(
host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM):
if family == socket.AF_INET:
ip, port = sockaddr
elif family == socket.AF_INET6:
ip, port, flow_info, scope_id = sockaddr
ips.append(ip)
if not ips:
ips = None
except Exception:
ips = None
return ips
def _generate_minion_id():
'''
Get list of possible host names and convention names.
:return:
'''
# There are three types of hostnames:
# 1. Network names. How host is accessed from the network.
# 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts)
# 3. Convention names, an internal nodename.
class DistinctList(list):
'''
List, which allows one to append only distinct objects.
Needs to work on Python 2.6, because of collections.OrderedDict only since 2.7 version.
Override 'filter()' for custom filtering.
'''
localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0',
r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa']
def append(self, p_object):
if p_object and p_object not in self and not self.filter(p_object):
super(self.__class__, self).append(p_object)
return self
def extend(self, iterable):
for obj in iterable:
self.append(obj)
return self
def filter(self, element):
'Returns True if element needs to be filtered'
for rgx in self.localhost_matchers:
if re.match(rgx, element):
return True
def first(self):
return self and self[0] or None
hosts = DistinctList().append(socket.getfqdn()).append(platform.node()).append(socket.gethostname())
if not hosts:
try:
for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET,
socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME):
if len(a_nfo) > 3:
hosts.append(a_nfo[3])
except socket.gaierror:
log.warning('Cannot resolve address {addr} info via socket: {message}'.format(
addr=hosts.first() or 'localhost (N/A)', message=socket.gaierror)
)
# Universal method for everywhere (Linux, Slowlaris, Windows etc)
for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts',
r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))):
try:
with salt.utils.files.fopen(f_name) as f_hdl:
for line in f_hdl:
line = salt.utils.stringutils.to_unicode(line)
hst = line.strip().split('#')[0].strip().split()
if hst:
if hst[0][:4] in ('127.', '::1') or len(hst) == 1:
hosts.extend(hst)
except IOError:
pass
# include public and private ipaddresses
return hosts.extend([addr for addr in ip_addrs()
if not ipaddress.ip_address(addr).is_loopback])
def generate_minion_id():
'''
Return only first element of the hostname from all possible list.
:return:
'''
try:
ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first())
except TypeError:
ret = None
return ret or 'localhost'
def get_socket(addr, type=socket.SOCK_STREAM, proto=0):
'''
Return a socket object for the addr
IP-version agnostic
'''
version = ipaddress.ip_address(addr).version
if version == 4:
family = socket.AF_INET
elif version == 6:
family = socket.AF_INET6
return socket.socket(family, type, proto)
def get_fqhostname():
'''
Returns the fully qualified hostname
'''
l = [socket.getfqdn()]
# try socket.getaddrinfo
try:
addrinfo = socket.getaddrinfo(
socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM,
socket.SOL_TCP, socket.AI_CANONNAME
)
for info in addrinfo:
# info struct [family, socktype, proto, canonname, sockaddr]
if len(info) >= 4:
l = [info[3]]
except socket.gaierror:
pass
return l and l[0] or None
def ip_to_host(ip):
'''
Returns the hostname of a given IP
'''
try:
hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip)
except Exception as exc:
log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc)
hostname = None
return hostname
# pylint: enable=C0103
def is_reachable_host(entity_name):
'''
Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc).
:param hostname:
:return:
'''
try:
assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list
ret = True
except socket.gaierror:
ret = False
return ret
def is_ip(ip):
'''
Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address.
'''
return is_ipv4(ip) or is_ipv6(ip)
def is_ipv4(ip):
'''
Returns a bool telling if the value passed to it was a valid IPv4 address
'''
try:
return ipaddress.ip_address(ip).version == 4
except ValueError:
return False
def is_ipv6(ip):
'''
Returns a bool telling if the value passed to it was a valid IPv6 address
'''
try:
return ipaddress.ip_address(ip).version == 6
except ValueError:
return False
def is_subnet(cidr):
'''
Returns a bool telling if the passed string is an IPv4 or IPv6 subnet
'''
return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr)
def is_ipv4_subnet(cidr):
'''
Returns a bool telling if the passed string is an IPv4 subnet
'''
try:
return '/' in cidr and bool(ipaddress.IPv4Network(cidr))
except Exception:
return False
def is_ipv6_subnet(cidr):
'''
Returns a bool telling if the passed string is an IPv6 subnet
'''
try:
return '/' in cidr and bool(ipaddress.IPv6Network(cidr))
except Exception:
return False
@jinja_filter('is_ip')
def is_ip_filter(ip, options=None):
'''
Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address.
'''
return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options)
def _ip_options_global(ip_obj, version):
return not ip_obj.is_private
def _ip_options_multicast(ip_obj, version):
return ip_obj.is_multicast
def _ip_options_loopback(ip_obj, version):
return ip_obj.is_loopback
def _ip_options_link_local(ip_obj, version):
return ip_obj.is_link_local
def _ip_options_private(ip_obj, version):
return ip_obj.is_private
def _ip_options_reserved(ip_obj, version):
return ip_obj.is_reserved
def _ip_options_site_local(ip_obj, version):
if version == 6:
return ip_obj.is_site_local
return False
def _ip_options_unspecified(ip_obj, version):
return ip_obj.is_unspecified
def _ip_options(ip_obj, version, options=None):
# will process and IP options
options_fun_map = {
'global': _ip_options_global,
'link-local': _ip_options_link_local,
'linklocal': _ip_options_link_local,
'll': _ip_options_link_local,
'link_local': _ip_options_link_local,
'loopback': _ip_options_loopback,
'lo': _ip_options_loopback,
'multicast': _ip_options_multicast,
'private': _ip_options_private,
'public': _ip_options_global,
'reserved': _ip_options_reserved,
'site-local': _ip_options_site_local,
'sl': _ip_options_site_local,
'site_local': _ip_options_site_local,
'unspecified': _ip_options_unspecified
}
if not options:
return six.text_type(ip_obj) # IP version already checked
options_list = [option.strip() for option in options.split(',')]
for option, fun in options_fun_map.items():
if option in options_list:
fun_res = fun(ip_obj, version)
if not fun_res:
return None
# stop at first failed test
# else continue
return six.text_type(ip_obj)
def _is_ipv(ip, version, options=None):
if not version:
version = 4
if version not in (4, 6):
return None
try:
ip_obj = ipaddress.ip_address(ip)
except ValueError:
# maybe it is an IP network
try:
ip_obj = ipaddress.ip_interface(ip)
except ValueError:
# nope, still not :(
return None
if not ip_obj.version == version:
return None
# has the right version, let's move on
return _ip_options(ip_obj, version, options=options)
@jinja_filter('is_ipv4')
def is_ipv4_filter(ip, options=None):
'''
Returns a bool telling if the value passed to it was a valid IPv4 address.
ip
The IP address.
net: False
Consider IP addresses followed by netmask.
options
CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc.
'''
_is_ipv4 = _is_ipv(ip, 4, options=options)
return isinstance(_is_ipv4, six.string_types)
@jinja_filter('is_ipv6')
def is_ipv6_filter(ip, options=None):
'''
Returns a bool telling if the value passed to it was a valid IPv6 address.
ip
The IP address.
net: False
Consider IP addresses followed by netmask.
options
CSV of options regarding the nature of the IP address. E.g.: loopback, multicast, private etc.
'''
_is_ipv6 = _is_ipv(ip, 6, options=options)
return isinstance(_is_ipv6, six.string_types)
def _ipv_filter(value, version, options=None):
if version not in (4, 6):
return
if isinstance(value, (six.string_types, six.text_type, six.binary_type)):
return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value`
elif isinstance(value, (list, tuple, types.GeneratorType)):
# calls is_ipv4 or is_ipv6 for each element in the list
# os it filters and returns only those elements having the desired IP version
return [
_is_ipv(addr, version, options=options)
for addr in value
if _is_ipv(addr, version, options=options) is not None
]
return None
@jinja_filter('ipv4')
def ipv4(value, options=None):
'''
Filters a list and returns IPv4 values only.
'''
return _ipv_filter(value, 4, options=options)
@jinja_filter('ipv6')
def ipv6(value, options=None):
'''
Filters a list and returns IPv6 values only.
'''
return _ipv_filter(value, 6, options=options)
@jinja_filter('ipaddr')
def ipaddr(value, options=None):
'''
Filters and returns only valid IP objects.
'''
ipv4_obj = ipv4(value, options=options)
ipv6_obj = ipv6(value, options=options)
if ipv4_obj is None or ipv6_obj is None:
# an IP address can be either IPv4 either IPv6
# therefofe if the value passed as arg is not a list, at least one of the calls above will return None
# if one of them is none, means that we should return only one of them
return ipv4_obj or ipv6_obj # one of them
else:
return ipv4_obj + ipv6_obj # extend lists
def _filter_ipaddr(value, options, version=None):
ipaddr_filter_out = None
if version:
if version == 4:
ipaddr_filter_out = ipv4(value, options)
elif version == 6:
ipaddr_filter_out = ipv6(value, options)
else:
ipaddr_filter_out = ipaddr(value, options)
if not ipaddr_filter_out:
return
if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)):
ipaddr_filter_out = [ipaddr_filter_out]
return ipaddr_filter_out
@jinja_filter('ip_host')
def ip_host(value, options=None, version=None):
'''
Returns the interfaces IP address, e.g.: 192.168.0.1/28.
'''
ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version)
if not ipaddr_filter_out:
return
if not isinstance(value, (list, tuple, types.GeneratorType)):
return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0]))
return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out]
def _network_hosts(ip_addr_entry):
return [
six.text_type(host)
for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts()
]
@jinja_filter('network_hosts')
def network_hosts(value, options=None, version=None):
'''
Return the list of hosts within a network.
.. note::
When running this command with a large IPv6 network, the command will
take a long time to gather all of the hosts.
'''
ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version)
if not ipaddr_filter_out:
return
if not isinstance(value, (list, tuple, types.GeneratorType)):
return _network_hosts(ipaddr_filter_out[0])
return [
_network_hosts(ip_a)
for ip_a in ipaddr_filter_out
]
def _network_size(ip_addr_entry):
return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses
@jinja_filter('network_size')
def network_size(value, options=None, version=None):
'''
Get the size of a network.
'''
ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version)
if not ipaddr_filter_out:
return
if not isinstance(value, (list, tuple, types.GeneratorType)):
return _network_size(ipaddr_filter_out[0])
return [
_network_size(ip_a)
for ip_a in ipaddr_filter_out
]
def natural_ipv4_netmask(ip, fmt='prefixlen'):
'''
Returns the "natural" mask of an IPv4 address
'''
bits = _ipv4_to_bits(ip)
if bits.startswith('11'):
mask = '24'
elif bits.startswith('1'):
mask = '16'
else:
mask = '8'
if fmt == 'netmask':
return cidr_to_ipv4_netmask(mask)
else:
return '/' + mask
def rpad_ipv4_network(ip):
'''
Returns an IP network address padded with zeros.
Ex: '192.168.3' -> '192.168.3.0'
'10.209' -> '10.209.0.0'
'''
return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0,
4))
def cidr_to_ipv4_netmask(cidr_bits):
'''
Returns an IPv4 netmask
'''
try:
cidr_bits = int(cidr_bits)
if not 1 <= cidr_bits <= 32:
return ''
except ValueError:
return ''
netmask = ''
for idx in range(4):
if idx:
netmask += '.'
if cidr_bits >= 8:
netmask += '255'
cidr_bits -= 8
else:
netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits)))
cidr_bits = 0
return netmask
def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103
'''
Returns an IPv4 netmask from the integer representation of that mask.
Ex. 0xffffff00 -> '255.255.255.0'
'''
return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits))
# pylint: disable=C0103
def _number_of_set_bits(x):
'''
Returns the number of bits that are set in a 32bit int
'''
# Taken from http://stackoverflow.com/a/4912729. Many thanks!
x -= (x >> 1) & 0x55555555
x = ((x >> 2) & 0x33333333) + (x & 0x33333333)
x = ((x >> 4) + x) & 0x0f0f0f0f
x += x >> 8
x += x >> 16
return x & 0x0000003f
# pylint: enable=C0103
def _interfaces_ip(out):
'''
Uses ip to return a dictionary of interfaces with various information about
each (up/down state, ip address, netmask, and hwaddr)
'''
ret = dict()
def parse_network(value, cols):
'''
Return a tuple of ip, netmask, broadcast
based on the current set of cols
'''
brd = None
scope = None
if '/' in value: # we have a CIDR in this address
ip, cidr = value.split('/') # pylint: disable=C0103
else:
ip = value # pylint: disable=C0103
cidr = 32
if type_ == 'inet':
mask = cidr_to_ipv4_netmask(int(cidr))
if 'brd' in cols:
brd = cols[cols.index('brd') + 1]
elif type_ == 'inet6':
mask = cidr
if 'scope' in cols:
scope = cols[cols.index('scope') + 1]
return (ip, mask, brd, scope)
groups = re.compile('\r?\n\\d').split(out)
for group in groups:
iface = None
data = dict()
for line in group.splitlines():
if ' ' not in line:
continue
match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line)
if match:
iface, parent, attrs = match.groups()
if 'UP' in attrs.split(','):
data['up'] = True
else:
data['up'] = False
if parent:
data['parent'] = parent
continue
cols = line.split()
if len(cols) >= 2:
type_, value = tuple(cols[0:2])
iflabel = cols[-1:][0]
if type_ in ('inet', 'inet6'):
if 'secondary' not in cols:
ipaddr, netmask, broadcast, scope = parse_network(value, cols)
if type_ == 'inet':
if 'inet' not in data:
data['inet'] = list()
addr_obj = dict()
addr_obj['address'] = ipaddr
addr_obj['netmask'] = netmask
addr_obj['broadcast'] = broadcast
addr_obj['label'] = iflabel
data['inet'].append(addr_obj)
elif type_ == 'inet6':
if 'inet6' not in data:
data['inet6'] = list()
addr_obj = dict()
addr_obj['address'] = ipaddr
addr_obj['prefixlen'] = netmask
addr_obj['scope'] = scope
data['inet6'].append(addr_obj)
else:
if 'secondary' not in data:
data['secondary'] = list()
ip_, mask, brd, scp = parse_network(value, cols)
data['secondary'].append({
'type': type_,
'address': ip_,
'netmask': mask,
'broadcast': brd,
'label': iflabel,
})
del ip_, mask, brd, scp
elif type_.startswith('link'):
data['hwaddr'] = value
if iface:
ret[iface] = data
del iface, data
return ret
def _interfaces_ifconfig(out):
'''
Uses ifconfig to return a dictionary of interfaces with various information
about each (up/down state, ip address, netmask, and hwaddr)
'''
ret = dict()
piface = re.compile(r'^([^\s:]+)')
pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)')
if salt.utils.platform.is_sunos():
pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)')
pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)')
pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*')
else:
pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s')
pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)')
pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?')
pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))')
pupdown = re.compile('UP')
pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)')
groups = re.compile('\r?\n(?=\\S)').split(out)
for group in groups:
data = dict()
iface = ''
updown = False
for line in group.splitlines():
miface = piface.match(line)
mmac = pmac.match(line)
mip = pip.match(line)
mip6 = pip6.match(line)
mupdown = pupdown.search(line)
if miface:
iface = miface.group(1)
if mmac:
data['hwaddr'] = mmac.group(1)
if salt.utils.platform.is_sunos():
expand_mac = []
for chunk in data['hwaddr'].split(':'):
expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk))
data['hwaddr'] = ':'.join(expand_mac)
if mip:
if 'inet' not in data:
data['inet'] = list()
addr_obj = dict()
addr_obj['address'] = mip.group(1)
mmask = pmask.match(line)
if mmask:
if mmask.group(1):
mmask = _number_of_set_bits_to_ipv4_netmask(
int(mmask.group(1), 16))
else:
mmask = mmask.group(2)
addr_obj['netmask'] = mmask
mbcast = pbcast.match(line)
if mbcast:
addr_obj['broadcast'] = mbcast.group(1)
data['inet'].append(addr_obj)
if mupdown:
updown = True
if mip6:
if 'inet6' not in data:
data['inet6'] = list()
addr_obj = dict()
addr_obj['address'] = mip6.group(1) or mip6.group(2)
mmask6 = pmask6.match(line)
if mmask6:
addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2)
if not salt.utils.platform.is_sunos():
ipv6scope = mmask6.group(3) or mmask6.group(4)
addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope
# SunOS sometimes has ::/0 as inet6 addr when using addrconf
if not salt.utils.platform.is_sunos() \
or addr_obj['address'] != '::' \
and addr_obj['prefixlen'] != 0:
data['inet6'].append(addr_obj)
data['up'] = updown
if iface in ret:
# SunOS optimization, where interfaces occur twice in 'ifconfig -a'
# output with the same name: for ipv4 and then for ipv6 addr family.
# Every instance has it's own 'UP' status and we assume that ipv4
# status determines global interface status.
#
# merge items with higher priority for older values
# after that merge the inet and inet6 sub items for both
ret[iface] = dict(list(data.items()) + list(ret[iface].items()))
if 'inet' in data:
ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet'])
if 'inet6' in data:
ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6'])
else:
ret[iface] = data
del data
return ret
def linux_interfaces():
'''
Obtain interface information for *NIX/BSD variants
'''
ifaces = dict()
ip_path = salt.utils.path.which('ip')
ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig')
if ip_path:
cmd1 = subprocess.Popen(
'{0} link show'.format(ip_path),
shell=True,
close_fds=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT).communicate()[0]
cmd2 = subprocess.Popen(
'{0} addr show'.format(ip_path),
shell=True,
close_fds=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT).communicate()[0]
ifaces = _interfaces_ip("{0}\n{1}".format(
salt.utils.stringutils.to_str(cmd1),
salt.utils.stringutils.to_str(cmd2)))
elif ifconfig_path:
cmd = subprocess.Popen(
'{0} -a'.format(ifconfig_path),
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT).communicate()[0]
ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd))
return ifaces
def _netbsd_interfaces_ifconfig(out):
'''
Uses ifconfig to return a dictionary of interfaces with various information
about each (up/down state, ip address, netmask, and hwaddr)
'''
ret = dict()
piface = re.compile(r'^([^\s:]+)')
pmac = re.compile('.*?address: ([0-9a-f:]+)')
pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s')
pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s')
pupdown = re.compile('UP')
pbcast = re.compile(r'.*?broadcast ([\d\.]+)')
groups = re.compile('\r?\n(?=\\S)').split(out)
for group in groups:
data = dict()
iface = ''
updown = False
for line in group.splitlines():
miface = piface.match(line)
mmac = pmac.match(line)
mip = pip.match(line)
mip6 = pip6.match(line)
mupdown = pupdown.search(line)
if miface:
iface = miface.group(1)
if mmac:
data['hwaddr'] = mmac.group(1)
if mip:
if 'inet' not in data:
data['inet'] = list()
addr_obj = dict()
addr_obj['address'] = mip.group(1)
mmask = mip.group(2)
if mip.group(2):
addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2))
mbcast = pbcast.match(line)
if mbcast:
addr_obj['broadcast'] = mbcast.group(1)
data['inet'].append(addr_obj)
if mupdown:
updown = True
if mip6:
if 'inet6' not in data:
data['inet6'] = list()
addr_obj = dict()
addr_obj['address'] = mip6.group(1)
mmask6 = mip6.group(3)
addr_obj['scope'] = mip6.group(2)
addr_obj['prefixlen'] = mip6.group(3)
data['inet6'].append(addr_obj)
data['up'] = updown
ret[iface] = data
del data
return ret
def netbsd_interfaces():
'''
Obtain interface information for NetBSD >= 8 where the ifconfig
output diverged from other BSD variants (Netmask is now part of the
address)
'''
# NetBSD versions prior to 8.0 can still use linux_interfaces()
if LooseVersion(os.uname()[2]) < LooseVersion('8.0'):
return linux_interfaces()
ifconfig_path = salt.utils.path.which('ifconfig')
cmd = subprocess.Popen(
'{0} -a'.format(ifconfig_path),
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT).communicate()[0]
return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd))
def _interfaces_ipconfig(out):
'''
Returns a dictionary of interfaces with various information about each
(up/down state, ip address, netmask, and hwaddr)
NOTE: This is not used by any function and may be able to be removed in the
future.
'''
ifaces = dict()
iface = None
adapter_iface_regex = re.compile(r'adapter (\S.+):$')
for line in out.splitlines():
if not line:
continue
# TODO what does Windows call Infiniband and 10/40gige adapters
if line.startswith('Ethernet'):
iface = ifaces[adapter_iface_regex.search(line).group(1)]
iface['up'] = True
addr = None
continue
if iface:
key, val = line.split(',', 1)
key = key.strip(' .')
val = val.strip()
if addr and key == 'Subnet Mask':
addr['netmask'] = val
elif key in ('IP Address', 'IPv4 Address'):
if 'inet' not in iface:
iface['inet'] = list()
addr = {'address': val.rstrip('(Preferred)'),
'netmask': None,
'broadcast': None} # TODO find the broadcast
iface['inet'].append(addr)
elif 'IPv6 Address' in key:
if 'inet6' not in iface:
iface['inet'] = list()
# XXX What is the prefixlen!?
addr = {'address': val.rstrip('(Preferred)'),
'prefixlen': None}
iface['inet6'].append(addr)
elif key == 'Physical Address':
iface['hwaddr'] = val
elif key == 'Media State':
# XXX seen used for tunnel adaptors
# might be useful
iface['up'] = (val != 'Media disconnected')
def win_interfaces():
'''
Obtain interface information for Windows systems
'''
with salt.utils.winapi.Com():
c = wmi.WMI()
ifaces = {}
for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1):
ifaces[iface.Description] = dict()
if iface.MACAddress:
ifaces[iface.Description]['hwaddr'] = iface.MACAddress
if iface.IPEnabled:
ifaces[iface.Description]['up'] = True
for ip in iface.IPAddress:
if '.' in ip:
if 'inet' not in ifaces[iface.Description]:
ifaces[iface.Description]['inet'] = []
item = {'address': ip,
'label': iface.Description}
if iface.DefaultIPGateway:
broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '')
if broadcast:
item['broadcast'] = broadcast
if iface.IPSubnet:
netmask = next((i for i in iface.IPSubnet if '.' in i), '')
if netmask:
item['netmask'] = netmask
ifaces[iface.Description]['inet'].append(item)
if ':' in ip:
if 'inet6' not in ifaces[iface.Description]:
ifaces[iface.Description]['inet6'] = []
item = {'address': ip}
if iface.DefaultIPGateway:
broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '')
if broadcast:
item['broadcast'] = broadcast
if iface.IPSubnet:
netmask = next((i for i in iface.IPSubnet if ':' in i), '')
if netmask:
item['netmask'] = netmask
ifaces[iface.Description]['inet6'].append(item)
else:
ifaces[iface.Description]['up'] = False
return ifaces
def interfaces():
'''
Return a dictionary of information about all the interfaces on the minion
'''
if salt.utils.platform.is_windows():
return win_interfaces()
elif salt.utils.platform.is_netbsd():
return netbsd_interfaces()
else:
return linux_interfaces()
def get_net_start(ipaddr, netmask):
'''
Return the address of the network
'''
net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False)
return six.text_type(net.network_address)
def get_net_size(mask):
'''
Turns an IPv4 netmask into it's corresponding prefix length
(255.255.255.0 -> 24 as in 192.168.1.10/24).
'''
binary_str = ''
for octet in mask.split('.'):
binary_str += bin(int(octet))[2:].zfill(8)
return len(binary_str.rstrip('0'))
def calc_net(ipaddr, netmask=None):
'''
Takes IP (CIDR notation supported) and optionally netmask
and returns the network in CIDR-notation.
(The IP can be any IP inside the subnet)
'''
if netmask is not None:
ipaddr = '{0}/{1}'.format(ipaddr, netmask)
return six.text_type(ipaddress.ip_network(ipaddr, strict=False))
def _ipv4_to_bits(ipaddr):
'''
Accepts an IPv4 dotted quad and returns a string representing its binary
counterpart
'''
return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')])
def _get_iface_info(iface):
'''
If `iface` is available, return interface info and no error, otherwise
return no info and log and return an error
'''
iface_info = interfaces()
if iface in iface_info.keys():
return iface_info, False
else:
error_msg = ('Interface "{0}" not in available interfaces: "{1}"'
''.format(iface, '", "'.join(iface_info.keys())))
log.error(error_msg)
return None, error_msg
def _hw_addr_aix(iface):
'''
Return the hardware address (a.k.a. MAC address) for a given interface on AIX
MAC address not available in through interfaces
'''
cmd = subprocess.Popen(
'entstat -d {0} | grep \'Hardware Address\''.format(iface),
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT).communicate()[0]
if cmd:
comps = cmd.split(' ')
if len(comps) == 3:
mac_addr = comps[2].strip('\'').strip()
return mac_addr
error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface))
log.error(error_msg)
return error_msg
def hw_addr(iface):
'''
Return the hardware address (a.k.a. MAC address) for a given interface
.. versionchanged:: 2016.11.4
Added support for AIX
'''
if salt.utils.platform.is_aix():
return _hw_addr_aix
iface_info, error = _get_iface_info(iface)
if error is False:
return iface_info.get(iface, {}).get('hwaddr', '')
else:
return error
def interface(iface):
'''
Return the details of `iface` or an error if it does not exist
'''
iface_info, error = _get_iface_info(iface)
if error is False:
return iface_info.get(iface, {}).get('inet', '')
else:
return error
def interface_ip(iface):
'''
Return `iface` IPv4 addr or an error if `iface` does not exist
'''
iface_info, error = _get_iface_info(iface)
if error is False:
inet = iface_info.get(iface, {}).get('inet', None)
return inet[0].get('address', '') if inet else ''
else:
return error
def _subnets(proto='inet', interfaces_=None):
'''
Returns a list of subnets to which the host belongs
'''
if interfaces_ is None:
ifaces = interfaces()
elif isinstance(interfaces_, list):
ifaces = {}
for key, value in six.iteritems(interfaces()):
if key in interfaces_:
ifaces[key] = value
else:
ifaces = {interfaces_: interfaces().get(interfaces_, {})}
ret = set()
if proto == 'inet':
subnet = 'netmask'
dflt_cidr = 32
elif proto == 'inet6':
subnet = 'prefixlen'
dflt_cidr = 128
else:
log.error('Invalid proto {0} calling subnets()'.format(proto))
return
for ip_info in six.itervalues(ifaces):
addrs = ip_info.get(proto, [])
addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto])
for intf in addrs:
if subnet in intf:
intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet]))
else:
intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr))
if not intf.is_loopback:
ret.add(intf.network)
return [six.text_type(net) for net in sorted(ret)]
def subnets(interfaces=None):
'''
Returns a list of IPv4 subnets to which the host belongs
'''
return _subnets('inet', interfaces_=interfaces)
def subnets6():
'''
Returns a list of IPv6 subnets to which the host belongs
'''
return _subnets('inet6')
def in_subnet(cidr, addr=None):
'''
Returns True if host or (any of) addrs is within specified subnet, otherwise False
'''
try:
cidr = ipaddress.ip_network(cidr)
except ValueError:
log.error('Invalid CIDR \'{0}\''.format(cidr))
return False
if addr is None:
addr = ip_addrs()
addr.extend(ip_addrs6())
elif isinstance(addr, six.string_types):
return ipaddress.ip_address(addr) in cidr
for ip_addr in addr:
if ipaddress.ip_address(ip_addr) in cidr:
return True
return False
def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'):
'''
Return the full list of IP adresses matching the criteria
proto = inet|inet6
'''
ret = set()
ifaces = interface_data \
if isinstance(interface_data, dict) \
else interfaces()
if interface is None:
target_ifaces = ifaces
else:
target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces)
if k == interface])
if not target_ifaces:
log.error('Interface {0} not found.'.format(interface))
for ip_info in six.itervalues(target_ifaces):
addrs = ip_info.get(proto, [])
addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto])
for addr in addrs:
addr = ipaddress.ip_address(addr.get('address'))
if not addr.is_loopback or include_loopback:
ret.add(addr)
return [six.text_type(addr) for addr in sorted(ret)]
def ip_addrs(interface=None, include_loopback=False, interface_data=None):
'''
Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is
ignored, unless 'include_loopback=True' is indicated. If 'interface' is
provided, then only IP addresses from that interface will be returned.
'''
return _ip_addrs(interface, include_loopback, interface_data, 'inet')
def ip_addrs6(interface=None, include_loopback=False, interface_data=None):
'''
Returns a list of IPv6 addresses assigned to the host. ::1 is ignored,
unless 'include_loopback=True' is indicated. If 'interface' is provided,
then only IP addresses from that interface will be returned.
'''
return _ip_addrs(interface, include_loopback, interface_data, 'inet6')
def hex2ip(hex_ip, invert=False):
'''
Convert a hex string to an ip, if a failure occurs the original hex is
returned. If 'invert=True' assume that ip from /proc/net/<proto>
'''
if len(hex_ip) == 32: # ipv6
ip = []
for i in range(0, 32, 8):
ip_part = hex_ip[i:i + 8]
ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)]
if invert:
ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part))
else:
ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part))
try:
address = ipaddress.IPv6Address(":".join(ip))
if address.ipv4_mapped:
return str(address.ipv4_mapped)
else:
return address.compressed
except ipaddress.AddressValueError as ex:
log.error('hex2ip - ipv6 address error: {0}'.format(ex))
return hex_ip
try:
hip = int(hex_ip, 16)
except ValueError:
return hex_ip
if invert:
return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255,
hip >> 16 & 255,
hip >> 8 & 255,
hip & 255)
return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255,
hip >> 16 & 255,
hip >> 8 & 255,
hip & 255)
def mac2eui64(mac, prefix=None):
'''
Convert a MAC address to a EUI64 identifier
or, with prefix provided, a full IPv6 address
'''
# http://tools.ietf.org/html/rfc4291#section-2.5.1
eui64 = re.sub(r'[.:-]', '', mac).lower()
eui64 = eui64[0:6] + 'fffe' + eui64[6:]
eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:]
if prefix is None:
return ':'.join(re.findall(r'.{4}', eui64))
else:
try:
net = ipaddress.ip_network(prefix, strict=False)
euil = int('0x{0}'.format(eui64), 16)
return '{0}/{1}'.format(net[euil], net.prefixlen)
except Exception:
return
def active_tcp():
'''
Return a dict describing all active tcp connections as quickly as possible
'''
ret = {}
for statf in ['/proc/net/tcp', '/proc/net/tcp6']:
if os.path.isfile(statf):
with salt.utils.files.fopen(statf, 'rb') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
if line.strip().startswith('sl'):
continue
iret = _parse_tcp_line(line)
sl = next(iter(iret))
if iret[sl]['state'] == 1: # 1 is ESTABLISHED
del iret[sl]['state']
ret[len(ret)] = iret[sl]
return ret
def local_port_tcp(port):
'''
Return a set of remote ip addrs attached to the specified local port
'''
ret = _remotes_on(port, 'local_port')
return ret
def remote_port_tcp(port):
'''
Return a set of ip addrs the current host is connected to on given port
'''
ret = _remotes_on(port, 'remote_port')
return ret
def _remotes_on(port, which_end):
'''
Return a set of ip addrs active tcp connections
'''
port = int(port)
ret = set()
proc_available = False
for statf in ['/proc/net/tcp', '/proc/net/tcp6']:
if os.path.isfile(statf):
proc_available = True
with salt.utils.files.fopen(statf, 'r') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
if line.strip().startswith('sl'):
continue
iret = _parse_tcp_line(line)
sl = next(iter(iret))
if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED
ret.add(iret[sl]['remote_addr'])
if not proc_available: # Fallback to use OS specific tools
if salt.utils.platform.is_sunos():
return _sunos_remotes_on(port, which_end)
if salt.utils.platform.is_freebsd():
return _freebsd_remotes_on(port, which_end)
if salt.utils.platform.is_netbsd():
return _netbsd_remotes_on(port, which_end)
if salt.utils.platform.is_openbsd():
return _openbsd_remotes_on(port, which_end)
if salt.utils.platform.is_windows():
return _windows_remotes_on(port, which_end)
if salt.utils.platform.is_aix():
return _aix_remotes_on(port, which_end)
return _linux_remotes_on(port, which_end)
return ret
def _parse_tcp_line(line):
'''
Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6
'''
ret = {}
comps = line.strip().split()
sl = comps[0].rstrip(':')
ret[sl] = {}
l_addr, l_port = comps[1].split(':')
r_addr, r_port = comps[2].split(':')
ret[sl]['local_addr'] = hex2ip(l_addr, True)
ret[sl]['local_port'] = int(l_port, 16)
ret[sl]['remote_addr'] = hex2ip(r_addr, True)
ret[sl]['remote_port'] = int(r_port, 16)
ret[sl]['state'] = int(comps[3], 16)
return ret
def _sunos_remotes_on(port, which_end):
'''
SunOS specific helper function.
Returns set of ipv4 host addresses of remote established connections
on local or remote tcp port.
Parses output of shell 'netstat' to get connections
[root@salt-master ~]# netstat -f inet -n
TCP: IPv4
Local Address Remote Address Swind Send-Q Rwind Recv-Q State
-------------------- -------------------- ----- ------ ----- ------ -----------
10.0.0.101.4505 10.0.0.1.45329 1064800 0 1055864 0 ESTABLISHED
10.0.0.101.4505 10.0.0.100.50798 1064800 0 1055864 0 ESTABLISHED
'''
remotes = set()
try:
data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version
except subprocess.CalledProcessError:
log.error('Failed netstat')
raise
lines = salt.utils.stringutils.to_str(data).split('\n')
for line in lines:
if 'ESTABLISHED' not in line:
continue
chunks = line.split()
local_host, local_port = chunks[0].rsplit('.', 1)
remote_host, remote_port = chunks[1].rsplit('.', 1)
if which_end == 'remote_port' and int(remote_port) != port:
continue
if which_end == 'local_port' and int(local_port) != port:
continue
remotes.add(remote_host)
return remotes
def _freebsd_remotes_on(port, which_end):
'''
Returns set of ipv4 host addresses of remote established connections
on local tcp port port.
Parses output of shell 'sockstat' (FreeBSD)
to get connections
$ sudo sockstat -4
USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS
root python2.7 1456 29 tcp4 *:4505 *:*
root python2.7 1445 17 tcp4 *:4506 *:*
root python2.7 1294 14 tcp4 127.0.0.1:11813 127.0.0.1:4505
root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506
$ sudo sockstat -4 -c -p 4506
USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS
root python2.7 1294 41 tcp4 127.0.0.1:61115 127.0.0.1:4506
'''
port = int(port)
remotes = set()
try:
cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port))
data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version
except subprocess.CalledProcessError as ex:
log.error('Failed "sockstat" with returncode = {0}'.format(ex.returncode))
raise
lines = salt.utils.stringutils.to_str(data).split('\n')
for line in lines:
chunks = line.split()
if not chunks:
continue
# ['root', 'python2.7', '1456', '37', 'tcp4',
# '127.0.0.1:4505-', '127.0.0.1:55703']
# print chunks
if 'COMMAND' in chunks[1]:
continue # ignore header
if len(chunks) < 2:
continue
# sockstat -4 -c -p 4506 does this with high PIDs:
# USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS
# salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143
local = chunks[-2]
remote = chunks[-1]
lhost, lport = local.split(':')
rhost, rport = remote.split(':')
if which_end == 'local' and int(lport) != port: # ignore if local port not port
continue
if which_end == 'remote' and int(rport) != port: # ignore if remote port not port
continue
remotes.add(rhost)
return remotes
def _netbsd_remotes_on(port, which_end):
'''
Returns set of ipv4 host addresses of remote established connections
on local tcp port port.
Parses output of shell 'sockstat' (NetBSD)
to get connections
$ sudo sockstat -4 -n
USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS
root python2.7 1456 29 tcp *.4505 *.*
root python2.7 1445 17 tcp *.4506 *.*
root python2.7 1294 14 tcp 127.0.0.1.11813 127.0.0.1.4505
root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506
$ sudo sockstat -4 -c -n -p 4506
USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS
root python2.7 1294 41 tcp 127.0.0.1.61115 127.0.0.1.4506
'''
port = int(port)
remotes = set()
try:
cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port))
data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version
except subprocess.CalledProcessError as ex:
log.error('Failed "sockstat" with returncode = {0}'.format(ex.returncode))
raise
lines = salt.utils.stringutils.to_str(data).split('\n')
for line in lines:
chunks = line.split()
if not chunks:
continue
# ['root', 'python2.7', '1456', '37', 'tcp',
# '127.0.0.1.4505-', '127.0.0.1.55703']
# print chunks
if 'COMMAND' in chunks[1]:
continue # ignore header
if len(chunks) < 2:
continue
local = chunks[5].split('.')
lport = local.pop()
lhost = '.'.join(local)
remote = chunks[6].split('.')
rport = remote.pop()
rhost = '.'.join(remote)
if which_end == 'local' and int(lport) != port: # ignore if local port not port
continue
if which_end == 'remote' and int(rport) != port: # ignore if remote port not port
continue
remotes.add(rhost)
return remotes
def _openbsd_remotes_on(port, which_end):
'''
OpenBSD specific helper function.
Returns set of ipv4 host addresses of remote established connections
on local or remote tcp port.
Parses output of shell 'netstat' to get connections
$ netstat -nf inet
Active Internet connections
Proto Recv-Q Send-Q Local Address Foreign Address (state)
tcp 0 0 10.0.0.101.4505 10.0.0.1.45329 ESTABLISHED
tcp 0 0 10.0.0.101.4505 10.0.0.100.50798 ESTABLISHED
'''
remotes = set()
try:
data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version
except subprocess.CalledProcessError:
log.error('Failed netstat')
raise
lines = data.split('\n')
for line in lines:
if 'ESTABLISHED' not in line:
continue
chunks = line.split()
local_host, local_port = chunks[3].rsplit('.', 1)
remote_host, remote_port = chunks[4].rsplit('.', 1)
if which_end == 'remote_port' and int(remote_port) != port:
continue
if which_end == 'local_port' and int(local_port) != port:
continue
remotes.add(remote_host)
return remotes
def _windows_remotes_on(port, which_end):
r'''
Windows specific helper function.
Returns set of ipv4 host addresses of remote established connections
on local or remote tcp port.
Parses output of shell 'netstat' to get connections
C:\>netstat -n
Active Connections
Proto Local Address Foreign Address State
TCP 10.2.33.17:3007 130.164.12.233:10123 ESTABLISHED
TCP 10.2.33.17:3389 130.164.30.5:10378 ESTABLISHED
'''
remotes = set()
try:
data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version
except subprocess.CalledProcessError:
log.error('Failed netstat')
raise
lines = salt.utils.stringutils.to_str(data).split('\n')
for line in lines:
if 'ESTABLISHED' not in line:
continue
chunks = line.split()
local_host, local_port = chunks[1].rsplit(':', 1)
remote_host, remote_port = chunks[2].rsplit(':', 1)
if which_end == 'remote_port' and int(remote_port) != port:
continue
if which_end == 'local_port' and int(local_port) != port:
continue
remotes.add(remote_host)
return remotes
def _linux_remotes_on(port, which_end):
'''
Linux specific helper function.
Returns set of ip host addresses of remote established connections
on local tcp port port.
Parses output of shell 'lsof'
to get connections
$ sudo lsof -iTCP:4505 -n
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
Python 9971 root 35u IPv4 0x18a8464a29ca329d 0t0 TCP *:4505 (LISTEN)
Python 9971 root 37u IPv4 0x18a8464a29b2b29d 0t0 TCP 127.0.0.1:4505->127.0.0.1:55703 (ESTABLISHED)
Python 10152 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP 127.0.0.1:55703->127.0.0.1:4505 (ESTABLISHED)
Python 10153 root 22u IPv4 0x18a8464a29c8cab5 0t0 TCP [fe80::249a]:4505->[fe80::150]:59367 (ESTABLISHED)
'''
remotes = set()
try:
data = subprocess.check_output(
['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version
)
except subprocess.CalledProcessError as ex:
if ex.returncode == 1:
# Lsof return 1 if any error was detected, including the failure
# to locate Internet addresses, and it is not an error in this case.
log.warning('"lsof" returncode = 1, likely no active TCP sessions.')
return remotes
log.error('Failed "lsof" with returncode = {0}'.format(ex.returncode))
raise
lines = salt.utils.stringutils.to_str(data).split('\n')
for line in lines:
chunks = line.split()
if not chunks:
continue
# ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0',
# 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)']
# print chunks
if 'COMMAND' in chunks[0]:
continue # ignore header
if 'ESTABLISHED' not in chunks[-1]:
continue # ignore if not ESTABLISHED
# '127.0.0.1:4505->127.0.0.1:55703'
local, remote = chunks[8].split('->')
_, lport = local.rsplit(':', 1)
rhost, rport = remote.rsplit(':', 1)
if which_end == 'remote_port' and int(rport) != port:
continue
if which_end == 'local_port' and int(lport) != port:
continue
remotes.add(rhost.strip("[]"))
return remotes
def _aix_remotes_on(port, which_end):
'''
AIX specific helper function.
Returns set of ipv4 host addresses of remote established connections
on local or remote tcp port.
Parses output of shell 'netstat' to get connections
root@la68pp002_pub:/opt/salt/lib/python2.7/site-packages/salt/modules# netstat -f inet -n
Active Internet connections
Proto Recv-Q Send-Q Local Address Foreign Address (state)
tcp4 0 0 172.29.149.95.50093 209.41.78.13.4505 ESTABLISHED
tcp4 0 0 127.0.0.1.9514 *.* LISTEN
tcp4 0 0 127.0.0.1.9515 *.* LISTEN
tcp4 0 0 127.0.0.1.199 127.0.0.1.32779 ESTABLISHED
tcp4 0 0 127.0.0.1.32779 127.0.0.1.199 ESTABLISHED
tcp4 0 40 172.29.149.95.22 172.29.96.83.41022 ESTABLISHED
tcp4 0 0 172.29.149.95.22 172.29.96.83.41032 ESTABLISHED
tcp4 0 0 127.0.0.1.32771 127.0.0.1.32775 ESTABLISHED
tcp 0 0 127.0.0.1.32775 127.0.0.1.32771 ESTABLISHED
tcp4 0 0 127.0.0.1.32771 127.0.0.1.32776 ESTABLISHED
tcp 0 0 127.0.0.1.32776 127.0.0.1.32771 ESTABLISHED
tcp4 0 0 127.0.0.1.32771 127.0.0.1.32777 ESTABLISHED
tcp 0 0 127.0.0.1.32777 127.0.0.1.32771 ESTABLISHED
tcp4 0 0 127.0.0.1.32771 127.0.0.1.32778 ESTABLISHED
tcp 0 0 127.0.0.1.32778 127.0.0.1.32771 ESTABLISHED
'''
remotes = set()
try:
data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version
except subprocess.CalledProcessError:
log.error('Failed netstat')
raise
lines = salt.utils.stringutils.to_str(data).split('\n')
for line in lines:
if 'ESTABLISHED' not in line:
continue
chunks = line.split()
local_host, local_port = chunks[3].rsplit('.', 1)
remote_host, remote_port = chunks[4].rsplit('.', 1)
if which_end == 'remote_port' and int(remote_port) != port:
continue
if which_end == 'local_port' and int(local_port) != port:
continue
remotes.add(remote_host)
return remotes
@jinja_filter('gen_mac')
def gen_mac(prefix='AC:DE:48'):
'''
Generates a MAC address with the defined OUI prefix.
Common prefixes:
- ``00:16:3E`` -- Xen
- ``00:18:51`` -- OpenVZ
- ``00:50:56`` -- VMware (manually generated)
- ``52:54:00`` -- QEMU/KVM
- ``AC:DE:48`` -- PRIVATE
References:
- http://standards.ieee.org/develop/regauth/oui/oui.txt
- https://www.wireshark.org/tools/oui-lookup.html
- https://en.wikipedia.org/wiki/MAC_address
'''
return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix,
random.randint(0, 0xff),
random.randint(0, 0xff),
random.randint(0, 0xff))
@jinja_filter('mac_str_to_bytes')
def mac_str_to_bytes(mac_str):
'''
Convert a MAC address string into bytes. Works with or without separators:
b1 = mac_str_to_bytes('08:00:27:13:69:77')
b2 = mac_str_to_bytes('080027136977')
assert b1 == b2
assert isinstance(b1, bytes)
'''
if len(mac_str) == 12:
pass
elif len(mac_str) == 17:
sep = mac_str[2]
mac_str = mac_str.replace(sep, '')
else:
raise ValueError('Invalid MAC address')
chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2))
return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars)
def refresh_dns():
'''
issue #21397: force glibc to re-read resolv.conf
'''
try:
res_init()
except NameError:
# Exception raised loading the library, thus res_init is not defined
pass
@jinja_filter('connection_check')
def connection_check(addr, port=80, safe=False, ipv6=None):
'''
Provides a convenient alias for the dns_check filter.
'''
return dns_check(addr, port, safe, ipv6)
@jinja_filter('dns_check')
def dns_check(addr, port=80, safe=False, ipv6=None):
'''
Return the ip resolved by dns, but do not exit on failure, only raise an
exception. Obeys system preference for IPv4/6 address resolution - this
can be overridden by the ipv6 flag.
Tries to connect to the address before considering it useful. If no address
can be reached, the first one resolved is used as a fallback.
'''
error = False
lookup = addr
seen_ipv6 = False
family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC
try:
refresh_dns()
hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM)
if not hostnames:
error = True
else:
resolved = False
candidates = []
for h in hostnames:
# Input is IP address, passed through unchanged, just return it
if h[4][0] == addr:
resolved = salt.utils.zeromq.ip_bracket(addr)
break
candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0])
candidates.append(candidate_addr)
try:
s = socket.socket(h[0], socket.SOCK_STREAM)
s.connect((candidate_addr.strip('[]'), h[4][1]))
s.close()
resolved = candidate_addr
break
except socket.error:
pass
if not resolved:
if len(candidates) > 0:
resolved = candidates[0]
else:
error = True
except TypeError:
err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup)
raise SaltSystemExit(code=42, msg=err)
except socket.error:
error = True
if error:
err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr)
if safe:
if salt.log.is_console_configured():
# If logging is not configured it also means that either
# the master or minion instance calling this hasn't even
# started running
log.error(err)
raise SaltClientError()
raise SaltSystemExit(code=42, msg=err)
return resolved
| 33.200209 | 134 | 0.566538 |
from __future__ import absolute_import, unicode_literals, print_function
import itertools
import os
import re
import types
import socket
import logging
import platform
import random
import subprocess
from string import ascii_letters, digits
from salt.ext import six
from salt.ext.six.moves import range
try:
import wmi
import salt.utils.winapi
except ImportError:
pass
import salt.utils.args
import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.zeromq
from salt._compat import ipaddress
from salt.exceptions import SaltClientError, SaltSystemExit
from salt.utils.decorators.jinja import jinja_filter
from salt.utils.versions import LooseVersion
if salt.utils.platform.is_windows():
from salt.ext import win_inet_pton
log = logging.getLogger(__name__)
try:
import ctypes
import ctypes.util
libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c"))
res_init = libc.__res_init
except (ImportError, OSError, AttributeError, TypeError):
pass
def sanitize_host(host):
return ''.join([
c for c in host[0:255] if c in (ascii_letters + digits + '.-')
])
def isportopen(host, port):
if not 1 <= int(port) <= 65535:
return False
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
out = sock.connect_ex((sanitize_host(host), int(port)))
return out
def host_to_ips(host):
ips = []
try:
for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo(
host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM):
if family == socket.AF_INET:
ip, port = sockaddr
elif family == socket.AF_INET6:
ip, port, flow_info, scope_id = sockaddr
ips.append(ip)
if not ips:
ips = None
except Exception:
ips = None
return ips
def _generate_minion_id():
class DistinctList(list):
localhost_matchers = [r'localhost.*', r'ip6-.*', r'127[.]\d', r'0\.0\.0\.0',
r'::1.*', r'ipv6-.*', r'fe00::.*', r'fe02::.*', r'1.0.0.*.ip6.arpa']
def append(self, p_object):
if p_object and p_object not in self and not self.filter(p_object):
super(self.__class__, self).append(p_object)
return self
def extend(self, iterable):
for obj in iterable:
self.append(obj)
return self
def filter(self, element):
for rgx in self.localhost_matchers:
if re.match(rgx, element):
return True
def first(self):
return self and self[0] or None
hosts = DistinctList().append(socket.getfqdn()).append(platform.node()).append(socket.gethostname())
if not hosts:
try:
for a_nfo in socket.getaddrinfo(hosts.first() or 'localhost', None, socket.AF_INET,
socket.SOCK_RAW, socket.IPPROTO_IP, socket.AI_CANONNAME):
if len(a_nfo) > 3:
hosts.append(a_nfo[3])
except socket.gaierror:
log.warning('Cannot resolve address {addr} info via socket: {message}'.format(
addr=hosts.first() or 'localhost (N/A)', message=socket.gaierror)
)
for f_name in ('/etc/hostname', '/etc/nodename', '/etc/hosts',
r'{win}\system32\drivers\etc\hosts'.format(win=os.getenv('WINDIR'))):
try:
with salt.utils.files.fopen(f_name) as f_hdl:
for line in f_hdl:
line = salt.utils.stringutils.to_unicode(line)
hst = line.strip().split('#')[0].strip().split()
if hst:
if hst[0][:4] in ('127.', '::1') or len(hst) == 1:
hosts.extend(hst)
except IOError:
pass
return hosts.extend([addr for addr in ip_addrs()
if not ipaddress.ip_address(addr).is_loopback])
def generate_minion_id():
try:
ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first())
except TypeError:
ret = None
return ret or 'localhost'
def get_socket(addr, type=socket.SOCK_STREAM, proto=0):
version = ipaddress.ip_address(addr).version
if version == 4:
family = socket.AF_INET
elif version == 6:
family = socket.AF_INET6
return socket.socket(family, type, proto)
def get_fqhostname():
l = [socket.getfqdn()]
try:
addrinfo = socket.getaddrinfo(
socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM,
socket.SOL_TCP, socket.AI_CANONNAME
)
for info in addrinfo:
if len(info) >= 4:
l = [info[3]]
except socket.gaierror:
pass
return l and l[0] or None
def ip_to_host(ip):
try:
hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip)
except Exception as exc:
log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc)
hostname = None
return hostname
def is_reachable_host(entity_name):
try:
assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list
ret = True
except socket.gaierror:
ret = False
return ret
def is_ip(ip):
return is_ipv4(ip) or is_ipv6(ip)
def is_ipv4(ip):
try:
return ipaddress.ip_address(ip).version == 4
except ValueError:
return False
def is_ipv6(ip):
try:
return ipaddress.ip_address(ip).version == 6
except ValueError:
return False
def is_subnet(cidr):
return is_ipv4_subnet(cidr) or is_ipv6_subnet(cidr)
def is_ipv4_subnet(cidr):
try:
return '/' in cidr and bool(ipaddress.IPv4Network(cidr))
except Exception:
return False
def is_ipv6_subnet(cidr):
try:
return '/' in cidr and bool(ipaddress.IPv6Network(cidr))
except Exception:
return False
@jinja_filter('is_ip')
def is_ip_filter(ip, options=None):
return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options)
def _ip_options_global(ip_obj, version):
return not ip_obj.is_private
def _ip_options_multicast(ip_obj, version):
return ip_obj.is_multicast
def _ip_options_loopback(ip_obj, version):
return ip_obj.is_loopback
def _ip_options_link_local(ip_obj, version):
return ip_obj.is_link_local
def _ip_options_private(ip_obj, version):
return ip_obj.is_private
def _ip_options_reserved(ip_obj, version):
return ip_obj.is_reserved
def _ip_options_site_local(ip_obj, version):
if version == 6:
return ip_obj.is_site_local
return False
def _ip_options_unspecified(ip_obj, version):
return ip_obj.is_unspecified
def _ip_options(ip_obj, version, options=None):
options_fun_map = {
'global': _ip_options_global,
'link-local': _ip_options_link_local,
'linklocal': _ip_options_link_local,
'll': _ip_options_link_local,
'link_local': _ip_options_link_local,
'loopback': _ip_options_loopback,
'lo': _ip_options_loopback,
'multicast': _ip_options_multicast,
'private': _ip_options_private,
'public': _ip_options_global,
'reserved': _ip_options_reserved,
'site-local': _ip_options_site_local,
'sl': _ip_options_site_local,
'site_local': _ip_options_site_local,
'unspecified': _ip_options_unspecified
}
if not options:
return six.text_type(ip_obj)
options_list = [option.strip() for option in options.split(',')]
for option, fun in options_fun_map.items():
if option in options_list:
fun_res = fun(ip_obj, version)
if not fun_res:
return None
return six.text_type(ip_obj)
def _is_ipv(ip, version, options=None):
if not version:
version = 4
if version not in (4, 6):
return None
try:
ip_obj = ipaddress.ip_address(ip)
except ValueError:
try:
ip_obj = ipaddress.ip_interface(ip)
except ValueError:
return None
if not ip_obj.version == version:
return None
return _ip_options(ip_obj, version, options=options)
@jinja_filter('is_ipv4')
def is_ipv4_filter(ip, options=None):
_is_ipv4 = _is_ipv(ip, 4, options=options)
return isinstance(_is_ipv4, six.string_types)
@jinja_filter('is_ipv6')
def is_ipv6_filter(ip, options=None):
_is_ipv6 = _is_ipv(ip, 6, options=options)
return isinstance(_is_ipv6, six.string_types)
def _ipv_filter(value, version, options=None):
if version not in (4, 6):
return
if isinstance(value, (six.string_types, six.text_type, six.binary_type)):
return _is_ipv(value, version, options=options) # calls is_ipv4 or is_ipv6 for `value`
elif isinstance(value, (list, tuple, types.GeneratorType)):
# calls is_ipv4 or is_ipv6 for each element in the list
# os it filters and returns only those elements having the desired IP version
return [
_is_ipv(addr, version, options=options)
for addr in value
if _is_ipv(addr, version, options=options) is not None
]
return None
@jinja_filter('ipv4')
def ipv4(value, options=None):
return _ipv_filter(value, 4, options=options)
@jinja_filter('ipv6')
def ipv6(value, options=None):
return _ipv_filter(value, 6, options=options)
@jinja_filter('ipaddr')
def ipaddr(value, options=None):
ipv4_obj = ipv4(value, options=options)
ipv6_obj = ipv6(value, options=options)
if ipv4_obj is None or ipv6_obj is None:
# an IP address can be either IPv4 either IPv6
# therefofe if the value passed as arg is not a list, at least one of the calls above will return None
# if one of them is none, means that we should return only one of them
return ipv4_obj or ipv6_obj # one of them
else:
return ipv4_obj + ipv6_obj # extend lists
def _filter_ipaddr(value, options, version=None):
ipaddr_filter_out = None
if version:
if version == 4:
ipaddr_filter_out = ipv4(value, options)
elif version == 6:
ipaddr_filter_out = ipv6(value, options)
else:
ipaddr_filter_out = ipaddr(value, options)
if not ipaddr_filter_out:
return
if not isinstance(ipaddr_filter_out, (list, tuple, types.GeneratorType)):
ipaddr_filter_out = [ipaddr_filter_out]
return ipaddr_filter_out
@jinja_filter('ip_host')
def ip_host(value, options=None, version=None):
ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version)
if not ipaddr_filter_out:
return
if not isinstance(value, (list, tuple, types.GeneratorType)):
return six.text_type(ipaddress.ip_interface(ipaddr_filter_out[0]))
return [six.text_type(ipaddress.ip_interface(ip_a)) for ip_a in ipaddr_filter_out]
def _network_hosts(ip_addr_entry):
return [
six.text_type(host)
for host in ipaddress.ip_network(ip_addr_entry, strict=False).hosts()
]
@jinja_filter('network_hosts')
def network_hosts(value, options=None, version=None):
ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version)
if not ipaddr_filter_out:
return
if not isinstance(value, (list, tuple, types.GeneratorType)):
return _network_hosts(ipaddr_filter_out[0])
return [
_network_hosts(ip_a)
for ip_a in ipaddr_filter_out
]
def _network_size(ip_addr_entry):
return ipaddress.ip_network(ip_addr_entry, strict=False).num_addresses
@jinja_filter('network_size')
def network_size(value, options=None, version=None):
ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version)
if not ipaddr_filter_out:
return
if not isinstance(value, (list, tuple, types.GeneratorType)):
return _network_size(ipaddr_filter_out[0])
return [
_network_size(ip_a)
for ip_a in ipaddr_filter_out
]
def natural_ipv4_netmask(ip, fmt='prefixlen'):
bits = _ipv4_to_bits(ip)
if bits.startswith('11'):
mask = '24'
elif bits.startswith('1'):
mask = '16'
else:
mask = '8'
if fmt == 'netmask':
return cidr_to_ipv4_netmask(mask)
else:
return '/' + mask
def rpad_ipv4_network(ip):
return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0,
4))
def cidr_to_ipv4_netmask(cidr_bits):
try:
cidr_bits = int(cidr_bits)
if not 1 <= cidr_bits <= 32:
return ''
except ValueError:
return ''
netmask = ''
for idx in range(4):
if idx:
netmask += '.'
if cidr_bits >= 8:
netmask += '255'
cidr_bits -= 8
else:
netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits)))
cidr_bits = 0
return netmask
def _number_of_set_bits_to_ipv4_netmask(set_bits): # pylint: disable=C0103
return cidr_to_ipv4_netmask(_number_of_set_bits(set_bits))
# pylint: disable=C0103
def _number_of_set_bits(x):
# Taken from http://stackoverflow.com/a/4912729. Many thanks!
x -= (x >> 1) & 0x55555555
x = ((x >> 2) & 0x33333333) + (x & 0x33333333)
x = ((x >> 4) + x) & 0x0f0f0f0f
x += x >> 8
x += x >> 16
return x & 0x0000003f
# pylint: enable=C0103
def _interfaces_ip(out):
ret = dict()
def parse_network(value, cols):
brd = None
scope = None
if '/' in value: # we have a CIDR in this address
ip, cidr = value.split('/') # pylint: disable=C0103
else:
ip = value # pylint: disable=C0103
cidr = 32
if type_ == 'inet':
mask = cidr_to_ipv4_netmask(int(cidr))
if 'brd' in cols:
brd = cols[cols.index('brd') + 1]
elif type_ == 'inet6':
mask = cidr
if 'scope' in cols:
scope = cols[cols.index('scope') + 1]
return (ip, mask, brd, scope)
groups = re.compile('\r?\n\\d').split(out)
for group in groups:
iface = None
data = dict()
for line in group.splitlines():
if ' ' not in line:
continue
match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line)
if match:
iface, parent, attrs = match.groups()
if 'UP' in attrs.split(','):
data['up'] = True
else:
data['up'] = False
if parent:
data['parent'] = parent
continue
cols = line.split()
if len(cols) >= 2:
type_, value = tuple(cols[0:2])
iflabel = cols[-1:][0]
if type_ in ('inet', 'inet6'):
if 'secondary' not in cols:
ipaddr, netmask, broadcast, scope = parse_network(value, cols)
if type_ == 'inet':
if 'inet' not in data:
data['inet'] = list()
addr_obj = dict()
addr_obj['address'] = ipaddr
addr_obj['netmask'] = netmask
addr_obj['broadcast'] = broadcast
addr_obj['label'] = iflabel
data['inet'].append(addr_obj)
elif type_ == 'inet6':
if 'inet6' not in data:
data['inet6'] = list()
addr_obj = dict()
addr_obj['address'] = ipaddr
addr_obj['prefixlen'] = netmask
addr_obj['scope'] = scope
data['inet6'].append(addr_obj)
else:
if 'secondary' not in data:
data['secondary'] = list()
ip_, mask, brd, scp = parse_network(value, cols)
data['secondary'].append({
'type': type_,
'address': ip_,
'netmask': mask,
'broadcast': brd,
'label': iflabel,
})
del ip_, mask, brd, scp
elif type_.startswith('link'):
data['hwaddr'] = value
if iface:
ret[iface] = data
del iface, data
return ret
def _interfaces_ifconfig(out):
ret = dict()
piface = re.compile(r'^([^\s:]+)')
pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)')
if salt.utils.platform.is_sunos():
pip = re.compile(r'.*?(?:inet\s+)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)')
pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)')
pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\d+)).*')
else:
pip = re.compile(r'.*?(?:inet addr:|inet [^\d]*)(.*?)\s')
pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)')
pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\d+)|prefixlen (\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?')
pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\d\.]+))')
pupdown = re.compile('UP')
pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\d\.]+)')
groups = re.compile('\r?\n(?=\\S)').split(out)
for group in groups:
data = dict()
iface = ''
updown = False
for line in group.splitlines():
miface = piface.match(line)
mmac = pmac.match(line)
mip = pip.match(line)
mip6 = pip6.match(line)
mupdown = pupdown.search(line)
if miface:
iface = miface.group(1)
if mmac:
data['hwaddr'] = mmac.group(1)
if salt.utils.platform.is_sunos():
expand_mac = []
for chunk in data['hwaddr'].split(':'):
expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk))
data['hwaddr'] = ':'.join(expand_mac)
if mip:
if 'inet' not in data:
data['inet'] = list()
addr_obj = dict()
addr_obj['address'] = mip.group(1)
mmask = pmask.match(line)
if mmask:
if mmask.group(1):
mmask = _number_of_set_bits_to_ipv4_netmask(
int(mmask.group(1), 16))
else:
mmask = mmask.group(2)
addr_obj['netmask'] = mmask
mbcast = pbcast.match(line)
if mbcast:
addr_obj['broadcast'] = mbcast.group(1)
data['inet'].append(addr_obj)
if mupdown:
updown = True
if mip6:
if 'inet6' not in data:
data['inet6'] = list()
addr_obj = dict()
addr_obj['address'] = mip6.group(1) or mip6.group(2)
mmask6 = pmask6.match(line)
if mmask6:
addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2)
if not salt.utils.platform.is_sunos():
ipv6scope = mmask6.group(3) or mmask6.group(4)
addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope
# SunOS sometimes has ::/0 as inet6 addr when using addrconf
if not salt.utils.platform.is_sunos() \
or addr_obj['address'] != '::' \
and addr_obj['prefixlen'] != 0:
data['inet6'].append(addr_obj)
data['up'] = updown
if iface in ret:
# SunOS optimization, where interfaces occur twice in 'ifconfig -a'
# output with the same name: for ipv4 and then for ipv6 addr family.
# Every instance has it's own 'UP' status and we assume that ipv4
ret[iface] = dict(list(data.items()) + list(ret[iface].items()))
if 'inet' in data:
ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet'])
if 'inet6' in data:
ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6'])
else:
ret[iface] = data
del data
return ret
def linux_interfaces():
ifaces = dict()
ip_path = salt.utils.path.which('ip')
ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig')
if ip_path:
cmd1 = subprocess.Popen(
'{0} link show'.format(ip_path),
shell=True,
close_fds=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT).communicate()[0]
cmd2 = subprocess.Popen(
'{0} addr show'.format(ip_path),
shell=True,
close_fds=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT).communicate()[0]
ifaces = _interfaces_ip("{0}\n{1}".format(
salt.utils.stringutils.to_str(cmd1),
salt.utils.stringutils.to_str(cmd2)))
elif ifconfig_path:
cmd = subprocess.Popen(
'{0} -a'.format(ifconfig_path),
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT).communicate()[0]
ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd))
return ifaces
def _netbsd_interfaces_ifconfig(out):
ret = dict()
piface = re.compile(r'^([^\s:]+)')
pmac = re.compile('.*?address: ([0-9a-f:]+)')
pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s')
pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s')
pupdown = re.compile('UP')
pbcast = re.compile(r'.*?broadcast ([\d\.]+)')
groups = re.compile('\r?\n(?=\\S)').split(out)
for group in groups:
data = dict()
iface = ''
updown = False
for line in group.splitlines():
miface = piface.match(line)
mmac = pmac.match(line)
mip = pip.match(line)
mip6 = pip6.match(line)
mupdown = pupdown.search(line)
if miface:
iface = miface.group(1)
if mmac:
data['hwaddr'] = mmac.group(1)
if mip:
if 'inet' not in data:
data['inet'] = list()
addr_obj = dict()
addr_obj['address'] = mip.group(1)
mmask = mip.group(2)
if mip.group(2):
addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2))
mbcast = pbcast.match(line)
if mbcast:
addr_obj['broadcast'] = mbcast.group(1)
data['inet'].append(addr_obj)
if mupdown:
updown = True
if mip6:
if 'inet6' not in data:
data['inet6'] = list()
addr_obj = dict()
addr_obj['address'] = mip6.group(1)
mmask6 = mip6.group(3)
addr_obj['scope'] = mip6.group(2)
addr_obj['prefixlen'] = mip6.group(3)
data['inet6'].append(addr_obj)
data['up'] = updown
ret[iface] = data
del data
return ret
def netbsd_interfaces():
if LooseVersion(os.uname()[2]) < LooseVersion('8.0'):
return linux_interfaces()
ifconfig_path = salt.utils.path.which('ifconfig')
cmd = subprocess.Popen(
'{0} -a'.format(ifconfig_path),
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT).communicate()[0]
return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd))
def _interfaces_ipconfig(out):
ifaces = dict()
iface = None
adapter_iface_regex = re.compile(r'adapter (\S.+):$')
for line in out.splitlines():
if not line:
continue
if line.startswith('Ethernet'):
iface = ifaces[adapter_iface_regex.search(line).group(1)]
iface['up'] = True
addr = None
continue
if iface:
key, val = line.split(',', 1)
key = key.strip(' .')
val = val.strip()
if addr and key == 'Subnet Mask':
addr['netmask'] = val
elif key in ('IP Address', 'IPv4 Address'):
if 'inet' not in iface:
iface['inet'] = list()
addr = {'address': val.rstrip('(Preferred)'),
'netmask': None,
'broadcast': None}
iface['inet'].append(addr)
elif 'IPv6 Address' in key:
if 'inet6' not in iface:
iface['inet'] = list()
addr = {'address': val.rstrip('(Preferred)'),
'prefixlen': None}
iface['inet6'].append(addr)
elif key == 'Physical Address':
iface['hwaddr'] = val
elif key == 'Media State':
iface['up'] = (val != 'Media disconnected')
def win_interfaces():
with salt.utils.winapi.Com():
c = wmi.WMI()
ifaces = {}
for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1):
ifaces[iface.Description] = dict()
if iface.MACAddress:
ifaces[iface.Description]['hwaddr'] = iface.MACAddress
if iface.IPEnabled:
ifaces[iface.Description]['up'] = True
for ip in iface.IPAddress:
if '.' in ip:
if 'inet' not in ifaces[iface.Description]:
ifaces[iface.Description]['inet'] = []
item = {'address': ip,
'label': iface.Description}
if iface.DefaultIPGateway:
broadcast = next((i for i in iface.DefaultIPGateway if '.' in i), '')
if broadcast:
item['broadcast'] = broadcast
if iface.IPSubnet:
netmask = next((i for i in iface.IPSubnet if '.' in i), '')
if netmask:
item['netmask'] = netmask
ifaces[iface.Description]['inet'].append(item)
if ':' in ip:
if 'inet6' not in ifaces[iface.Description]:
ifaces[iface.Description]['inet6'] = []
item = {'address': ip}
if iface.DefaultIPGateway:
broadcast = next((i for i in iface.DefaultIPGateway if ':' in i), '')
if broadcast:
item['broadcast'] = broadcast
if iface.IPSubnet:
netmask = next((i for i in iface.IPSubnet if ':' in i), '')
if netmask:
item['netmask'] = netmask
ifaces[iface.Description]['inet6'].append(item)
else:
ifaces[iface.Description]['up'] = False
return ifaces
def interfaces():
if salt.utils.platform.is_windows():
return win_interfaces()
elif salt.utils.platform.is_netbsd():
return netbsd_interfaces()
else:
return linux_interfaces()
def get_net_start(ipaddr, netmask):
net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False)
return six.text_type(net.network_address)
def get_net_size(mask):
binary_str = ''
for octet in mask.split('.'):
binary_str += bin(int(octet))[2:].zfill(8)
return len(binary_str.rstrip('0'))
def calc_net(ipaddr, netmask=None):
if netmask is not None:
ipaddr = '{0}/{1}'.format(ipaddr, netmask)
return six.text_type(ipaddress.ip_network(ipaddr, strict=False))
def _ipv4_to_bits(ipaddr):
return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')])
def _get_iface_info(iface):
iface_info = interfaces()
if iface in iface_info.keys():
return iface_info, False
else:
error_msg = ('Interface "{0}" not in available interfaces: "{1}"'
''.format(iface, '", "'.join(iface_info.keys())))
log.error(error_msg)
return None, error_msg
def _hw_addr_aix(iface):
cmd = subprocess.Popen(
'entstat -d {0} | grep \'Hardware Address\''.format(iface),
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT).communicate()[0]
if cmd:
comps = cmd.split(' ')
if len(comps) == 3:
mac_addr = comps[2].strip('\'').strip()
return mac_addr
error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface))
log.error(error_msg)
return error_msg
def hw_addr(iface):
if salt.utils.platform.is_aix():
return _hw_addr_aix
iface_info, error = _get_iface_info(iface)
if error is False:
return iface_info.get(iface, {}).get('hwaddr', '')
else:
return error
def interface(iface):
iface_info, error = _get_iface_info(iface)
if error is False:
return iface_info.get(iface, {}).get('inet', '')
else:
return error
def interface_ip(iface):
iface_info, error = _get_iface_info(iface)
if error is False:
inet = iface_info.get(iface, {}).get('inet', None)
return inet[0].get('address', '') if inet else ''
else:
return error
def _subnets(proto='inet', interfaces_=None):
if interfaces_ is None:
ifaces = interfaces()
elif isinstance(interfaces_, list):
ifaces = {}
for key, value in six.iteritems(interfaces()):
if key in interfaces_:
ifaces[key] = value
else:
ifaces = {interfaces_: interfaces().get(interfaces_, {})}
ret = set()
if proto == 'inet':
subnet = 'netmask'
dflt_cidr = 32
elif proto == 'inet6':
subnet = 'prefixlen'
dflt_cidr = 128
else:
log.error('Invalid proto {0} calling subnets()'.format(proto))
return
for ip_info in six.itervalues(ifaces):
addrs = ip_info.get(proto, [])
addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto])
for intf in addrs:
if subnet in intf:
intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], intf[subnet]))
else:
intf = ipaddress.ip_interface('{0}/{1}'.format(intf['address'], dflt_cidr))
if not intf.is_loopback:
ret.add(intf.network)
return [six.text_type(net) for net in sorted(ret)]
def subnets(interfaces=None):
return _subnets('inet', interfaces_=interfaces)
def subnets6():
return _subnets('inet6')
def in_subnet(cidr, addr=None):
try:
cidr = ipaddress.ip_network(cidr)
except ValueError:
log.error('Invalid CIDR \'{0}\''.format(cidr))
return False
if addr is None:
addr = ip_addrs()
addr.extend(ip_addrs6())
elif isinstance(addr, six.string_types):
return ipaddress.ip_address(addr) in cidr
for ip_addr in addr:
if ipaddress.ip_address(ip_addr) in cidr:
return True
return False
def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'):
ret = set()
ifaces = interface_data \
if isinstance(interface_data, dict) \
else interfaces()
if interface is None:
target_ifaces = ifaces
else:
target_ifaces = dict([(k, v) for k, v in six.iteritems(ifaces)
if k == interface])
if not target_ifaces:
log.error('Interface {0} not found.'.format(interface))
for ip_info in six.itervalues(target_ifaces):
addrs = ip_info.get(proto, [])
addrs.extend([addr for addr in ip_info.get('secondary', []) if addr.get('type') == proto])
for addr in addrs:
addr = ipaddress.ip_address(addr.get('address'))
if not addr.is_loopback or include_loopback:
ret.add(addr)
return [six.text_type(addr) for addr in sorted(ret)]
def ip_addrs(interface=None, include_loopback=False, interface_data=None):
return _ip_addrs(interface, include_loopback, interface_data, 'inet')
def ip_addrs6(interface=None, include_loopback=False, interface_data=None):
return _ip_addrs(interface, include_loopback, interface_data, 'inet6')
def hex2ip(hex_ip, invert=False):
if len(hex_ip) == 32: # ipv6
ip = []
for i in range(0, 32, 8):
ip_part = hex_ip[i:i + 8]
ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)]
if invert:
ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part))
else:
ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part))
try:
address = ipaddress.IPv6Address(":".join(ip))
if address.ipv4_mapped:
return str(address.ipv4_mapped)
else:
return address.compressed
except ipaddress.AddressValueError as ex:
log.error('hex2ip - ipv6 address error: {0}'.format(ex))
return hex_ip
try:
hip = int(hex_ip, 16)
except ValueError:
return hex_ip
if invert:
return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255,
hip >> 16 & 255,
hip >> 8 & 255,
hip & 255)
return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255,
hip >> 16 & 255,
hip >> 8 & 255,
hip & 255)
def mac2eui64(mac, prefix=None):
# http://tools.ietf.org/html/rfc4291#section-2.5.1
eui64 = re.sub(r'[.:-]', '', mac).lower()
eui64 = eui64[0:6] + 'fffe' + eui64[6:]
eui64 = hex(int(eui64[0:2], 16) | 2)[2:].zfill(2) + eui64[2:]
if prefix is None:
return ':'.join(re.findall(r'.{4}', eui64))
else:
try:
net = ipaddress.ip_network(prefix, strict=False)
euil = int('0x{0}'.format(eui64), 16)
return '{0}/{1}'.format(net[euil], net.prefixlen)
except Exception:
return
def active_tcp():
ret = {}
for statf in ['/proc/net/tcp', '/proc/net/tcp6']:
if os.path.isfile(statf):
with salt.utils.files.fopen(statf, 'rb') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
if line.strip().startswith('sl'):
continue
iret = _parse_tcp_line(line)
sl = next(iter(iret))
if iret[sl]['state'] == 1: # 1 is ESTABLISHED
del iret[sl]['state']
ret[len(ret)] = iret[sl]
return ret
def local_port_tcp(port):
ret = _remotes_on(port, 'local_port')
return ret
def remote_port_tcp(port):
ret = _remotes_on(port, 'remote_port')
return ret
def _remotes_on(port, which_end):
port = int(port)
ret = set()
proc_available = False
for statf in ['/proc/net/tcp', '/proc/net/tcp6']:
if os.path.isfile(statf):
proc_available = True
with salt.utils.files.fopen(statf, 'r') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
if line.strip().startswith('sl'):
continue
iret = _parse_tcp_line(line)
sl = next(iter(iret))
if iret[sl][which_end] == port and iret[sl]['state'] == 1: # 1 is ESTABLISHED
ret.add(iret[sl]['remote_addr'])
if not proc_available: # Fallback to use OS specific tools
if salt.utils.platform.is_sunos():
return _sunos_remotes_on(port, which_end)
if salt.utils.platform.is_freebsd():
return _freebsd_remotes_on(port, which_end)
if salt.utils.platform.is_netbsd():
return _netbsd_remotes_on(port, which_end)
if salt.utils.platform.is_openbsd():
return _openbsd_remotes_on(port, which_end)
if salt.utils.platform.is_windows():
return _windows_remotes_on(port, which_end)
if salt.utils.platform.is_aix():
return _aix_remotes_on(port, which_end)
return _linux_remotes_on(port, which_end)
return ret
def _parse_tcp_line(line):
ret = {}
comps = line.strip().split()
sl = comps[0].rstrip(':')
ret[sl] = {}
l_addr, l_port = comps[1].split(':')
r_addr, r_port = comps[2].split(':')
ret[sl]['local_addr'] = hex2ip(l_addr, True)
ret[sl]['local_port'] = int(l_port, 16)
ret[sl]['remote_addr'] = hex2ip(r_addr, True)
ret[sl]['remote_port'] = int(r_port, 16)
ret[sl]['state'] = int(comps[3], 16)
return ret
def _sunos_remotes_on(port, which_end):
remotes = set()
try:
data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version
except subprocess.CalledProcessError:
log.error('Failed netstat')
raise
lines = salt.utils.stringutils.to_str(data).split('\n')
for line in lines:
if 'ESTABLISHED' not in line:
continue
chunks = line.split()
local_host, local_port = chunks[0].rsplit('.', 1)
remote_host, remote_port = chunks[1].rsplit('.', 1)
if which_end == 'remote_port' and int(remote_port) != port:
continue
if which_end == 'local_port' and int(local_port) != port:
continue
remotes.add(remote_host)
return remotes
def _freebsd_remotes_on(port, which_end):
port = int(port)
remotes = set()
try:
cmd = salt.utils.args.shlex_split('sockstat -4 -c -p {0}'.format(port))
data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version
except subprocess.CalledProcessError as ex:
log.error('Failed "sockstat" with returncode = {0}'.format(ex.returncode))
raise
lines = salt.utils.stringutils.to_str(data).split('\n')
for line in lines:
chunks = line.split()
if not chunks:
continue
# ['root', 'python2.7', '1456', '37', 'tcp4',
# '127.0.0.1:4505-', '127.0.0.1:55703']
# print chunks
if 'COMMAND' in chunks[1]:
continue # ignore header
if len(chunks) < 2:
continue
# sockstat -4 -c -p 4506 does this with high PIDs:
# USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS
# salt-master python2.781106 35 tcp4 192.168.12.34:4506 192.168.12.45:60143
local = chunks[-2]
remote = chunks[-1]
lhost, lport = local.split(':')
rhost, rport = remote.split(':')
if which_end == 'local' and int(lport) != port: # ignore if local port not port
continue
if which_end == 'remote' and int(rport) != port: # ignore if remote port not port
continue
remotes.add(rhost)
return remotes
def _netbsd_remotes_on(port, which_end):
port = int(port)
remotes = set()
try:
cmd = salt.utils.args.shlex_split('sockstat -4 -c -n -p {0}'.format(port))
data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version
except subprocess.CalledProcessError as ex:
log.error('Failed "sockstat" with returncode = {0}'.format(ex.returncode))
raise
lines = salt.utils.stringutils.to_str(data).split('\n')
for line in lines:
chunks = line.split()
if not chunks:
continue
# ['root', 'python2.7', '1456', '37', 'tcp',
# '127.0.0.1.4505-', '127.0.0.1.55703']
# print chunks
if 'COMMAND' in chunks[1]:
continue # ignore header
if len(chunks) < 2:
continue
local = chunks[5].split('.')
lport = local.pop()
lhost = '.'.join(local)
remote = chunks[6].split('.')
rport = remote.pop()
rhost = '.'.join(remote)
if which_end == 'local' and int(lport) != port: # ignore if local port not port
continue
if which_end == 'remote' and int(rport) != port: # ignore if remote port not port
continue
remotes.add(rhost)
return remotes
def _openbsd_remotes_on(port, which_end):
remotes = set()
try:
data = subprocess.check_output(['netstat', '-nf', 'inet']) # pylint: disable=minimum-python-version
except subprocess.CalledProcessError:
log.error('Failed netstat')
raise
lines = data.split('\n')
for line in lines:
if 'ESTABLISHED' not in line:
continue
chunks = line.split()
local_host, local_port = chunks[3].rsplit('.', 1)
remote_host, remote_port = chunks[4].rsplit('.', 1)
if which_end == 'remote_port' and int(remote_port) != port:
continue
if which_end == 'local_port' and int(local_port) != port:
continue
remotes.add(remote_host)
return remotes
def _windows_remotes_on(port, which_end):
remotes = set()
try:
data = subprocess.check_output(['netstat', '-n']) # pylint: disable=minimum-python-version
except subprocess.CalledProcessError:
log.error('Failed netstat')
raise
lines = salt.utils.stringutils.to_str(data).split('\n')
for line in lines:
if 'ESTABLISHED' not in line:
continue
chunks = line.split()
local_host, local_port = chunks[1].rsplit(':', 1)
remote_host, remote_port = chunks[2].rsplit(':', 1)
if which_end == 'remote_port' and int(remote_port) != port:
continue
if which_end == 'local_port' and int(local_port) != port:
continue
remotes.add(remote_host)
return remotes
def _linux_remotes_on(port, which_end):
remotes = set()
try:
data = subprocess.check_output(
['lsof', '-iTCP:{0:d}'.format(port), '-n', '-P'] # pylint: disable=minimum-python-version
)
except subprocess.CalledProcessError as ex:
if ex.returncode == 1:
# Lsof return 1 if any error was detected, including the failure
# to locate Internet addresses, and it is not an error in this case.
log.warning('"lsof" returncode = 1, likely no active TCP sessions.')
return remotes
log.error('Failed "lsof" with returncode = {0}'.format(ex.returncode))
raise
lines = salt.utils.stringutils.to_str(data).split('\n')
for line in lines:
chunks = line.split()
if not chunks:
continue
# ['Python', '9971', 'root', '37u', 'IPv4', '0x18a8464a29b2b29d', '0t0',
# 'TCP', '127.0.0.1:4505->127.0.0.1:55703', '(ESTABLISHED)']
# print chunks
if 'COMMAND' in chunks[0]:
continue # ignore header
if 'ESTABLISHED' not in chunks[-1]:
continue # ignore if not ESTABLISHED
# '127.0.0.1:4505->127.0.0.1:55703'
local, remote = chunks[8].split('->')
_, lport = local.rsplit(':', 1)
rhost, rport = remote.rsplit(':', 1)
if which_end == 'remote_port' and int(rport) != port:
continue
if which_end == 'local_port' and int(lport) != port:
continue
remotes.add(rhost.strip("[]"))
return remotes
def _aix_remotes_on(port, which_end):
remotes = set()
try:
data = subprocess.check_output(['netstat', '-f', 'inet', '-n']) # pylint: disable=minimum-python-version
except subprocess.CalledProcessError:
log.error('Failed netstat')
raise
lines = salt.utils.stringutils.to_str(data).split('\n')
for line in lines:
if 'ESTABLISHED' not in line:
continue
chunks = line.split()
local_host, local_port = chunks[3].rsplit('.', 1)
remote_host, remote_port = chunks[4].rsplit('.', 1)
if which_end == 'remote_port' and int(remote_port) != port:
continue
if which_end == 'local_port' and int(local_port) != port:
continue
remotes.add(remote_host)
return remotes
@jinja_filter('gen_mac')
def gen_mac(prefix='AC:DE:48'):
return '{0}:{1:02X}:{2:02X}:{3:02X}'.format(prefix,
random.randint(0, 0xff),
random.randint(0, 0xff),
random.randint(0, 0xff))
@jinja_filter('mac_str_to_bytes')
def mac_str_to_bytes(mac_str):
if len(mac_str) == 12:
pass
elif len(mac_str) == 17:
sep = mac_str[2]
mac_str = mac_str.replace(sep, '')
else:
raise ValueError('Invalid MAC address')
chars = (int(mac_str[s:s+2], 16) for s in range(0, 12, 2))
return bytes(chars) if six.PY3 else b''.join(chr(x) for x in chars)
def refresh_dns():
try:
res_init()
except NameError:
# Exception raised loading the library, thus res_init is not defined
pass
@jinja_filter('connection_check')
def connection_check(addr, port=80, safe=False, ipv6=None):
return dns_check(addr, port, safe, ipv6)
@jinja_filter('dns_check')
def dns_check(addr, port=80, safe=False, ipv6=None):
error = False
lookup = addr
seen_ipv6 = False
family = socket.AF_INET6 if ipv6 else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC
try:
refresh_dns()
hostnames = socket.getaddrinfo(addr, port, family, socket.SOCK_STREAM)
if not hostnames:
error = True
else:
resolved = False
candidates = []
for h in hostnames:
# Input is IP address, passed through unchanged, just return it
if h[4][0] == addr:
resolved = salt.utils.zeromq.ip_bracket(addr)
break
candidate_addr = salt.utils.zeromq.ip_bracket(h[4][0])
candidates.append(candidate_addr)
try:
s = socket.socket(h[0], socket.SOCK_STREAM)
s.connect((candidate_addr.strip('[]'), h[4][1]))
s.close()
resolved = candidate_addr
break
except socket.error:
pass
if not resolved:
if len(candidates) > 0:
resolved = candidates[0]
else:
error = True
except TypeError:
err = ('Attempt to resolve address \'{0}\' failed. Invalid or unresolveable address').format(lookup)
raise SaltSystemExit(code=42, msg=err)
except socket.error:
error = True
if error:
err = ('DNS lookup or connection check of \'{0}\' failed.').format(addr)
if safe:
if salt.log.is_console_configured():
# If logging is not configured it also means that either
# the master or minion instance calling this hasn't even
log.error(err)
raise SaltClientError()
raise SaltSystemExit(code=42, msg=err)
return resolved
| true | true |
f7f766642397ef85a2fa7f20d230bb307e3a6828 | 7,804 | py | Python | docs/conf.py | ProkMar/case5_homework | 7606dfc2127aec366f48d14c4d4737e93ceb0a87 | [
"MIT"
] | null | null | null | docs/conf.py | ProkMar/case5_homework | 7606dfc2127aec366f48d14c4d4737e93ceb0a87 | [
"MIT"
] | null | null | null | docs/conf.py | ProkMar/case5_homework | 7606dfc2127aec366f48d14c4d4737e93ceb0a87 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
#
# case5_homework documentation build configuration file, created by
# sphinx-quickstart.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import os
import sys
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = []
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'case5_homework'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.1'
# The full version, including alpha/beta/rc tags.
release = '0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module index is generated.
# html_domain_indices = True
# If false, no index is generated.
# html_use_index = True
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'case5_homeworkdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
# 'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index',
'case5_homework.tex',
u'case5_homework Documentation',
u"ProkMar", 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
# latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'case5_homework', u'case5_homework Documentation',
[u"ProkMar"], 1)
]
# If true, show URL addresses after external links.
# man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'case5_homework', u'case5_homework Documentation',
u"ProkMar", 'case5_homework',
'Домашняя работа по 5-му кейсу', 'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
# texinfo_appendices = []
# If false, no module index is generated.
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'
| 31.853061 | 80 | 0.708355 |
import os
import sys
extensions = []
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'case5_homework'
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.1'
# The full version, including alpha/beta/rc tags.
release = '0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module index is generated.
# html_domain_indices = True
# If false, no index is generated.
# html_use_index = True
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'case5_homeworkdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
# 'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index',
'case5_homework.tex',
u'case5_homework Documentation',
u"ProkMar", 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
# latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'case5_homework', u'case5_homework Documentation',
[u"ProkMar"], 1)
]
# If true, show URL addresses after external links.
# man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'case5_homework', u'case5_homework Documentation',
u"ProkMar", 'case5_homework',
'Домашняя работа по 5-му кейсу', 'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
# texinfo_appendices = []
# If false, no module index is generated.
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'
| true | true |
f7f7676817428dfeaa132ad7ad9fa21330e6fe0c | 2,396 | py | Python | pc-bot/cmd.py | magnickolas/pc-bot | 32c16a5213deaba5e66265cbadb73bafe9078404 | [
"MIT"
] | null | null | null | pc-bot/cmd.py | magnickolas/pc-bot | 32c16a5213deaba5e66265cbadb73bafe9078404 | [
"MIT"
] | null | null | null | pc-bot/cmd.py | magnickolas/pc-bot | 32c16a5213deaba5e66265cbadb73bafe9078404 | [
"MIT"
] | null | null | null | from functools import wraps
from pathlib import Path
from subprocess import CalledProcessError, check_call, DEVNULL
from urllib.request import urlopen
from loguru import logger
from paramiko import AutoAddPolicy
from paramiko.client import SSHClient
from paramiko.config import SSHConfig
from .config import TG_ID, MAC, SSH_INSTANCE, RPC_PASSWORD, RPC_SERVER, RPC_USER
def authcmd(cmd):
@wraps(cmd)
def wrapper(update, context):
user_id = update.effective_chat.id
if str(user_id) == TG_ID:
reply = cmd()
context.bot.send_message(chat_id=user_id, text=reply)
return wrapper
@authcmd
def power_on() -> str:
try:
check_call(["wakeonlan", MAC], stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL)
return "Turned on!"
except CalledProcessError:
logger.exception("Failed to turn on")
return "Failed to turn on..."
@authcmd
def power_off() -> str:
try:
if __is_windows():
__power_off_windows()
elif SSH_INSTANCE is not None:
__power_off_linux()
return "Turned off!"
except Exception:
logger.exception("Failed to turn off")
return "Failed to turn off..."
@authcmd
def global_ip() -> str:
try:
external_ip = urlopen('https://ident.me').read().decode('utf8')
return f"The IP address is {external_ip}"
except Exception:
logger.exception("Failed to get IP")
return "Failed to get IP..."
def __is_windows() -> bool:
if RPC_SERVER is None:
return False
try:
check_call(["net", "rpc", "user", "info", RPC_USER, "-S", RPC_SERVER, "-U", f"{RPC_USER}%{RPC_PASSWORD}"])
return True
except CalledProcessError:
return False
def __power_off_windows():
check_call(["net", "rpc", "-S", RPC_SERVER, "-U", f"{RPC_USER}%{RPC_PASSWORD}", "shutdown", "-t", "0", "-f"])
def __power_off_linux():
cfg = SSHConfig.from_path(Path.home() / ".ssh" / "config")\
.lookup(SSH_INSTANCE)
ssh = SSHClient()
ssh.set_missing_host_key_policy(AutoAddPolicy())
ssh.connect(**{
"hostname": cfg.get("hostname"),
"port": cfg.get("port") or 22,
"username": cfg.get("user"),
"password": cfg.get("password"),
"key_filename": cfg.get("identityfile"),
})
ssh.exec_command("sudo poweroff")
| 30.329114 | 114 | 0.628965 | from functools import wraps
from pathlib import Path
from subprocess import CalledProcessError, check_call, DEVNULL
from urllib.request import urlopen
from loguru import logger
from paramiko import AutoAddPolicy
from paramiko.client import SSHClient
from paramiko.config import SSHConfig
from .config import TG_ID, MAC, SSH_INSTANCE, RPC_PASSWORD, RPC_SERVER, RPC_USER
def authcmd(cmd):
@wraps(cmd)
def wrapper(update, context):
user_id = update.effective_chat.id
if str(user_id) == TG_ID:
reply = cmd()
context.bot.send_message(chat_id=user_id, text=reply)
return wrapper
@authcmd
def power_on() -> str:
try:
check_call(["wakeonlan", MAC], stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL)
return "Turned on!"
except CalledProcessError:
logger.exception("Failed to turn on")
return "Failed to turn on..."
@authcmd
def power_off() -> str:
try:
if __is_windows():
__power_off_windows()
elif SSH_INSTANCE is not None:
__power_off_linux()
return "Turned off!"
except Exception:
logger.exception("Failed to turn off")
return "Failed to turn off..."
@authcmd
def global_ip() -> str:
try:
external_ip = urlopen('https://ident.me').read().decode('utf8')
return f"The IP address is {external_ip}"
except Exception:
logger.exception("Failed to get IP")
return "Failed to get IP..."
def __is_windows() -> bool:
if RPC_SERVER is None:
return False
try:
check_call(["net", "rpc", "user", "info", RPC_USER, "-S", RPC_SERVER, "-U", f"{RPC_USER}%{RPC_PASSWORD}"])
return True
except CalledProcessError:
return False
def __power_off_windows():
check_call(["net", "rpc", "-S", RPC_SERVER, "-U", f"{RPC_USER}%{RPC_PASSWORD}", "shutdown", "-t", "0", "-f"])
def __power_off_linux():
cfg = SSHConfig.from_path(Path.home() / ".ssh" / "config")\
.lookup(SSH_INSTANCE)
ssh = SSHClient()
ssh.set_missing_host_key_policy(AutoAddPolicy())
ssh.connect(**{
"hostname": cfg.get("hostname"),
"port": cfg.get("port") or 22,
"username": cfg.get("user"),
"password": cfg.get("password"),
"key_filename": cfg.get("identityfile"),
})
ssh.exec_command("sudo poweroff")
| true | true |
f7f7688a6bdc0768e6e4e2abb0bd6f041e48c972 | 2,175 | py | Python | Month 03/Week 01/Day 04/d.py | KevinKnott/Coding-Review | 6a83cb798cc317d1e4357ac6b2b1fbf76fa034fb | [
"MIT"
] | null | null | null | Month 03/Week 01/Day 04/d.py | KevinKnott/Coding-Review | 6a83cb798cc317d1e4357ac6b2b1fbf76fa034fb | [
"MIT"
] | null | null | null | Month 03/Week 01/Day 04/d.py | KevinKnott/Coding-Review | 6a83cb798cc317d1e4357ac6b2b1fbf76fa034fb | [
"MIT"
] | null | null | null | # Is Graph Bipartite?: https://leetcode.com/problems/is-graph-bipartite/
# There is an undirected graph with n nodes, where each node is numbered between 0 and n - 1. You are given a 2D array graph, where graph[u] is an array of nodes that node u is adjacent to. More formally, for each v in graph[u], there is an undirected edge between node u and node v. The graph has the following properties:
# There are no self-edges (graph[u] does not contain u).
# There are no parallel edges (graph[u] does not contain duplicate values).
# If v is in graph[u], then u is in graph[v] (the graph is undirected).
# The graph may not be connected, meaning there may be two nodes u and v such that there is no path between them.
# A graph is bipartite if the nodes can be partitioned into two independent sets A and B such that every edge in the graph connects a node in set A and a node in set B.
# Return true if and only if it is bipartite.
# This problem is actually pretty easy you recursively dfs through the nodes and label them in your visited with a color red/black or 0/1
# Continue this and if you ever try to color a node in an opposite color you return false else the problem is true
class Solution:
def isBipartite(self, graph) -> bool:
visited = {}
self.hasFaled = False
def dfs(node, color=0):
if node in visited:
if visited[node] ^ color:
self.hasFaled = True
return False
return True
visited[node] = color
for nei in graph[node]:
if not dfs(nei, color ^ 1):
return False
return True
for i in range(len(graph)):
if i not in visited:
if not dfs(i):
return False
return True
# The above works and is actually kind of neat by coloring as we go we can limit this problem to a
# time complexity of O(V+E) and a space complexity of only O(V)
# Score Card
# Did I need hints? N
# Did you finish within 30 min? 10
# Was the solution optimal? This is optimal
# Were there any bugs? No
# 5 5 5 5 = 5
| 39.545455 | 323 | 0.648736 |
class Solution:
def isBipartite(self, graph) -> bool:
visited = {}
self.hasFaled = False
def dfs(node, color=0):
if node in visited:
if visited[node] ^ color:
self.hasFaled = True
return False
return True
visited[node] = color
for nei in graph[node]:
if not dfs(nei, color ^ 1):
return False
return True
for i in range(len(graph)):
if i not in visited:
if not dfs(i):
return False
return True
| true | true |
f7f76895dbd522ada9e5faf2505b3b065054aa1b | 5,616 | py | Python | bird_view/models/birdview.py | jostl/masters-thesis | 211e1f12a07428d37507e2bddc808f6da1149efb | [
"MIT"
] | 3 | 2021-06-19T10:49:26.000Z | 2022-03-26T11:31:28.000Z | bird_view/models/birdview.py | jostl/masters-thesis | 211e1f12a07428d37507e2bddc808f6da1149efb | [
"MIT"
] | 1 | 2021-10-12T15:40:55.000Z | 2021-10-12T15:40:55.000Z | bird_view/models/birdview.py | jostl/masters-thesis | 211e1f12a07428d37507e2bddc808f6da1149efb | [
"MIT"
] | null | null | null | import cv2
import numpy as np
import torch
import torch.nn as nn
from . import common
from .agent import Agent
from .controller import PIDController, CustomController
from .controller import ls_circle
STEPS = 5
SPEED_STEPS = 3
COMMANDS = 4
DT = 0.1
CROP_SIZE = 192
PIXELS_PER_METER = 5
def regression_base():
return nn.Sequential(
nn.ConvTranspose2d(640,256,4,2,1,0),
nn.BatchNorm2d(256),
nn.ReLU(True),
nn.ConvTranspose2d(256,128,4,2,1,0),
nn.BatchNorm2d(128),
nn.ReLU(True),
nn.ConvTranspose2d(128,64,4,2,1,0),
nn.BatchNorm2d(64),
nn.ReLU(True))
def spatial_softmax_base():
return nn.Sequential(
nn.BatchNorm2d(640),
nn.ConvTranspose2d(640,256,3,2,1,1),
nn.ReLU(True),
nn.BatchNorm2d(256),
nn.ConvTranspose2d(256,128,3,2,1,1),
nn.ReLU(True),
nn.BatchNorm2d(128),
nn.ConvTranspose2d(128,64,3,2,1,1),
nn.ReLU(True))
class BirdViewPolicyModelSS(common.ResnetBase):
def __init__(self, backbone='resnet18', input_channel=7, n_step=5, all_branch=False, **kwargs):
super().__init__(backbone=backbone, input_channel=input_channel, bias_first=False)
self.deconv = spatial_softmax_base()
self.location_pred = nn.ModuleList([
nn.Sequential(
nn.BatchNorm2d(64),
nn.Conv2d(64,STEPS,1,1,0),
common.SpatialSoftmax(48,48,STEPS)) for i in range(COMMANDS)
])
self.all_branch = all_branch
def forward(self, bird_view, velocity, command):
h = self.conv(bird_view)
b, c, kh, kw = h.size()
# Late fusion for velocity
velocity = velocity[...,None,None,None].repeat((1,128,kh,kw))
h = torch.cat((h, velocity), dim=1)
h = self.deconv(h)
location_preds = [location_pred(h) for location_pred in self.location_pred]
location_preds = torch.stack(location_preds, dim=1)
location_pred = common.select_branch(location_preds, command)
if self.all_branch:
return location_pred, location_preds
return location_pred
class BirdViewAgent(Agent):
def __init__(self, steer_points=None, pid=None, gap=5, **kwargs):
super().__init__(**kwargs)
self.speed_control = PIDController(K_P=1.0, K_I=0.1, K_D=2.5)
if steer_points is None:
steer_points = {"1": 3, "2": 2, "3": 2, "4": 2}
if pid is None:
pid = {
"1": {"Kp": 1.0, "Ki": 0.1, "Kd": 0}, # Left
"2": {"Kp": 1.0, "Ki": 0.1, "Kd": 0}, # Right
"3": {"Kp": 0.8, "Ki": 0.1, "Kd": 0}, # Straight
"4": {"Kp": 0.8, "Ki": 0.1, "Kd": 0}, # Follow
}
self.turn_control = CustomController(pid)
self.steer_points = steer_points
self.gap = gap
def run_step(self, observations, teaching=False):
birdview = common.crop_birdview(observations['birdview'], dx=-10)
speed = np.linalg.norm(observations['velocity'])
command = self.one_hot[int(observations['command']) - 1]
with torch.no_grad():
_birdview = self.transform(birdview).to(self.device).unsqueeze(0)
_speed = torch.FloatTensor([speed]).to(self.device)
_command = command.to(self.device).unsqueeze(0)
if self.model.all_branch:
_locations, _ = self.model(_birdview, _speed, _command)
else:
_locations = self.model(_birdview, _speed, _command)
_locations = _locations.squeeze().detach().cpu().numpy()
_map_locations = _locations
# Pixel coordinates.
_locations = (_locations + 1) / 2 * CROP_SIZE
targets = list()
for i in range(STEPS):
pixel_dx, pixel_dy = _locations[i]
pixel_dx = pixel_dx - CROP_SIZE / 2
pixel_dy = CROP_SIZE - pixel_dy
angle = np.arctan2(pixel_dx, pixel_dy)
dist = np.linalg.norm([pixel_dx, pixel_dy]) / PIXELS_PER_METER
targets.append([dist * np.cos(angle), dist * np.sin(angle)])
target_speed = 0.0
for i in range(1, SPEED_STEPS):
pixel_dx, pixel_dy = _locations[i]
prev_dx, prev_dy = _locations[i-1]
dx = pixel_dx - prev_dx
dy = pixel_dy - prev_dy
delta = np.linalg.norm([dx, dy])
target_speed += delta / (PIXELS_PER_METER * self.gap * DT) / (SPEED_STEPS-1)
_cmd = int(observations['command'])
n = self.steer_points.get(str(_cmd), 1)
targets = np.concatenate([[[0, 0]], targets], 0)
c, r = ls_circle(targets)
closest = common.project_point_to_circle(targets[n], c, r)
v = [1.0, 0.0, 0.0]
w = [closest[0], closest[1], 0.0]
alpha = common.signed_angle(v, w)
steer = self.turn_control.run_step(alpha, _cmd)
throttle = self.speed_control.step(target_speed - speed)
brake = 0.0
if target_speed < 1.0:
steer = 0.0
throttle = 0.0
brake = 1.0
self.debug['locations_birdview'] = _locations[:,::-1].astype(int)
self.debug['target'] = closest
self.debug['target_speed'] = target_speed
control = self.postprocess(steer, throttle, brake)
if teaching:
return control, _map_locations
else:
return control
| 32.091429 | 99 | 0.567308 | import cv2
import numpy as np
import torch
import torch.nn as nn
from . import common
from .agent import Agent
from .controller import PIDController, CustomController
from .controller import ls_circle
STEPS = 5
SPEED_STEPS = 3
COMMANDS = 4
DT = 0.1
CROP_SIZE = 192
PIXELS_PER_METER = 5
def regression_base():
return nn.Sequential(
nn.ConvTranspose2d(640,256,4,2,1,0),
nn.BatchNorm2d(256),
nn.ReLU(True),
nn.ConvTranspose2d(256,128,4,2,1,0),
nn.BatchNorm2d(128),
nn.ReLU(True),
nn.ConvTranspose2d(128,64,4,2,1,0),
nn.BatchNorm2d(64),
nn.ReLU(True))
def spatial_softmax_base():
return nn.Sequential(
nn.BatchNorm2d(640),
nn.ConvTranspose2d(640,256,3,2,1,1),
nn.ReLU(True),
nn.BatchNorm2d(256),
nn.ConvTranspose2d(256,128,3,2,1,1),
nn.ReLU(True),
nn.BatchNorm2d(128),
nn.ConvTranspose2d(128,64,3,2,1,1),
nn.ReLU(True))
class BirdViewPolicyModelSS(common.ResnetBase):
def __init__(self, backbone='resnet18', input_channel=7, n_step=5, all_branch=False, **kwargs):
super().__init__(backbone=backbone, input_channel=input_channel, bias_first=False)
self.deconv = spatial_softmax_base()
self.location_pred = nn.ModuleList([
nn.Sequential(
nn.BatchNorm2d(64),
nn.Conv2d(64,STEPS,1,1,0),
common.SpatialSoftmax(48,48,STEPS)) for i in range(COMMANDS)
])
self.all_branch = all_branch
def forward(self, bird_view, velocity, command):
h = self.conv(bird_view)
b, c, kh, kw = h.size()
velocity = velocity[...,None,None,None].repeat((1,128,kh,kw))
h = torch.cat((h, velocity), dim=1)
h = self.deconv(h)
location_preds = [location_pred(h) for location_pred in self.location_pred]
location_preds = torch.stack(location_preds, dim=1)
location_pred = common.select_branch(location_preds, command)
if self.all_branch:
return location_pred, location_preds
return location_pred
class BirdViewAgent(Agent):
def __init__(self, steer_points=None, pid=None, gap=5, **kwargs):
super().__init__(**kwargs)
self.speed_control = PIDController(K_P=1.0, K_I=0.1, K_D=2.5)
if steer_points is None:
steer_points = {"1": 3, "2": 2, "3": 2, "4": 2}
if pid is None:
pid = {
"1": {"Kp": 1.0, "Ki": 0.1, "Kd": 0},
"2": {"Kp": 1.0, "Ki": 0.1, "Kd": 0},
"3": {"Kp": 0.8, "Ki": 0.1, "Kd": 0},
"4": {"Kp": 0.8, "Ki": 0.1, "Kd": 0},
}
self.turn_control = CustomController(pid)
self.steer_points = steer_points
self.gap = gap
def run_step(self, observations, teaching=False):
birdview = common.crop_birdview(observations['birdview'], dx=-10)
speed = np.linalg.norm(observations['velocity'])
command = self.one_hot[int(observations['command']) - 1]
with torch.no_grad():
_birdview = self.transform(birdview).to(self.device).unsqueeze(0)
_speed = torch.FloatTensor([speed]).to(self.device)
_command = command.to(self.device).unsqueeze(0)
if self.model.all_branch:
_locations, _ = self.model(_birdview, _speed, _command)
else:
_locations = self.model(_birdview, _speed, _command)
_locations = _locations.squeeze().detach().cpu().numpy()
_map_locations = _locations
_locations = (_locations + 1) / 2 * CROP_SIZE
targets = list()
for i in range(STEPS):
pixel_dx, pixel_dy = _locations[i]
pixel_dx = pixel_dx - CROP_SIZE / 2
pixel_dy = CROP_SIZE - pixel_dy
angle = np.arctan2(pixel_dx, pixel_dy)
dist = np.linalg.norm([pixel_dx, pixel_dy]) / PIXELS_PER_METER
targets.append([dist * np.cos(angle), dist * np.sin(angle)])
target_speed = 0.0
for i in range(1, SPEED_STEPS):
pixel_dx, pixel_dy = _locations[i]
prev_dx, prev_dy = _locations[i-1]
dx = pixel_dx - prev_dx
dy = pixel_dy - prev_dy
delta = np.linalg.norm([dx, dy])
target_speed += delta / (PIXELS_PER_METER * self.gap * DT) / (SPEED_STEPS-1)
_cmd = int(observations['command'])
n = self.steer_points.get(str(_cmd), 1)
targets = np.concatenate([[[0, 0]], targets], 0)
c, r = ls_circle(targets)
closest = common.project_point_to_circle(targets[n], c, r)
v = [1.0, 0.0, 0.0]
w = [closest[0], closest[1], 0.0]
alpha = common.signed_angle(v, w)
steer = self.turn_control.run_step(alpha, _cmd)
throttle = self.speed_control.step(target_speed - speed)
brake = 0.0
if target_speed < 1.0:
steer = 0.0
throttle = 0.0
brake = 1.0
self.debug['locations_birdview'] = _locations[:,::-1].astype(int)
self.debug['target'] = closest
self.debug['target_speed'] = target_speed
control = self.postprocess(steer, throttle, brake)
if teaching:
return control, _map_locations
else:
return control
| true | true |
f7f768f7511e008b1772d075266a4d419b58f3d7 | 75,962 | py | Python | synapse/handlers/sync.py | zauguin/synapse | ea00f18135ce30e8415526ce68585ea90da5b856 | [
"Apache-2.0"
] | null | null | null | synapse/handlers/sync.py | zauguin/synapse | ea00f18135ce30e8415526ce68585ea90da5b856 | [
"Apache-2.0"
] | null | null | null | synapse/handlers/sync.py | zauguin/synapse | ea00f18135ce30e8415526ce68585ea90da5b856 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
# Copyright 2018 New Vector Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import collections
import itertools
import logging
from six import iteritems, itervalues
from prometheus_client import Counter
from twisted.internet import defer
from synapse.api.constants import EventTypes, Membership
from synapse.push.clientformat import format_push_rules_for_user
from synapse.storage.roommember import MemberSummary
from synapse.storage.state import StateFilter
from synapse.types import RoomStreamToken
from synapse.util.async_helpers import concurrently_execute
from synapse.util.caches.expiringcache import ExpiringCache
from synapse.util.caches.lrucache import LruCache
from synapse.util.caches.response_cache import ResponseCache
from synapse.util.logcontext import LoggingContext
from synapse.util.metrics import Measure, measure_func
from synapse.visibility import filter_events_for_client
logger = logging.getLogger(__name__)
# Counts the number of times we returned a non-empty sync. `type` is one of
# "initial_sync", "full_state_sync" or "incremental_sync", `lazy_loaded` is
# "true" or "false" depending on if the request asked for lazy loaded members or
# not.
non_empty_sync_counter = Counter(
"synapse_handlers_sync_nonempty_total",
"Count of non empty sync responses. type is initial_sync/full_state_sync"
"/incremental_sync. lazy_loaded indicates if lazy loaded members were "
"enabled for that request.",
["type", "lazy_loaded"],
)
# Store the cache that tracks which lazy-loaded members have been sent to a given
# client for no more than 30 minutes.
LAZY_LOADED_MEMBERS_CACHE_MAX_AGE = 30 * 60 * 1000
# Remember the last 100 members we sent to a client for the purposes of
# avoiding redundantly sending the same lazy-loaded members to the client
LAZY_LOADED_MEMBERS_CACHE_MAX_SIZE = 100
SyncConfig = collections.namedtuple("SyncConfig", [
"user",
"filter_collection",
"is_guest",
"request_key",
"device_id",
])
class TimelineBatch(collections.namedtuple("TimelineBatch", [
"prev_batch",
"events",
"limited",
])):
__slots__ = []
def __nonzero__(self):
"""Make the result appear empty if there are no updates. This is used
to tell if room needs to be part of the sync result.
"""
return bool(self.events)
__bool__ = __nonzero__ # python3
class JoinedSyncResult(collections.namedtuple("JoinedSyncResult", [
"room_id", # str
"timeline", # TimelineBatch
"state", # dict[(str, str), FrozenEvent]
"ephemeral",
"account_data",
"unread_notifications",
"summary",
])):
__slots__ = []
def __nonzero__(self):
"""Make the result appear empty if there are no updates. This is used
to tell if room needs to be part of the sync result.
"""
return bool(
self.timeline
or self.state
or self.ephemeral
or self.account_data
# nb the notification count does not, er, count: if there's nothing
# else in the result, we don't need to send it.
)
__bool__ = __nonzero__ # python3
class ArchivedSyncResult(collections.namedtuple("ArchivedSyncResult", [
"room_id", # str
"timeline", # TimelineBatch
"state", # dict[(str, str), FrozenEvent]
"account_data",
])):
__slots__ = []
def __nonzero__(self):
"""Make the result appear empty if there are no updates. This is used
to tell if room needs to be part of the sync result.
"""
return bool(
self.timeline
or self.state
or self.account_data
)
__bool__ = __nonzero__ # python3
class InvitedSyncResult(collections.namedtuple("InvitedSyncResult", [
"room_id", # str
"invite", # FrozenEvent: the invite event
])):
__slots__ = []
def __nonzero__(self):
"""Invited rooms should always be reported to the client"""
return True
__bool__ = __nonzero__ # python3
class GroupsSyncResult(collections.namedtuple("GroupsSyncResult", [
"join",
"invite",
"leave",
])):
__slots__ = []
def __nonzero__(self):
return bool(self.join or self.invite or self.leave)
__bool__ = __nonzero__ # python3
class DeviceLists(collections.namedtuple("DeviceLists", [
"changed", # list of user_ids whose devices may have changed
"left", # list of user_ids whose devices we no longer track
])):
__slots__ = []
def __nonzero__(self):
return bool(self.changed or self.left)
__bool__ = __nonzero__ # python3
class SyncResult(collections.namedtuple("SyncResult", [
"next_batch", # Token for the next sync
"presence", # List of presence events for the user.
"account_data", # List of account_data events for the user.
"joined", # JoinedSyncResult for each joined room.
"invited", # InvitedSyncResult for each invited room.
"archived", # ArchivedSyncResult for each archived room.
"to_device", # List of direct messages for the device.
"device_lists", # List of user_ids whose devices have changed
"device_one_time_keys_count", # Dict of algorithm to count for one time keys
# for this device
"groups",
])):
__slots__ = []
def __nonzero__(self):
"""Make the result appear empty if there are no updates. This is used
to tell if the notifier needs to wait for more events when polling for
events.
"""
return bool(
self.presence or
self.joined or
self.invited or
self.archived or
self.account_data or
self.to_device or
self.device_lists or
self.groups
)
__bool__ = __nonzero__ # python3
class SyncHandler(object):
def __init__(self, hs):
self.hs_config = hs.config
self.store = hs.get_datastore()
self.notifier = hs.get_notifier()
self.presence_handler = hs.get_presence_handler()
self.event_sources = hs.get_event_sources()
self.clock = hs.get_clock()
self.response_cache = ResponseCache(hs, "sync")
self.state = hs.get_state_handler()
self.auth = hs.get_auth()
# ExpiringCache((User, Device)) -> LruCache(state_key => event_id)
self.lazy_loaded_members_cache = ExpiringCache(
"lazy_loaded_members_cache", self.clock,
max_len=0, expiry_ms=LAZY_LOADED_MEMBERS_CACHE_MAX_AGE,
)
@defer.inlineCallbacks
def wait_for_sync_for_user(self, sync_config, since_token=None, timeout=0,
full_state=False):
"""Get the sync for a client if we have new data for it now. Otherwise
wait for new data to arrive on the server. If the timeout expires, then
return an empty sync result.
Returns:
Deferred[SyncResult]
"""
# If the user is not part of the mau group, then check that limits have
# not been exceeded (if not part of the group by this point, almost certain
# auth_blocking will occur)
user_id = sync_config.user.to_string()
yield self.auth.check_auth_blocking(user_id)
res = yield self.response_cache.wrap(
sync_config.request_key,
self._wait_for_sync_for_user,
sync_config, since_token, timeout, full_state,
)
defer.returnValue(res)
@defer.inlineCallbacks
def _wait_for_sync_for_user(self, sync_config, since_token, timeout,
full_state):
if since_token is None:
sync_type = "initial_sync"
elif full_state:
sync_type = "full_state_sync"
else:
sync_type = "incremental_sync"
context = LoggingContext.current_context()
if context:
context.tag = sync_type
if timeout == 0 or since_token is None or full_state:
# we are going to return immediately, so don't bother calling
# notifier.wait_for_events.
result = yield self.current_sync_for_user(
sync_config, since_token, full_state=full_state,
)
else:
def current_sync_callback(before_token, after_token):
return self.current_sync_for_user(sync_config, since_token)
result = yield self.notifier.wait_for_events(
sync_config.user.to_string(), timeout, current_sync_callback,
from_token=since_token,
)
if result:
if sync_config.filter_collection.lazy_load_members():
lazy_loaded = "true"
else:
lazy_loaded = "false"
non_empty_sync_counter.labels(sync_type, lazy_loaded).inc()
defer.returnValue(result)
def current_sync_for_user(self, sync_config, since_token=None,
full_state=False):
"""Get the sync for client needed to match what the server has now.
Returns:
A Deferred SyncResult.
"""
return self.generate_sync_result(sync_config, since_token, full_state)
@defer.inlineCallbacks
def push_rules_for_user(self, user):
user_id = user.to_string()
rules = yield self.store.get_push_rules_for_user(user_id)
rules = format_push_rules_for_user(user, rules)
defer.returnValue(rules)
@defer.inlineCallbacks
def ephemeral_by_room(self, sync_result_builder, now_token, since_token=None):
"""Get the ephemeral events for each room the user is in
Args:
sync_result_builder(SyncResultBuilder)
now_token (StreamToken): Where the server is currently up to.
since_token (StreamToken): Where the server was when the client
last synced.
Returns:
A tuple of the now StreamToken, updated to reflect the which typing
events are included, and a dict mapping from room_id to a list of
typing events for that room.
"""
sync_config = sync_result_builder.sync_config
with Measure(self.clock, "ephemeral_by_room"):
typing_key = since_token.typing_key if since_token else "0"
room_ids = sync_result_builder.joined_room_ids
typing_source = self.event_sources.sources["typing"]
typing, typing_key = yield typing_source.get_new_events(
user=sync_config.user,
from_key=typing_key,
limit=sync_config.filter_collection.ephemeral_limit(),
room_ids=room_ids,
is_guest=sync_config.is_guest,
)
now_token = now_token.copy_and_replace("typing_key", typing_key)
ephemeral_by_room = {}
for event in typing:
# we want to exclude the room_id from the event, but modifying the
# result returned by the event source is poor form (it might cache
# the object)
room_id = event["room_id"]
event_copy = {k: v for (k, v) in iteritems(event)
if k != "room_id"}
ephemeral_by_room.setdefault(room_id, []).append(event_copy)
receipt_key = since_token.receipt_key if since_token else "0"
receipt_source = self.event_sources.sources["receipt"]
receipts, receipt_key = yield receipt_source.get_new_events(
user=sync_config.user,
from_key=receipt_key,
limit=sync_config.filter_collection.ephemeral_limit(),
room_ids=room_ids,
is_guest=sync_config.is_guest,
)
now_token = now_token.copy_and_replace("receipt_key", receipt_key)
for event in receipts:
room_id = event["room_id"]
# exclude room id, as above
event_copy = {k: v for (k, v) in iteritems(event)
if k != "room_id"}
ephemeral_by_room.setdefault(room_id, []).append(event_copy)
defer.returnValue((now_token, ephemeral_by_room))
@defer.inlineCallbacks
def _load_filtered_recents(self, room_id, sync_config, now_token,
since_token=None, recents=None, newly_joined_room=False):
"""
Returns:
a Deferred TimelineBatch
"""
with Measure(self.clock, "load_filtered_recents"):
timeline_limit = sync_config.filter_collection.timeline_limit()
block_all_timeline = sync_config.filter_collection.blocks_all_room_timeline()
if recents is None or newly_joined_room or timeline_limit < len(recents):
limited = True
else:
limited = False
if recents:
recents = sync_config.filter_collection.filter_room_timeline(recents)
# We check if there are any state events, if there are then we pass
# all current state events to the filter_events function. This is to
# ensure that we always include current state in the timeline
current_state_ids = frozenset()
if any(e.is_state() for e in recents):
current_state_ids = yield self.state.get_current_state_ids(room_id)
current_state_ids = frozenset(itervalues(current_state_ids))
recents = yield filter_events_for_client(
self.store,
sync_config.user.to_string(),
recents,
always_include_ids=current_state_ids,
)
else:
recents = []
if not limited or block_all_timeline:
defer.returnValue(TimelineBatch(
events=recents,
prev_batch=now_token,
limited=False
))
filtering_factor = 2
load_limit = max(timeline_limit * filtering_factor, 10)
max_repeat = 5 # Only try a few times per room, otherwise
room_key = now_token.room_key
end_key = room_key
since_key = None
if since_token and not newly_joined_room:
since_key = since_token.room_key
while limited and len(recents) < timeline_limit and max_repeat:
# If we have a since_key then we are trying to get any events
# that have happened since `since_key` up to `end_key`, so we
# can just use `get_room_events_stream_for_room`.
# Otherwise, we want to return the last N events in the room
# in toplogical ordering.
if since_key:
events, end_key = yield self.store.get_room_events_stream_for_room(
room_id,
limit=load_limit + 1,
from_key=since_key,
to_key=end_key,
)
else:
events, end_key = yield self.store.get_recent_events_for_room(
room_id,
limit=load_limit + 1,
end_token=end_key,
)
loaded_recents = sync_config.filter_collection.filter_room_timeline(
events
)
# We check if there are any state events, if there are then we pass
# all current state events to the filter_events function. This is to
# ensure that we always include current state in the timeline
current_state_ids = frozenset()
if any(e.is_state() for e in loaded_recents):
current_state_ids = yield self.state.get_current_state_ids(room_id)
current_state_ids = frozenset(itervalues(current_state_ids))
loaded_recents = yield filter_events_for_client(
self.store,
sync_config.user.to_string(),
loaded_recents,
always_include_ids=current_state_ids,
)
loaded_recents.extend(recents)
recents = loaded_recents
if len(events) <= load_limit:
limited = False
break
max_repeat -= 1
if len(recents) > timeline_limit:
limited = True
recents = recents[-timeline_limit:]
room_key = recents[0].internal_metadata.before
prev_batch_token = now_token.copy_and_replace(
"room_key", room_key
)
defer.returnValue(TimelineBatch(
events=recents,
prev_batch=prev_batch_token,
limited=limited or newly_joined_room
))
@defer.inlineCallbacks
def get_state_after_event(self, event, state_filter=StateFilter.all()):
"""
Get the room state after the given event
Args:
event(synapse.events.EventBase): event of interest
state_filter (StateFilter): The state filter used to fetch state
from the database.
Returns:
A Deferred map from ((type, state_key)->Event)
"""
state_ids = yield self.store.get_state_ids_for_event(
event.event_id, state_filter=state_filter,
)
if event.is_state():
state_ids = state_ids.copy()
state_ids[(event.type, event.state_key)] = event.event_id
defer.returnValue(state_ids)
@defer.inlineCallbacks
def get_state_at(self, room_id, stream_position, state_filter=StateFilter.all()):
""" Get the room state at a particular stream position
Args:
room_id(str): room for which to get state
stream_position(StreamToken): point at which to get state
state_filter (StateFilter): The state filter used to fetch state
from the database.
Returns:
A Deferred map from ((type, state_key)->Event)
"""
# FIXME this claims to get the state at a stream position, but
# get_recent_events_for_room operates by topo ordering. This therefore
# does not reliably give you the state at the given stream position.
# (https://github.com/matrix-org/synapse/issues/3305)
last_events, _ = yield self.store.get_recent_events_for_room(
room_id, end_token=stream_position.room_key, limit=1,
)
if last_events:
last_event = last_events[-1]
state = yield self.get_state_after_event(
last_event, state_filter=state_filter,
)
else:
# no events in this room - so presumably no state
state = {}
defer.returnValue(state)
@defer.inlineCallbacks
def compute_summary(self, room_id, sync_config, batch, state, now_token):
""" Works out a room summary block for this room, summarising the number
of joined members in the room, and providing the 'hero' members if the
room has no name so clients can consistently name rooms. Also adds
state events to 'state' if needed to describe the heroes.
Args:
room_id(str):
sync_config(synapse.handlers.sync.SyncConfig):
batch(synapse.handlers.sync.TimelineBatch): The timeline batch for
the room that will be sent to the user.
state(dict): dict of (type, state_key) -> Event as returned by
compute_state_delta
now_token(str): Token of the end of the current batch.
Returns:
A deferred dict describing the room summary
"""
# FIXME: we could/should get this from room_stats when matthew/stats lands
# FIXME: this promulgates https://github.com/matrix-org/synapse/issues/3305
last_events, _ = yield self.store.get_recent_event_ids_for_room(
room_id, end_token=now_token.room_key, limit=1,
)
if not last_events:
defer.returnValue(None)
return
last_event = last_events[-1]
state_ids = yield self.store.get_state_ids_for_event(
last_event.event_id,
state_filter=StateFilter.from_types([
(EventTypes.Name, ''),
(EventTypes.CanonicalAlias, ''),
]),
)
# this is heavily cached, thus: fast.
details = yield self.store.get_room_summary(room_id)
name_id = state_ids.get((EventTypes.Name, ''))
canonical_alias_id = state_ids.get((EventTypes.CanonicalAlias, ''))
summary = {}
empty_ms = MemberSummary([], 0)
# TODO: only send these when they change.
summary["m.joined_member_count"] = (
details.get(Membership.JOIN, empty_ms).count
)
summary["m.invited_member_count"] = (
details.get(Membership.INVITE, empty_ms).count
)
# if the room has a name or canonical_alias set, we can skip
# calculating heroes. we assume that if the event has contents, it'll
# be a valid name or canonical_alias - i.e. we're checking that they
# haven't been "deleted" by blatting {} over the top.
if name_id:
name = yield self.store.get_event(name_id, allow_none=True)
if name and name.content:
defer.returnValue(summary)
if canonical_alias_id:
canonical_alias = yield self.store.get_event(
canonical_alias_id, allow_none=True,
)
if canonical_alias and canonical_alias.content:
defer.returnValue(summary)
joined_user_ids = [
r[0] for r in details.get(Membership.JOIN, empty_ms).members
]
invited_user_ids = [
r[0] for r in details.get(Membership.INVITE, empty_ms).members
]
gone_user_ids = (
[r[0] for r in details.get(Membership.LEAVE, empty_ms).members] +
[r[0] for r in details.get(Membership.BAN, empty_ms).members]
)
# FIXME: only build up a member_ids list for our heroes
member_ids = {}
for membership in (
Membership.JOIN,
Membership.INVITE,
Membership.LEAVE,
Membership.BAN
):
for user_id, event_id in details.get(membership, empty_ms).members:
member_ids[user_id] = event_id
# FIXME: order by stream ordering rather than as returned by SQL
me = sync_config.user.to_string()
if (joined_user_ids or invited_user_ids):
summary['m.heroes'] = sorted(
[
user_id
for user_id in (joined_user_ids + invited_user_ids)
if user_id != me
]
)[0:5]
else:
summary['m.heroes'] = sorted(
[
user_id
for user_id in gone_user_ids
if user_id != me
]
)[0:5]
if not sync_config.filter_collection.lazy_load_members():
defer.returnValue(summary)
# ensure we send membership events for heroes if needed
cache_key = (sync_config.user.to_string(), sync_config.device_id)
cache = self.get_lazy_loaded_members_cache(cache_key)
# track which members the client should already know about via LL:
# Ones which are already in state...
existing_members = set(
user_id for (typ, user_id) in state.keys()
if typ == EventTypes.Member
)
# ...or ones which are in the timeline...
for ev in batch.events:
if ev.type == EventTypes.Member:
existing_members.add(ev.state_key)
# ...and then ensure any missing ones get included in state.
missing_hero_event_ids = [
member_ids[hero_id]
for hero_id in summary['m.heroes']
if (
cache.get(hero_id) != member_ids[hero_id] and
hero_id not in existing_members
)
]
missing_hero_state = yield self.store.get_events(missing_hero_event_ids)
missing_hero_state = missing_hero_state.values()
for s in missing_hero_state:
cache.set(s.state_key, s.event_id)
state[(EventTypes.Member, s.state_key)] = s
defer.returnValue(summary)
def get_lazy_loaded_members_cache(self, cache_key):
cache = self.lazy_loaded_members_cache.get(cache_key)
if cache is None:
logger.debug("creating LruCache for %r", cache_key)
cache = LruCache(LAZY_LOADED_MEMBERS_CACHE_MAX_SIZE)
self.lazy_loaded_members_cache[cache_key] = cache
else:
logger.debug("found LruCache for %r", cache_key)
return cache
@defer.inlineCallbacks
def compute_state_delta(self, room_id, batch, sync_config, since_token, now_token,
full_state):
""" Works out the difference in state between the start of the timeline
and the previous sync.
Args:
room_id(str):
batch(synapse.handlers.sync.TimelineBatch): The timeline batch for
the room that will be sent to the user.
sync_config(synapse.handlers.sync.SyncConfig):
since_token(str|None): Token of the end of the previous batch. May
be None.
now_token(str): Token of the end of the current batch.
full_state(bool): Whether to force returning the full state.
Returns:
A deferred dict of (type, state_key) -> Event
"""
# TODO(mjark) Check if the state events were received by the server
# after the previous sync, since we need to include those state
# updates even if they occured logically before the previous event.
# TODO(mjark) Check for new redactions in the state events.
with Measure(self.clock, "compute_state_delta"):
members_to_fetch = None
lazy_load_members = sync_config.filter_collection.lazy_load_members()
include_redundant_members = (
sync_config.filter_collection.include_redundant_members()
)
if lazy_load_members:
# We only request state for the members needed to display the
# timeline:
members_to_fetch = set(
event.sender # FIXME: we also care about invite targets etc.
for event in batch.events
)
if full_state:
# always make sure we LL ourselves so we know we're in the room
# (if we are) to fix https://github.com/vector-im/riot-web/issues/7209
# We only need apply this on full state syncs given we disabled
# LL for incr syncs in #3840.
members_to_fetch.add(sync_config.user.to_string())
state_filter = StateFilter.from_lazy_load_member_list(members_to_fetch)
else:
state_filter = StateFilter.all()
timeline_state = {
(event.type, event.state_key): event.event_id
for event in batch.events if event.is_state()
}
if full_state:
if batch:
current_state_ids = yield self.store.get_state_ids_for_event(
batch.events[-1].event_id, state_filter=state_filter,
)
state_ids = yield self.store.get_state_ids_for_event(
batch.events[0].event_id, state_filter=state_filter,
)
else:
current_state_ids = yield self.get_state_at(
room_id, stream_position=now_token,
state_filter=state_filter,
)
state_ids = current_state_ids
state_ids = _calculate_state(
timeline_contains=timeline_state,
timeline_start=state_ids,
previous={},
current=current_state_ids,
lazy_load_members=lazy_load_members,
)
elif batch.limited:
state_at_timeline_start = yield self.store.get_state_ids_for_event(
batch.events[0].event_id, state_filter=state_filter,
)
# for now, we disable LL for gappy syncs - see
# https://github.com/vector-im/riot-web/issues/7211#issuecomment-419976346
# N.B. this slows down incr syncs as we are now processing way
# more state in the server than if we were LLing.
#
# We still have to filter timeline_start to LL entries (above) in order
# for _calculate_state's LL logic to work, as we have to include LL
# members for timeline senders in case they weren't loaded in the initial
# sync. We do this by (counterintuitively) by filtering timeline_start
# members to just be ones which were timeline senders, which then ensures
# all of the rest get included in the state block (if we need to know
# about them).
state_filter = StateFilter.all()
state_at_previous_sync = yield self.get_state_at(
room_id, stream_position=since_token,
state_filter=state_filter,
)
current_state_ids = yield self.store.get_state_ids_for_event(
batch.events[-1].event_id, state_filter=state_filter,
)
state_ids = _calculate_state(
timeline_contains=timeline_state,
timeline_start=state_at_timeline_start,
previous=state_at_previous_sync,
current=current_state_ids,
# we have to include LL members in case LL initial sync missed them
lazy_load_members=lazy_load_members,
)
else:
state_ids = {}
if lazy_load_members:
if members_to_fetch and batch.events:
# We're returning an incremental sync, with no
# "gap" since the previous sync, so normally there would be
# no state to return.
# But we're lazy-loading, so the client might need some more
# member events to understand the events in this timeline.
# So we fish out all the member events corresponding to the
# timeline here, and then dedupe any redundant ones below.
state_ids = yield self.store.get_state_ids_for_event(
batch.events[0].event_id,
# we only want members!
state_filter=StateFilter.from_types(
(EventTypes.Member, member)
for member in members_to_fetch
),
)
if lazy_load_members and not include_redundant_members:
cache_key = (sync_config.user.to_string(), sync_config.device_id)
cache = self.get_lazy_loaded_members_cache(cache_key)
# if it's a new sync sequence, then assume the client has had
# amnesia and doesn't want any recent lazy-loaded members
# de-duplicated.
if since_token is None:
logger.debug("clearing LruCache for %r", cache_key)
cache.clear()
else:
# only send members which aren't in our LruCache (either
# because they're new to this client or have been pushed out
# of the cache)
logger.debug("filtering state from %r...", state_ids)
state_ids = {
t: event_id
for t, event_id in iteritems(state_ids)
if cache.get(t[1]) != event_id
}
logger.debug("...to %r", state_ids)
# add any member IDs we are about to send into our LruCache
for t, event_id in itertools.chain(
state_ids.items(),
timeline_state.items(),
):
if t[0] == EventTypes.Member:
cache.set(t[1], event_id)
state = {}
if state_ids:
state = yield self.store.get_events(list(state_ids.values()))
defer.returnValue({
(e.type, e.state_key): e
for e in sync_config.filter_collection.filter_room_state(list(state.values()))
})
@defer.inlineCallbacks
def unread_notifs_for_room_id(self, room_id, sync_config):
with Measure(self.clock, "unread_notifs_for_room_id"):
last_unread_event_id = yield self.store.get_last_receipt_event_id_for_user(
user_id=sync_config.user.to_string(),
room_id=room_id,
receipt_type="m.read"
)
notifs = []
if last_unread_event_id:
notifs = yield self.store.get_unread_event_push_actions_by_room_for_user(
room_id, sync_config.user.to_string(), last_unread_event_id
)
defer.returnValue(notifs)
# There is no new information in this period, so your notification
# count is whatever it was last time.
defer.returnValue(None)
@defer.inlineCallbacks
def generate_sync_result(self, sync_config, since_token=None, full_state=False):
"""Generates a sync result.
Args:
sync_config (SyncConfig)
since_token (StreamToken)
full_state (bool)
Returns:
Deferred(SyncResult)
"""
logger.info("Calculating sync response for %r", sync_config.user)
# NB: The now_token gets changed by some of the generate_sync_* methods,
# this is due to some of the underlying streams not supporting the ability
# to query up to a given point.
# Always use the `now_token` in `SyncResultBuilder`
now_token = yield self.event_sources.get_current_token()
user_id = sync_config.user.to_string()
app_service = self.store.get_app_service_by_user_id(user_id)
if app_service:
# We no longer support AS users using /sync directly.
# See https://github.com/matrix-org/matrix-doc/issues/1144
raise NotImplementedError()
else:
joined_room_ids = yield self.get_rooms_for_user_at(
user_id, now_token.room_stream_id,
)
sync_result_builder = SyncResultBuilder(
sync_config, full_state,
since_token=since_token,
now_token=now_token,
joined_room_ids=joined_room_ids,
)
account_data_by_room = yield self._generate_sync_entry_for_account_data(
sync_result_builder
)
res = yield self._generate_sync_entry_for_rooms(
sync_result_builder, account_data_by_room
)
newly_joined_rooms, newly_joined_users, _, _ = res
_, _, newly_left_rooms, newly_left_users = res
block_all_presence_data = (
since_token is None and
sync_config.filter_collection.blocks_all_presence()
)
if self.hs_config.use_presence and not block_all_presence_data:
yield self._generate_sync_entry_for_presence(
sync_result_builder, newly_joined_rooms, newly_joined_users
)
yield self._generate_sync_entry_for_to_device(sync_result_builder)
device_lists = yield self._generate_sync_entry_for_device_list(
sync_result_builder,
newly_joined_rooms=newly_joined_rooms,
newly_joined_users=newly_joined_users,
newly_left_rooms=newly_left_rooms,
newly_left_users=newly_left_users,
)
device_id = sync_config.device_id
one_time_key_counts = {}
if device_id:
one_time_key_counts = yield self.store.count_e2e_one_time_keys(
user_id, device_id
)
yield self._generate_sync_entry_for_groups(sync_result_builder)
defer.returnValue(SyncResult(
presence=sync_result_builder.presence,
account_data=sync_result_builder.account_data,
joined=sync_result_builder.joined,
invited=sync_result_builder.invited,
archived=sync_result_builder.archived,
to_device=sync_result_builder.to_device,
device_lists=device_lists,
groups=sync_result_builder.groups,
device_one_time_keys_count=one_time_key_counts,
next_batch=sync_result_builder.now_token,
))
@measure_func("_generate_sync_entry_for_groups")
@defer.inlineCallbacks
def _generate_sync_entry_for_groups(self, sync_result_builder):
user_id = sync_result_builder.sync_config.user.to_string()
since_token = sync_result_builder.since_token
now_token = sync_result_builder.now_token
if since_token and since_token.groups_key:
results = yield self.store.get_groups_changes_for_user(
user_id, since_token.groups_key, now_token.groups_key,
)
else:
results = yield self.store.get_all_groups_for_user(
user_id, now_token.groups_key,
)
invited = {}
joined = {}
left = {}
for result in results:
membership = result["membership"]
group_id = result["group_id"]
gtype = result["type"]
content = result["content"]
if membership == "join":
if gtype == "membership":
# TODO: Add profile
content.pop("membership", None)
joined[group_id] = content["content"]
else:
joined.setdefault(group_id, {})[gtype] = content
elif membership == "invite":
if gtype == "membership":
content.pop("membership", None)
invited[group_id] = content["content"]
else:
if gtype == "membership":
left[group_id] = content["content"]
sync_result_builder.groups = GroupsSyncResult(
join=joined,
invite=invited,
leave=left,
)
@measure_func("_generate_sync_entry_for_device_list")
@defer.inlineCallbacks
def _generate_sync_entry_for_device_list(self, sync_result_builder,
newly_joined_rooms, newly_joined_users,
newly_left_rooms, newly_left_users):
user_id = sync_result_builder.sync_config.user.to_string()
since_token = sync_result_builder.since_token
if since_token and since_token.device_list_key:
changed = yield self.store.get_user_whose_devices_changed(
since_token.device_list_key
)
# TODO: Be more clever than this, i.e. remove users who we already
# share a room with?
for room_id in newly_joined_rooms:
joined_users = yield self.state.get_current_user_in_room(room_id)
newly_joined_users.update(joined_users)
for room_id in newly_left_rooms:
left_users = yield self.state.get_current_user_in_room(room_id)
newly_left_users.update(left_users)
# TODO: Check that these users are actually new, i.e. either they
# weren't in the previous sync *or* they left and rejoined.
changed.update(newly_joined_users)
if not changed and not newly_left_users:
defer.returnValue(DeviceLists(
changed=[],
left=newly_left_users,
))
users_who_share_room = yield self.store.get_users_who_share_room_with_user(
user_id
)
defer.returnValue(DeviceLists(
changed=users_who_share_room & changed,
left=set(newly_left_users) - users_who_share_room,
))
else:
defer.returnValue(DeviceLists(
changed=[],
left=[],
))
@defer.inlineCallbacks
def _generate_sync_entry_for_to_device(self, sync_result_builder):
"""Generates the portion of the sync response. Populates
`sync_result_builder` with the result.
Args:
sync_result_builder(SyncResultBuilder)
Returns:
Deferred(dict): A dictionary containing the per room account data.
"""
user_id = sync_result_builder.sync_config.user.to_string()
device_id = sync_result_builder.sync_config.device_id
now_token = sync_result_builder.now_token
since_stream_id = 0
if sync_result_builder.since_token is not None:
since_stream_id = int(sync_result_builder.since_token.to_device_key)
if since_stream_id != int(now_token.to_device_key):
# We only delete messages when a new message comes in, but that's
# fine so long as we delete them at some point.
deleted = yield self.store.delete_messages_for_device(
user_id, device_id, since_stream_id
)
logger.debug("Deleted %d to-device messages up to %d",
deleted, since_stream_id)
messages, stream_id = yield self.store.get_new_messages_for_device(
user_id, device_id, since_stream_id, now_token.to_device_key
)
logger.debug(
"Returning %d to-device messages between %d and %d (current token: %d)",
len(messages), since_stream_id, stream_id, now_token.to_device_key
)
sync_result_builder.now_token = now_token.copy_and_replace(
"to_device_key", stream_id
)
sync_result_builder.to_device = messages
else:
sync_result_builder.to_device = []
@defer.inlineCallbacks
def _generate_sync_entry_for_account_data(self, sync_result_builder):
"""Generates the account data portion of the sync response. Populates
`sync_result_builder` with the result.
Args:
sync_result_builder(SyncResultBuilder)
Returns:
Deferred(dict): A dictionary containing the per room account data.
"""
sync_config = sync_result_builder.sync_config
user_id = sync_result_builder.sync_config.user.to_string()
since_token = sync_result_builder.since_token
if since_token and not sync_result_builder.full_state:
account_data, account_data_by_room = (
yield self.store.get_updated_account_data_for_user(
user_id,
since_token.account_data_key,
)
)
push_rules_changed = yield self.store.have_push_rules_changed_for_user(
user_id, int(since_token.push_rules_key)
)
if push_rules_changed:
account_data["m.push_rules"] = yield self.push_rules_for_user(
sync_config.user
)
else:
account_data, account_data_by_room = (
yield self.store.get_account_data_for_user(
sync_config.user.to_string()
)
)
account_data['m.push_rules'] = yield self.push_rules_for_user(
sync_config.user
)
account_data_for_user = sync_config.filter_collection.filter_account_data([
{"type": account_data_type, "content": content}
for account_data_type, content in account_data.items()
])
sync_result_builder.account_data = account_data_for_user
defer.returnValue(account_data_by_room)
@defer.inlineCallbacks
def _generate_sync_entry_for_presence(self, sync_result_builder, newly_joined_rooms,
newly_joined_users):
"""Generates the presence portion of the sync response. Populates the
`sync_result_builder` with the result.
Args:
sync_result_builder(SyncResultBuilder)
newly_joined_rooms(list): List of rooms that the user has joined
since the last sync (or empty if an initial sync)
newly_joined_users(list): List of users that have joined rooms
since the last sync (or empty if an initial sync)
"""
now_token = sync_result_builder.now_token
sync_config = sync_result_builder.sync_config
user = sync_result_builder.sync_config.user
presence_source = self.event_sources.sources["presence"]
since_token = sync_result_builder.since_token
if since_token and not sync_result_builder.full_state:
presence_key = since_token.presence_key
include_offline = True
else:
presence_key = None
include_offline = False
presence, presence_key = yield presence_source.get_new_events(
user=user,
from_key=presence_key,
is_guest=sync_config.is_guest,
include_offline=include_offline,
)
sync_result_builder.now_token = now_token.copy_and_replace(
"presence_key", presence_key
)
extra_users_ids = set(newly_joined_users)
for room_id in newly_joined_rooms:
users = yield self.state.get_current_user_in_room(room_id)
extra_users_ids.update(users)
extra_users_ids.discard(user.to_string())
if extra_users_ids:
states = yield self.presence_handler.get_states(
extra_users_ids,
)
presence.extend(states)
# Deduplicate the presence entries so that there's at most one per user
presence = list({p.user_id: p for p in presence}.values())
presence = sync_config.filter_collection.filter_presence(
presence
)
sync_result_builder.presence = presence
@defer.inlineCallbacks
def _generate_sync_entry_for_rooms(self, sync_result_builder, account_data_by_room):
"""Generates the rooms portion of the sync response. Populates the
`sync_result_builder` with the result.
Args:
sync_result_builder(SyncResultBuilder)
account_data_by_room(dict): Dictionary of per room account data
Returns:
Deferred(tuple): Returns a 4-tuple of
`(newly_joined_rooms, newly_joined_users, newly_left_rooms, newly_left_users)`
"""
user_id = sync_result_builder.sync_config.user.to_string()
block_all_room_ephemeral = (
sync_result_builder.since_token is None and
sync_result_builder.sync_config.filter_collection.blocks_all_room_ephemeral()
)
if block_all_room_ephemeral:
ephemeral_by_room = {}
else:
now_token, ephemeral_by_room = yield self.ephemeral_by_room(
sync_result_builder,
now_token=sync_result_builder.now_token,
since_token=sync_result_builder.since_token,
)
sync_result_builder.now_token = now_token
# We check up front if anything has changed, if it hasn't then there is
# no point in going futher.
since_token = sync_result_builder.since_token
if not sync_result_builder.full_state:
if since_token and not ephemeral_by_room and not account_data_by_room:
have_changed = yield self._have_rooms_changed(sync_result_builder)
if not have_changed:
tags_by_room = yield self.store.get_updated_tags(
user_id,
since_token.account_data_key,
)
if not tags_by_room:
logger.debug("no-oping sync")
defer.returnValue(([], [], [], []))
ignored_account_data = yield self.store.get_global_account_data_by_type_for_user(
"m.ignored_user_list", user_id=user_id,
)
if ignored_account_data:
ignored_users = ignored_account_data.get("ignored_users", {}).keys()
else:
ignored_users = frozenset()
if since_token:
res = yield self._get_rooms_changed(sync_result_builder, ignored_users)
room_entries, invited, newly_joined_rooms, newly_left_rooms = res
tags_by_room = yield self.store.get_updated_tags(
user_id, since_token.account_data_key,
)
else:
res = yield self._get_all_rooms(sync_result_builder, ignored_users)
room_entries, invited, newly_joined_rooms = res
newly_left_rooms = []
tags_by_room = yield self.store.get_tags_for_user(user_id)
def handle_room_entries(room_entry):
return self._generate_room_entry(
sync_result_builder,
ignored_users,
room_entry,
ephemeral=ephemeral_by_room.get(room_entry.room_id, []),
tags=tags_by_room.get(room_entry.room_id),
account_data=account_data_by_room.get(room_entry.room_id, {}),
always_include=sync_result_builder.full_state,
)
yield concurrently_execute(handle_room_entries, room_entries, 10)
sync_result_builder.invited.extend(invited)
# Now we want to get any newly joined users
newly_joined_users = set()
newly_left_users = set()
if since_token:
for joined_sync in sync_result_builder.joined:
it = itertools.chain(
joined_sync.timeline.events, itervalues(joined_sync.state)
)
for event in it:
if event.type == EventTypes.Member:
if event.membership == Membership.JOIN:
newly_joined_users.add(event.state_key)
else:
prev_content = event.unsigned.get("prev_content", {})
prev_membership = prev_content.get("membership", None)
if prev_membership == Membership.JOIN:
newly_left_users.add(event.state_key)
newly_left_users -= newly_joined_users
defer.returnValue((
newly_joined_rooms,
newly_joined_users,
newly_left_rooms,
newly_left_users,
))
@defer.inlineCallbacks
def _have_rooms_changed(self, sync_result_builder):
"""Returns whether there may be any new events that should be sent down
the sync. Returns True if there are.
"""
user_id = sync_result_builder.sync_config.user.to_string()
since_token = sync_result_builder.since_token
now_token = sync_result_builder.now_token
assert since_token
# Get a list of membership change events that have happened.
rooms_changed = yield self.store.get_membership_changes_for_user(
user_id, since_token.room_key, now_token.room_key
)
if rooms_changed:
defer.returnValue(True)
stream_id = RoomStreamToken.parse_stream_token(since_token.room_key).stream
for room_id in sync_result_builder.joined_room_ids:
if self.store.has_room_changed_since(room_id, stream_id):
defer.returnValue(True)
defer.returnValue(False)
@defer.inlineCallbacks
def _get_rooms_changed(self, sync_result_builder, ignored_users):
"""Gets the the changes that have happened since the last sync.
Args:
sync_result_builder(SyncResultBuilder)
ignored_users(set(str)): Set of users ignored by user.
Returns:
Deferred(tuple): Returns a tuple of the form:
`(room_entries, invited_rooms, newly_joined_rooms, newly_left_rooms)`
where:
room_entries is a list [RoomSyncResultBuilder]
invited_rooms is a list [InvitedSyncResult]
newly_joined rooms is a list[str] of room ids
newly_left_rooms is a list[str] of room ids
"""
user_id = sync_result_builder.sync_config.user.to_string()
since_token = sync_result_builder.since_token
now_token = sync_result_builder.now_token
sync_config = sync_result_builder.sync_config
assert since_token
# Get a list of membership change events that have happened.
rooms_changed = yield self.store.get_membership_changes_for_user(
user_id, since_token.room_key, now_token.room_key
)
mem_change_events_by_room_id = {}
for event in rooms_changed:
mem_change_events_by_room_id.setdefault(event.room_id, []).append(event)
newly_joined_rooms = []
newly_left_rooms = []
room_entries = []
invited = []
for room_id, events in iteritems(mem_change_events_by_room_id):
non_joins = [e for e in events if e.membership != Membership.JOIN]
has_join = len(non_joins) != len(events)
# We want to figure out if we joined the room at some point since
# the last sync (even if we have since left). This is to make sure
# we do send down the room, and with full state, where necessary
old_state_ids = None
if room_id in sync_result_builder.joined_room_ids and non_joins:
# Always include if the user (re)joined the room, especially
# important so that device list changes are calculated correctly.
# If there are non join member events, but we are still in the room,
# then the user must have left and joined
newly_joined_rooms.append(room_id)
# User is in the room so we don't need to do the invite/leave checks
continue
if room_id in sync_result_builder.joined_room_ids or has_join:
old_state_ids = yield self.get_state_at(room_id, since_token)
old_mem_ev_id = old_state_ids.get((EventTypes.Member, user_id), None)
old_mem_ev = None
if old_mem_ev_id:
old_mem_ev = yield self.store.get_event(
old_mem_ev_id, allow_none=True
)
if not old_mem_ev or old_mem_ev.membership != Membership.JOIN:
newly_joined_rooms.append(room_id)
# If user is in the room then we don't need to do the invite/leave checks
if room_id in sync_result_builder.joined_room_ids:
continue
if not non_joins:
continue
# Check if we have left the room. This can either be because we were
# joined before *or* that we since joined and then left.
if events[-1].membership != Membership.JOIN:
if has_join:
newly_left_rooms.append(room_id)
else:
if not old_state_ids:
old_state_ids = yield self.get_state_at(room_id, since_token)
old_mem_ev_id = old_state_ids.get(
(EventTypes.Member, user_id),
None,
)
old_mem_ev = None
if old_mem_ev_id:
old_mem_ev = yield self.store.get_event(
old_mem_ev_id, allow_none=True
)
if old_mem_ev and old_mem_ev.membership == Membership.JOIN:
newly_left_rooms.append(room_id)
# Only bother if we're still currently invited
should_invite = non_joins[-1].membership == Membership.INVITE
if should_invite:
if event.sender not in ignored_users:
room_sync = InvitedSyncResult(room_id, invite=non_joins[-1])
if room_sync:
invited.append(room_sync)
# Always include leave/ban events. Just take the last one.
# TODO: How do we handle ban -> leave in same batch?
leave_events = [
e for e in non_joins
if e.membership in (Membership.LEAVE, Membership.BAN)
]
if leave_events:
leave_event = leave_events[-1]
leave_stream_token = yield self.store.get_stream_token_for_event(
leave_event.event_id
)
leave_token = since_token.copy_and_replace(
"room_key", leave_stream_token
)
if since_token and since_token.is_after(leave_token):
continue
room_entries.append(RoomSyncResultBuilder(
room_id=room_id,
rtype="archived",
events=None,
newly_joined=room_id in newly_joined_rooms,
full_state=False,
since_token=since_token,
upto_token=leave_token,
))
timeline_limit = sync_config.filter_collection.timeline_limit()
# Get all events for rooms we're currently joined to.
room_to_events = yield self.store.get_room_events_stream_for_rooms(
room_ids=sync_result_builder.joined_room_ids,
from_key=since_token.room_key,
to_key=now_token.room_key,
limit=timeline_limit + 1,
)
# We loop through all room ids, even if there are no new events, in case
# there are non room events taht we need to notify about.
for room_id in sync_result_builder.joined_room_ids:
room_entry = room_to_events.get(room_id, None)
if room_entry:
events, start_key = room_entry
prev_batch_token = now_token.copy_and_replace("room_key", start_key)
room_entries.append(RoomSyncResultBuilder(
room_id=room_id,
rtype="joined",
events=events,
newly_joined=room_id in newly_joined_rooms,
full_state=False,
since_token=None if room_id in newly_joined_rooms else since_token,
upto_token=prev_batch_token,
))
else:
room_entries.append(RoomSyncResultBuilder(
room_id=room_id,
rtype="joined",
events=[],
newly_joined=room_id in newly_joined_rooms,
full_state=False,
since_token=since_token,
upto_token=since_token,
))
defer.returnValue((room_entries, invited, newly_joined_rooms, newly_left_rooms))
@defer.inlineCallbacks
def _get_all_rooms(self, sync_result_builder, ignored_users):
"""Returns entries for all rooms for the user.
Args:
sync_result_builder(SyncResultBuilder)
ignored_users(set(str)): Set of users ignored by user.
Returns:
Deferred(tuple): Returns a tuple of the form:
`([RoomSyncResultBuilder], [InvitedSyncResult], [])`
"""
user_id = sync_result_builder.sync_config.user.to_string()
since_token = sync_result_builder.since_token
now_token = sync_result_builder.now_token
sync_config = sync_result_builder.sync_config
membership_list = (
Membership.INVITE, Membership.JOIN, Membership.LEAVE, Membership.BAN
)
room_list = yield self.store.get_rooms_for_user_where_membership_is(
user_id=user_id,
membership_list=membership_list
)
room_entries = []
invited = []
for event in room_list:
if event.membership == Membership.JOIN:
room_entries.append(RoomSyncResultBuilder(
room_id=event.room_id,
rtype="joined",
events=None,
newly_joined=False,
full_state=True,
since_token=since_token,
upto_token=now_token,
))
elif event.membership == Membership.INVITE:
if event.sender in ignored_users:
continue
invite = yield self.store.get_event(event.event_id)
invited.append(InvitedSyncResult(
room_id=event.room_id,
invite=invite,
))
elif event.membership in (Membership.LEAVE, Membership.BAN):
# Always send down rooms we were banned or kicked from.
if not sync_config.filter_collection.include_leave:
if event.membership == Membership.LEAVE:
if user_id == event.sender:
continue
leave_token = now_token.copy_and_replace(
"room_key", "s%d" % (event.stream_ordering,)
)
room_entries.append(RoomSyncResultBuilder(
room_id=event.room_id,
rtype="archived",
events=None,
newly_joined=False,
full_state=True,
since_token=since_token,
upto_token=leave_token,
))
defer.returnValue((room_entries, invited, []))
@defer.inlineCallbacks
def _generate_room_entry(self, sync_result_builder, ignored_users,
room_builder, ephemeral, tags, account_data,
always_include=False):
"""Populates the `joined` and `archived` section of `sync_result_builder`
based on the `room_builder`.
Args:
sync_result_builder(SyncResultBuilder)
ignored_users(set(str)): Set of users ignored by user.
room_builder(RoomSyncResultBuilder)
ephemeral(list): List of new ephemeral events for room
tags(list): List of *all* tags for room, or None if there has been
no change.
account_data(list): List of new account data for room
always_include(bool): Always include this room in the sync response,
even if empty.
"""
newly_joined = room_builder.newly_joined
full_state = (
room_builder.full_state
or newly_joined
or sync_result_builder.full_state
)
events = room_builder.events
# We want to shortcut out as early as possible.
if not (always_include or account_data or ephemeral or full_state):
if events == [] and tags is None:
return
now_token = sync_result_builder.now_token
sync_config = sync_result_builder.sync_config
room_id = room_builder.room_id
since_token = room_builder.since_token
upto_token = room_builder.upto_token
batch = yield self._load_filtered_recents(
room_id, sync_config,
now_token=upto_token,
since_token=since_token,
recents=events,
newly_joined_room=newly_joined,
)
# When we join the room (or the client requests full_state), we should
# send down any existing tags. Usually the user won't have tags in a
# newly joined room, unless either a) they've joined before or b) the
# tag was added by synapse e.g. for server notice rooms.
if full_state:
user_id = sync_result_builder.sync_config.user.to_string()
tags = yield self.store.get_tags_for_room(user_id, room_id)
# If there aren't any tags, don't send the empty tags list down
# sync
if not tags:
tags = None
account_data_events = []
if tags is not None:
account_data_events.append({
"type": "m.tag",
"content": {"tags": tags},
})
for account_data_type, content in account_data.items():
account_data_events.append({
"type": account_data_type,
"content": content,
})
account_data_events = sync_config.filter_collection.filter_room_account_data(
account_data_events
)
ephemeral = sync_config.filter_collection.filter_room_ephemeral(ephemeral)
if not (always_include
or batch
or account_data_events
or ephemeral
or full_state):
return
state = yield self.compute_state_delta(
room_id, batch, sync_config, since_token, now_token,
full_state=full_state
)
summary = {}
# we include a summary in room responses when we're lazy loading
# members (as the client otherwise doesn't have enough info to form
# the name itself).
if (
sync_config.filter_collection.lazy_load_members() and
(
# we recalulate the summary:
# if there are membership changes in the timeline, or
# if membership has changed during a gappy sync, or
# if this is an initial sync.
any(ev.type == EventTypes.Member for ev in batch.events) or
(
# XXX: this may include false positives in the form of LL
# members which have snuck into state
batch.limited and
any(t == EventTypes.Member for (t, k) in state)
) or
since_token is None
)
):
summary = yield self.compute_summary(
room_id, sync_config, batch, state, now_token
)
if room_builder.rtype == "joined":
unread_notifications = {}
room_sync = JoinedSyncResult(
room_id=room_id,
timeline=batch,
state=state,
ephemeral=ephemeral,
account_data=account_data_events,
unread_notifications=unread_notifications,
summary=summary,
)
if room_sync or always_include:
notifs = yield self.unread_notifs_for_room_id(
room_id, sync_config
)
if notifs is not None:
unread_notifications["notification_count"] = notifs["notify_count"]
unread_notifications["highlight_count"] = notifs["highlight_count"]
sync_result_builder.joined.append(room_sync)
if batch.limited and since_token:
user_id = sync_result_builder.sync_config.user.to_string()
logger.info(
"Incremental gappy sync of %s for user %s with %d state events" % (
room_id,
user_id,
len(state),
)
)
elif room_builder.rtype == "archived":
room_sync = ArchivedSyncResult(
room_id=room_id,
timeline=batch,
state=state,
account_data=account_data_events,
)
if room_sync or always_include:
sync_result_builder.archived.append(room_sync)
else:
raise Exception("Unrecognized rtype: %r", room_builder.rtype)
@defer.inlineCallbacks
def get_rooms_for_user_at(self, user_id, stream_ordering):
"""Get set of joined rooms for a user at the given stream ordering.
The stream ordering *must* be recent, otherwise this may throw an
exception if older than a month. (This function is called with the
current token, which should be perfectly fine).
Args:
user_id (str)
stream_ordering (int)
ReturnValue:
Deferred[frozenset[str]]: Set of room_ids the user is in at given
stream_ordering.
"""
joined_rooms = yield self.store.get_rooms_for_user_with_stream_ordering(
user_id,
)
joined_room_ids = set()
# We need to check that the stream ordering of the join for each room
# is before the stream_ordering asked for. This might not be the case
# if the user joins a room between us getting the current token and
# calling `get_rooms_for_user_with_stream_ordering`.
# If the membership's stream ordering is after the given stream
# ordering, we need to go and work out if the user was in the room
# before.
for room_id, membership_stream_ordering in joined_rooms:
if membership_stream_ordering <= stream_ordering:
joined_room_ids.add(room_id)
continue
logger.info("User joined room after current token: %s", room_id)
extrems = yield self.store.get_forward_extremeties_for_room(
room_id, stream_ordering,
)
users_in_room = yield self.state.get_current_user_in_room(
room_id, extrems,
)
if user_id in users_in_room:
joined_room_ids.add(room_id)
joined_room_ids = frozenset(joined_room_ids)
defer.returnValue(joined_room_ids)
def _action_has_highlight(actions):
for action in actions:
try:
if action.get("set_tweak", None) == "highlight":
return action.get("value", True)
except AttributeError:
pass
return False
def _calculate_state(
timeline_contains, timeline_start, previous, current, lazy_load_members,
):
"""Works out what state to include in a sync response.
Args:
timeline_contains (dict): state in the timeline
timeline_start (dict): state at the start of the timeline
previous (dict): state at the end of the previous sync (or empty dict
if this is an initial sync)
current (dict): state at the end of the timeline
lazy_load_members (bool): whether to return members from timeline_start
or not. assumes that timeline_start has already been filtered to
include only the members the client needs to know about.
Returns:
dict
"""
event_id_to_key = {
e: key
for key, e in itertools.chain(
iteritems(timeline_contains),
iteritems(previous),
iteritems(timeline_start),
iteritems(current),
)
}
c_ids = set(e for e in itervalues(current))
ts_ids = set(e for e in itervalues(timeline_start))
p_ids = set(e for e in itervalues(previous))
tc_ids = set(e for e in itervalues(timeline_contains))
# If we are lazyloading room members, we explicitly add the membership events
# for the senders in the timeline into the state block returned by /sync,
# as we may not have sent them to the client before. We find these membership
# events by filtering them out of timeline_start, which has already been filtered
# to only include membership events for the senders in the timeline.
# In practice, we can do this by removing them from the p_ids list,
# which is the list of relevant state we know we have already sent to the client.
# see https://github.com/matrix-org/synapse/pull/2970
# /files/efcdacad7d1b7f52f879179701c7e0d9b763511f#r204732809
if lazy_load_members:
p_ids.difference_update(
e for t, e in iteritems(timeline_start)
if t[0] == EventTypes.Member
)
state_ids = ((c_ids | ts_ids) - p_ids) - tc_ids
return {
event_id_to_key[e]: e for e in state_ids
}
class SyncResultBuilder(object):
"Used to help build up a new SyncResult for a user"
def __init__(self, sync_config, full_state, since_token, now_token,
joined_room_ids):
"""
Args:
sync_config(SyncConfig)
full_state(bool): The full_state flag as specified by user
since_token(StreamToken): The token supplied by user, or None.
now_token(StreamToken): The token to sync up to.
"""
self.sync_config = sync_config
self.full_state = full_state
self.since_token = since_token
self.now_token = now_token
self.joined_room_ids = joined_room_ids
self.presence = []
self.account_data = []
self.joined = []
self.invited = []
self.archived = []
self.device = []
self.groups = None
self.to_device = []
class RoomSyncResultBuilder(object):
"""Stores information needed to create either a `JoinedSyncResult` or
`ArchivedSyncResult`.
"""
def __init__(self, room_id, rtype, events, newly_joined, full_state,
since_token, upto_token):
"""
Args:
room_id(str)
rtype(str): One of `"joined"` or `"archived"`
events(list): List of events to include in the room, (more events
may be added when generating result).
newly_joined(bool): If the user has newly joined the room
full_state(bool): Whether the full state should be sent in result
since_token(StreamToken): Earliest point to return events from, or None
upto_token(StreamToken): Latest point to return events from.
"""
self.room_id = room_id
self.rtype = rtype
self.events = events
self.newly_joined = newly_joined
self.full_state = full_state
self.since_token = since_token
self.upto_token = upto_token
| 39.440291 | 90 | 0.596746 |
import collections
import itertools
import logging
from six import iteritems, itervalues
from prometheus_client import Counter
from twisted.internet import defer
from synapse.api.constants import EventTypes, Membership
from synapse.push.clientformat import format_push_rules_for_user
from synapse.storage.roommember import MemberSummary
from synapse.storage.state import StateFilter
from synapse.types import RoomStreamToken
from synapse.util.async_helpers import concurrently_execute
from synapse.util.caches.expiringcache import ExpiringCache
from synapse.util.caches.lrucache import LruCache
from synapse.util.caches.response_cache import ResponseCache
from synapse.util.logcontext import LoggingContext
from synapse.util.metrics import Measure, measure_func
from synapse.visibility import filter_events_for_client
logger = logging.getLogger(__name__)
non_empty_sync_counter = Counter(
"synapse_handlers_sync_nonempty_total",
"Count of non empty sync responses. type is initial_sync/full_state_sync"
"/incremental_sync. lazy_loaded indicates if lazy loaded members were "
"enabled for that request.",
["type", "lazy_loaded"],
)
LAZY_LOADED_MEMBERS_CACHE_MAX_AGE = 30 * 60 * 1000
LAZY_LOADED_MEMBERS_CACHE_MAX_SIZE = 100
SyncConfig = collections.namedtuple("SyncConfig", [
"user",
"filter_collection",
"is_guest",
"request_key",
"device_id",
])
class TimelineBatch(collections.namedtuple("TimelineBatch", [
"prev_batch",
"events",
"limited",
])):
__slots__ = []
def __nonzero__(self):
return bool(self.events)
__bool__ = __nonzero__
class JoinedSyncResult(collections.namedtuple("JoinedSyncResult", [
"room_id",
"timeline",
"state",
"ephemeral",
"account_data",
"unread_notifications",
"summary",
])):
__slots__ = []
def __nonzero__(self):
return bool(
self.timeline
or self.state
or self.ephemeral
or self.account_data
# else in the result, we don't need to send it.
)
__bool__ = __nonzero__
class ArchivedSyncResult(collections.namedtuple("ArchivedSyncResult", [
"room_id",
"timeline",
"state",
"account_data",
])):
__slots__ = []
def __nonzero__(self):
return bool(
self.timeline
or self.state
or self.account_data
)
__bool__ = __nonzero__
class InvitedSyncResult(collections.namedtuple("InvitedSyncResult", [
"room_id",
"invite",
])):
__slots__ = []
def __nonzero__(self):
return True
__bool__ = __nonzero__
class GroupsSyncResult(collections.namedtuple("GroupsSyncResult", [
"join",
"invite",
"leave",
])):
__slots__ = []
def __nonzero__(self):
return bool(self.join or self.invite or self.leave)
__bool__ = __nonzero__
class DeviceLists(collections.namedtuple("DeviceLists", [
"changed",
"left",
])):
__slots__ = []
def __nonzero__(self):
return bool(self.changed or self.left)
__bool__ = __nonzero__
class SyncResult(collections.namedtuple("SyncResult", [
"next_batch",
"presence",
"account_data",
"joined",
"invited",
"archived",
"to_device",
"device_lists",
"device_one_time_keys_count",
"groups",
])):
__slots__ = []
def __nonzero__(self):
return bool(
self.presence or
self.joined or
self.invited or
self.archived or
self.account_data or
self.to_device or
self.device_lists or
self.groups
)
__bool__ = __nonzero__
class SyncHandler(object):
def __init__(self, hs):
self.hs_config = hs.config
self.store = hs.get_datastore()
self.notifier = hs.get_notifier()
self.presence_handler = hs.get_presence_handler()
self.event_sources = hs.get_event_sources()
self.clock = hs.get_clock()
self.response_cache = ResponseCache(hs, "sync")
self.state = hs.get_state_handler()
self.auth = hs.get_auth()
self.lazy_loaded_members_cache = ExpiringCache(
"lazy_loaded_members_cache", self.clock,
max_len=0, expiry_ms=LAZY_LOADED_MEMBERS_CACHE_MAX_AGE,
)
@defer.inlineCallbacks
def wait_for_sync_for_user(self, sync_config, since_token=None, timeout=0,
full_state=False):
user_id = sync_config.user.to_string()
yield self.auth.check_auth_blocking(user_id)
res = yield self.response_cache.wrap(
sync_config.request_key,
self._wait_for_sync_for_user,
sync_config, since_token, timeout, full_state,
)
defer.returnValue(res)
@defer.inlineCallbacks
def _wait_for_sync_for_user(self, sync_config, since_token, timeout,
full_state):
if since_token is None:
sync_type = "initial_sync"
elif full_state:
sync_type = "full_state_sync"
else:
sync_type = "incremental_sync"
context = LoggingContext.current_context()
if context:
context.tag = sync_type
if timeout == 0 or since_token is None or full_state:
# notifier.wait_for_events.
result = yield self.current_sync_for_user(
sync_config, since_token, full_state=full_state,
)
else:
def current_sync_callback(before_token, after_token):
return self.current_sync_for_user(sync_config, since_token)
result = yield self.notifier.wait_for_events(
sync_config.user.to_string(), timeout, current_sync_callback,
from_token=since_token,
)
if result:
if sync_config.filter_collection.lazy_load_members():
lazy_loaded = "true"
else:
lazy_loaded = "false"
non_empty_sync_counter.labels(sync_type, lazy_loaded).inc()
defer.returnValue(result)
def current_sync_for_user(self, sync_config, since_token=None,
full_state=False):
return self.generate_sync_result(sync_config, since_token, full_state)
@defer.inlineCallbacks
def push_rules_for_user(self, user):
user_id = user.to_string()
rules = yield self.store.get_push_rules_for_user(user_id)
rules = format_push_rules_for_user(user, rules)
defer.returnValue(rules)
@defer.inlineCallbacks
def ephemeral_by_room(self, sync_result_builder, now_token, since_token=None):
sync_config = sync_result_builder.sync_config
with Measure(self.clock, "ephemeral_by_room"):
typing_key = since_token.typing_key if since_token else "0"
room_ids = sync_result_builder.joined_room_ids
typing_source = self.event_sources.sources["typing"]
typing, typing_key = yield typing_source.get_new_events(
user=sync_config.user,
from_key=typing_key,
limit=sync_config.filter_collection.ephemeral_limit(),
room_ids=room_ids,
is_guest=sync_config.is_guest,
)
now_token = now_token.copy_and_replace("typing_key", typing_key)
ephemeral_by_room = {}
for event in typing:
# we want to exclude the room_id from the event, but modifying the
# result returned by the event source is poor form (it might cache
# the object)
room_id = event["room_id"]
event_copy = {k: v for (k, v) in iteritems(event)
if k != "room_id"}
ephemeral_by_room.setdefault(room_id, []).append(event_copy)
receipt_key = since_token.receipt_key if since_token else "0"
receipt_source = self.event_sources.sources["receipt"]
receipts, receipt_key = yield receipt_source.get_new_events(
user=sync_config.user,
from_key=receipt_key,
limit=sync_config.filter_collection.ephemeral_limit(),
room_ids=room_ids,
is_guest=sync_config.is_guest,
)
now_token = now_token.copy_and_replace("receipt_key", receipt_key)
for event in receipts:
room_id = event["room_id"]
# exclude room id, as above
event_copy = {k: v for (k, v) in iteritems(event)
if k != "room_id"}
ephemeral_by_room.setdefault(room_id, []).append(event_copy)
defer.returnValue((now_token, ephemeral_by_room))
@defer.inlineCallbacks
def _load_filtered_recents(self, room_id, sync_config, now_token,
since_token=None, recents=None, newly_joined_room=False):
with Measure(self.clock, "load_filtered_recents"):
timeline_limit = sync_config.filter_collection.timeline_limit()
block_all_timeline = sync_config.filter_collection.blocks_all_room_timeline()
if recents is None or newly_joined_room or timeline_limit < len(recents):
limited = True
else:
limited = False
if recents:
recents = sync_config.filter_collection.filter_room_timeline(recents)
# We check if there are any state events, if there are then we pass
# all current state events to the filter_events function. This is to
# ensure that we always include current state in the timeline
current_state_ids = frozenset()
if any(e.is_state() for e in recents):
current_state_ids = yield self.state.get_current_state_ids(room_id)
current_state_ids = frozenset(itervalues(current_state_ids))
recents = yield filter_events_for_client(
self.store,
sync_config.user.to_string(),
recents,
always_include_ids=current_state_ids,
)
else:
recents = []
if not limited or block_all_timeline:
defer.returnValue(TimelineBatch(
events=recents,
prev_batch=now_token,
limited=False
))
filtering_factor = 2
load_limit = max(timeline_limit * filtering_factor, 10)
max_repeat = 5 # Only try a few times per room, otherwise
room_key = now_token.room_key
end_key = room_key
since_key = None
if since_token and not newly_joined_room:
since_key = since_token.room_key
while limited and len(recents) < timeline_limit and max_repeat:
# If we have a since_key then we are trying to get any events
# that have happened since `since_key` up to `end_key`, so we
# can just use `get_room_events_stream_for_room`.
# Otherwise, we want to return the last N events in the room
# in toplogical ordering.
if since_key:
events, end_key = yield self.store.get_room_events_stream_for_room(
room_id,
limit=load_limit + 1,
from_key=since_key,
to_key=end_key,
)
else:
events, end_key = yield self.store.get_recent_events_for_room(
room_id,
limit=load_limit + 1,
end_token=end_key,
)
loaded_recents = sync_config.filter_collection.filter_room_timeline(
events
)
# We check if there are any state events, if there are then we pass
# all current state events to the filter_events function. This is to
# ensure that we always include current state in the timeline
current_state_ids = frozenset()
if any(e.is_state() for e in loaded_recents):
current_state_ids = yield self.state.get_current_state_ids(room_id)
current_state_ids = frozenset(itervalues(current_state_ids))
loaded_recents = yield filter_events_for_client(
self.store,
sync_config.user.to_string(),
loaded_recents,
always_include_ids=current_state_ids,
)
loaded_recents.extend(recents)
recents = loaded_recents
if len(events) <= load_limit:
limited = False
break
max_repeat -= 1
if len(recents) > timeline_limit:
limited = True
recents = recents[-timeline_limit:]
room_key = recents[0].internal_metadata.before
prev_batch_token = now_token.copy_and_replace(
"room_key", room_key
)
defer.returnValue(TimelineBatch(
events=recents,
prev_batch=prev_batch_token,
limited=limited or newly_joined_room
))
@defer.inlineCallbacks
def get_state_after_event(self, event, state_filter=StateFilter.all()):
state_ids = yield self.store.get_state_ids_for_event(
event.event_id, state_filter=state_filter,
)
if event.is_state():
state_ids = state_ids.copy()
state_ids[(event.type, event.state_key)] = event.event_id
defer.returnValue(state_ids)
@defer.inlineCallbacks
def get_state_at(self, room_id, stream_position, state_filter=StateFilter.all()):
# FIXME this claims to get the state at a stream position, but
# get_recent_events_for_room operates by topo ordering. This therefore
# does not reliably give you the state at the given stream position.
# (https://github.com/matrix-org/synapse/issues/3305)
last_events, _ = yield self.store.get_recent_events_for_room(
room_id, end_token=stream_position.room_key, limit=1,
)
if last_events:
last_event = last_events[-1]
state = yield self.get_state_after_event(
last_event, state_filter=state_filter,
)
else:
# no events in this room - so presumably no state
state = {}
defer.returnValue(state)
@defer.inlineCallbacks
def compute_summary(self, room_id, sync_config, batch, state, now_token):
# FIXME: we could/should get this from room_stats when matthew/stats lands
# FIXME: this promulgates https://github.com/matrix-org/synapse/issues/3305
last_events, _ = yield self.store.get_recent_event_ids_for_room(
room_id, end_token=now_token.room_key, limit=1,
)
if not last_events:
defer.returnValue(None)
return
last_event = last_events[-1]
state_ids = yield self.store.get_state_ids_for_event(
last_event.event_id,
state_filter=StateFilter.from_types([
(EventTypes.Name, ''),
(EventTypes.CanonicalAlias, ''),
]),
)
# this is heavily cached, thus: fast.
details = yield self.store.get_room_summary(room_id)
name_id = state_ids.get((EventTypes.Name, ''))
canonical_alias_id = state_ids.get((EventTypes.CanonicalAlias, ''))
summary = {}
empty_ms = MemberSummary([], 0)
# TODO: only send these when they change.
summary["m.joined_member_count"] = (
details.get(Membership.JOIN, empty_ms).count
)
summary["m.invited_member_count"] = (
details.get(Membership.INVITE, empty_ms).count
)
# if the room has a name or canonical_alias set, we can skip
# calculating heroes. we assume that if the event has contents, it'll
# haven't been "deleted" by blatting {} over the top.
if name_id:
name = yield self.store.get_event(name_id, allow_none=True)
if name and name.content:
defer.returnValue(summary)
if canonical_alias_id:
canonical_alias = yield self.store.get_event(
canonical_alias_id, allow_none=True,
)
if canonical_alias and canonical_alias.content:
defer.returnValue(summary)
joined_user_ids = [
r[0] for r in details.get(Membership.JOIN, empty_ms).members
]
invited_user_ids = [
r[0] for r in details.get(Membership.INVITE, empty_ms).members
]
gone_user_ids = (
[r[0] for r in details.get(Membership.LEAVE, empty_ms).members] +
[r[0] for r in details.get(Membership.BAN, empty_ms).members]
)
member_ids = {}
for membership in (
Membership.JOIN,
Membership.INVITE,
Membership.LEAVE,
Membership.BAN
):
for user_id, event_id in details.get(membership, empty_ms).members:
member_ids[user_id] = event_id
me = sync_config.user.to_string()
if (joined_user_ids or invited_user_ids):
summary['m.heroes'] = sorted(
[
user_id
for user_id in (joined_user_ids + invited_user_ids)
if user_id != me
]
)[0:5]
else:
summary['m.heroes'] = sorted(
[
user_id
for user_id in gone_user_ids
if user_id != me
]
)[0:5]
if not sync_config.filter_collection.lazy_load_members():
defer.returnValue(summary)
cache_key = (sync_config.user.to_string(), sync_config.device_id)
cache = self.get_lazy_loaded_members_cache(cache_key)
existing_members = set(
user_id for (typ, user_id) in state.keys()
if typ == EventTypes.Member
)
for ev in batch.events:
if ev.type == EventTypes.Member:
existing_members.add(ev.state_key)
missing_hero_event_ids = [
member_ids[hero_id]
for hero_id in summary['m.heroes']
if (
cache.get(hero_id) != member_ids[hero_id] and
hero_id not in existing_members
)
]
missing_hero_state = yield self.store.get_events(missing_hero_event_ids)
missing_hero_state = missing_hero_state.values()
for s in missing_hero_state:
cache.set(s.state_key, s.event_id)
state[(EventTypes.Member, s.state_key)] = s
defer.returnValue(summary)
def get_lazy_loaded_members_cache(self, cache_key):
cache = self.lazy_loaded_members_cache.get(cache_key)
if cache is None:
logger.debug("creating LruCache for %r", cache_key)
cache = LruCache(LAZY_LOADED_MEMBERS_CACHE_MAX_SIZE)
self.lazy_loaded_members_cache[cache_key] = cache
else:
logger.debug("found LruCache for %r", cache_key)
return cache
@defer.inlineCallbacks
def compute_state_delta(self, room_id, batch, sync_config, since_token, now_token,
full_state):
with Measure(self.clock, "compute_state_delta"):
members_to_fetch = None
lazy_load_members = sync_config.filter_collection.lazy_load_members()
include_redundant_members = (
sync_config.filter_collection.include_redundant_members()
)
if lazy_load_members:
members_to_fetch = set(
event.sender
for event in batch.events
)
if full_state:
# (if we are) to fix https://github.com/vector-im/riot-web/issues/7209
# We only need apply this on full state syncs given we disabled
# LL for incr syncs in #3840.
members_to_fetch.add(sync_config.user.to_string())
state_filter = StateFilter.from_lazy_load_member_list(members_to_fetch)
else:
state_filter = StateFilter.all()
timeline_state = {
(event.type, event.state_key): event.event_id
for event in batch.events if event.is_state()
}
if full_state:
if batch:
current_state_ids = yield self.store.get_state_ids_for_event(
batch.events[-1].event_id, state_filter=state_filter,
)
state_ids = yield self.store.get_state_ids_for_event(
batch.events[0].event_id, state_filter=state_filter,
)
else:
current_state_ids = yield self.get_state_at(
room_id, stream_position=now_token,
state_filter=state_filter,
)
state_ids = current_state_ids
state_ids = _calculate_state(
timeline_contains=timeline_state,
timeline_start=state_ids,
previous={},
current=current_state_ids,
lazy_load_members=lazy_load_members,
)
elif batch.limited:
state_at_timeline_start = yield self.store.get_state_ids_for_event(
batch.events[0].event_id, state_filter=state_filter,
)
# for now, we disable LL for gappy syncs - see
# https://github.com/vector-im/riot-web/issues/7211#issuecomment-419976346
# N.B. this slows down incr syncs as we are now processing way
# more state in the server than if we were LLing.
#
# We still have to filter timeline_start to LL entries (above) in order
# for _calculate_state's LL logic to work, as we have to include LL
# sync. We do this by (counterintuitively) by filtering timeline_start
# members to just be ones which were timeline senders, which then ensures
# all of the rest get included in the state block (if we need to know
# about them).
state_filter = StateFilter.all()
state_at_previous_sync = yield self.get_state_at(
room_id, stream_position=since_token,
state_filter=state_filter,
)
current_state_ids = yield self.store.get_state_ids_for_event(
batch.events[-1].event_id, state_filter=state_filter,
)
state_ids = _calculate_state(
timeline_contains=timeline_state,
timeline_start=state_at_timeline_start,
previous=state_at_previous_sync,
current=current_state_ids,
# we have to include LL members in case LL initial sync missed them
lazy_load_members=lazy_load_members,
)
else:
state_ids = {}
if lazy_load_members:
if members_to_fetch and batch.events:
# We're returning an incremental sync, with no
# member events to understand the events in this timeline.
# So we fish out all the member events corresponding to the
# timeline here, and then dedupe any redundant ones below.
state_ids = yield self.store.get_state_ids_for_event(
batch.events[0].event_id,
# we only want members!
state_filter=StateFilter.from_types(
(EventTypes.Member, member)
for member in members_to_fetch
),
)
if lazy_load_members and not include_redundant_members:
cache_key = (sync_config.user.to_string(), sync_config.device_id)
cache = self.get_lazy_loaded_members_cache(cache_key)
# if it's a new sync sequence, then assume the client has had
# de-duplicated.
if since_token is None:
logger.debug("clearing LruCache for %r", cache_key)
cache.clear()
else:
# only send members which aren't in our LruCache (either
# of the cache)
logger.debug("filtering state from %r...", state_ids)
state_ids = {
t: event_id
for t, event_id in iteritems(state_ids)
if cache.get(t[1]) != event_id
}
logger.debug("...to %r", state_ids)
# add any member IDs we are about to send into our LruCache
for t, event_id in itertools.chain(
state_ids.items(),
timeline_state.items(),
):
if t[0] == EventTypes.Member:
cache.set(t[1], event_id)
state = {}
if state_ids:
state = yield self.store.get_events(list(state_ids.values()))
defer.returnValue({
(e.type, e.state_key): e
for e in sync_config.filter_collection.filter_room_state(list(state.values()))
})
@defer.inlineCallbacks
def unread_notifs_for_room_id(self, room_id, sync_config):
with Measure(self.clock, "unread_notifs_for_room_id"):
last_unread_event_id = yield self.store.get_last_receipt_event_id_for_user(
user_id=sync_config.user.to_string(),
room_id=room_id,
receipt_type="m.read"
)
notifs = []
if last_unread_event_id:
notifs = yield self.store.get_unread_event_push_actions_by_room_for_user(
room_id, sync_config.user.to_string(), last_unread_event_id
)
defer.returnValue(notifs)
# There is no new information in this period, so your notification
# count is whatever it was last time.
defer.returnValue(None)
@defer.inlineCallbacks
def generate_sync_result(self, sync_config, since_token=None, full_state=False):
logger.info("Calculating sync response for %r", sync_config.user)
# NB: The now_token gets changed by some of the generate_sync_* methods,
# this is due to some of the underlying streams not supporting the ability
# to query up to a given point.
# Always use the `now_token` in `SyncResultBuilder`
now_token = yield self.event_sources.get_current_token()
user_id = sync_config.user.to_string()
app_service = self.store.get_app_service_by_user_id(user_id)
if app_service:
# We no longer support AS users using /sync directly.
# See https://github.com/matrix-org/matrix-doc/issues/1144
raise NotImplementedError()
else:
joined_room_ids = yield self.get_rooms_for_user_at(
user_id, now_token.room_stream_id,
)
sync_result_builder = SyncResultBuilder(
sync_config, full_state,
since_token=since_token,
now_token=now_token,
joined_room_ids=joined_room_ids,
)
account_data_by_room = yield self._generate_sync_entry_for_account_data(
sync_result_builder
)
res = yield self._generate_sync_entry_for_rooms(
sync_result_builder, account_data_by_room
)
newly_joined_rooms, newly_joined_users, _, _ = res
_, _, newly_left_rooms, newly_left_users = res
block_all_presence_data = (
since_token is None and
sync_config.filter_collection.blocks_all_presence()
)
if self.hs_config.use_presence and not block_all_presence_data:
yield self._generate_sync_entry_for_presence(
sync_result_builder, newly_joined_rooms, newly_joined_users
)
yield self._generate_sync_entry_for_to_device(sync_result_builder)
device_lists = yield self._generate_sync_entry_for_device_list(
sync_result_builder,
newly_joined_rooms=newly_joined_rooms,
newly_joined_users=newly_joined_users,
newly_left_rooms=newly_left_rooms,
newly_left_users=newly_left_users,
)
device_id = sync_config.device_id
one_time_key_counts = {}
if device_id:
one_time_key_counts = yield self.store.count_e2e_one_time_keys(
user_id, device_id
)
yield self._generate_sync_entry_for_groups(sync_result_builder)
defer.returnValue(SyncResult(
presence=sync_result_builder.presence,
account_data=sync_result_builder.account_data,
joined=sync_result_builder.joined,
invited=sync_result_builder.invited,
archived=sync_result_builder.archived,
to_device=sync_result_builder.to_device,
device_lists=device_lists,
groups=sync_result_builder.groups,
device_one_time_keys_count=one_time_key_counts,
next_batch=sync_result_builder.now_token,
))
@measure_func("_generate_sync_entry_for_groups")
@defer.inlineCallbacks
def _generate_sync_entry_for_groups(self, sync_result_builder):
user_id = sync_result_builder.sync_config.user.to_string()
since_token = sync_result_builder.since_token
now_token = sync_result_builder.now_token
if since_token and since_token.groups_key:
results = yield self.store.get_groups_changes_for_user(
user_id, since_token.groups_key, now_token.groups_key,
)
else:
results = yield self.store.get_all_groups_for_user(
user_id, now_token.groups_key,
)
invited = {}
joined = {}
left = {}
for result in results:
membership = result["membership"]
group_id = result["group_id"]
gtype = result["type"]
content = result["content"]
if membership == "join":
if gtype == "membership":
# TODO: Add profile
content.pop("membership", None)
joined[group_id] = content["content"]
else:
joined.setdefault(group_id, {})[gtype] = content
elif membership == "invite":
if gtype == "membership":
content.pop("membership", None)
invited[group_id] = content["content"]
else:
if gtype == "membership":
left[group_id] = content["content"]
sync_result_builder.groups = GroupsSyncResult(
join=joined,
invite=invited,
leave=left,
)
@measure_func("_generate_sync_entry_for_device_list")
@defer.inlineCallbacks
def _generate_sync_entry_for_device_list(self, sync_result_builder,
newly_joined_rooms, newly_joined_users,
newly_left_rooms, newly_left_users):
user_id = sync_result_builder.sync_config.user.to_string()
since_token = sync_result_builder.since_token
if since_token and since_token.device_list_key:
changed = yield self.store.get_user_whose_devices_changed(
since_token.device_list_key
)
# TODO: Be more clever than this, i.e. remove users who we already
# share a room with?
for room_id in newly_joined_rooms:
joined_users = yield self.state.get_current_user_in_room(room_id)
newly_joined_users.update(joined_users)
for room_id in newly_left_rooms:
left_users = yield self.state.get_current_user_in_room(room_id)
newly_left_users.update(left_users)
# TODO: Check that these users are actually new, i.e. either they
# weren't in the previous sync *or* they left and rejoined.
changed.update(newly_joined_users)
if not changed and not newly_left_users:
defer.returnValue(DeviceLists(
changed=[],
left=newly_left_users,
))
users_who_share_room = yield self.store.get_users_who_share_room_with_user(
user_id
)
defer.returnValue(DeviceLists(
changed=users_who_share_room & changed,
left=set(newly_left_users) - users_who_share_room,
))
else:
defer.returnValue(DeviceLists(
changed=[],
left=[],
))
@defer.inlineCallbacks
def _generate_sync_entry_for_to_device(self, sync_result_builder):
user_id = sync_result_builder.sync_config.user.to_string()
device_id = sync_result_builder.sync_config.device_id
now_token = sync_result_builder.now_token
since_stream_id = 0
if sync_result_builder.since_token is not None:
since_stream_id = int(sync_result_builder.since_token.to_device_key)
if since_stream_id != int(now_token.to_device_key):
# fine so long as we delete them at some point.
deleted = yield self.store.delete_messages_for_device(
user_id, device_id, since_stream_id
)
logger.debug("Deleted %d to-device messages up to %d",
deleted, since_stream_id)
messages, stream_id = yield self.store.get_new_messages_for_device(
user_id, device_id, since_stream_id, now_token.to_device_key
)
logger.debug(
"Returning %d to-device messages between %d and %d (current token: %d)",
len(messages), since_stream_id, stream_id, now_token.to_device_key
)
sync_result_builder.now_token = now_token.copy_and_replace(
"to_device_key", stream_id
)
sync_result_builder.to_device = messages
else:
sync_result_builder.to_device = []
@defer.inlineCallbacks
def _generate_sync_entry_for_account_data(self, sync_result_builder):
sync_config = sync_result_builder.sync_config
user_id = sync_result_builder.sync_config.user.to_string()
since_token = sync_result_builder.since_token
if since_token and not sync_result_builder.full_state:
account_data, account_data_by_room = (
yield self.store.get_updated_account_data_for_user(
user_id,
since_token.account_data_key,
)
)
push_rules_changed = yield self.store.have_push_rules_changed_for_user(
user_id, int(since_token.push_rules_key)
)
if push_rules_changed:
account_data["m.push_rules"] = yield self.push_rules_for_user(
sync_config.user
)
else:
account_data, account_data_by_room = (
yield self.store.get_account_data_for_user(
sync_config.user.to_string()
)
)
account_data['m.push_rules'] = yield self.push_rules_for_user(
sync_config.user
)
account_data_for_user = sync_config.filter_collection.filter_account_data([
{"type": account_data_type, "content": content}
for account_data_type, content in account_data.items()
])
sync_result_builder.account_data = account_data_for_user
defer.returnValue(account_data_by_room)
@defer.inlineCallbacks
def _generate_sync_entry_for_presence(self, sync_result_builder, newly_joined_rooms,
newly_joined_users):
now_token = sync_result_builder.now_token
sync_config = sync_result_builder.sync_config
user = sync_result_builder.sync_config.user
presence_source = self.event_sources.sources["presence"]
since_token = sync_result_builder.since_token
if since_token and not sync_result_builder.full_state:
presence_key = since_token.presence_key
include_offline = True
else:
presence_key = None
include_offline = False
presence, presence_key = yield presence_source.get_new_events(
user=user,
from_key=presence_key,
is_guest=sync_config.is_guest,
include_offline=include_offline,
)
sync_result_builder.now_token = now_token.copy_and_replace(
"presence_key", presence_key
)
extra_users_ids = set(newly_joined_users)
for room_id in newly_joined_rooms:
users = yield self.state.get_current_user_in_room(room_id)
extra_users_ids.update(users)
extra_users_ids.discard(user.to_string())
if extra_users_ids:
states = yield self.presence_handler.get_states(
extra_users_ids,
)
presence.extend(states)
# Deduplicate the presence entries so that there's at most one per user
presence = list({p.user_id: p for p in presence}.values())
presence = sync_config.filter_collection.filter_presence(
presence
)
sync_result_builder.presence = presence
@defer.inlineCallbacks
def _generate_sync_entry_for_rooms(self, sync_result_builder, account_data_by_room):
user_id = sync_result_builder.sync_config.user.to_string()
block_all_room_ephemeral = (
sync_result_builder.since_token is None and
sync_result_builder.sync_config.filter_collection.blocks_all_room_ephemeral()
)
if block_all_room_ephemeral:
ephemeral_by_room = {}
else:
now_token, ephemeral_by_room = yield self.ephemeral_by_room(
sync_result_builder,
now_token=sync_result_builder.now_token,
since_token=sync_result_builder.since_token,
)
sync_result_builder.now_token = now_token
# no point in going futher.
since_token = sync_result_builder.since_token
if not sync_result_builder.full_state:
if since_token and not ephemeral_by_room and not account_data_by_room:
have_changed = yield self._have_rooms_changed(sync_result_builder)
if not have_changed:
tags_by_room = yield self.store.get_updated_tags(
user_id,
since_token.account_data_key,
)
if not tags_by_room:
logger.debug("no-oping sync")
defer.returnValue(([], [], [], []))
ignored_account_data = yield self.store.get_global_account_data_by_type_for_user(
"m.ignored_user_list", user_id=user_id,
)
if ignored_account_data:
ignored_users = ignored_account_data.get("ignored_users", {}).keys()
else:
ignored_users = frozenset()
if since_token:
res = yield self._get_rooms_changed(sync_result_builder, ignored_users)
room_entries, invited, newly_joined_rooms, newly_left_rooms = res
tags_by_room = yield self.store.get_updated_tags(
user_id, since_token.account_data_key,
)
else:
res = yield self._get_all_rooms(sync_result_builder, ignored_users)
room_entries, invited, newly_joined_rooms = res
newly_left_rooms = []
tags_by_room = yield self.store.get_tags_for_user(user_id)
def handle_room_entries(room_entry):
return self._generate_room_entry(
sync_result_builder,
ignored_users,
room_entry,
ephemeral=ephemeral_by_room.get(room_entry.room_id, []),
tags=tags_by_room.get(room_entry.room_id),
account_data=account_data_by_room.get(room_entry.room_id, {}),
always_include=sync_result_builder.full_state,
)
yield concurrently_execute(handle_room_entries, room_entries, 10)
sync_result_builder.invited.extend(invited)
# Now we want to get any newly joined users
newly_joined_users = set()
newly_left_users = set()
if since_token:
for joined_sync in sync_result_builder.joined:
it = itertools.chain(
joined_sync.timeline.events, itervalues(joined_sync.state)
)
for event in it:
if event.type == EventTypes.Member:
if event.membership == Membership.JOIN:
newly_joined_users.add(event.state_key)
else:
prev_content = event.unsigned.get("prev_content", {})
prev_membership = prev_content.get("membership", None)
if prev_membership == Membership.JOIN:
newly_left_users.add(event.state_key)
newly_left_users -= newly_joined_users
defer.returnValue((
newly_joined_rooms,
newly_joined_users,
newly_left_rooms,
newly_left_users,
))
@defer.inlineCallbacks
def _have_rooms_changed(self, sync_result_builder):
user_id = sync_result_builder.sync_config.user.to_string()
since_token = sync_result_builder.since_token
now_token = sync_result_builder.now_token
assert since_token
# Get a list of membership change events that have happened.
rooms_changed = yield self.store.get_membership_changes_for_user(
user_id, since_token.room_key, now_token.room_key
)
if rooms_changed:
defer.returnValue(True)
stream_id = RoomStreamToken.parse_stream_token(since_token.room_key).stream
for room_id in sync_result_builder.joined_room_ids:
if self.store.has_room_changed_since(room_id, stream_id):
defer.returnValue(True)
defer.returnValue(False)
@defer.inlineCallbacks
def _get_rooms_changed(self, sync_result_builder, ignored_users):
user_id = sync_result_builder.sync_config.user.to_string()
since_token = sync_result_builder.since_token
now_token = sync_result_builder.now_token
sync_config = sync_result_builder.sync_config
assert since_token
# Get a list of membership change events that have happened.
rooms_changed = yield self.store.get_membership_changes_for_user(
user_id, since_token.room_key, now_token.room_key
)
mem_change_events_by_room_id = {}
for event in rooms_changed:
mem_change_events_by_room_id.setdefault(event.room_id, []).append(event)
newly_joined_rooms = []
newly_left_rooms = []
room_entries = []
invited = []
for room_id, events in iteritems(mem_change_events_by_room_id):
non_joins = [e for e in events if e.membership != Membership.JOIN]
has_join = len(non_joins) != len(events)
# We want to figure out if we joined the room at some point since
# the last sync (even if we have since left). This is to make sure
# we do send down the room, and with full state, where necessary
old_state_ids = None
if room_id in sync_result_builder.joined_room_ids and non_joins:
# Always include if the user (re)joined the room, especially
# important so that device list changes are calculated correctly.
# If there are non join member events, but we are still in the room,
# then the user must have left and joined
newly_joined_rooms.append(room_id)
# User is in the room so we don't need to do the invite/leave checks
continue
if room_id in sync_result_builder.joined_room_ids or has_join:
old_state_ids = yield self.get_state_at(room_id, since_token)
old_mem_ev_id = old_state_ids.get((EventTypes.Member, user_id), None)
old_mem_ev = None
if old_mem_ev_id:
old_mem_ev = yield self.store.get_event(
old_mem_ev_id, allow_none=True
)
if not old_mem_ev or old_mem_ev.membership != Membership.JOIN:
newly_joined_rooms.append(room_id)
if room_id in sync_result_builder.joined_room_ids:
continue
if not non_joins:
continue
# Check if we have left the room. This can either be because we were
# joined before *or* that we since joined and then left.
if events[-1].membership != Membership.JOIN:
if has_join:
newly_left_rooms.append(room_id)
else:
if not old_state_ids:
old_state_ids = yield self.get_state_at(room_id, since_token)
old_mem_ev_id = old_state_ids.get(
(EventTypes.Member, user_id),
None,
)
old_mem_ev = None
if old_mem_ev_id:
old_mem_ev = yield self.store.get_event(
old_mem_ev_id, allow_none=True
)
if old_mem_ev and old_mem_ev.membership == Membership.JOIN:
newly_left_rooms.append(room_id)
# Only bother if we're still currently invited
should_invite = non_joins[-1].membership == Membership.INVITE
if should_invite:
if event.sender not in ignored_users:
room_sync = InvitedSyncResult(room_id, invite=non_joins[-1])
if room_sync:
invited.append(room_sync)
leave_events = [
e for e in non_joins
if e.membership in (Membership.LEAVE, Membership.BAN)
]
if leave_events:
leave_event = leave_events[-1]
leave_stream_token = yield self.store.get_stream_token_for_event(
leave_event.event_id
)
leave_token = since_token.copy_and_replace(
"room_key", leave_stream_token
)
if since_token and since_token.is_after(leave_token):
continue
room_entries.append(RoomSyncResultBuilder(
room_id=room_id,
rtype="archived",
events=None,
newly_joined=room_id in newly_joined_rooms,
full_state=False,
since_token=since_token,
upto_token=leave_token,
))
timeline_limit = sync_config.filter_collection.timeline_limit()
room_to_events = yield self.store.get_room_events_stream_for_rooms(
room_ids=sync_result_builder.joined_room_ids,
from_key=since_token.room_key,
to_key=now_token.room_key,
limit=timeline_limit + 1,
)
# We loop through all room ids, even if there are no new events, in case
# there are non room events taht we need to notify about.
for room_id in sync_result_builder.joined_room_ids:
room_entry = room_to_events.get(room_id, None)
if room_entry:
events, start_key = room_entry
prev_batch_token = now_token.copy_and_replace("room_key", start_key)
room_entries.append(RoomSyncResultBuilder(
room_id=room_id,
rtype="joined",
events=events,
newly_joined=room_id in newly_joined_rooms,
full_state=False,
since_token=None if room_id in newly_joined_rooms else since_token,
upto_token=prev_batch_token,
))
else:
room_entries.append(RoomSyncResultBuilder(
room_id=room_id,
rtype="joined",
events=[],
newly_joined=room_id in newly_joined_rooms,
full_state=False,
since_token=since_token,
upto_token=since_token,
))
defer.returnValue((room_entries, invited, newly_joined_rooms, newly_left_rooms))
@defer.inlineCallbacks
def _get_all_rooms(self, sync_result_builder, ignored_users):
user_id = sync_result_builder.sync_config.user.to_string()
since_token = sync_result_builder.since_token
now_token = sync_result_builder.now_token
sync_config = sync_result_builder.sync_config
membership_list = (
Membership.INVITE, Membership.JOIN, Membership.LEAVE, Membership.BAN
)
room_list = yield self.store.get_rooms_for_user_where_membership_is(
user_id=user_id,
membership_list=membership_list
)
room_entries = []
invited = []
for event in room_list:
if event.membership == Membership.JOIN:
room_entries.append(RoomSyncResultBuilder(
room_id=event.room_id,
rtype="joined",
events=None,
newly_joined=False,
full_state=True,
since_token=since_token,
upto_token=now_token,
))
elif event.membership == Membership.INVITE:
if event.sender in ignored_users:
continue
invite = yield self.store.get_event(event.event_id)
invited.append(InvitedSyncResult(
room_id=event.room_id,
invite=invite,
))
elif event.membership in (Membership.LEAVE, Membership.BAN):
# Always send down rooms we were banned or kicked from.
if not sync_config.filter_collection.include_leave:
if event.membership == Membership.LEAVE:
if user_id == event.sender:
continue
leave_token = now_token.copy_and_replace(
"room_key", "s%d" % (event.stream_ordering,)
)
room_entries.append(RoomSyncResultBuilder(
room_id=event.room_id,
rtype="archived",
events=None,
newly_joined=False,
full_state=True,
since_token=since_token,
upto_token=leave_token,
))
defer.returnValue((room_entries, invited, []))
@defer.inlineCallbacks
def _generate_room_entry(self, sync_result_builder, ignored_users,
room_builder, ephemeral, tags, account_data,
always_include=False):
newly_joined = room_builder.newly_joined
full_state = (
room_builder.full_state
or newly_joined
or sync_result_builder.full_state
)
events = room_builder.events
# We want to shortcut out as early as possible.
if not (always_include or account_data or ephemeral or full_state):
if events == [] and tags is None:
return
now_token = sync_result_builder.now_token
sync_config = sync_result_builder.sync_config
room_id = room_builder.room_id
since_token = room_builder.since_token
upto_token = room_builder.upto_token
batch = yield self._load_filtered_recents(
room_id, sync_config,
now_token=upto_token,
since_token=since_token,
recents=events,
newly_joined_room=newly_joined,
)
# When we join the room (or the client requests full_state), we should
# send down any existing tags. Usually the user won't have tags in a
# tag was added by synapse e.g. for server notice rooms.
if full_state:
user_id = sync_result_builder.sync_config.user.to_string()
tags = yield self.store.get_tags_for_room(user_id, room_id)
# If there aren't any tags, don't send the empty tags list down
# sync
if not tags:
tags = None
account_data_events = []
if tags is not None:
account_data_events.append({
"type": "m.tag",
"content": {"tags": tags},
})
for account_data_type, content in account_data.items():
account_data_events.append({
"type": account_data_type,
"content": content,
})
account_data_events = sync_config.filter_collection.filter_room_account_data(
account_data_events
)
ephemeral = sync_config.filter_collection.filter_room_ephemeral(ephemeral)
if not (always_include
or batch
or account_data_events
or ephemeral
or full_state):
return
state = yield self.compute_state_delta(
room_id, batch, sync_config, since_token, now_token,
full_state=full_state
)
summary = {}
# we include a summary in room responses when we're lazy loading
# the name itself).
if (
sync_config.filter_collection.lazy_load_members() and
(
# we recalulate the summary:
# if there are membership changes in the timeline, or
# if membership has changed during a gappy sync, or
# if this is an initial sync.
any(ev.type == EventTypes.Member for ev in batch.events) or
(
# XXX: this may include false positives in the form of LL
# members which have snuck into state
batch.limited and
any(t == EventTypes.Member for (t, k) in state)
) or
since_token is None
)
):
summary = yield self.compute_summary(
room_id, sync_config, batch, state, now_token
)
if room_builder.rtype == "joined":
unread_notifications = {}
room_sync = JoinedSyncResult(
room_id=room_id,
timeline=batch,
state=state,
ephemeral=ephemeral,
account_data=account_data_events,
unread_notifications=unread_notifications,
summary=summary,
)
if room_sync or always_include:
notifs = yield self.unread_notifs_for_room_id(
room_id, sync_config
)
if notifs is not None:
unread_notifications["notification_count"] = notifs["notify_count"]
unread_notifications["highlight_count"] = notifs["highlight_count"]
sync_result_builder.joined.append(room_sync)
if batch.limited and since_token:
user_id = sync_result_builder.sync_config.user.to_string()
logger.info(
"Incremental gappy sync of %s for user %s with %d state events" % (
room_id,
user_id,
len(state),
)
)
elif room_builder.rtype == "archived":
room_sync = ArchivedSyncResult(
room_id=room_id,
timeline=batch,
state=state,
account_data=account_data_events,
)
if room_sync or always_include:
sync_result_builder.archived.append(room_sync)
else:
raise Exception("Unrecognized rtype: %r", room_builder.rtype)
@defer.inlineCallbacks
def get_rooms_for_user_at(self, user_id, stream_ordering):
joined_rooms = yield self.store.get_rooms_for_user_with_stream_ordering(
user_id,
)
joined_room_ids = set()
# We need to check that the stream ordering of the join for each room
# is before the stream_ordering asked for. This might not be the case
# if the user joins a room between us getting the current token and
# calling `get_rooms_for_user_with_stream_ordering`.
# If the membership's stream ordering is after the given stream
for room_id, membership_stream_ordering in joined_rooms:
if membership_stream_ordering <= stream_ordering:
joined_room_ids.add(room_id)
continue
logger.info("User joined room after current token: %s", room_id)
extrems = yield self.store.get_forward_extremeties_for_room(
room_id, stream_ordering,
)
users_in_room = yield self.state.get_current_user_in_room(
room_id, extrems,
)
if user_id in users_in_room:
joined_room_ids.add(room_id)
joined_room_ids = frozenset(joined_room_ids)
defer.returnValue(joined_room_ids)
def _action_has_highlight(actions):
for action in actions:
try:
if action.get("set_tweak", None) == "highlight":
return action.get("value", True)
except AttributeError:
pass
return False
def _calculate_state(
timeline_contains, timeline_start, previous, current, lazy_load_members,
):
event_id_to_key = {
e: key
for key, e in itertools.chain(
iteritems(timeline_contains),
iteritems(previous),
iteritems(timeline_start),
iteritems(current),
)
}
c_ids = set(e for e in itervalues(current))
ts_ids = set(e for e in itervalues(timeline_start))
p_ids = set(e for e in itervalues(previous))
tc_ids = set(e for e in itervalues(timeline_contains))
zy_load_members:
p_ids.difference_update(
e for t, e in iteritems(timeline_start)
if t[0] == EventTypes.Member
)
state_ids = ((c_ids | ts_ids) - p_ids) - tc_ids
return {
event_id_to_key[e]: e for e in state_ids
}
class SyncResultBuilder(object):
def __init__(self, sync_config, full_state, since_token, now_token,
joined_room_ids):
self.sync_config = sync_config
self.full_state = full_state
self.since_token = since_token
self.now_token = now_token
self.joined_room_ids = joined_room_ids
self.presence = []
self.account_data = []
self.joined = []
self.invited = []
self.archived = []
self.device = []
self.groups = None
self.to_device = []
class RoomSyncResultBuilder(object):
def __init__(self, room_id, rtype, events, newly_joined, full_state,
since_token, upto_token):
self.room_id = room_id
self.rtype = rtype
self.events = events
self.newly_joined = newly_joined
self.full_state = full_state
self.since_token = since_token
self.upto_token = upto_token
| true | true |
f7f76a8dbbe03fcfd920e2164c035881009fb089 | 31 | py | Python | test/example/python/kwargs.py | Hirse/brackets-outline-list | a42568bb92d2b9a98f1d33d89f251c8b97b662b1 | [
"MIT"
] | 88 | 2015-01-03T11:20:13.000Z | 2021-08-19T19:15:40.000Z | test/example/python/kwargs.py | Hirse/brackets-outline-list | a42568bb92d2b9a98f1d33d89f251c8b97b662b1 | [
"MIT"
] | 101 | 2015-01-08T12:28:47.000Z | 2022-03-02T03:34:12.000Z | test/example/python/kwargs.py | Hirse/brackets-outline-list | a42568bb92d2b9a98f1d33d89f251c8b97b662b1 | [
"MIT"
] | 51 | 2015-01-03T11:20:14.000Z | 2021-02-23T07:09:59.000Z | def whoami(**kwargs):
pass
| 10.333333 | 21 | 0.612903 | def whoami(**kwargs):
pass
| true | true |
f7f76ad3a9f9e445bf7a7b2318ffb9bc4aa25f30 | 3,996 | py | Python | University/sem 1/Roots/RootMethods.py | Watcher1337/Python | e063bdce3d972cf71fbdf7df567afbd6b6623141 | [
"MIT"
] | null | null | null | University/sem 1/Roots/RootMethods.py | Watcher1337/Python | e063bdce3d972cf71fbdf7df567afbd6b6623141 | [
"MIT"
] | null | null | null | University/sem 1/Roots/RootMethods.py | Watcher1337/Python | e063bdce3d972cf71fbdf7df567afbd6b6623141 | [
"MIT"
] | 1 | 2019-01-17T15:49:06.000Z | 2019-01-17T15:49:06.000Z | import math as m
# Методы для нахождения корней уравнения с точностью eps на заданном промежутке
def f(x):
return x ** 3 + x - 2
def f_prime(x):
return 3 * x ** 2 + 1
# ------------------------------------------------------
# Метод Ньютона(касательных)
# Для получения сжимающего отображения применяется метод простых итераций
# Затем для приближенных рассчетов используется производная данной функции
def newtone(a,b,eps):
c = a
result = c
x = c - f(c) / f_prime(c)
while abs(result - x) > eps:
result = x
x = x - f(x) / f_prime(x)
return x
# ------------------------------------------------------
# Упрощенный метод Ньютона
# Производная вычисляется только для первого элемента x0
def easy_newtone(a,b,eps):
c = (a + b) / 2
result = c
x = c - f(c) / f_prime(c) # x0
prime = f_prime(x)
while abs(result - x) > eps:
result = x
x = x - f(x) / prime
return x
# ------------------------------------------------------
# Метод Стеффенсена
def steffensen(a,b,eps):
c = (a + b) / 2
result = c
x = c - f(c) * f(c) / (f(c + f(c)) - f(c))
while abs(result - x) > eps:
result = x
x = x - f(x) * f(x) / (f(x + f(x)) - f(x))
return x
# ------------------------------------------------------
# Метод секущих
def sek(a,b,eps):
c0 = a
c = (a+b)/2
result = c
x0 = c
x0 = c - (c - c0) / (f(c) - f(c0)) * f(c)
x = x0 - ((x0 - c) / (f(x0) - f(c))) * f(x0)
while abs(result - x) > eps:
result = x
x = x - ((x - x0) / (f(x) - f(x0))) * f(x)
x0 = result
return x
# ------------------------------------------------------
# Комбинированный метод
def f_pp(x): # сторая производная от функции
return 6 * x
def combo(a,b,eps):
while abs(a-b)>2 * eps:
if f(a) * f_pp(a) < 0:
a = a - f(a) * (a-b) / (f(a) - f(b))
elif f(a) * f_pp(a) > 0:
a = a - f(a)/f_prime(a)
if f(b) * f_pp(b) < 0:
b = b - f(b) * (b-a) / (f(b) - f(a))
elif f(b) * f_pp(b) > 0:
b = b - f(b)/f_prime(b)
x = (a + b) / 2
return x
# ------------------------------------------------------
# Метод дихотомии(бисекции)
# Рассматриваемый интервал должен пересеекать 0
# Вычисляется средняя позиция в интервале и значение ф-ции в ней
# Если значение удовлетворяет условию |f(mid)| < eps, то return
# Иначе вычисляется знак f(mid) и передается в рекурсию так, чтобы в новой последовательности
# Было пересечение с 0
def dihotomy(a,b,eps):
c = (a + b) / 2
if abs(f(c)) < eps:
return c
if f(c) * f(a) < 0:
return dihotomy(a,c,eps)
else:
return dihotomy(c,b,eps)
# ------------------------------------------------------
# Метод Хорд
# Начальная хорда проходит через точки
# С(a,f(a)) : D(b,f(b))
def chord(a, b, eps):
xn = a - f(a) * (a - b) / (f(a) - f(b)) # Уравнение хорды через 2 точки в точке пересечения с осью
if abs(f(xn)) < eps:
return xn
if f(a) * f(xn) < 0:
return chord(a,xn,eps)
else:
return chord(xn,a,eps)
# ------------------------------------------------------
# Метод Итераций
# !!! требуется подобрать сходящуюся эквивалентную функцию, выраженную через х
# x = f(x)
# Затем значение постепенно уточняется, приближаясь к нужному корню
def g(x): # функция вида x = g(x), где g(x) = f(x) + x
return 2 / (x**2 + 1)
def iterations(a,b, eps):
result = (a + b) / 2 # В качестве начальных данных берется значение ф-ции в начале интервала
x = g(a)
while abs(result - x) > eps:
result = x
x = g(x)
return x
# ------------------------------------------------------
a = -10 # Начало и конец интервала уточнения
b = 10
eps = 0.01
print("Уравнение: y = x^3 + x - 2")
print("Рассматриваемый интервал: [{},{}]".format(a,b) )
print("Выбранная точность: ", eps)
print()
print("Метод дихотомии: ", dihotomy(a,b,eps))
print("Метод хорд: ", chord(a,b,eps))
print("Метод Ньютона: ", newtone(a, b, eps))
print("Упрощенный метод Ньютона: ", easy_newtone(a, b, eps))
print("Метод Стеффенсена: ", steffensen(a, b, eps))
print("Метод секущих: ", sek(a, b, eps))
print("Комбинированный метод: ", combo(a, b, eps))
print("Метод итераций: ", iterations(a, b, eps))
a = input() | 29.6 | 99 | 0.535536 | import math as m
def f(x):
return x ** 3 + x - 2
def f_prime(x):
return 3 * x ** 2 + 1
def newtone(a,b,eps):
c = a
result = c
x = c - f(c) / f_prime(c)
while abs(result - x) > eps:
result = x
x = x - f(x) / f_prime(x)
return x
def easy_newtone(a,b,eps):
c = (a + b) / 2
result = c
x = c - f(c) / f_prime(c)
prime = f_prime(x)
while abs(result - x) > eps:
result = x
x = x - f(x) / prime
return x
def steffensen(a,b,eps):
c = (a + b) / 2
result = c
x = c - f(c) * f(c) / (f(c + f(c)) - f(c))
while abs(result - x) > eps:
result = x
x = x - f(x) * f(x) / (f(x + f(x)) - f(x))
return x
def sek(a,b,eps):
c0 = a
c = (a+b)/2
result = c
x0 = c
x0 = c - (c - c0) / (f(c) - f(c0)) * f(c)
x = x0 - ((x0 - c) / (f(x0) - f(c))) * f(x0)
while abs(result - x) > eps:
result = x
x = x - ((x - x0) / (f(x) - f(x0))) * f(x)
x0 = result
return x
def f_pp(x):
return 6 * x
def combo(a,b,eps):
while abs(a-b)>2 * eps:
if f(a) * f_pp(a) < 0:
a = a - f(a) * (a-b) / (f(a) - f(b))
elif f(a) * f_pp(a) > 0:
a = a - f(a)/f_prime(a)
if f(b) * f_pp(b) < 0:
b = b - f(b) * (b-a) / (f(b) - f(a))
elif f(b) * f_pp(b) > 0:
b = b - f(b)/f_prime(b)
x = (a + b) / 2
return x
def dihotomy(a,b,eps):
c = (a + b) / 2
if abs(f(c)) < eps:
return c
if f(c) * f(a) < 0:
return dihotomy(a,c,eps)
else:
return dihotomy(c,b,eps)
def chord(a, b, eps):
xn = a - f(a) * (a - b) / (f(a) - f(b))
if abs(f(xn)) < eps:
return xn
if f(a) * f(xn) < 0:
return chord(a,xn,eps)
else:
return chord(xn,a,eps)
def g(x):
return 2 / (x**2 + 1)
def iterations(a,b, eps):
result = (a + b) / 2
x = g(a)
while abs(result - x) > eps:
result = x
x = g(x)
return x
a = -10
b = 10
eps = 0.01
print("Уравнение: y = x^3 + x - 2")
print("Рассматриваемый интервал: [{},{}]".format(a,b) )
print("Выбранная точность: ", eps)
print()
print("Метод дихотомии: ", dihotomy(a,b,eps))
print("Метод хорд: ", chord(a,b,eps))
print("Метод Ньютона: ", newtone(a, b, eps))
print("Упрощенный метод Ньютона: ", easy_newtone(a, b, eps))
print("Метод Стеффенсена: ", steffensen(a, b, eps))
print("Метод секущих: ", sek(a, b, eps))
print("Комбинированный метод: ", combo(a, b, eps))
print("Метод итераций: ", iterations(a, b, eps))
a = input() | true | true |
f7f76b1eeda6ae1996bf716246f781b095c6da3a | 4,089 | py | Python | tutorials/stats-sensor-space/plot_stats_cluster_1samp_test_time_frequency.py | abramhindle/mne-python | 989390a484cba219aae74c778b71568586f9edb2 | [
"BSD-3-Clause"
] | null | null | null | tutorials/stats-sensor-space/plot_stats_cluster_1samp_test_time_frequency.py | abramhindle/mne-python | 989390a484cba219aae74c778b71568586f9edb2 | [
"BSD-3-Clause"
] | 1 | 2019-09-17T23:54:38.000Z | 2019-09-17T23:54:38.000Z | tutorials/stats-sensor-space/plot_stats_cluster_1samp_test_time_frequency.py | abramhindle/mne-python | 989390a484cba219aae74c778b71568586f9edb2 | [
"BSD-3-Clause"
] | null | null | null | """
===============================================================
Non-parametric 1 sample cluster statistic on single trial power
===============================================================
This script shows how to estimate significant clusters
in time-frequency power estimates. It uses a non-parametric
statistical procedure based on permutations and cluster
level statistics.
The procedure consists of:
- extracting epochs
- compute single trial power estimates
- baseline line correct the power estimates (power ratios)
- compute stats to see if ratio deviates from 1.
"""
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.time_frequency import tfr_morlet
from mne.stats import permutation_cluster_1samp_test
from mne.datasets import sample
print(__doc__)
###############################################################################
# Set parameters
# --------------
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
tmin, tmax, event_id = -0.3, 0.6, 1
# Setup for reading the raw data
raw = mne.io.read_raw_fif(raw_fname)
events = mne.find_events(raw, stim_channel='STI 014')
include = []
raw.info['bads'] += ['MEG 2443', 'EEG 053'] # bads + 2 more
# picks MEG gradiometers
picks = mne.pick_types(raw.info, meg='grad', eeg=False, eog=True,
stim=False, include=include, exclude='bads')
# Load condition 1
event_id = 1
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
baseline=(None, 0), preload=True,
reject=dict(grad=4000e-13, eog=150e-6))
# Take only one channel
ch_name = 'MEG 1332'
epochs.pick_channels([ch_name])
evoked = epochs.average()
# Factor to down-sample the temporal dimension of the TFR computed by
# tfr_morlet. Decimation occurs after frequency decomposition and can
# be used to reduce memory usage (and possibly computational time of downstream
# operations such as nonparametric statistics) if you don't need high
# spectrotemporal resolution.
decim = 5
freqs = np.arange(8, 40, 2) # define frequencies of interest
sfreq = raw.info['sfreq'] # sampling in Hz
tfr_epochs = tfr_morlet(epochs, freqs, n_cycles=4., decim=decim,
average=False, return_itc=False, n_jobs=1)
# Baseline power
tfr_epochs.apply_baseline(mode='logratio', baseline=(-.100, 0))
# Crop in time to keep only what is between 0 and 400 ms
evoked.crop(0., 0.4)
tfr_epochs.crop(0., 0.4)
epochs_power = tfr_epochs.data[:, 0, :, :] # take the 1 channel
###############################################################################
# Compute statistic
# -----------------
threshold = 2.5
n_permutations = 100 # Warning: 100 is too small for real-world analysis.
T_obs, clusters, cluster_p_values, H0 = \
permutation_cluster_1samp_test(epochs_power, n_permutations=n_permutations,
threshold=threshold, tail=0)
###############################################################################
# View time-frequency plots
# -------------------------
evoked_data = evoked.data
times = 1e3 * evoked.times
plt.figure()
plt.subplots_adjust(0.12, 0.08, 0.96, 0.94, 0.2, 0.43)
# Create new stats image with only significant clusters
T_obs_plot = np.nan * np.ones_like(T_obs)
for c, p_val in zip(clusters, cluster_p_values):
if p_val <= 0.05:
T_obs_plot[c] = T_obs[c]
vmax = np.max(np.abs(T_obs))
vmin = -vmax
plt.subplot(2, 1, 1)
plt.imshow(T_obs, cmap=plt.cm.gray,
extent=[times[0], times[-1], freqs[0], freqs[-1]],
aspect='auto', origin='lower', vmin=vmin, vmax=vmax)
plt.imshow(T_obs_plot, cmap=plt.cm.RdBu_r,
extent=[times[0], times[-1], freqs[0], freqs[-1]],
aspect='auto', origin='lower', vmin=vmin, vmax=vmax)
plt.colorbar()
plt.xlabel('Time (ms)')
plt.ylabel('Frequency (Hz)')
plt.title('Induced power (%s)' % ch_name)
ax2 = plt.subplot(2, 1, 2)
evoked.plot(axes=[ax2], time_unit='s')
plt.show()
| 32.712 | 79 | 0.630227 |
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.time_frequency import tfr_morlet
from mne.stats import permutation_cluster_1samp_test
from mne.datasets import sample
print(__doc__)
| true | true |
f7f76b7f9f4b3d20d8a6b74c87176038ceefa163 | 20,840 | py | Python | baselines/deepq_n_step/build_graph.py | LinghengMeng/openai_baselines_extension | 65ec57a71be77b6cfd92defd070d76ae225a92e7 | [
"MIT"
] | null | null | null | baselines/deepq_n_step/build_graph.py | LinghengMeng/openai_baselines_extension | 65ec57a71be77b6cfd92defd070d76ae225a92e7 | [
"MIT"
] | null | null | null | baselines/deepq_n_step/build_graph.py | LinghengMeng/openai_baselines_extension | 65ec57a71be77b6cfd92defd070d76ae225a92e7 | [
"MIT"
] | null | null | null | """Deep Q learning graph
The functions in this file can are used to create the following functions:
======= act ========
Function to chose an action given an observation
Parameters
----------
observation: object
Observation that can be feed into the output of make_obs_ph
stochastic: bool
if set to False all the actions are always deterministic (default False)
update_eps_ph: float
update epsilon a new value, if negative not update happens
(default: no update)
Returns
-------
Tensor of dtype tf.int64 and shape (BATCH_SIZE,) with an action to be performed for
every element of the batch.
======= act (in case of parameter noise) ========
Function to chose an action given an observation
Parameters
----------
observation: object
Observation that can be feed into the output of make_obs_ph
stochastic: bool
if set to False all the actions are always deterministic (default False)
update_eps_ph: float
update epsilon to a new value, if negative no update happens
(default: no update)
reset_ph: bool
reset the perturbed policy by sampling a new perturbation
update_param_noise_threshold_ph: float
the desired threshold for the difference between non-perturbed and perturbed policy
update_param_noise_scale_ph: bool
whether or not to update the scale of the noise for the next time it is re-perturbed
Returns
-------
Tensor of dtype tf.int64 and shape (BATCH_SIZE,) with an action to be performed for
every element of the batch.
======= train =======
Function that takes a transition (s,a,r,s') and optimizes Bellman equation's error:
td_error = Q(s,a) - (r + gamma * max_a' Q(s', a'))
loss = huber_loss[td_error]
Parameters
----------
obs_t: object
a batch of observations
action: np.array
actions that were selected upon seeing obs_t.
dtype must be int32 and shape must be (batch_size,)
reward: np.array
immediate reward attained after executing those actions
dtype must be float32 and shape must be (batch_size,)
obs_tp1: object
observations that followed obs_t
done: np.array
1 if obs_t was the last observation in the episode and 0 otherwise
obs_tp1 gets ignored, but must be of the valid shape.
dtype must be float32 and shape must be (batch_size,)
weight: np.array
imporance weights for every element of the batch (gradient is multiplied
by the importance weight) dtype must be float32 and shape must be (batch_size,)
Returns
-------
td_error: np.array
a list of differences between Q(s,a) and the target in Bellman's equation.
dtype is float32 and shape is (batch_size,)
======= update_target ========
copy the parameters from optimized Q function to the target Q function.
In Q learning we actually optimize the following error:
Q(s,a) - (r + gamma * max_a' Q'(s', a'))
Where Q' is lagging behind Q to stablize the learning. For example for Atari
Q' is set to Q once every 10000 updates training steps.
"""
import tensorflow as tf
import baselines.common.tf_util as U
def scope_vars(scope, trainable_only=False):
"""
Get variables inside a scope
The scope can be specified as a string
Parameters
----------
scope: str or VariableScope
scope in which the variables reside.
trainable_only: bool
whether or not to return only the variables that were marked as trainable.
Returns
-------
vars: [tf.Variable]
list of variables in `scope`.
"""
return tf.get_collection(
tf.GraphKeys.TRAINABLE_VARIABLES if trainable_only else tf.GraphKeys.GLOBAL_VARIABLES,
scope=scope if isinstance(scope, str) else scope.name
)
def scope_name():
"""Returns the name of current scope as a string, e.g. deepq/q_func"""
return tf.get_variable_scope().name
def absolute_scope_name(relative_scope_name):
"""Appends parent scope name to `relative_scope_name`"""
return scope_name() + "/" + relative_scope_name
def default_param_noise_filter(var):
if var not in tf.trainable_variables():
# We never perturb non-trainable vars.
return False
if "fully_connected" in var.name:
# We perturb fully-connected layers.
return True
# The remaining layers are likely conv or layer norm layers, which we do not wish to
# perturb (in the former case because they only extract features, in the latter case because
# we use them for normalization purposes). If you change your network, you will likely want
# to re-consider which layers to perturb and which to keep untouched.
return False
def build_act(make_obs_ph, q_func, num_actions, scope="deepq", reuse=None):
"""Creates the act function:
Parameters
----------
make_obs_ph: str -> tf.placeholder or TfInput
a function that take a name and creates a placeholder of input with that name
q_func: (tf.Variable, int, str, bool) -> tf.Variable
the model that takes the following inputs:
observation_in: object
the output of observation placeholder
num_actions: int
number of actions
scope: str
reuse: bool
should be passed to outer variable scope
and returns a tensor of shape (batch_size, num_actions) with values of every action.
num_actions: int
number of actions.
scope: str or VariableScope
optional scope for variable_scope.
reuse: bool or None
whether or not the variables should be reused. To be able to reuse the scope must be given.
Returns
-------
act: (tf.Variable, bool, float) -> tf.Variable
function to select and action given observation.
` See the top of the file for details.
"""
with tf.variable_scope(scope, reuse=reuse):
observations_ph = make_obs_ph("observation")
stochastic_ph = tf.placeholder(tf.bool, (), name="stochastic")
update_eps_ph = tf.placeholder(tf.float32, (), name="update_eps")
eps = tf.get_variable("eps", (), initializer=tf.constant_initializer(0))
q_values = q_func(observations_ph.get(), num_actions, scope="q_func")
deterministic_actions = tf.argmax(q_values, axis=1)
batch_size = tf.shape(observations_ph.get())[0]
random_actions = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=num_actions, dtype=tf.int64)
chose_random = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=1, dtype=tf.float32) < eps
stochastic_actions = tf.where(chose_random, random_actions, deterministic_actions)
output_actions = tf.cond(stochastic_ph, lambda: stochastic_actions, lambda: deterministic_actions)
update_eps_expr = eps.assign(tf.cond(update_eps_ph >= 0, lambda: update_eps_ph, lambda: eps))
_act = U.function(inputs=[observations_ph, stochastic_ph, update_eps_ph],
outputs=output_actions,
givens={update_eps_ph: -1.0, stochastic_ph: True},
updates=[update_eps_expr])
def act(ob, stochastic=True, update_eps=-1):
return _act(ob, stochastic, update_eps)
return act
def build_act_with_param_noise(make_obs_ph, q_func, num_actions, scope="deepq", reuse=None, param_noise_filter_func=None):
"""Creates the act function with support for parameter space noise exploration (https://arxiv.org/abs/1706.01905):
Parameters
----------
make_obs_ph: str -> tf.placeholder or TfInput
a function that take a name and creates a placeholder of input with that name
q_func: (tf.Variable, int, str, bool) -> tf.Variable
the model that takes the following inputs:
observation_in: object
the output of observation placeholder
num_actions: int
number of actions
scope: str
reuse: bool
should be passed to outer variable scope
and returns a tensor of shape (batch_size, num_actions) with values of every action.
num_actions: int
number of actions.
scope: str or VariableScope
optional scope for variable_scope.
reuse: bool or None
whether or not the variables should be reused. To be able to reuse the scope must be given.
param_noise_filter_func: tf.Variable -> bool
function that decides whether or not a variable should be perturbed. Only applicable
if param_noise is True. If set to None, default_param_noise_filter is used by default.
Returns
-------
act: (tf.Variable, bool, float, bool, float, bool) -> tf.Variable
function to select and action given observation.
` See the top of the file for details.
"""
if param_noise_filter_func is None:
param_noise_filter_func = default_param_noise_filter
with tf.variable_scope(scope, reuse=reuse):
observations_ph = make_obs_ph("observation")
stochastic_ph = tf.placeholder(tf.bool, (), name="stochastic")
update_eps_ph = tf.placeholder(tf.float32, (), name="update_eps")
update_param_noise_threshold_ph = tf.placeholder(tf.float32, (), name="update_param_noise_threshold")
update_param_noise_scale_ph = tf.placeholder(tf.bool, (), name="update_param_noise_scale")
reset_ph = tf.placeholder(tf.bool, (), name="reset")
eps = tf.get_variable("eps", (), initializer=tf.constant_initializer(0))
param_noise_scale = tf.get_variable("param_noise_scale", (), initializer=tf.constant_initializer(0.01), trainable=False)
param_noise_threshold = tf.get_variable("param_noise_threshold", (), initializer=tf.constant_initializer(0.05), trainable=False)
# Unmodified Q.
q_values = q_func(observations_ph.get(), num_actions, scope="q_func")
# Perturbable Q used for the actual rollout.
q_values_perturbed = q_func(observations_ph.get(), num_actions, scope="perturbed_q_func")
# We have to wrap this code into a function due to the way tf.cond() works. See
# https://stackoverflow.com/questions/37063952/confused-by-the-behavior-of-tf-cond for
# a more detailed discussion.
def perturb_vars(original_scope, perturbed_scope):
all_vars = scope_vars(absolute_scope_name(original_scope))
all_perturbed_vars = scope_vars(absolute_scope_name(perturbed_scope))
assert len(all_vars) == len(all_perturbed_vars)
perturb_ops = []
for var, perturbed_var in zip(all_vars, all_perturbed_vars):
if param_noise_filter_func(perturbed_var):
# Perturb this variable.
op = tf.assign(perturbed_var, var + tf.random_normal(shape=tf.shape(var), mean=0., stddev=param_noise_scale))
else:
# Do not perturb, just assign.
op = tf.assign(perturbed_var, var)
perturb_ops.append(op)
assert len(perturb_ops) == len(all_vars)
return tf.group(*perturb_ops)
# Set up functionality to re-compute `param_noise_scale`. This perturbs yet another copy
# of the network and measures the effect of that perturbation in action space. If the perturbation
# is too big, reduce scale of perturbation, otherwise increase.
q_values_adaptive = q_func(observations_ph.get(), num_actions, scope="adaptive_q_func")
perturb_for_adaption = perturb_vars(original_scope="q_func", perturbed_scope="adaptive_q_func")
kl = tf.reduce_sum(tf.nn.softmax(q_values) * (tf.log(tf.nn.softmax(q_values)) - tf.log(tf.nn.softmax(q_values_adaptive))), axis=-1)
mean_kl = tf.reduce_mean(kl)
def update_scale():
with tf.control_dependencies([perturb_for_adaption]):
update_scale_expr = tf.cond(mean_kl < param_noise_threshold,
lambda: param_noise_scale.assign(param_noise_scale * 1.01),
lambda: param_noise_scale.assign(param_noise_scale / 1.01),
)
return update_scale_expr
# Functionality to update the threshold for parameter space noise.
update_param_noise_threshold_expr = param_noise_threshold.assign(tf.cond(update_param_noise_threshold_ph >= 0,
lambda: update_param_noise_threshold_ph, lambda: param_noise_threshold))
# Put everything together.
deterministic_actions = tf.argmax(q_values_perturbed, axis=1)
batch_size = tf.shape(observations_ph.get())[0]
random_actions = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=num_actions, dtype=tf.int64)
chose_random = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=1, dtype=tf.float32) < eps
stochastic_actions = tf.where(chose_random, random_actions, deterministic_actions)
output_actions = tf.cond(stochastic_ph, lambda: stochastic_actions, lambda: deterministic_actions)
update_eps_expr = eps.assign(tf.cond(update_eps_ph >= 0, lambda: update_eps_ph, lambda: eps))
updates = [
update_eps_expr,
tf.cond(reset_ph, lambda: perturb_vars(original_scope="q_func", perturbed_scope="perturbed_q_func"), lambda: tf.group(*[])),
tf.cond(update_param_noise_scale_ph, lambda: update_scale(), lambda: tf.Variable(0., trainable=False)),
update_param_noise_threshold_expr,
]
_act = U.function(inputs=[observations_ph, stochastic_ph, update_eps_ph, reset_ph, update_param_noise_threshold_ph, update_param_noise_scale_ph],
outputs=output_actions,
givens={update_eps_ph: -1.0, stochastic_ph: True, reset_ph: False, update_param_noise_threshold_ph: False, update_param_noise_scale_ph: False},
updates=updates)
def act(ob, reset=False, update_param_noise_threshold=False, update_param_noise_scale=False, stochastic=True, update_eps=-1):
return _act(ob, stochastic, update_eps, reset, update_param_noise_threshold, update_param_noise_scale)
return act
def build_train(n_step, make_obs_ph, q_func, num_actions, optimizer, grad_norm_clipping=None, gamma=1.0,
double_q=True, scope="deepq", reuse=None, param_noise=False, param_noise_filter_func=None):
"""Creates the train function:
Parameters
----------
make_obs_ph: str -> tf.placeholder or TfInput
a function that takes a name and creates a placeholder of input with that name
q_func: (tf.Variable, int, str, bool) -> tf.Variable
the model that takes the following inputs:
observation_in: object
the output of observation placeholder
num_actions: int
number of actions
scope: str
reuse: bool
should be passed to outer variable scope
and returns a tensor of shape (batch_size, num_actions) with values of every action.
num_actions: int
number of actions
reuse: bool
whether or not to reuse the graph variables
optimizer: tf.train.Optimizer
optimizer to use for the Q-learning objective.
grad_norm_clipping: float or None
clip gradient norms to this value. If None no clipping is performed.
gamma: float
discount rate.
double_q: bool
if true will use Double Q Learning (https://arxiv.org/abs/1509.06461).
In general it is a good idea to keep it enabled.
scope: str or VariableScope
optional scope for variable_scope.
reuse: bool or None
whether or not the variables should be reused. To be able to reuse the scope must be given.
param_noise: bool
whether or not to use parameter space noise (https://arxiv.org/abs/1706.01905)
param_noise_filter_func: tf.Variable -> bool
function that decides whether or not a variable should be perturbed. Only applicable
if param_noise is True. If set to None, default_param_noise_filter is used by default.
Returns
-------
act: (tf.Variable, bool, float) -> tf.Variable
function to select and action given observation.
` See the top of the file for details.
train: (object, np.array, np.array, object, np.array, np.array) -> np.array
optimize the error in Bellman's equation.
` See the top of the file for details.
update_target: () -> ()
copy the parameters from optimized Q function to the target Q function.
` See the top of the file for details.
debug: {str: function}
a bunch of functions to print debug data like q_values.
"""
if param_noise:
act_f = build_act_with_param_noise(make_obs_ph, q_func, num_actions, scope=scope, reuse=reuse,
param_noise_filter_func=param_noise_filter_func)
else:
act_f = build_act(make_obs_ph, q_func, num_actions, scope=scope, reuse=reuse)
with tf.variable_scope(scope, reuse=reuse):
# set up placeholders
obs_t_input = make_obs_ph("obs_t")
act_t_ph = tf.placeholder(tf.int32, [None], name="action")
rew_t_ph = tf.placeholder(tf.float32, shape=(None, n_step), name="reward")
obs_tp1_input = make_obs_ph("obs_tp1")
done_mask_ph = tf.placeholder(tf.float32, shape=(None, n_step), name="done")
importance_weights_ph = tf.placeholder(tf.float32, [None], name="weight")
# q network evaluation
q_t = q_func(obs_t_input.get(), num_actions, scope="q_func", reuse=True) # reuse parameters from act
q_func_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=tf.get_variable_scope().name + "/q_func")
# target q network evalution
q_tp1 = q_func(obs_tp1_input.get(), num_actions, scope="target_q_func")
target_q_func_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=tf.get_variable_scope().name + "/target_q_func")
# q scores for actions which we know were selected in the given state.
q_t_selected = tf.reduce_sum(q_t * tf.one_hot(act_t_ph, num_actions), 1)
# compute estimate of best possible value starting from state at t + 1
if double_q:
q_tp1_using_online_net = q_func(obs_tp1_input.get(), num_actions, scope="q_func", reuse=True)
q_tp1_best_using_online_net = tf.argmax(q_tp1_using_online_net, 1)
q_tp1_best = tf.reduce_sum(q_tp1 * tf.one_hot(q_tp1_best_using_online_net, num_actions), 1)
else:
q_tp1_best = tf.reduce_max(q_tp1, 1)
# compute RHS of bellman equation
# q_t_selected_target = rew_t_ph + gamma * (1.0 - done_mask_ph) * q_tp1_best
q_t_selected_target = tf.reduce_sum(tf.multiply([gamma ** (i) for i in range(n_step)] * (1 - done_mask_ph), rew_t_ph), axis=1)\
+ gamma ** n_step * (1 - done_mask_ph[:, -1]) * q_tp1_best
# compute the error (potentially clipped)
td_error = q_t_selected - tf.stop_gradient(q_t_selected_target)
errors = U.huber_loss(td_error)
weighted_error = tf.reduce_mean(importance_weights_ph * errors)
# compute optimization op (potentially with gradient clipping)
if grad_norm_clipping is not None:
gradients = optimizer.compute_gradients(weighted_error, var_list=q_func_vars)
for i, (grad, var) in enumerate(gradients):
if grad is not None:
gradients[i] = (tf.clip_by_norm(grad, grad_norm_clipping), var)
optimize_expr = optimizer.apply_gradients(gradients)
else:
optimize_expr = optimizer.minimize(weighted_error, var_list=q_func_vars)
# update_target_fn will be called periodically to copy Q network to target Q network
update_target_expr = []
for var, var_target in zip(sorted(q_func_vars, key=lambda v: v.name),
sorted(target_q_func_vars, key=lambda v: v.name)):
update_target_expr.append(var_target.assign(var))
update_target_expr = tf.group(*update_target_expr)
# Create callable functions
train = U.function(
inputs=[
obs_t_input,
act_t_ph,
rew_t_ph,
obs_tp1_input,
done_mask_ph,
importance_weights_ph
],
outputs=td_error,
updates=[optimize_expr]
)
update_target = U.function([], [], updates=[update_target_expr])
q_values = U.function([obs_t_input], q_t)
return act_f, train, update_target, {'q_values': q_values}
| 46.208426 | 168 | 0.669674 | import tensorflow as tf
import baselines.common.tf_util as U
def scope_vars(scope, trainable_only=False):
return tf.get_collection(
tf.GraphKeys.TRAINABLE_VARIABLES if trainable_only else tf.GraphKeys.GLOBAL_VARIABLES,
scope=scope if isinstance(scope, str) else scope.name
)
def scope_name():
return tf.get_variable_scope().name
def absolute_scope_name(relative_scope_name):
return scope_name() + "/" + relative_scope_name
def default_param_noise_filter(var):
if var not in tf.trainable_variables():
return False
if "fully_connected" in var.name:
return True
return False
def build_act(make_obs_ph, q_func, num_actions, scope="deepq", reuse=None):
with tf.variable_scope(scope, reuse=reuse):
observations_ph = make_obs_ph("observation")
stochastic_ph = tf.placeholder(tf.bool, (), name="stochastic")
update_eps_ph = tf.placeholder(tf.float32, (), name="update_eps")
eps = tf.get_variable("eps", (), initializer=tf.constant_initializer(0))
q_values = q_func(observations_ph.get(), num_actions, scope="q_func")
deterministic_actions = tf.argmax(q_values, axis=1)
batch_size = tf.shape(observations_ph.get())[0]
random_actions = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=num_actions, dtype=tf.int64)
chose_random = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=1, dtype=tf.float32) < eps
stochastic_actions = tf.where(chose_random, random_actions, deterministic_actions)
output_actions = tf.cond(stochastic_ph, lambda: stochastic_actions, lambda: deterministic_actions)
update_eps_expr = eps.assign(tf.cond(update_eps_ph >= 0, lambda: update_eps_ph, lambda: eps))
_act = U.function(inputs=[observations_ph, stochastic_ph, update_eps_ph],
outputs=output_actions,
givens={update_eps_ph: -1.0, stochastic_ph: True},
updates=[update_eps_expr])
def act(ob, stochastic=True, update_eps=-1):
return _act(ob, stochastic, update_eps)
return act
def build_act_with_param_noise(make_obs_ph, q_func, num_actions, scope="deepq", reuse=None, param_noise_filter_func=None):
if param_noise_filter_func is None:
param_noise_filter_func = default_param_noise_filter
with tf.variable_scope(scope, reuse=reuse):
observations_ph = make_obs_ph("observation")
stochastic_ph = tf.placeholder(tf.bool, (), name="stochastic")
update_eps_ph = tf.placeholder(tf.float32, (), name="update_eps")
update_param_noise_threshold_ph = tf.placeholder(tf.float32, (), name="update_param_noise_threshold")
update_param_noise_scale_ph = tf.placeholder(tf.bool, (), name="update_param_noise_scale")
reset_ph = tf.placeholder(tf.bool, (), name="reset")
eps = tf.get_variable("eps", (), initializer=tf.constant_initializer(0))
param_noise_scale = tf.get_variable("param_noise_scale", (), initializer=tf.constant_initializer(0.01), trainable=False)
param_noise_threshold = tf.get_variable("param_noise_threshold", (), initializer=tf.constant_initializer(0.05), trainable=False)
q_values = q_func(observations_ph.get(), num_actions, scope="q_func")
q_values_perturbed = q_func(observations_ph.get(), num_actions, scope="perturbed_q_func")
def perturb_vars(original_scope, perturbed_scope):
all_vars = scope_vars(absolute_scope_name(original_scope))
all_perturbed_vars = scope_vars(absolute_scope_name(perturbed_scope))
assert len(all_vars) == len(all_perturbed_vars)
perturb_ops = []
for var, perturbed_var in zip(all_vars, all_perturbed_vars):
if param_noise_filter_func(perturbed_var):
op = tf.assign(perturbed_var, var + tf.random_normal(shape=tf.shape(var), mean=0., stddev=param_noise_scale))
else:
op = tf.assign(perturbed_var, var)
perturb_ops.append(op)
assert len(perturb_ops) == len(all_vars)
return tf.group(*perturb_ops)
q_values_adaptive = q_func(observations_ph.get(), num_actions, scope="adaptive_q_func")
perturb_for_adaption = perturb_vars(original_scope="q_func", perturbed_scope="adaptive_q_func")
kl = tf.reduce_sum(tf.nn.softmax(q_values) * (tf.log(tf.nn.softmax(q_values)) - tf.log(tf.nn.softmax(q_values_adaptive))), axis=-1)
mean_kl = tf.reduce_mean(kl)
def update_scale():
with tf.control_dependencies([perturb_for_adaption]):
update_scale_expr = tf.cond(mean_kl < param_noise_threshold,
lambda: param_noise_scale.assign(param_noise_scale * 1.01),
lambda: param_noise_scale.assign(param_noise_scale / 1.01),
)
return update_scale_expr
update_param_noise_threshold_expr = param_noise_threshold.assign(tf.cond(update_param_noise_threshold_ph >= 0,
lambda: update_param_noise_threshold_ph, lambda: param_noise_threshold))
deterministic_actions = tf.argmax(q_values_perturbed, axis=1)
batch_size = tf.shape(observations_ph.get())[0]
random_actions = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=num_actions, dtype=tf.int64)
chose_random = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=1, dtype=tf.float32) < eps
stochastic_actions = tf.where(chose_random, random_actions, deterministic_actions)
output_actions = tf.cond(stochastic_ph, lambda: stochastic_actions, lambda: deterministic_actions)
update_eps_expr = eps.assign(tf.cond(update_eps_ph >= 0, lambda: update_eps_ph, lambda: eps))
updates = [
update_eps_expr,
tf.cond(reset_ph, lambda: perturb_vars(original_scope="q_func", perturbed_scope="perturbed_q_func"), lambda: tf.group(*[])),
tf.cond(update_param_noise_scale_ph, lambda: update_scale(), lambda: tf.Variable(0., trainable=False)),
update_param_noise_threshold_expr,
]
_act = U.function(inputs=[observations_ph, stochastic_ph, update_eps_ph, reset_ph, update_param_noise_threshold_ph, update_param_noise_scale_ph],
outputs=output_actions,
givens={update_eps_ph: -1.0, stochastic_ph: True, reset_ph: False, update_param_noise_threshold_ph: False, update_param_noise_scale_ph: False},
updates=updates)
def act(ob, reset=False, update_param_noise_threshold=False, update_param_noise_scale=False, stochastic=True, update_eps=-1):
return _act(ob, stochastic, update_eps, reset, update_param_noise_threshold, update_param_noise_scale)
return act
def build_train(n_step, make_obs_ph, q_func, num_actions, optimizer, grad_norm_clipping=None, gamma=1.0,
double_q=True, scope="deepq", reuse=None, param_noise=False, param_noise_filter_func=None):
if param_noise:
act_f = build_act_with_param_noise(make_obs_ph, q_func, num_actions, scope=scope, reuse=reuse,
param_noise_filter_func=param_noise_filter_func)
else:
act_f = build_act(make_obs_ph, q_func, num_actions, scope=scope, reuse=reuse)
with tf.variable_scope(scope, reuse=reuse):
obs_t_input = make_obs_ph("obs_t")
act_t_ph = tf.placeholder(tf.int32, [None], name="action")
rew_t_ph = tf.placeholder(tf.float32, shape=(None, n_step), name="reward")
obs_tp1_input = make_obs_ph("obs_tp1")
done_mask_ph = tf.placeholder(tf.float32, shape=(None, n_step), name="done")
importance_weights_ph = tf.placeholder(tf.float32, [None], name="weight")
q_t = q_func(obs_t_input.get(), num_actions, scope="q_func", reuse=True)
q_func_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=tf.get_variable_scope().name + "/q_func")
q_tp1 = q_func(obs_tp1_input.get(), num_actions, scope="target_q_func")
target_q_func_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=tf.get_variable_scope().name + "/target_q_func")
q_t_selected = tf.reduce_sum(q_t * tf.one_hot(act_t_ph, num_actions), 1)
if double_q:
q_tp1_using_online_net = q_func(obs_tp1_input.get(), num_actions, scope="q_func", reuse=True)
q_tp1_best_using_online_net = tf.argmax(q_tp1_using_online_net, 1)
q_tp1_best = tf.reduce_sum(q_tp1 * tf.one_hot(q_tp1_best_using_online_net, num_actions), 1)
else:
q_tp1_best = tf.reduce_max(q_tp1, 1)
q_t_selected_target = tf.reduce_sum(tf.multiply([gamma ** (i) for i in range(n_step)] * (1 - done_mask_ph), rew_t_ph), axis=1)\
+ gamma ** n_step * (1 - done_mask_ph[:, -1]) * q_tp1_best
td_error = q_t_selected - tf.stop_gradient(q_t_selected_target)
errors = U.huber_loss(td_error)
weighted_error = tf.reduce_mean(importance_weights_ph * errors)
if grad_norm_clipping is not None:
gradients = optimizer.compute_gradients(weighted_error, var_list=q_func_vars)
for i, (grad, var) in enumerate(gradients):
if grad is not None:
gradients[i] = (tf.clip_by_norm(grad, grad_norm_clipping), var)
optimize_expr = optimizer.apply_gradients(gradients)
else:
optimize_expr = optimizer.minimize(weighted_error, var_list=q_func_vars)
update_target_expr = []
for var, var_target in zip(sorted(q_func_vars, key=lambda v: v.name),
sorted(target_q_func_vars, key=lambda v: v.name)):
update_target_expr.append(var_target.assign(var))
update_target_expr = tf.group(*update_target_expr)
train = U.function(
inputs=[
obs_t_input,
act_t_ph,
rew_t_ph,
obs_tp1_input,
done_mask_ph,
importance_weights_ph
],
outputs=td_error,
updates=[optimize_expr]
)
update_target = U.function([], [], updates=[update_target_expr])
q_values = U.function([obs_t_input], q_t)
return act_f, train, update_target, {'q_values': q_values}
| true | true |
f7f76c59e08fe8569a149d156bf36cfecb763081 | 985 | py | Python | generator/group.py | AlreyQuin/python_training | 7b14723a61768cb5cbf58c3192e64fd9fc98d6ab | [
"Apache-2.0"
] | null | null | null | generator/group.py | AlreyQuin/python_training | 7b14723a61768cb5cbf58c3192e64fd9fc98d6ab | [
"Apache-2.0"
] | null | null | null | generator/group.py | AlreyQuin/python_training | 7b14723a61768cb5cbf58c3192e64fd9fc98d6ab | [
"Apache-2.0"
] | null | null | null | from model.group import Group
import random
import string
import os.path
import jsonpickle
import getopt
import sys
try:
opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of groups", "file"])
except getopt.GetoptError as err:
getopt.usage()
sys.exit(2)
n = 5
f = "data/groups.json"
for o, a in opts:
if o == "-n":
n = int(a)
elif o == "-f":
f = a
def random_string(prefix, maxlen):
symbols = string.ascii_letters + string.digits + " "*10
return prefix + "".join([random.choice(symbols) for i in range(random.randrange(maxlen))])
testdata = [Group(name="", header="", footer="")] + [
Group(name=random_string("name", 10), header=random_string("header", 20), footer=random_string("footer", 20)) for i in range(n)
]
file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", f)
with open(file, "w") as out:
jsonpickle.set_encoder_options("json", indent=2)
out.write(jsonpickle.encode(testdata)) | 24.625 | 135 | 0.647716 | from model.group import Group
import random
import string
import os.path
import jsonpickle
import getopt
import sys
try:
opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of groups", "file"])
except getopt.GetoptError as err:
getopt.usage()
sys.exit(2)
n = 5
f = "data/groups.json"
for o, a in opts:
if o == "-n":
n = int(a)
elif o == "-f":
f = a
def random_string(prefix, maxlen):
symbols = string.ascii_letters + string.digits + " "*10
return prefix + "".join([random.choice(symbols) for i in range(random.randrange(maxlen))])
testdata = [Group(name="", header="", footer="")] + [
Group(name=random_string("name", 10), header=random_string("header", 20), footer=random_string("footer", 20)) for i in range(n)
]
file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", f)
with open(file, "w") as out:
jsonpickle.set_encoder_options("json", indent=2)
out.write(jsonpickle.encode(testdata)) | true | true |
f7f76cd61bc4095247c0f7686a55424c769bfb33 | 14,393 | py | Python | projectq/ops/_qubit_operator_test.py | VirtueQuantumCloud/projectqX | fa484fe037a3a1772127bbd00fe4628ddba34611 | [
"Apache-2.0"
] | null | null | null | projectq/ops/_qubit_operator_test.py | VirtueQuantumCloud/projectqX | fa484fe037a3a1772127bbd00fe4628ddba34611 | [
"Apache-2.0"
] | null | null | null | projectq/ops/_qubit_operator_test.py | VirtueQuantumCloud/projectqX | fa484fe037a3a1772127bbd00fe4628ddba34611 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 ProjectQ-Framework (www.projectq.ch)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for _qubit_operator.py."""
import copy
import numpy
import pytest
from projectq.ops import _qubit_operator as qo
def test_pauli_operator_product_unchanged():
correct = {('I', 'I'): (1., 'I'),
('I', 'X'): (1., 'X'),
('X', 'I'): (1., 'X'),
('I', 'Y'): (1., 'Y'),
('Y', 'I'): (1., 'Y'),
('I', 'Z'): (1., 'Z'),
('Z', 'I'): (1., 'Z'),
('X', 'X'): (1., 'I'),
('Y', 'Y'): (1., 'I'),
('Z', 'Z'): (1., 'I'),
('X', 'Y'): (1.j, 'Z'),
('X', 'Z'): (-1.j, 'Y'),
('Y', 'X'): (-1.j, 'Z'),
('Y', 'Z'): (1.j, 'X'),
('Z', 'X'): (1.j, 'Y'),
('Z', 'Y'): (-1.j, 'X')}
assert qo._PAULI_OPERATOR_PRODUCTS == correct
def test_init_defaults():
loc_op = qo.QubitOperator()
assert len(loc_op.terms) == 0
@pytest.mark.parametrize("coefficient", [0.5, 0.6j, numpy.float64(2.303),
numpy.complex128(-1j)])
def test_init_tuple(coefficient):
loc_op = ((0, 'X'), (5, 'Y'), (6, 'Z'))
qubit_op = qo.QubitOperator(loc_op, coefficient)
assert len(qubit_op.terms) == 1
assert qubit_op.terms[loc_op] == coefficient
def test_init_str():
qubit_op = qo.QubitOperator('X0 Y5 Z12', -1.)
correct = ((0, 'X'), (5, 'Y'), (12, 'Z'))
assert correct in qubit_op.terms
assert qubit_op.terms[correct] == -1.0
def test_init_str_identity():
qubit_op = qo.QubitOperator('', 2.)
assert len(qubit_op.terms) == 1
assert () in qubit_op.terms
assert qubit_op.terms[()] == pytest.approx(2.)
def test_init_bad_term():
with pytest.raises(ValueError):
qubit_op = qo.QubitOperator(list())
def test_init_bad_coefficient():
with pytest.raises(ValueError):
qubit_op = qo.QubitOperator('X0', "0.5")
def test_init_bad_action():
with pytest.raises(ValueError):
qubit_op = qo.QubitOperator('Q0')
def test_init_bad_action_in_tuple():
with pytest.raises(ValueError):
qubit_op = qo.QubitOperator(((1, 'Q'),))
def test_init_bad_qubit_num_in_tuple():
with pytest.raises(qo.QubitOperatorError):
qubit_op = qo.QubitOperator((("1", 'X'),))
def test_init_bad_tuple():
with pytest.raises(ValueError):
qubit_op = qo.QubitOperator(((0, 1, 'X'),))
def test_init_bad_str():
with pytest.raises(ValueError):
qubit_op = qo.QubitOperator('X')
def test_init_bad_qubit_num():
with pytest.raises(qo.QubitOperatorError):
qubit_op = qo.QubitOperator('X-1')
def test_isclose_abs_tol():
a = qo.QubitOperator('X0', -1.)
b = qo.QubitOperator('X0', -1.05)
c = qo.QubitOperator('X0', -1.11)
assert a.isclose(b, rel_tol=1e-14, abs_tol=0.1)
assert not a.isclose(c, rel_tol=1e-14, abs_tol=0.1)
a = qo.QubitOperator('X0', -1.0j)
b = qo.QubitOperator('X0', -1.05j)
c = qo.QubitOperator('X0', -1.11j)
assert a.isclose(b, rel_tol=1e-14, abs_tol=0.1)
assert not a.isclose(c, rel_tol=1e-14, abs_tol=0.1)
def test_compress():
a = qo.QubitOperator('X0', .9e-12)
assert len(a.terms) == 1
a.compress()
assert len(a.terms) == 0
a = qo.QubitOperator('X0', 1. + 1j)
a.compress(.5)
assert len(a.terms) == 1
for term in a.terms:
assert a.terms[term] == 1. + 1j
a = qo.QubitOperator('X0', 1.1 + 1j)
a.compress(1.)
assert len(a.terms) == 1
for term in a.terms:
assert a.terms[term] == 1.1
a = qo.QubitOperator('X0', 1.1 + 1j) + qo.QubitOperator('X1', 1.e-6j)
a.compress()
assert len(a.terms) == 2
for term in a.terms:
assert isinstance(a.terms[term], complex)
a.compress(1.e-5)
assert len(a.terms) == 1
for term in a.terms:
assert isinstance(a.terms[term], complex)
a.compress(1.)
assert len(a.terms) == 1
for term in a.terms:
assert isinstance(a.terms[term], float)
def test_isclose_rel_tol():
a = qo.QubitOperator('X0', 1)
b = qo.QubitOperator('X0', 2)
assert a.isclose(b, rel_tol=2.5, abs_tol=0.1)
# Test symmetry
assert a.isclose(b, rel_tol=1, abs_tol=0.1)
assert b.isclose(a, rel_tol=1, abs_tol=0.1)
def test_isclose_zero_terms():
op = qo.QubitOperator(((1, 'Y'), (0, 'X')), -1j) * 0
assert op.isclose(qo.QubitOperator((), 0.0), rel_tol=1e-12, abs_tol=1e-12)
assert qo.QubitOperator((), 0.0).isclose(op, rel_tol=1e-12, abs_tol=1e-12)
def test_isclose_different_terms():
a = qo.QubitOperator(((1, 'Y'),), -0.1j)
b = qo.QubitOperator(((1, 'X'),), -0.1j)
assert a.isclose(b, rel_tol=1e-12, abs_tol=0.2)
assert not a.isclose(b, rel_tol=1e-12, abs_tol=0.05)
assert b.isclose(a, rel_tol=1e-12, abs_tol=0.2)
assert not b.isclose(a, rel_tol=1e-12, abs_tol=0.05)
def test_isclose_different_num_terms():
a = qo.QubitOperator(((1, 'Y'),), -0.1j)
a += qo.QubitOperator(((2, 'Y'),), -0.1j)
b = qo.QubitOperator(((1, 'X'),), -0.1j)
assert not b.isclose(a, rel_tol=1e-12, abs_tol=0.05)
assert not a.isclose(b, rel_tol=1e-12, abs_tol=0.05)
def test_imul_inplace():
qubit_op = qo.QubitOperator("X1")
prev_id = id(qubit_op)
qubit_op *= 3.
assert id(qubit_op) == prev_id
@pytest.mark.parametrize("multiplier", [0.5, 0.6j, numpy.float64(2.303),
numpy.complex128(-1j)])
def test_imul_scalar(multiplier):
loc_op = ((1, 'X'), (2, 'Y'))
qubit_op = qo.QubitOperator(loc_op)
qubit_op *= multiplier
assert qubit_op.terms[loc_op] == pytest.approx(multiplier)
def test_imul_qubit_op():
op1 = qo.QubitOperator(((0, 'Y'), (3, 'X'), (8, 'Z'), (11, 'X')), 3.j)
op2 = qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5)
op1 *= op2
correct_coefficient = 1.j * 3.0j * 0.5
correct_term = ((0, 'Y'), (1, 'X'), (3, 'Z'), (11, 'X'))
assert len(op1.terms) == 1
assert correct_term in op1.terms
def test_imul_qubit_op_2():
op3 = qo.QubitOperator(((1, 'Y'), (0, 'X')), -1j)
op4 = qo.QubitOperator(((1, 'Y'), (0, 'X'), (2, 'Z')), -1.5)
op3 *= op4
op4 *= op3
assert ((2, 'Z'),) in op3.terms
assert op3.terms[((2, 'Z'),)] == 1.5j
def test_imul_bidir():
op_a = qo.QubitOperator(((1, 'Y'), (0, 'X')), -1j)
op_b = qo.QubitOperator(((1, 'Y'), (0, 'X'), (2, 'Z')), -1.5)
op_a *= op_b
op_b *= op_a
assert ((2, 'Z'),) in op_a.terms
assert op_a.terms[((2, 'Z'),)] == 1.5j
assert ((0, 'X'), (1, 'Y')) in op_b.terms
assert op_b.terms[((0, 'X'), (1, 'Y'))] == -2.25j
def test_imul_bad_multiplier():
op = qo.QubitOperator(((1, 'Y'), (0, 'X')), -1j)
with pytest.raises(TypeError):
op *= "1"
def test_mul_by_scalarzero():
op = qo.QubitOperator(((1, 'Y'), (0, 'X')), -1j) * 0
assert ((0, 'X'), (1, 'Y')) in op.terms
assert op.terms[((0, 'X'), (1, 'Y'))] == pytest.approx(0.0)
def test_mul_bad_multiplier():
op = qo.QubitOperator(((1, 'Y'), (0, 'X')), -1j)
with pytest.raises(TypeError):
op = op * "0.5"
def test_mul_out_of_place():
op1 = qo.QubitOperator(((0, 'Y'), (3, 'X'), (8, 'Z'), (11, 'X')), 3.j)
op2 = qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5)
op3 = op1 * op2
correct_coefficient = 1.j * 3.0j * 0.5
correct_term = ((0, 'Y'), (1, 'X'), (3, 'Z'), (11, 'X'))
assert op1.isclose(qo.QubitOperator(
((0, 'Y'), (3, 'X'), (8, 'Z'), (11, 'X')), 3.j))
assert op2.isclose(qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5))
assert op3.isclose(qo.QubitOperator(correct_term, correct_coefficient))
def test_mul_npfloat64():
op = qo.QubitOperator(((1, 'X'), (3, 'Y')), 0.5)
res = op * numpy.float64(0.5)
assert res.isclose(qo.QubitOperator(((1, 'X'), (3, 'Y')), 0.5 * 0.5))
def test_mul_multiple_terms():
op = qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5)
op += qo.QubitOperator(((1, 'Z'), (3, 'X'), (8, 'Z')), 1.2)
op += qo.QubitOperator(((1, 'Z'), (3, 'Y'), (9, 'Z')), 1.4j)
res = op * op
correct = qo.QubitOperator((), 0.5**2 + 1.2**2 + 1.4j**2)
correct += qo.QubitOperator(((1, 'Y'), (3, 'Z')),
2j * 1j * 0.5 * 1.2)
assert res.isclose(correct)
@pytest.mark.parametrize("multiplier", [0.5, 0.6j, numpy.float64(2.303),
numpy.complex128(-1j)])
def test_rmul_scalar(multiplier):
op = qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5)
res1 = op * multiplier
res2 = multiplier * op
assert res1.isclose(res2)
def test_rmul_bad_multiplier():
op = qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5)
with pytest.raises(TypeError):
op = "0.5" * op
@pytest.mark.parametrize("divisor", [0.5, 0.6j, numpy.float64(2.303),
numpy.complex128(-1j), 2])
def test_truediv_and_div(divisor):
op = qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5)
op2 = copy.deepcopy(op)
original = copy.deepcopy(op)
res = op / divisor
res2 = op2.__div__(divisor) # To test python 2 version as well
correct = op * (1. / divisor)
assert res.isclose(correct)
assert res2.isclose(correct)
# Test if done out of place
assert op.isclose(original)
assert op2.isclose(original)
def test_truediv_bad_divisor():
op = qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5)
with pytest.raises(TypeError):
op = op / "0.5"
@pytest.mark.parametrize("divisor", [0.5, 0.6j, numpy.float64(2.303),
numpy.complex128(-1j), 2])
def test_itruediv_and_idiv(divisor):
op = qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5)
op2 = copy.deepcopy(op)
original = copy.deepcopy(op)
correct = op * (1. / divisor)
op /= divisor
op2.__idiv__(divisor) # To test python 2 version as well
assert op.isclose(correct)
assert op2.isclose(correct)
# Test if done in-place
assert not op.isclose(original)
assert not op2.isclose(original)
def test_itruediv_bad_divisor():
op = qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5)
with pytest.raises(TypeError):
op /= "0.5"
def test_iadd_cancellation():
term_a = ((1, 'X'), (3, 'Y'), (8, 'Z'))
term_b = ((1, 'X'), (3, 'Y'), (8, 'Z'))
a = qo.QubitOperator(term_a, 1.0)
a += qo.QubitOperator(term_b, -1.0)
assert len(a.terms) == 0
def test_iadd_different_term():
term_a = ((1, 'X'), (3, 'Y'), (8, 'Z'))
term_b = ((1, 'Z'), (3, 'Y'), (8, 'Z'))
a = qo.QubitOperator(term_a, 1.0)
a += qo.QubitOperator(term_b, 0.5)
assert len(a.terms) == 2
assert a.terms[term_a] == pytest.approx(1.0)
assert a.terms[term_b] == pytest.approx(0.5)
a += qo.QubitOperator(term_b, 0.5)
assert len(a.terms) == 2
assert a.terms[term_a] == pytest.approx(1.0)
assert a.terms[term_b] == pytest.approx(1.0)
def test_iadd_bad_addend():
op = qo.QubitOperator((), 1.0)
with pytest.raises(TypeError):
op += "0.5"
def test_add():
term_a = ((1, 'X'), (3, 'Y'), (8, 'Z'))
term_b = ((1, 'Z'), (3, 'Y'), (8, 'Z'))
a = qo.QubitOperator(term_a, 1.0)
b = qo.QubitOperator(term_b, 0.5)
res = a + b + b
assert len(res.terms) == 2
assert res.terms[term_a] == pytest.approx(1.0)
assert res.terms[term_b] == pytest.approx(1.0)
# Test out of place
assert a.isclose(qo.QubitOperator(term_a, 1.0))
assert b.isclose(qo.QubitOperator(term_b, 0.5))
def test_add_bad_addend():
op = qo.QubitOperator((), 1.0)
with pytest.raises(TypeError):
op = op + "0.5"
def test_sub():
term_a = ((1, 'X'), (3, 'Y'), (8, 'Z'))
term_b = ((1, 'Z'), (3, 'Y'), (8, 'Z'))
a = qo.QubitOperator(term_a, 1.0)
b = qo.QubitOperator(term_b, 0.5)
res = a - b
assert len(res.terms) == 2
assert res.terms[term_a] == pytest.approx(1.0)
assert res.terms[term_b] == pytest.approx(-0.5)
res2 = b - a
assert len(res2.terms) == 2
assert res2.terms[term_a] == pytest.approx(-1.0)
assert res2.terms[term_b] == pytest.approx(0.5)
def test_sub_bad_subtrahend():
op = qo.QubitOperator((), 1.0)
with pytest.raises(TypeError):
op = op - "0.5"
def test_isub_different_term():
term_a = ((1, 'X'), (3, 'Y'), (8, 'Z'))
term_b = ((1, 'Z'), (3, 'Y'), (8, 'Z'))
a = qo.QubitOperator(term_a, 1.0)
a -= qo.QubitOperator(term_b, 0.5)
assert len(a.terms) == 2
assert a.terms[term_a] == pytest.approx(1.0)
assert a.terms[term_b] == pytest.approx(-0.5)
a -= qo.QubitOperator(term_b, 0.5)
assert len(a.terms) == 2
assert a.terms[term_a] == pytest.approx(1.0)
assert a.terms[term_b] == pytest.approx(-1.0)
def test_isub_bad_addend():
op = qo.QubitOperator((), 1.0)
with pytest.raises(TypeError):
op -= "0.5"
def test_neg():
op = qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5)
-op
# out of place
assert op.isclose(qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5))
correct = -1.0 * op
assert correct.isclose(-op)
def test_str():
op = qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5)
assert str(op) == "0.5 X1 Y3 Z8"
op2 = qo.QubitOperator((), 2)
assert str(op2) == "2 I"
def test_str_empty():
op = qo.QubitOperator()
assert str(op) == '0'
def test_str_multiple_terms():
op = qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5)
op += qo.QubitOperator(((1, 'Y'), (3, 'Y'), (8, 'Z')), 0.6)
assert (str(op) == "0.5 X1 Y3 Z8 +\n0.6 Y1 Y3 Z8" or
str(op) == "0.6 Y1 Y3 Z8 +\n0.5 X1 Y3 Z8")
op2 = qo.QubitOperator((), 2)
assert str(op2) == "2 I"
def test_rep():
op = qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5)
# Not necessary, repr could do something in addition
assert repr(op) == str(op)
| 31.15368 | 78 | 0.564302 |
import copy
import numpy
import pytest
from projectq.ops import _qubit_operator as qo
def test_pauli_operator_product_unchanged():
correct = {('I', 'I'): (1., 'I'),
('I', 'X'): (1., 'X'),
('X', 'I'): (1., 'X'),
('I', 'Y'): (1., 'Y'),
('Y', 'I'): (1., 'Y'),
('I', 'Z'): (1., 'Z'),
('Z', 'I'): (1., 'Z'),
('X', 'X'): (1., 'I'),
('Y', 'Y'): (1., 'I'),
('Z', 'Z'): (1., 'I'),
('X', 'Y'): (1.j, 'Z'),
('X', 'Z'): (-1.j, 'Y'),
('Y', 'X'): (-1.j, 'Z'),
('Y', 'Z'): (1.j, 'X'),
('Z', 'X'): (1.j, 'Y'),
('Z', 'Y'): (-1.j, 'X')}
assert qo._PAULI_OPERATOR_PRODUCTS == correct
def test_init_defaults():
loc_op = qo.QubitOperator()
assert len(loc_op.terms) == 0
@pytest.mark.parametrize("coefficient", [0.5, 0.6j, numpy.float64(2.303),
numpy.complex128(-1j)])
def test_init_tuple(coefficient):
loc_op = ((0, 'X'), (5, 'Y'), (6, 'Z'))
qubit_op = qo.QubitOperator(loc_op, coefficient)
assert len(qubit_op.terms) == 1
assert qubit_op.terms[loc_op] == coefficient
def test_init_str():
qubit_op = qo.QubitOperator('X0 Y5 Z12', -1.)
correct = ((0, 'X'), (5, 'Y'), (12, 'Z'))
assert correct in qubit_op.terms
assert qubit_op.terms[correct] == -1.0
def test_init_str_identity():
qubit_op = qo.QubitOperator('', 2.)
assert len(qubit_op.terms) == 1
assert () in qubit_op.terms
assert qubit_op.terms[()] == pytest.approx(2.)
def test_init_bad_term():
with pytest.raises(ValueError):
qubit_op = qo.QubitOperator(list())
def test_init_bad_coefficient():
with pytest.raises(ValueError):
qubit_op = qo.QubitOperator('X0', "0.5")
def test_init_bad_action():
with pytest.raises(ValueError):
qubit_op = qo.QubitOperator('Q0')
def test_init_bad_action_in_tuple():
with pytest.raises(ValueError):
qubit_op = qo.QubitOperator(((1, 'Q'),))
def test_init_bad_qubit_num_in_tuple():
with pytest.raises(qo.QubitOperatorError):
qubit_op = qo.QubitOperator((("1", 'X'),))
def test_init_bad_tuple():
with pytest.raises(ValueError):
qubit_op = qo.QubitOperator(((0, 1, 'X'),))
def test_init_bad_str():
with pytest.raises(ValueError):
qubit_op = qo.QubitOperator('X')
def test_init_bad_qubit_num():
with pytest.raises(qo.QubitOperatorError):
qubit_op = qo.QubitOperator('X-1')
def test_isclose_abs_tol():
a = qo.QubitOperator('X0', -1.)
b = qo.QubitOperator('X0', -1.05)
c = qo.QubitOperator('X0', -1.11)
assert a.isclose(b, rel_tol=1e-14, abs_tol=0.1)
assert not a.isclose(c, rel_tol=1e-14, abs_tol=0.1)
a = qo.QubitOperator('X0', -1.0j)
b = qo.QubitOperator('X0', -1.05j)
c = qo.QubitOperator('X0', -1.11j)
assert a.isclose(b, rel_tol=1e-14, abs_tol=0.1)
assert not a.isclose(c, rel_tol=1e-14, abs_tol=0.1)
def test_compress():
a = qo.QubitOperator('X0', .9e-12)
assert len(a.terms) == 1
a.compress()
assert len(a.terms) == 0
a = qo.QubitOperator('X0', 1. + 1j)
a.compress(.5)
assert len(a.terms) == 1
for term in a.terms:
assert a.terms[term] == 1. + 1j
a = qo.QubitOperator('X0', 1.1 + 1j)
a.compress(1.)
assert len(a.terms) == 1
for term in a.terms:
assert a.terms[term] == 1.1
a = qo.QubitOperator('X0', 1.1 + 1j) + qo.QubitOperator('X1', 1.e-6j)
a.compress()
assert len(a.terms) == 2
for term in a.terms:
assert isinstance(a.terms[term], complex)
a.compress(1.e-5)
assert len(a.terms) == 1
for term in a.terms:
assert isinstance(a.terms[term], complex)
a.compress(1.)
assert len(a.terms) == 1
for term in a.terms:
assert isinstance(a.terms[term], float)
def test_isclose_rel_tol():
a = qo.QubitOperator('X0', 1)
b = qo.QubitOperator('X0', 2)
assert a.isclose(b, rel_tol=2.5, abs_tol=0.1)
assert a.isclose(b, rel_tol=1, abs_tol=0.1)
assert b.isclose(a, rel_tol=1, abs_tol=0.1)
def test_isclose_zero_terms():
op = qo.QubitOperator(((1, 'Y'), (0, 'X')), -1j) * 0
assert op.isclose(qo.QubitOperator((), 0.0), rel_tol=1e-12, abs_tol=1e-12)
assert qo.QubitOperator((), 0.0).isclose(op, rel_tol=1e-12, abs_tol=1e-12)
def test_isclose_different_terms():
a = qo.QubitOperator(((1, 'Y'),), -0.1j)
b = qo.QubitOperator(((1, 'X'),), -0.1j)
assert a.isclose(b, rel_tol=1e-12, abs_tol=0.2)
assert not a.isclose(b, rel_tol=1e-12, abs_tol=0.05)
assert b.isclose(a, rel_tol=1e-12, abs_tol=0.2)
assert not b.isclose(a, rel_tol=1e-12, abs_tol=0.05)
def test_isclose_different_num_terms():
a = qo.QubitOperator(((1, 'Y'),), -0.1j)
a += qo.QubitOperator(((2, 'Y'),), -0.1j)
b = qo.QubitOperator(((1, 'X'),), -0.1j)
assert not b.isclose(a, rel_tol=1e-12, abs_tol=0.05)
assert not a.isclose(b, rel_tol=1e-12, abs_tol=0.05)
def test_imul_inplace():
qubit_op = qo.QubitOperator("X1")
prev_id = id(qubit_op)
qubit_op *= 3.
assert id(qubit_op) == prev_id
@pytest.mark.parametrize("multiplier", [0.5, 0.6j, numpy.float64(2.303),
numpy.complex128(-1j)])
def test_imul_scalar(multiplier):
loc_op = ((1, 'X'), (2, 'Y'))
qubit_op = qo.QubitOperator(loc_op)
qubit_op *= multiplier
assert qubit_op.terms[loc_op] == pytest.approx(multiplier)
def test_imul_qubit_op():
op1 = qo.QubitOperator(((0, 'Y'), (3, 'X'), (8, 'Z'), (11, 'X')), 3.j)
op2 = qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5)
op1 *= op2
correct_coefficient = 1.j * 3.0j * 0.5
correct_term = ((0, 'Y'), (1, 'X'), (3, 'Z'), (11, 'X'))
assert len(op1.terms) == 1
assert correct_term in op1.terms
def test_imul_qubit_op_2():
op3 = qo.QubitOperator(((1, 'Y'), (0, 'X')), -1j)
op4 = qo.QubitOperator(((1, 'Y'), (0, 'X'), (2, 'Z')), -1.5)
op3 *= op4
op4 *= op3
assert ((2, 'Z'),) in op3.terms
assert op3.terms[((2, 'Z'),)] == 1.5j
def test_imul_bidir():
op_a = qo.QubitOperator(((1, 'Y'), (0, 'X')), -1j)
op_b = qo.QubitOperator(((1, 'Y'), (0, 'X'), (2, 'Z')), -1.5)
op_a *= op_b
op_b *= op_a
assert ((2, 'Z'),) in op_a.terms
assert op_a.terms[((2, 'Z'),)] == 1.5j
assert ((0, 'X'), (1, 'Y')) in op_b.terms
assert op_b.terms[((0, 'X'), (1, 'Y'))] == -2.25j
def test_imul_bad_multiplier():
op = qo.QubitOperator(((1, 'Y'), (0, 'X')), -1j)
with pytest.raises(TypeError):
op *= "1"
def test_mul_by_scalarzero():
op = qo.QubitOperator(((1, 'Y'), (0, 'X')), -1j) * 0
assert ((0, 'X'), (1, 'Y')) in op.terms
assert op.terms[((0, 'X'), (1, 'Y'))] == pytest.approx(0.0)
def test_mul_bad_multiplier():
op = qo.QubitOperator(((1, 'Y'), (0, 'X')), -1j)
with pytest.raises(TypeError):
op = op * "0.5"
def test_mul_out_of_place():
op1 = qo.QubitOperator(((0, 'Y'), (3, 'X'), (8, 'Z'), (11, 'X')), 3.j)
op2 = qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5)
op3 = op1 * op2
correct_coefficient = 1.j * 3.0j * 0.5
correct_term = ((0, 'Y'), (1, 'X'), (3, 'Z'), (11, 'X'))
assert op1.isclose(qo.QubitOperator(
((0, 'Y'), (3, 'X'), (8, 'Z'), (11, 'X')), 3.j))
assert op2.isclose(qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5))
assert op3.isclose(qo.QubitOperator(correct_term, correct_coefficient))
def test_mul_npfloat64():
op = qo.QubitOperator(((1, 'X'), (3, 'Y')), 0.5)
res = op * numpy.float64(0.5)
assert res.isclose(qo.QubitOperator(((1, 'X'), (3, 'Y')), 0.5 * 0.5))
def test_mul_multiple_terms():
op = qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5)
op += qo.QubitOperator(((1, 'Z'), (3, 'X'), (8, 'Z')), 1.2)
op += qo.QubitOperator(((1, 'Z'), (3, 'Y'), (9, 'Z')), 1.4j)
res = op * op
correct = qo.QubitOperator((), 0.5**2 + 1.2**2 + 1.4j**2)
correct += qo.QubitOperator(((1, 'Y'), (3, 'Z')),
2j * 1j * 0.5 * 1.2)
assert res.isclose(correct)
@pytest.mark.parametrize("multiplier", [0.5, 0.6j, numpy.float64(2.303),
numpy.complex128(-1j)])
def test_rmul_scalar(multiplier):
op = qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5)
res1 = op * multiplier
res2 = multiplier * op
assert res1.isclose(res2)
def test_rmul_bad_multiplier():
op = qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5)
with pytest.raises(TypeError):
op = "0.5" * op
@pytest.mark.parametrize("divisor", [0.5, 0.6j, numpy.float64(2.303),
numpy.complex128(-1j), 2])
def test_truediv_and_div(divisor):
op = qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5)
op2 = copy.deepcopy(op)
original = copy.deepcopy(op)
res = op / divisor
res2 = op2.__div__(divisor)
correct = op * (1. / divisor)
assert res.isclose(correct)
assert res2.isclose(correct)
assert op.isclose(original)
assert op2.isclose(original)
def test_truediv_bad_divisor():
op = qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5)
with pytest.raises(TypeError):
op = op / "0.5"
@pytest.mark.parametrize("divisor", [0.5, 0.6j, numpy.float64(2.303),
numpy.complex128(-1j), 2])
def test_itruediv_and_idiv(divisor):
op = qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5)
op2 = copy.deepcopy(op)
original = copy.deepcopy(op)
correct = op * (1. / divisor)
op /= divisor
op2.__idiv__(divisor)
assert op.isclose(correct)
assert op2.isclose(correct)
assert not op.isclose(original)
assert not op2.isclose(original)
def test_itruediv_bad_divisor():
op = qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5)
with pytest.raises(TypeError):
op /= "0.5"
def test_iadd_cancellation():
term_a = ((1, 'X'), (3, 'Y'), (8, 'Z'))
term_b = ((1, 'X'), (3, 'Y'), (8, 'Z'))
a = qo.QubitOperator(term_a, 1.0)
a += qo.QubitOperator(term_b, -1.0)
assert len(a.terms) == 0
def test_iadd_different_term():
term_a = ((1, 'X'), (3, 'Y'), (8, 'Z'))
term_b = ((1, 'Z'), (3, 'Y'), (8, 'Z'))
a = qo.QubitOperator(term_a, 1.0)
a += qo.QubitOperator(term_b, 0.5)
assert len(a.terms) == 2
assert a.terms[term_a] == pytest.approx(1.0)
assert a.terms[term_b] == pytest.approx(0.5)
a += qo.QubitOperator(term_b, 0.5)
assert len(a.terms) == 2
assert a.terms[term_a] == pytest.approx(1.0)
assert a.terms[term_b] == pytest.approx(1.0)
def test_iadd_bad_addend():
op = qo.QubitOperator((), 1.0)
with pytest.raises(TypeError):
op += "0.5"
def test_add():
term_a = ((1, 'X'), (3, 'Y'), (8, 'Z'))
term_b = ((1, 'Z'), (3, 'Y'), (8, 'Z'))
a = qo.QubitOperator(term_a, 1.0)
b = qo.QubitOperator(term_b, 0.5)
res = a + b + b
assert len(res.terms) == 2
assert res.terms[term_a] == pytest.approx(1.0)
assert res.terms[term_b] == pytest.approx(1.0)
assert a.isclose(qo.QubitOperator(term_a, 1.0))
assert b.isclose(qo.QubitOperator(term_b, 0.5))
def test_add_bad_addend():
op = qo.QubitOperator((), 1.0)
with pytest.raises(TypeError):
op = op + "0.5"
def test_sub():
term_a = ((1, 'X'), (3, 'Y'), (8, 'Z'))
term_b = ((1, 'Z'), (3, 'Y'), (8, 'Z'))
a = qo.QubitOperator(term_a, 1.0)
b = qo.QubitOperator(term_b, 0.5)
res = a - b
assert len(res.terms) == 2
assert res.terms[term_a] == pytest.approx(1.0)
assert res.terms[term_b] == pytest.approx(-0.5)
res2 = b - a
assert len(res2.terms) == 2
assert res2.terms[term_a] == pytest.approx(-1.0)
assert res2.terms[term_b] == pytest.approx(0.5)
def test_sub_bad_subtrahend():
op = qo.QubitOperator((), 1.0)
with pytest.raises(TypeError):
op = op - "0.5"
def test_isub_different_term():
term_a = ((1, 'X'), (3, 'Y'), (8, 'Z'))
term_b = ((1, 'Z'), (3, 'Y'), (8, 'Z'))
a = qo.QubitOperator(term_a, 1.0)
a -= qo.QubitOperator(term_b, 0.5)
assert len(a.terms) == 2
assert a.terms[term_a] == pytest.approx(1.0)
assert a.terms[term_b] == pytest.approx(-0.5)
a -= qo.QubitOperator(term_b, 0.5)
assert len(a.terms) == 2
assert a.terms[term_a] == pytest.approx(1.0)
assert a.terms[term_b] == pytest.approx(-1.0)
def test_isub_bad_addend():
op = qo.QubitOperator((), 1.0)
with pytest.raises(TypeError):
op -= "0.5"
def test_neg():
op = qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5)
-op
assert op.isclose(qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5))
correct = -1.0 * op
assert correct.isclose(-op)
def test_str():
op = qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5)
assert str(op) == "0.5 X1 Y3 Z8"
op2 = qo.QubitOperator((), 2)
assert str(op2) == "2 I"
def test_str_empty():
op = qo.QubitOperator()
assert str(op) == '0'
def test_str_multiple_terms():
op = qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5)
op += qo.QubitOperator(((1, 'Y'), (3, 'Y'), (8, 'Z')), 0.6)
assert (str(op) == "0.5 X1 Y3 Z8 +\n0.6 Y1 Y3 Z8" or
str(op) == "0.6 Y1 Y3 Z8 +\n0.5 X1 Y3 Z8")
op2 = qo.QubitOperator((), 2)
assert str(op2) == "2 I"
def test_rep():
op = qo.QubitOperator(((1, 'X'), (3, 'Y'), (8, 'Z')), 0.5)
assert repr(op) == str(op)
| true | true |
f7f76dcfbd7015d65610d16e50728f5601080041 | 326 | py | Python | bann/b_frameworks/pytorch/p_activation_fun/p_activation_fun_enum.py | arturOnRails/BANN | 027af04349304941fb73c2ede502aca4b76f1ad1 | [
"MIT"
] | null | null | null | bann/b_frameworks/pytorch/p_activation_fun/p_activation_fun_enum.py | arturOnRails/BANN | 027af04349304941fb73c2ede502aca4b76f1ad1 | [
"MIT"
] | null | null | null | bann/b_frameworks/pytorch/p_activation_fun/p_activation_fun_enum.py | arturOnRails/BANN | 027af04349304941fb73c2ede502aca4b76f1ad1 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
""".. moduleauthor:: Artur Lissin"""
from enum import Enum
from typing import final
@final
class PActId(Enum):
LOGSOFTMAX = 'LogSoftMax'
NONE = 'NoLayer'
SOFTMAX = 'SoftMax'
RELU = 'ReLu'
ELU = 'ELu'
LRELU = 'LReLu'
SILU = 'SiLu'
TANH = 'Tanh'
SIGMOID = 'Sigmoid'
| 18.111111 | 36 | 0.58589 |
from enum import Enum
from typing import final
@final
class PActId(Enum):
LOGSOFTMAX = 'LogSoftMax'
NONE = 'NoLayer'
SOFTMAX = 'SoftMax'
RELU = 'ReLu'
ELU = 'ELu'
LRELU = 'LReLu'
SILU = 'SiLu'
TANH = 'Tanh'
SIGMOID = 'Sigmoid'
| true | true |
f7f76e0fc7a709ebf9eb534fcbcfe6f125ceb1ce | 1,416 | py | Python | src/Miscellaneous/Parser/ParserClass.py | edouard-lebas/CryptoGenerator | d43f2b3fa472493f49015e8402e382681692a63c | [
"MIT"
] | null | null | null | src/Miscellaneous/Parser/ParserClass.py | edouard-lebas/CryptoGenerator | d43f2b3fa472493f49015e8402e382681692a63c | [
"MIT"
] | null | null | null | src/Miscellaneous/Parser/ParserClass.py | edouard-lebas/CryptoGenerator | d43f2b3fa472493f49015e8402e382681692a63c | [
"MIT"
] | null | null | null | import argparse
class ParserClass:
def __init__(self):
self.parser = argparse.ArgumentParser(description="Crypto / Hash Translator", usage="\npython CryptoHashTranslator.py --translate --text textToTranslate --md5 \npython CryptoHashTranslator.py --generate --text textToGenerate --md5")
self.setArguments()
def generateArgs(self):
args = []
args.append(["--md5","Use md5",'store_true'])
args.append(["--sha1","Use sha1",'store_true'])
args.append(["--sha256","Use sha256",'store_true'])
args.append(["--sha384","Use sha384",'store_true'])
args.append(["--sha512","Use sha512",'store_true'])
args.append(["--cesar","Use Cesar",'store_true'])
args.append(["--vigenere","Use Vigenere",'store_true'])
args.append(["--translate","Used to translate text to Hahs/Crypto",'store_true'])
args.append(["--generate","Used to generate text to Hahs/Crypto",'store_true'])
args.append(["--text","Pass the text to generate / translate"])
return args
def setArguments(self):
for arg in self.generateArgs():
if len(arg) == 3:
self.parser.add_argument(arg[0],help=arg[1],action=arg[2])
else:
self.parser.add_argument(arg[0],help=arg[1])
self.parsed = self.parser.parse_args()
def getParsed(self):
return self.parsed
| 42.909091 | 240 | 0.617938 | import argparse
class ParserClass:
def __init__(self):
self.parser = argparse.ArgumentParser(description="Crypto / Hash Translator", usage="\npython CryptoHashTranslator.py --translate --text textToTranslate --md5 \npython CryptoHashTranslator.py --generate --text textToGenerate --md5")
self.setArguments()
def generateArgs(self):
args = []
args.append(["--md5","Use md5",'store_true'])
args.append(["--sha1","Use sha1",'store_true'])
args.append(["--sha256","Use sha256",'store_true'])
args.append(["--sha384","Use sha384",'store_true'])
args.append(["--sha512","Use sha512",'store_true'])
args.append(["--cesar","Use Cesar",'store_true'])
args.append(["--vigenere","Use Vigenere",'store_true'])
args.append(["--translate","Used to translate text to Hahs/Crypto",'store_true'])
args.append(["--generate","Used to generate text to Hahs/Crypto",'store_true'])
args.append(["--text","Pass the text to generate / translate"])
return args
def setArguments(self):
for arg in self.generateArgs():
if len(arg) == 3:
self.parser.add_argument(arg[0],help=arg[1],action=arg[2])
else:
self.parser.add_argument(arg[0],help=arg[1])
self.parsed = self.parser.parse_args()
def getParsed(self):
return self.parsed
| true | true |
f7f76e61faf32cac7de3d02a9884550a03a23708 | 211 | py | Python | tests/test_version.py | dataops-tk/tapdance | 9ba09ab1625bb3bb49ca7cc4fe659402280b038f | [
"MIT"
] | 8 | 2020-04-23T05:45:38.000Z | 2020-08-29T23:26:58.000Z | tests/test_version.py | aaronsteers/tapdance | 9ba09ab1625bb3bb49ca7cc4fe659402280b038f | [
"MIT"
] | 7 | 2020-05-11T17:36:59.000Z | 2021-02-10T20:48:30.000Z | tests/test_version.py | dataops-tk/tapdance | 9ba09ab1625bb3bb49ca7cc4fe659402280b038f | [
"MIT"
] | null | null | null | """Test Version Prints"""
from tapdance import cli
def test_print_version():
"""Test the ability to print a version string"""
cli.print_version()
if __name__ == "__main__":
test_print_version()
| 16.230769 | 52 | 0.691943 |
from tapdance import cli
def test_print_version():
cli.print_version()
if __name__ == "__main__":
test_print_version()
| true | true |
f7f76ee4ab2c9f7027d85ae0fa5e6d857e647a38 | 675 | py | Python | easydbo/main/cli/select/alias.py | kinkalow/easydbo | a1925e130f74d03b77683b7906d5ca46eff56167 | [
"MIT"
] | 1 | 2021-12-16T03:11:06.000Z | 2021-12-16T03:11:06.000Z | easydbo/main/cli/select/alias.py | kinkalow/easydbo | a1925e130f74d03b77683b7906d5ca46eff56167 | [
"MIT"
] | null | null | null | easydbo/main/cli/select/alias.py | kinkalow/easydbo | a1925e130f74d03b77683b7906d5ca46eff56167 | [
"MIT"
] | null | null | null | from easydbo.init.alias import AliasManagerCLI
from easydbo.output.print_ import SimplePrint as SP
def main(arguments, configs, tableop, dbop):
aliasmgr = AliasManagerCLI()
# Check
tgt_alias_name = arguments.name
if not tgt_alias_name:
SP.error('--alias option is required at this time')
aliasmgr.check_alias_name(tgt_alias_name)
# Access database
dbop.authenticate()
tgt_alias = aliasmgr.get_alias_by_name(tgt_alias_name)
tgt_cmd = tgt_alias.query
rows = dbop.select_by_cmd(tgt_cmd) # Perform this method first
columns = dbop.get_current_columns()
title = dbop.get_current_query()
return title, columns, rows
| 30.681818 | 67 | 0.734815 | from easydbo.init.alias import AliasManagerCLI
from easydbo.output.print_ import SimplePrint as SP
def main(arguments, configs, tableop, dbop):
aliasmgr = AliasManagerCLI()
tgt_alias_name = arguments.name
if not tgt_alias_name:
SP.error('--alias option is required at this time')
aliasmgr.check_alias_name(tgt_alias_name)
dbop.authenticate()
tgt_alias = aliasmgr.get_alias_by_name(tgt_alias_name)
tgt_cmd = tgt_alias.query
rows = dbop.select_by_cmd(tgt_cmd)
columns = dbop.get_current_columns()
title = dbop.get_current_query()
return title, columns, rows
| true | true |
f7f76ee957473f9252e6a9858c5daa7ac006e93b | 1,958 | py | Python | openaerostruct/structures/tests/test_vonmises_wingbox.py | EricUrbineer/OpenAeroStruct | 26c37a0e86074517680405687824e27b3b2caaec | [
"Apache-2.0"
] | 4 | 2020-09-15T23:24:15.000Z | 2021-01-11T19:59:39.000Z | openaerostruct/structures/tests/test_vonmises_wingbox.py | EricUrbineer/OpenAeroStruct | 26c37a0e86074517680405687824e27b3b2caaec | [
"Apache-2.0"
] | null | null | null | openaerostruct/structures/tests/test_vonmises_wingbox.py | EricUrbineer/OpenAeroStruct | 26c37a0e86074517680405687824e27b3b2caaec | [
"Apache-2.0"
] | 2 | 2020-08-25T16:38:14.000Z | 2020-12-03T09:49:45.000Z | import unittest
import numpy as np
from openmdao.api import Group, IndepVarComp
from openaerostruct.structures.vonmises_wingbox import VonMisesWingbox
from openaerostruct.utils.testing import run_test, get_default_surfaces
class Test(unittest.TestCase):
def test(self):
surface = get_default_surfaces()[0]
# turn down some of these properties, so the absolute deriv error isn't magnified
surface['E'] = 7
surface['G'] = 3
surface['yield'] = .02
surface['strength_factor_for_upper_skin'] = 1.0
comp = VonMisesWingbox(surface=surface)
group = Group()
indep_var_comp = IndepVarComp()
ny = surface['mesh'].shape[1]
nodesval = np.array([[0., 0., 0.],
[0., 1., 0.],
[0., 2., 0.],
[0., 3., 0.]])
indep_var_comp.add_output('nodes', val=nodesval)
indep_var_comp.add_output('disp', val=np.ones((ny, 6)))
indep_var_comp.add_output('Qz', val=np.ones((ny - 1)))
indep_var_comp.add_output('Iz', val=np.ones((ny - 1)))
indep_var_comp.add_output('J', val=np.ones((ny - 1)))
indep_var_comp.add_output('A_enc', val=np.ones((ny - 1)))
indep_var_comp.add_output('spar_thickness', val=np.ones((ny - 1)))
indep_var_comp.add_output('skin_thickness', val=np.ones((ny - 1)))
indep_var_comp.add_output('htop', val=np.ones((ny - 1)))
indep_var_comp.add_output('hbottom', val=np.ones((ny - 1)))
indep_var_comp.add_output('hfront', val=np.ones((ny - 1)))
indep_var_comp.add_output('hrear', val=np.ones((ny - 1)))
group.add_subsystem('indep_var_comp', indep_var_comp, promotes=['*'])
group.add_subsystem('vonmises_wingbox', comp, promotes=['*'])
run_test(self, group, complex_flag=True, step=1e-8, atol=2e-5, compact_print=True)
if __name__ == '__main__':
unittest.main()
| 36.259259 | 91 | 0.615424 | import unittest
import numpy as np
from openmdao.api import Group, IndepVarComp
from openaerostruct.structures.vonmises_wingbox import VonMisesWingbox
from openaerostruct.utils.testing import run_test, get_default_surfaces
class Test(unittest.TestCase):
def test(self):
surface = get_default_surfaces()[0]
surface['E'] = 7
surface['G'] = 3
surface['yield'] = .02
surface['strength_factor_for_upper_skin'] = 1.0
comp = VonMisesWingbox(surface=surface)
group = Group()
indep_var_comp = IndepVarComp()
ny = surface['mesh'].shape[1]
nodesval = np.array([[0., 0., 0.],
[0., 1., 0.],
[0., 2., 0.],
[0., 3., 0.]])
indep_var_comp.add_output('nodes', val=nodesval)
indep_var_comp.add_output('disp', val=np.ones((ny, 6)))
indep_var_comp.add_output('Qz', val=np.ones((ny - 1)))
indep_var_comp.add_output('Iz', val=np.ones((ny - 1)))
indep_var_comp.add_output('J', val=np.ones((ny - 1)))
indep_var_comp.add_output('A_enc', val=np.ones((ny - 1)))
indep_var_comp.add_output('spar_thickness', val=np.ones((ny - 1)))
indep_var_comp.add_output('skin_thickness', val=np.ones((ny - 1)))
indep_var_comp.add_output('htop', val=np.ones((ny - 1)))
indep_var_comp.add_output('hbottom', val=np.ones((ny - 1)))
indep_var_comp.add_output('hfront', val=np.ones((ny - 1)))
indep_var_comp.add_output('hrear', val=np.ones((ny - 1)))
group.add_subsystem('indep_var_comp', indep_var_comp, promotes=['*'])
group.add_subsystem('vonmises_wingbox', comp, promotes=['*'])
run_test(self, group, complex_flag=True, step=1e-8, atol=2e-5, compact_print=True)
if __name__ == '__main__':
unittest.main()
| true | true |
f7f76fce8fecfca7f63f370a75e89d265e1f2469 | 4,607 | py | Python | python/otimage/deformations.py | evarol/ot_tracking | cddf27558fa5679ef06aad6a0945c34db0209ee7 | [
"MIT"
] | 1 | 2020-04-05T17:01:39.000Z | 2020-04-05T17:01:39.000Z | python/otimage/deformations.py | evarol/ot_tracking | cddf27558fa5679ef06aad6a0945c34db0209ee7 | [
"MIT"
] | null | null | null | python/otimage/deformations.py | evarol/ot_tracking | cddf27558fa5679ef06aad6a0945c34db0209ee7 | [
"MIT"
] | 1 | 2021-06-03T16:48:45.000Z | 2021-06-03T16:48:45.000Z | """Deformation models for worm registration"""
from abc import ABC, abstractmethod
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline
class DeformationModel(ABC):
@abstractmethod
def fit(self, x, y, weights):
pass
@abstractmethod
def predict(self, x):
pass
class Affine(DeformationModel):
def __init__(self):
self._model = Pipeline([
('poly', PolynomialFeatures(degree=1, include_bias=True)),
('linear', LinearRegression(fit_intercept=False))
])
@property
def beta(self):
return self._model.named_steps['linear'].coef_
def fit(self, x, y, weights):
self._model.fit(x, y, linear__sample_weight=weights)
return self
def predict(self, x):
return self._model.predict(x)
def det_jac(self, x):
mtx = self.beta[:, 1:4]
det = np.linalg.det(mtx)
return np.full((x.shape[0], 1), det)
class Quadratic(DeformationModel):
def __init__(self):
self._model = Pipeline([
('poly', PolynomialFeatures(degree=2, include_bias=True)),
('linear', LinearRegression(fit_intercept=False))
])
@property
def beta(self):
return self._model.named_steps['linear'].coef_
def fit(self, x, y, weights):
self._model.fit(x, y, linear__sample_weight=weights)
return self
def predict(self, x):
return self._model.predict(x)
def _compute_jac(self, x):
x0 = x[0]
x1 = x[1]
x2 = x[2]
d_phi = np.array([
[0, 0, 0 ],
[1, 0, 0 ],
[0, 1, 0 ],
[0, 0, 1 ],
[2 * x0, 0, 0 ],
[x1, x0, 0 ],
[x2, 0, x0 ],
[0, 2 * x1, 0 ],
[0, x2, x1 ],
[0, 0, 2 * x2 ],
])
return self.beta @ d_phi
def det_jac(self, x):
det_vals = [np.linalg.det(self._compute_jac(x_i)) for x_i in x]
return np.array(det_vals).reshape(-1, 1)
class Cubic(DeformationModel):
def __init__(self):
self._model = Pipeline([
('poly', PolynomialFeatures(degree=3, include_bias=True)),
('linear', LinearRegression(fit_intercept=False))
])
@property
def beta(self):
return self._model.named_steps['linear'].coef_
def fit(self, x, y, weights):
self._model.fit(x, y, linear__sample_weight=weights)
return self
def predict(self, x):
return self._model.predict(x)
def _compute_jac(self, x):
x0 = x[0]
x1 = x[1]
x2 = x[2]
x0_2 = x0 ** 2
x1_2 = x1 ** 2
x2_2 = x2 ** 2
x0_x1 = x0 * x1
x1_x2 = x1 * x2
x0_x2 = x0 * x2
d_phi = np.array([
[0, 0, 0 ],
[1, 0, 0 ],
[0, 1, 0 ],
[0, 0, 1 ],
[2 * x0, 0, 0 ],
[x1, x0, 0 ],
[x2, 0, x0 ],
[0, 2 * x1, 0 ],
[0, x2, x1 ],
[0, 0, 2 * x2 ],
[3 * x0_2, 0, 0 ],
[2 * x0_x1, x0_2, 0 ],
[2 * x0_x2, 0, x0_2 ],
[x1_2, 2 * x0_x1, 0 ],
[x1_x2, x0_x2, x0_x1 ],
[x2_2, 0, 2 * x0_x2],
[0, 3 * x1_2, 0 ],
[0, 2 * x1_x2, x1_2 ],
[0, x2_2, 2 * x1_x2],
[0, 0, 3 * x2_2 ],
])
return self.beta @ d_phi
def det_jac(self, x):
det_vals = [np.linalg.det(self._compute_jac(x_i)) for x_i in x]
return np.array(det_vals).reshape(-1, 1)
| 26.477011 | 71 | 0.408292 |
from abc import ABC, abstractmethod
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline
class DeformationModel(ABC):
@abstractmethod
def fit(self, x, y, weights):
pass
@abstractmethod
def predict(self, x):
pass
class Affine(DeformationModel):
def __init__(self):
self._model = Pipeline([
('poly', PolynomialFeatures(degree=1, include_bias=True)),
('linear', LinearRegression(fit_intercept=False))
])
@property
def beta(self):
return self._model.named_steps['linear'].coef_
def fit(self, x, y, weights):
self._model.fit(x, y, linear__sample_weight=weights)
return self
def predict(self, x):
return self._model.predict(x)
def det_jac(self, x):
mtx = self.beta[:, 1:4]
det = np.linalg.det(mtx)
return np.full((x.shape[0], 1), det)
class Quadratic(DeformationModel):
def __init__(self):
self._model = Pipeline([
('poly', PolynomialFeatures(degree=2, include_bias=True)),
('linear', LinearRegression(fit_intercept=False))
])
@property
def beta(self):
return self._model.named_steps['linear'].coef_
def fit(self, x, y, weights):
self._model.fit(x, y, linear__sample_weight=weights)
return self
def predict(self, x):
return self._model.predict(x)
def _compute_jac(self, x):
x0 = x[0]
x1 = x[1]
x2 = x[2]
d_phi = np.array([
[0, 0, 0 ],
[1, 0, 0 ],
[0, 1, 0 ],
[0, 0, 1 ],
[2 * x0, 0, 0 ],
[x1, x0, 0 ],
[x2, 0, x0 ],
[0, 2 * x1, 0 ],
[0, x2, x1 ],
[0, 0, 2 * x2 ],
])
return self.beta @ d_phi
def det_jac(self, x):
det_vals = [np.linalg.det(self._compute_jac(x_i)) for x_i in x]
return np.array(det_vals).reshape(-1, 1)
class Cubic(DeformationModel):
def __init__(self):
self._model = Pipeline([
('poly', PolynomialFeatures(degree=3, include_bias=True)),
('linear', LinearRegression(fit_intercept=False))
])
@property
def beta(self):
return self._model.named_steps['linear'].coef_
def fit(self, x, y, weights):
self._model.fit(x, y, linear__sample_weight=weights)
return self
def predict(self, x):
return self._model.predict(x)
def _compute_jac(self, x):
x0 = x[0]
x1 = x[1]
x2 = x[2]
x0_2 = x0 ** 2
x1_2 = x1 ** 2
x2_2 = x2 ** 2
x0_x1 = x0 * x1
x1_x2 = x1 * x2
x0_x2 = x0 * x2
d_phi = np.array([
[0, 0, 0 ],
[1, 0, 0 ],
[0, 1, 0 ],
[0, 0, 1 ],
[2 * x0, 0, 0 ],
[x1, x0, 0 ],
[x2, 0, x0 ],
[0, 2 * x1, 0 ],
[0, x2, x1 ],
[0, 0, 2 * x2 ],
[3 * x0_2, 0, 0 ],
[2 * x0_x1, x0_2, 0 ],
[2 * x0_x2, 0, x0_2 ],
[x1_2, 2 * x0_x1, 0 ],
[x1_x2, x0_x2, x0_x1 ],
[x2_2, 0, 2 * x0_x2],
[0, 3 * x1_2, 0 ],
[0, 2 * x1_x2, x1_2 ],
[0, x2_2, 2 * x1_x2],
[0, 0, 3 * x2_2 ],
])
return self.beta @ d_phi
def det_jac(self, x):
det_vals = [np.linalg.det(self._compute_jac(x_i)) for x_i in x]
return np.array(det_vals).reshape(-1, 1)
| true | true |
f7f7704b4a1f14593200d6d01e141ad1264d40b9 | 1,866 | py | Python | doepy/Test/doepy/read_write.py | Sigmun/doepy | 091df7e3cc8efd5e604fa99e40c4ca5f7f49de25 | [
"MIT"
] | 92 | 2019-07-22T17:34:34.000Z | 2022-03-29T08:58:22.000Z | doepy/Test/doepy/read_write.py | Sigmun/doepy | 091df7e3cc8efd5e604fa99e40c4ca5f7f49de25 | [
"MIT"
] | 10 | 2020-02-14T11:27:15.000Z | 2022-02-13T22:07:33.000Z | doepy/Test/doepy/read_write.py | Sigmun/doepy | 091df7e3cc8efd5e604fa99e40c4ca5f7f49de25 | [
"MIT"
] | 26 | 2019-08-15T14:18:55.000Z | 2022-03-31T15:48:10.000Z | import csv
# ==========================================================
# Function for reading a CSV file into a dictionary format
# ==========================================================
def read_variables_csv(csvfile):
"""
Builds a Python dictionary object from an input CSV file.
Helper function to read a CSV file on the disk, where user stores the limits/ranges of the process variables.
Output of this function can be used directly with any DOE builder function
The CSV file should be in the same directory
"""
dict_key={}
try:
with open(csvfile) as f:
reader = csv.DictReader(f)
fields = reader.fieldnames
for field in fields:
lst=[]
with open(csvfile) as f:
reader = csv.DictReader(f)
for row in reader:
lst.append(float(row[field]))
dict_key[field]=lst
return dict_key
except:
print("Error in reading the specified file from the disk. Please make sure it is in current directory.")
return -1
# ===============================================================
# Function for writing the design matrix into an output CSV file
# ===============================================================
def write_csv(df,filename,rounding=2):
"""
Writes a CSV file on to the disk from the computed design matrix
filename: To be specified by the user. Just a name is fine. .CSV extension will be added automatically.
rounding: Number up to which decimal the output will be rounded off. Often needed for practical DOE plans.
"""
df_copy = round(df,rounding)
try:
if '.csv' not in filename:
filename=filename+'.csv'
df_copy.to_csv(filename,index=False)
except:
return -1 | 38.875 | 113 | 0.543408 | import csv
def read_variables_csv(csvfile):
dict_key={}
try:
with open(csvfile) as f:
reader = csv.DictReader(f)
fields = reader.fieldnames
for field in fields:
lst=[]
with open(csvfile) as f:
reader = csv.DictReader(f)
for row in reader:
lst.append(float(row[field]))
dict_key[field]=lst
return dict_key
except:
print("Error in reading the specified file from the disk. Please make sure it is in current directory.")
return -1
def write_csv(df,filename,rounding=2):
df_copy = round(df,rounding)
try:
if '.csv' not in filename:
filename=filename+'.csv'
df_copy.to_csv(filename,index=False)
except:
return -1 | true | true |
f7f770cfaffd2ea33312dd398bd03d14defe7aa1 | 27,386 | py | Python | lib/dev_server_wrapper.py | hustwei/chromite | 10eb79abeb64e859362546214b7e039096ac9830 | [
"BSD-3-Clause"
] | null | null | null | lib/dev_server_wrapper.py | hustwei/chromite | 10eb79abeb64e859362546214b7e039096ac9830 | [
"BSD-3-Clause"
] | null | null | null | lib/dev_server_wrapper.py | hustwei/chromite | 10eb79abeb64e859362546214b7e039096ac9830 | [
"BSD-3-Clause"
] | null | null | null | # Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Module containing methods and classes to interact with a devserver instance.
"""
from __future__ import print_function
import multiprocessing
import os
import socket
import shutil
import sys
import tempfile
import httplib
import urllib2
import urlparse
from chromite.lib import constants
from chromite.cli import command
from chromite.lib import cros_build_lib
from chromite.lib import cros_logging as logging
from chromite.lib import gs
from chromite.lib import osutils
from chromite.lib import path_util
from chromite.lib import remote_access
from chromite.lib import timeout_util
DEFAULT_PORT = 8080
DEVSERVER_PKG_DIR = os.path.join(constants.SOURCE_ROOT, 'src/platform/dev')
DEFAULT_STATIC_DIR = path_util.FromChrootPath(
os.path.join(constants.SOURCE_ROOT, 'src', 'platform', 'dev', 'static'))
XBUDDY_REMOTE = 'remote'
XBUDDY_LOCAL = 'local'
ROOTFS_FILENAME = 'update.gz'
STATEFUL_FILENAME = 'stateful.tgz'
class ImagePathError(Exception):
"""Raised when the provided path can't be resolved to an image."""
def ConvertTranslatedPath(original_path, translated_path):
"""Converts a translated xbuddy path to an xbuddy path.
Devserver/xbuddy does not accept requests with translated xbuddy
path (build-id/version/image-name). This function converts such a
translated path to an xbuddy path that is suitable to used in
devserver requests.
Args:
original_path: the xbuddy path before translation.
(e.g., remote/peppy/latest-canary).
translated_path: the translated xbuddy path
(e.g., peppy-release/R36-5760.0.0).
Returns:
A xbuddy path uniquely identifies a build and can be used in devserver
requests: {local|remote}/build-id/version/image_type
"""
chunks = translated_path.split(os.path.sep)
chunks[-1] = constants.IMAGE_NAME_TO_TYPE[chunks[-1]]
if GetXbuddyPath(original_path).startswith(XBUDDY_REMOTE):
chunks = [XBUDDY_REMOTE] + chunks
else:
chunks = [XBUDDY_LOCAL] + chunks
return os.path.sep.join(chunks)
def GetXbuddyPath(path):
"""A helper function to parse an xbuddy path.
Args:
path: Either a path without no scheme or an xbuddy://path/for/xbuddy
Returns:
path/for/xbuddy if |path| is xbuddy://path/for/xbuddy; otherwise,
returns |path|.
Raises:
ValueError if |path| uses any scheme other than xbuddy://.
"""
parsed = urlparse.urlparse(path)
# pylint: disable=E1101
if parsed.scheme == 'xbuddy':
return '%s%s' % (parsed.netloc, parsed.path)
elif parsed.scheme == '':
logging.debug('Assuming %s is an xbuddy path.', path)
return path
else:
raise ValueError('Do not support scheme %s.', parsed.scheme)
def GetImagePathWithXbuddy(path, board, version=None,
static_dir=DEFAULT_STATIC_DIR, lookup_only=False):
"""Gets image path and resolved XBuddy path using xbuddy.
Ask xbuddy to translate |path|, and if necessary, download and stage the
image, then return a translated path to the image. Also returns the resolved
XBuddy path, which may be useful for subsequent calls in case the argument is
an alias.
Args:
path: The xbuddy path.
board: The default board to use if board is not specified in |path|.
version: The default version to use if one is not specified in |path|.
static_dir: Static directory to stage the image in.
lookup_only: Caller only wants to translate the path not download the
artifact.
Returns:
A tuple consisting of a translated path to the image
(build-id/version/image_name) as well as the fully resolved XBuddy path (in
the case where |path| is an XBuddy alias).
"""
# Since xbuddy often wants to use gsutil from $PATH, make sure our local copy
# shows up first.
upath = os.environ['PATH'].split(os.pathsep)
upath.insert(0, os.path.dirname(gs.GSContext.GetDefaultGSUtilBin()))
os.environ['PATH'] = os.pathsep.join(upath)
# Import xbuddy for translating, downloading and staging the image.
if not os.path.exists(DEVSERVER_PKG_DIR):
raise Exception('Cannot find xbuddy module. Devserver package directory '
'does not exist: %s' % DEVSERVER_PKG_DIR)
sys.path.append(DEVSERVER_PKG_DIR)
# pylint: disable=import-error
import xbuddy
import cherrypy
# If we are using the progress bar, quiet the logging output of cherrypy.
if command.UseProgressBar():
if (hasattr(cherrypy.log, 'access_log') and
hasattr(cherrypy.log, 'error_log')):
cherrypy.log.access_log.setLevel(logging.NOTICE)
cherrypy.log.error_log.setLevel(logging.NOTICE)
else:
cherrypy.config.update({'server.log_to_screen': False})
xb = xbuddy.XBuddy(static_dir=static_dir, board=board, version=version,
log_screen=False)
path_list = GetXbuddyPath(path).rsplit(os.path.sep)
try:
if lookup_only:
build_id, file_name = xb.Translate(path_list)
else:
build_id, file_name = xb.Get(path_list)
resolved_path, _ = xb.LookupAlias(os.path.sep.join(path_list))
return os.path.join(build_id, file_name), resolved_path
except xbuddy.XBuddyException as e:
logging.error('Locating image "%s" failed. The path might not be valid or '
'the image might not exist.', path)
raise ImagePathError('Cannot locate image %s: %s' % (path, e))
def GenerateXbuddyRequest(path, req_type):
"""Generate an xbuddy request used to retreive payloads.
This function generates a xbuddy request based on |path| and
|req_type|, which can be used to query the devserver. For request
type 'image' ('update'), the devserver will repond with a URL
pointing to the folder where the image (update payloads) is stored.
Args:
path: An xbuddy path (with or without xbuddy://).
req_type: xbuddy request type ('update', 'image', or 'translate').
Returns:
A xbuddy request.
"""
if req_type == 'update':
return 'xbuddy/%s?for_update=true&return_dir=true' % GetXbuddyPath(path)
elif req_type == 'image':
return 'xbuddy/%s?return_dir=true' % GetXbuddyPath(path)
elif req_type == 'translate':
return 'xbuddy_translate/%s' % GetXbuddyPath(path)
else:
raise ValueError('Does not support xbuddy request type %s' % req_type)
def TranslatedPathToLocalPath(translated_path, static_dir):
"""Convert the translated path to a local path to the image file.
Args:
translated_path: the translated xbuddy path
(e.g., peppy-release/R36-5760.0.0/chromiumos_image).
static_dir: The static directory used by the devserver.
Returns:
A local path to the image file.
"""
real_path = osutils.ExpandPath(os.path.join(static_dir, translated_path))
if os.path.exists(real_path):
return real_path
else:
return path_util.FromChrootPath(real_path)
def GetUpdatePayloadsFromLocalPath(path, payload_dir,
src_image_to_delta=None,
static_dir=DEFAULT_STATIC_DIR):
"""Generates update payloads from a local image path.
This function wraps around ConvertLocalPathToXbuddy and GetUpdatePayloads,
managing the creation and destruction of the necessary temporary directories
required by this process.
Args:
path: Path to an image.
payload_dir: The directory to store the payloads. On failure, the devserver
log will be copied to |payload_dir|.
src_image_to_delta: Image used as the base to generate the delta payloads.
static_dir: Devserver static dir to use.
"""
with cros_build_lib.ContextManagerStack() as stack:
image_tempdir = stack.Add(
osutils.TempDir,
base_dir=path_util.FromChrootPath('/tmp'),
prefix='dev_server_wrapper_local_image', sudo_rm=True)
static_tempdir = stack.Add(osutils.TempDir,
base_dir=static_dir,
prefix='local_image', sudo_rm=True)
xbuddy_path = ConvertLocalPathToXbuddyPath(path, image_tempdir,
static_tempdir, static_dir)
GetUpdatePayloads(xbuddy_path, payload_dir,
src_image_to_delta=src_image_to_delta,
static_dir=static_dir)
def ConvertLocalPathToXbuddyPath(path, image_tempdir, static_tempdir,
static_dir=DEFAULT_STATIC_DIR):
"""Converts |path| to an xbuddy path.
This function copies the image into a temprary directory in chroot
and creates a symlink in static_dir for devserver/xbuddy to
access.
Note that the temporary directories need to be cleaned up by the caller
once they are no longer needed.
Args:
path: Path to an image.
image_tempdir: osutils.TempDir instance to copy the image into. The
directory must be located within the chroot.
static_tempdir: osutils.TempDir instance to be symlinked to by the static
directory.
static_dir: Static directory to create the symlink in.
Returns:
The xbuddy path for |path|
"""
tempdir_path = image_tempdir.tempdir
logging.info('Copying image to temporary directory %s', tempdir_path)
# Devserver only knows the image names listed in IMAGE_TYPE_TO_NAME.
# Rename the image to chromiumos_test_image.bin when copying.
TEMP_IMAGE_TYPE = 'test'
shutil.copy(path,
os.path.join(tempdir_path,
constants.IMAGE_TYPE_TO_NAME[TEMP_IMAGE_TYPE]))
chroot_path = path_util.ToChrootPath(tempdir_path)
# Create and link static_dir/local_imagexxxx/link to the image
# folder, so that xbuddy/devserver can understand the path.
relative_dir = os.path.join(os.path.basename(static_tempdir.tempdir), 'link')
symlink_path = os.path.join(static_dir, relative_dir)
logging.info('Creating a symlink %s -> %s', symlink_path, chroot_path)
os.symlink(chroot_path, symlink_path)
return os.path.join(relative_dir, TEMP_IMAGE_TYPE)
def GetUpdatePayloads(path, payload_dir, board=None,
src_image_to_delta=None, timeout=60 * 15,
static_dir=DEFAULT_STATIC_DIR):
"""Launch devserver to get the update payloads.
Args:
path: The xbuddy path.
payload_dir: The directory to store the payloads. On failure, the devserver
log will be copied to |payload_dir|.
board: The default board to use when |path| is None.
src_image_to_delta: Image used as the base to generate the delta payloads.
timeout: Timeout for launching devserver (seconds).
static_dir: Devserver static dir to use.
"""
ds = DevServerWrapper(static_dir=static_dir, src_image=src_image_to_delta,
board=board)
req = GenerateXbuddyRequest(path, 'update')
logging.info('Starting local devserver to generate/serve payloads...')
try:
ds.Start()
url = ds.OpenURL(ds.GetURL(sub_dir=req), timeout=timeout)
ds.DownloadFile(os.path.join(url, ROOTFS_FILENAME), payload_dir)
ds.DownloadFile(os.path.join(url, STATEFUL_FILENAME), payload_dir)
except DevServerException:
logging.warning(ds.TailLog() or 'No devserver log is available.')
raise
else:
logging.debug(ds.TailLog() or 'No devserver log is available.')
finally:
ds.Stop()
if os.path.exists(ds.log_file):
shutil.copyfile(ds.log_file,
os.path.join(payload_dir, 'local_devserver.log'))
else:
logging.warning('Could not find %s', ds.log_file)
def GenerateUpdateId(target, src, key, for_vm):
"""Returns a simple representation id of |target| and |src| paths.
Args:
target: Target image of the update payloads.
src: Base image to of the delta update payloads.
key: Private key used to sign the payloads.
for_vm: Whether the update payloads are to be used in a VM .
"""
update_id = target
if src:
update_id = '->'.join([src, update_id])
if key:
update_id = '+'.join([update_id, key])
if not for_vm:
update_id = '+'.join([update_id, 'patched_kernel'])
return update_id
class DevServerException(Exception):
"""Base exception class of devserver errors."""
class DevServerStartupError(DevServerException):
"""Thrown when the devserver fails to start up."""
class DevServerStopError(DevServerException):
"""Thrown when the devserver fails to stop."""
class DevServerResponseError(DevServerException):
"""Thrown when the devserver responds with an error."""
class DevServerConnectionError(DevServerException):
"""Thrown when unable to connect to devserver."""
class DevServerWrapper(multiprocessing.Process):
"""A Simple wrapper around a dev server instance."""
# Wait up to 15 minutes for the dev server to start. It can take a
# while to start when generating payloads in parallel.
DEV_SERVER_TIMEOUT = 900
KILL_TIMEOUT = 10
def __init__(self, static_dir=None, port=None, log_dir=None, src_image=None,
board=None):
"""Initialize a DevServerWrapper instance.
Args:
static_dir: The static directory to be used by the devserver.
port: The port to used by the devserver.
log_dir: Directory to store the log files.
src_image: The path to the image to be used as the base to
generate delta payloads.
board: Override board to pass to the devserver for xbuddy pathing.
"""
super(DevServerWrapper, self).__init__()
self.devserver_bin = 'start_devserver'
# Set port if it is given. Otherwise, devserver will start at any
# available port.
self.port = None if not port else port
self.src_image = src_image
self.board = board
self.tempdir = None
self.log_dir = log_dir
if not self.log_dir:
self.tempdir = osutils.TempDir(
base_dir=path_util.FromChrootPath('/tmp'),
prefix='devserver_wrapper',
sudo_rm=True)
self.log_dir = self.tempdir.tempdir
self.static_dir = static_dir
self.log_file = os.path.join(self.log_dir, 'dev_server.log')
self.port_file = os.path.join(self.log_dir, 'dev_server.port')
self._pid_file = self._GetPIDFilePath()
self._pid = None
@classmethod
def DownloadFile(cls, url, dest):
"""Download the file from the URL to a local path."""
if os.path.isdir(dest):
dest = os.path.join(dest, os.path.basename(url))
logging.info('Downloading %s to %s', url, dest)
osutils.WriteFile(dest, DevServerWrapper.OpenURL(url), mode='wb')
def GetURL(self, sub_dir=None):
"""Returns the URL of this devserver instance."""
return self.GetDevServerURL(port=self.port, sub_dir=sub_dir)
@classmethod
def GetDevServerURL(cls, ip=None, port=None, sub_dir=None):
"""Returns the dev server url.
Args:
ip: IP address of the devserver. If not set, use the IP
address of this machine.
port: Port number of devserver.
sub_dir: The subdirectory of the devserver url.
"""
ip = cros_build_lib.GetIPv4Address() if not ip else ip
# If port number is not given, assume 8080 for backward
# compatibility.
port = DEFAULT_PORT if not port else port
url = 'http://%(ip)s:%(port)s' % {'ip': ip, 'port': str(port)}
if sub_dir:
url += '/' + sub_dir
return url
@classmethod
def OpenURL(cls, url, ignore_url_error=False, timeout=60):
"""Returns the HTTP response of a URL."""
logging.debug('Retrieving %s', url)
try:
res = urllib2.urlopen(url, timeout=timeout)
except (urllib2.HTTPError, httplib.HTTPException) as e:
logging.error('Devserver responded with an error!')
raise DevServerResponseError(e)
except (urllib2.URLError, socket.timeout) as e:
if not ignore_url_error:
logging.error('Cannot connect to devserver!')
raise DevServerConnectionError(e)
else:
return res.read()
@classmethod
def WipeStaticDirectory(cls, static_dir):
"""Cleans up |static_dir|.
Args:
static_dir: path to the static directory of the devserver instance.
"""
# Wipe the payload cache.
cls.WipePayloadCache(static_dir=static_dir)
logging.info('Cleaning up directory %s', static_dir)
osutils.RmDir(static_dir, ignore_missing=True, sudo=True)
@classmethod
def WipePayloadCache(cls, devserver_bin='start_devserver', static_dir=None):
"""Cleans up devserver cache of payloads.
Args:
devserver_bin: path to the devserver binary.
static_dir: path to use as the static directory of the devserver instance.
"""
logging.info('Cleaning up previously generated payloads.')
cmd = [devserver_bin, '--clear_cache', '--exit']
if static_dir:
cmd.append('--static_dir=%s' % path_util.ToChrootPath(static_dir))
cros_build_lib.SudoRunCommand(
cmd, enter_chroot=True, print_cmd=False, combine_stdout_stderr=True,
redirect_stdout=True, redirect_stderr=True, cwd=constants.SOURCE_ROOT)
def _ReadPortNumber(self):
"""Read port number from file."""
if not self.is_alive():
raise DevServerStartupError('Devserver terminated unexpectedly!')
try:
timeout_util.WaitForReturnTrue(os.path.exists,
func_args=[self.port_file],
timeout=self.DEV_SERVER_TIMEOUT,
period=5)
except timeout_util.TimeoutError:
self.terminate()
raise DevServerStartupError('Devserver portfile does not exist!')
self.port = int(osutils.ReadFile(self.port_file).strip())
def IsReady(self):
"""Check if devserver is up and running."""
if not self.is_alive():
raise DevServerStartupError('Devserver terminated unexpectedly!')
url = os.path.join('http://%s:%d' % (remote_access.LOCALHOST_IP, self.port),
'check_health')
if self.OpenURL(url, ignore_url_error=True, timeout=2):
return True
return False
def _GetPIDFilePath(self):
"""Returns pid file path."""
return tempfile.NamedTemporaryFile(prefix='devserver_wrapper',
dir=self.log_dir,
delete=False).name
def _GetPID(self):
"""Returns the pid read from the pid file."""
# Pid file was passed into the chroot.
return osutils.ReadFile(self._pid_file).rstrip()
def _WaitUntilStarted(self):
"""Wait until the devserver has started."""
if not self.port:
self._ReadPortNumber()
try:
timeout_util.WaitForReturnTrue(self.IsReady,
timeout=self.DEV_SERVER_TIMEOUT,
period=5)
except timeout_util.TimeoutError:
self.terminate()
raise DevServerStartupError('Devserver did not start')
def run(self):
"""Kicks off devserver in a separate process and waits for it to finish."""
# Truncate the log file if it already exists.
if os.path.exists(self.log_file):
osutils.SafeUnlink(self.log_file, sudo=True)
path_resolver = path_util.ChrootPathResolver()
port = self.port if self.port else 0
cmd = [self.devserver_bin,
'--pidfile', path_resolver.ToChroot(self._pid_file),
'--logfile', path_resolver.ToChroot(self.log_file),
'--port=%d' % port,
'--critical_update']
if not self.port:
cmd.append('--portfile=%s' % path_resolver.ToChroot(self.port_file))
if self.static_dir:
cmd.append(
'--static_dir=%s' % path_resolver.ToChroot(self.static_dir))
if self.src_image:
cmd.append('--src_image=%s' % path_resolver.ToChroot(self.src_image))
if self.board:
cmd.append('--board=%s' % self.board)
chroot_args = ['--no-ns-pid']
result = self._RunCommand(
cmd, enter_chroot=True, chroot_args=chroot_args,
cwd=constants.SOURCE_ROOT, error_code_ok=True,
redirect_stdout=True, combine_stdout_stderr=True)
if result.returncode != 0:
msg = (('Devserver failed to start!\n'
'--- Start output from the devserver startup command ---\n'
'%s'
'--- End output from the devserver startup command ---') %
(result.output))
logging.error(msg)
def Start(self):
"""Starts a background devserver and waits for it to start.
Starts a background devserver and waits for it to start. Will only return
once devserver has started and running pid has been read.
"""
self.start()
self._WaitUntilStarted()
self._pid = self._GetPID()
def Stop(self):
"""Kills the devserver instance with SIGTERM and SIGKILL if SIGTERM fails"""
if not self._pid:
logging.debug('No devserver running.')
return
logging.debug('Stopping devserver instance with pid %s', self._pid)
if self.is_alive():
self._RunCommand(['kill', self._pid], error_code_ok=True)
else:
logging.debug('Devserver not running!')
return
self.join(self.KILL_TIMEOUT)
if self.is_alive():
logging.warning('Devserver is unstoppable. Killing with SIGKILL')
try:
self._RunCommand(['kill', '-9', self._pid])
except cros_build_lib.RunCommandError as e:
raise DevServerStopError('Unable to stop devserver: %s' % e)
def PrintLog(self):
"""Print devserver output to stdout."""
print(self.TailLog(num_lines='+1'))
def TailLog(self, num_lines=50):
"""Returns the most recent |num_lines| lines of the devserver log file."""
fname = self.log_file
# We use self._RunCommand here to check the existence of the log
# file, so it works for RemoteDevserverWrapper as well.
if self._RunCommand(
['test', '-f', fname], error_code_ok=True).returncode == 0:
result = self._RunCommand(['tail', '-n', str(num_lines), fname],
capture_output=True)
output = '--- Start output from %s ---' % fname
output += result.output
output += '--- End output from %s ---' % fname
return output
def _RunCommand(self, *args, **kwargs):
"""Runs a shell commmand."""
kwargs.setdefault('debug_level', logging.DEBUG)
return cros_build_lib.SudoRunCommand(*args, **kwargs)
class RemoteDevServerWrapper(DevServerWrapper):
"""A wrapper of a devserver on a remote device.
Devserver wrapper for RemoteDevice. This wrapper kills all existing
running devserver instances before startup, thus allowing one
devserver running at a time.
We assume there is no chroot on the device, thus we do not launch
devserver inside chroot.
"""
# Shorter timeout because the remote devserver instance does not
# need to generate payloads.
DEV_SERVER_TIMEOUT = 30
KILL_TIMEOUT = 10
PID_FILE_PATH = '/tmp/devserver_wrapper.pid'
CHERRYPY_ERROR_MSG = """
Your device does not have cherrypy package installed; cherrypy is
necessary for launching devserver on the device. Your device may be
running an older image (<R33-4986.0.0), where cherrypy is not
installed by default.
You can fix this with one of the following three options:
1. Update the device to a newer image with a USB stick.
2. Run 'cros deploy device cherrypy' to install cherrpy.
3. Run cros flash with --no-rootfs-update to update only the stateful
parition to a newer image (with the risk that the rootfs/stateful version
mismatch may cause some problems).
"""
def __init__(self, remote_device, devserver_bin, **kwargs):
"""Initializes a RemoteDevserverPortal object with the remote device.
Args:
remote_device: A RemoteDevice object.
devserver_bin: The path to the devserver script on the device.
**kwargs: See DevServerWrapper documentation.
"""
super(RemoteDevServerWrapper, self).__init__(**kwargs)
self.device = remote_device
self.devserver_bin = devserver_bin
self.hostname = remote_device.hostname
def _GetPID(self):
"""Returns the pid read from pid file."""
result = self._RunCommand(['cat', self._pid_file])
return result.output
def _GetPIDFilePath(self):
"""Returns the pid filename"""
return self.PID_FILE_PATH
def _RunCommand(self, *args, **kwargs):
"""Runs a remote shell command.
Args:
*args: See RemoteAccess.RemoteDevice documentation.
**kwargs: See RemoteAccess.RemoteDevice documentation.
"""
kwargs.setdefault('debug_level', logging.DEBUG)
return self.device.RunCommand(*args, **kwargs)
def _ReadPortNumber(self):
"""Read port number from file."""
if not self.is_alive():
raise DevServerStartupError('Devserver terminated unexpectedly!')
def PortFileExists():
result = self._RunCommand(['test', '-f', self.port_file],
error_code_ok=True)
return result.returncode == 0
try:
timeout_util.WaitForReturnTrue(PortFileExists,
timeout=self.DEV_SERVER_TIMEOUT,
period=5)
except timeout_util.TimeoutError:
self.terminate()
raise DevServerStartupError('Devserver portfile does not exist!')
self.port = int(self._RunCommand(
['cat', self.port_file], capture_output=True).output.strip())
def IsReady(self):
"""Returns True if devserver is ready to accept requests."""
if not self.is_alive():
raise DevServerStartupError('Devserver terminated unexpectedly!')
url = os.path.join('http://127.0.0.1:%d' % self.port, 'check_health')
# Running wget through ssh because the port on the device is not
# accessible by default.
result = self.device.RunCommand(
['wget', url, '-q', '-O', '/dev/null'], error_code_ok=True)
return result.returncode == 0
def run(self):
"""Launches a devserver process on the device."""
self._RunCommand(['cat', '/dev/null', '>|', self.log_file])
port = self.port if self.port else 0
cmd = ['python2', self.devserver_bin,
'--logfile=%s' % self.log_file,
'--pidfile', self._pid_file,
'--port=%d' % port,
'--critical_update']
if not self.port:
cmd.append('--portfile=%s' % self.port_file)
if self.static_dir:
cmd.append('--static_dir=%s' % self.static_dir)
logging.info('Starting devserver on %s', self.hostname)
result = self._RunCommand(cmd, error_code_ok=True, redirect_stdout=True,
combine_stdout_stderr=True)
if result.returncode != 0:
msg = (('Remote devserver failed to start!\n'
'--- Start output from the devserver startup command ---\n'
'%s'
'--- End output from the devserver startup command ---') %
(result.output))
logging.error(msg)
if 'ImportError: No module named cherrypy' in result.output:
logging.error(self.CHERRYPY_ERROR_MSG)
def GetURL(self, sub_dir=None):
"""Returns the URL of this devserver instance."""
return self.GetDevServerURL(ip=self.hostname, port=self.port,
sub_dir=sub_dir)
@classmethod
def WipePayloadCache(cls, devserver_bin='start_devserver', static_dir=None):
"""Cleans up devserver cache of payloads."""
raise NotImplementedError()
@classmethod
def WipeStaticDirectory(cls, static_dir):
"""Cleans up |static_dir|."""
raise NotImplementedError()
| 35.705346 | 80 | 0.682429 |
from __future__ import print_function
import multiprocessing
import os
import socket
import shutil
import sys
import tempfile
import httplib
import urllib2
import urlparse
from chromite.lib import constants
from chromite.cli import command
from chromite.lib import cros_build_lib
from chromite.lib import cros_logging as logging
from chromite.lib import gs
from chromite.lib import osutils
from chromite.lib import path_util
from chromite.lib import remote_access
from chromite.lib import timeout_util
DEFAULT_PORT = 8080
DEVSERVER_PKG_DIR = os.path.join(constants.SOURCE_ROOT, 'src/platform/dev')
DEFAULT_STATIC_DIR = path_util.FromChrootPath(
os.path.join(constants.SOURCE_ROOT, 'src', 'platform', 'dev', 'static'))
XBUDDY_REMOTE = 'remote'
XBUDDY_LOCAL = 'local'
ROOTFS_FILENAME = 'update.gz'
STATEFUL_FILENAME = 'stateful.tgz'
class ImagePathError(Exception):
def ConvertTranslatedPath(original_path, translated_path):
chunks = translated_path.split(os.path.sep)
chunks[-1] = constants.IMAGE_NAME_TO_TYPE[chunks[-1]]
if GetXbuddyPath(original_path).startswith(XBUDDY_REMOTE):
chunks = [XBUDDY_REMOTE] + chunks
else:
chunks = [XBUDDY_LOCAL] + chunks
return os.path.sep.join(chunks)
def GetXbuddyPath(path):
parsed = urlparse.urlparse(path)
if parsed.scheme == 'xbuddy':
return '%s%s' % (parsed.netloc, parsed.path)
elif parsed.scheme == '':
logging.debug('Assuming %s is an xbuddy path.', path)
return path
else:
raise ValueError('Do not support scheme %s.', parsed.scheme)
def GetImagePathWithXbuddy(path, board, version=None,
static_dir=DEFAULT_STATIC_DIR, lookup_only=False):
upath = os.environ['PATH'].split(os.pathsep)
upath.insert(0, os.path.dirname(gs.GSContext.GetDefaultGSUtilBin()))
os.environ['PATH'] = os.pathsep.join(upath)
if not os.path.exists(DEVSERVER_PKG_DIR):
raise Exception('Cannot find xbuddy module. Devserver package directory '
'does not exist: %s' % DEVSERVER_PKG_DIR)
sys.path.append(DEVSERVER_PKG_DIR)
import xbuddy
import cherrypy
if command.UseProgressBar():
if (hasattr(cherrypy.log, 'access_log') and
hasattr(cherrypy.log, 'error_log')):
cherrypy.log.access_log.setLevel(logging.NOTICE)
cherrypy.log.error_log.setLevel(logging.NOTICE)
else:
cherrypy.config.update({'server.log_to_screen': False})
xb = xbuddy.XBuddy(static_dir=static_dir, board=board, version=version,
log_screen=False)
path_list = GetXbuddyPath(path).rsplit(os.path.sep)
try:
if lookup_only:
build_id, file_name = xb.Translate(path_list)
else:
build_id, file_name = xb.Get(path_list)
resolved_path, _ = xb.LookupAlias(os.path.sep.join(path_list))
return os.path.join(build_id, file_name), resolved_path
except xbuddy.XBuddyException as e:
logging.error('Locating image "%s" failed. The path might not be valid or '
'the image might not exist.', path)
raise ImagePathError('Cannot locate image %s: %s' % (path, e))
def GenerateXbuddyRequest(path, req_type):
if req_type == 'update':
return 'xbuddy/%s?for_update=true&return_dir=true' % GetXbuddyPath(path)
elif req_type == 'image':
return 'xbuddy/%s?return_dir=true' % GetXbuddyPath(path)
elif req_type == 'translate':
return 'xbuddy_translate/%s' % GetXbuddyPath(path)
else:
raise ValueError('Does not support xbuddy request type %s' % req_type)
def TranslatedPathToLocalPath(translated_path, static_dir):
real_path = osutils.ExpandPath(os.path.join(static_dir, translated_path))
if os.path.exists(real_path):
return real_path
else:
return path_util.FromChrootPath(real_path)
def GetUpdatePayloadsFromLocalPath(path, payload_dir,
src_image_to_delta=None,
static_dir=DEFAULT_STATIC_DIR):
with cros_build_lib.ContextManagerStack() as stack:
image_tempdir = stack.Add(
osutils.TempDir,
base_dir=path_util.FromChrootPath('/tmp'),
prefix='dev_server_wrapper_local_image', sudo_rm=True)
static_tempdir = stack.Add(osutils.TempDir,
base_dir=static_dir,
prefix='local_image', sudo_rm=True)
xbuddy_path = ConvertLocalPathToXbuddyPath(path, image_tempdir,
static_tempdir, static_dir)
GetUpdatePayloads(xbuddy_path, payload_dir,
src_image_to_delta=src_image_to_delta,
static_dir=static_dir)
def ConvertLocalPathToXbuddyPath(path, image_tempdir, static_tempdir,
static_dir=DEFAULT_STATIC_DIR):
tempdir_path = image_tempdir.tempdir
logging.info('Copying image to temporary directory %s', tempdir_path)
TEMP_IMAGE_TYPE = 'test'
shutil.copy(path,
os.path.join(tempdir_path,
constants.IMAGE_TYPE_TO_NAME[TEMP_IMAGE_TYPE]))
chroot_path = path_util.ToChrootPath(tempdir_path)
relative_dir = os.path.join(os.path.basename(static_tempdir.tempdir), 'link')
symlink_path = os.path.join(static_dir, relative_dir)
logging.info('Creating a symlink %s -> %s', symlink_path, chroot_path)
os.symlink(chroot_path, symlink_path)
return os.path.join(relative_dir, TEMP_IMAGE_TYPE)
def GetUpdatePayloads(path, payload_dir, board=None,
src_image_to_delta=None, timeout=60 * 15,
static_dir=DEFAULT_STATIC_DIR):
ds = DevServerWrapper(static_dir=static_dir, src_image=src_image_to_delta,
board=board)
req = GenerateXbuddyRequest(path, 'update')
logging.info('Starting local devserver to generate/serve payloads...')
try:
ds.Start()
url = ds.OpenURL(ds.GetURL(sub_dir=req), timeout=timeout)
ds.DownloadFile(os.path.join(url, ROOTFS_FILENAME), payload_dir)
ds.DownloadFile(os.path.join(url, STATEFUL_FILENAME), payload_dir)
except DevServerException:
logging.warning(ds.TailLog() or 'No devserver log is available.')
raise
else:
logging.debug(ds.TailLog() or 'No devserver log is available.')
finally:
ds.Stop()
if os.path.exists(ds.log_file):
shutil.copyfile(ds.log_file,
os.path.join(payload_dir, 'local_devserver.log'))
else:
logging.warning('Could not find %s', ds.log_file)
def GenerateUpdateId(target, src, key, for_vm):
update_id = target
if src:
update_id = '->'.join([src, update_id])
if key:
update_id = '+'.join([update_id, key])
if not for_vm:
update_id = '+'.join([update_id, 'patched_kernel'])
return update_id
class DevServerException(Exception):
class DevServerStartupError(DevServerException):
class DevServerStopError(DevServerException):
class DevServerResponseError(DevServerException):
class DevServerConnectionError(DevServerException):
class DevServerWrapper(multiprocessing.Process):
DEV_SERVER_TIMEOUT = 900
KILL_TIMEOUT = 10
def __init__(self, static_dir=None, port=None, log_dir=None, src_image=None,
board=None):
super(DevServerWrapper, self).__init__()
self.devserver_bin = 'start_devserver'
self.port = None if not port else port
self.src_image = src_image
self.board = board
self.tempdir = None
self.log_dir = log_dir
if not self.log_dir:
self.tempdir = osutils.TempDir(
base_dir=path_util.FromChrootPath('/tmp'),
prefix='devserver_wrapper',
sudo_rm=True)
self.log_dir = self.tempdir.tempdir
self.static_dir = static_dir
self.log_file = os.path.join(self.log_dir, 'dev_server.log')
self.port_file = os.path.join(self.log_dir, 'dev_server.port')
self._pid_file = self._GetPIDFilePath()
self._pid = None
@classmethod
def DownloadFile(cls, url, dest):
if os.path.isdir(dest):
dest = os.path.join(dest, os.path.basename(url))
logging.info('Downloading %s to %s', url, dest)
osutils.WriteFile(dest, DevServerWrapper.OpenURL(url), mode='wb')
def GetURL(self, sub_dir=None):
return self.GetDevServerURL(port=self.port, sub_dir=sub_dir)
@classmethod
def GetDevServerURL(cls, ip=None, port=None, sub_dir=None):
ip = cros_build_lib.GetIPv4Address() if not ip else ip
port = DEFAULT_PORT if not port else port
url = 'http://%(ip)s:%(port)s' % {'ip': ip, 'port': str(port)}
if sub_dir:
url += '/' + sub_dir
return url
@classmethod
def OpenURL(cls, url, ignore_url_error=False, timeout=60):
logging.debug('Retrieving %s', url)
try:
res = urllib2.urlopen(url, timeout=timeout)
except (urllib2.HTTPError, httplib.HTTPException) as e:
logging.error('Devserver responded with an error!')
raise DevServerResponseError(e)
except (urllib2.URLError, socket.timeout) as e:
if not ignore_url_error:
logging.error('Cannot connect to devserver!')
raise DevServerConnectionError(e)
else:
return res.read()
@classmethod
def WipeStaticDirectory(cls, static_dir):
cls.WipePayloadCache(static_dir=static_dir)
logging.info('Cleaning up directory %s', static_dir)
osutils.RmDir(static_dir, ignore_missing=True, sudo=True)
@classmethod
def WipePayloadCache(cls, devserver_bin='start_devserver', static_dir=None):
logging.info('Cleaning up previously generated payloads.')
cmd = [devserver_bin, '--clear_cache', '--exit']
if static_dir:
cmd.append('--static_dir=%s' % path_util.ToChrootPath(static_dir))
cros_build_lib.SudoRunCommand(
cmd, enter_chroot=True, print_cmd=False, combine_stdout_stderr=True,
redirect_stdout=True, redirect_stderr=True, cwd=constants.SOURCE_ROOT)
def _ReadPortNumber(self):
if not self.is_alive():
raise DevServerStartupError('Devserver terminated unexpectedly!')
try:
timeout_util.WaitForReturnTrue(os.path.exists,
func_args=[self.port_file],
timeout=self.DEV_SERVER_TIMEOUT,
period=5)
except timeout_util.TimeoutError:
self.terminate()
raise DevServerStartupError('Devserver portfile does not exist!')
self.port = int(osutils.ReadFile(self.port_file).strip())
def IsReady(self):
if not self.is_alive():
raise DevServerStartupError('Devserver terminated unexpectedly!')
url = os.path.join('http://%s:%d' % (remote_access.LOCALHOST_IP, self.port),
'check_health')
if self.OpenURL(url, ignore_url_error=True, timeout=2):
return True
return False
def _GetPIDFilePath(self):
return tempfile.NamedTemporaryFile(prefix='devserver_wrapper',
dir=self.log_dir,
delete=False).name
def _GetPID(self):
return osutils.ReadFile(self._pid_file).rstrip()
def _WaitUntilStarted(self):
if not self.port:
self._ReadPortNumber()
try:
timeout_util.WaitForReturnTrue(self.IsReady,
timeout=self.DEV_SERVER_TIMEOUT,
period=5)
except timeout_util.TimeoutError:
self.terminate()
raise DevServerStartupError('Devserver did not start')
def run(self):
if os.path.exists(self.log_file):
osutils.SafeUnlink(self.log_file, sudo=True)
path_resolver = path_util.ChrootPathResolver()
port = self.port if self.port else 0
cmd = [self.devserver_bin,
'--pidfile', path_resolver.ToChroot(self._pid_file),
'--logfile', path_resolver.ToChroot(self.log_file),
'--port=%d' % port,
'--critical_update']
if not self.port:
cmd.append('--portfile=%s' % path_resolver.ToChroot(self.port_file))
if self.static_dir:
cmd.append(
'--static_dir=%s' % path_resolver.ToChroot(self.static_dir))
if self.src_image:
cmd.append('--src_image=%s' % path_resolver.ToChroot(self.src_image))
if self.board:
cmd.append('--board=%s' % self.board)
chroot_args = ['--no-ns-pid']
result = self._RunCommand(
cmd, enter_chroot=True, chroot_args=chroot_args,
cwd=constants.SOURCE_ROOT, error_code_ok=True,
redirect_stdout=True, combine_stdout_stderr=True)
if result.returncode != 0:
msg = (('Devserver failed to start!\n'
'--- Start output from the devserver startup command ---\n'
'%s'
'--- End output from the devserver startup command ---') %
(result.output))
logging.error(msg)
def Start(self):
self.start()
self._WaitUntilStarted()
self._pid = self._GetPID()
def Stop(self):
if not self._pid:
logging.debug('No devserver running.')
return
logging.debug('Stopping devserver instance with pid %s', self._pid)
if self.is_alive():
self._RunCommand(['kill', self._pid], error_code_ok=True)
else:
logging.debug('Devserver not running!')
return
self.join(self.KILL_TIMEOUT)
if self.is_alive():
logging.warning('Devserver is unstoppable. Killing with SIGKILL')
try:
self._RunCommand(['kill', '-9', self._pid])
except cros_build_lib.RunCommandError as e:
raise DevServerStopError('Unable to stop devserver: %s' % e)
def PrintLog(self):
print(self.TailLog(num_lines='+1'))
def TailLog(self, num_lines=50):
fname = self.log_file
if self._RunCommand(
['test', '-f', fname], error_code_ok=True).returncode == 0:
result = self._RunCommand(['tail', '-n', str(num_lines), fname],
capture_output=True)
output = '--- Start output from %s ---' % fname
output += result.output
output += '--- End output from %s ---' % fname
return output
def _RunCommand(self, *args, **kwargs):
kwargs.setdefault('debug_level', logging.DEBUG)
return cros_build_lib.SudoRunCommand(*args, **kwargs)
class RemoteDevServerWrapper(DevServerWrapper):
DEV_SERVER_TIMEOUT = 30
KILL_TIMEOUT = 10
PID_FILE_PATH = '/tmp/devserver_wrapper.pid'
CHERRYPY_ERROR_MSG = """
Your device does not have cherrypy package installed; cherrypy is
necessary for launching devserver on the device. Your device may be
running an older image (<R33-4986.0.0), where cherrypy is not
installed by default.
You can fix this with one of the following three options:
1. Update the device to a newer image with a USB stick.
2. Run 'cros deploy device cherrypy' to install cherrpy.
3. Run cros flash with --no-rootfs-update to update only the stateful
parition to a newer image (with the risk that the rootfs/stateful version
mismatch may cause some problems).
"""
def __init__(self, remote_device, devserver_bin, **kwargs):
super(RemoteDevServerWrapper, self).__init__(**kwargs)
self.device = remote_device
self.devserver_bin = devserver_bin
self.hostname = remote_device.hostname
def _GetPID(self):
result = self._RunCommand(['cat', self._pid_file])
return result.output
def _GetPIDFilePath(self):
return self.PID_FILE_PATH
def _RunCommand(self, *args, **kwargs):
kwargs.setdefault('debug_level', logging.DEBUG)
return self.device.RunCommand(*args, **kwargs)
def _ReadPortNumber(self):
if not self.is_alive():
raise DevServerStartupError('Devserver terminated unexpectedly!')
def PortFileExists():
result = self._RunCommand(['test', '-f', self.port_file],
error_code_ok=True)
return result.returncode == 0
try:
timeout_util.WaitForReturnTrue(PortFileExists,
timeout=self.DEV_SERVER_TIMEOUT,
period=5)
except timeout_util.TimeoutError:
self.terminate()
raise DevServerStartupError('Devserver portfile does not exist!')
self.port = int(self._RunCommand(
['cat', self.port_file], capture_output=True).output.strip())
def IsReady(self):
if not self.is_alive():
raise DevServerStartupError('Devserver terminated unexpectedly!')
url = os.path.join('http://127.0.0.1:%d' % self.port, 'check_health')
result = self.device.RunCommand(
['wget', url, '-q', '-O', '/dev/null'], error_code_ok=True)
return result.returncode == 0
def run(self):
self._RunCommand(['cat', '/dev/null', '>|', self.log_file])
port = self.port if self.port else 0
cmd = ['python2', self.devserver_bin,
'--logfile=%s' % self.log_file,
'--pidfile', self._pid_file,
'--port=%d' % port,
'--critical_update']
if not self.port:
cmd.append('--portfile=%s' % self.port_file)
if self.static_dir:
cmd.append('--static_dir=%s' % self.static_dir)
logging.info('Starting devserver on %s', self.hostname)
result = self._RunCommand(cmd, error_code_ok=True, redirect_stdout=True,
combine_stdout_stderr=True)
if result.returncode != 0:
msg = (('Remote devserver failed to start!\n'
'--- Start output from the devserver startup command ---\n'
'%s'
'--- End output from the devserver startup command ---') %
(result.output))
logging.error(msg)
if 'ImportError: No module named cherrypy' in result.output:
logging.error(self.CHERRYPY_ERROR_MSG)
def GetURL(self, sub_dir=None):
return self.GetDevServerURL(ip=self.hostname, port=self.port,
sub_dir=sub_dir)
@classmethod
def WipePayloadCache(cls, devserver_bin='start_devserver', static_dir=None):
raise NotImplementedError()
@classmethod
def WipeStaticDirectory(cls, static_dir):
raise NotImplementedError()
| true | true |
f7f770d77835c8395aa86ea8522e3f36a6066d2d | 6,003 | py | Python | awx_collection/plugins/modules/tower_instance_group.py | DamoR25/awxnew | 03ed6e97558ae090ea52703caf6ed1b196557981 | [
"Apache-2.0"
] | 11,396 | 2017-09-07T04:56:02.000Z | 2022-03-31T13:56:17.000Z | awx_collection/plugins/modules/tower_instance_group.py | DamoR25/awxnew | 03ed6e97558ae090ea52703caf6ed1b196557981 | [
"Apache-2.0"
] | 11,046 | 2017-09-07T09:30:46.000Z | 2022-03-31T20:28:01.000Z | awx_collection/plugins/modules/tower_instance_group.py | TinLe/awx | 73d8c12e3bf5b193305ed1202549331ea00088c1 | [
"Apache-2.0"
] | 3,592 | 2017-09-07T04:14:31.000Z | 2022-03-31T23:53:09.000Z | #!/usr/bin/python
# coding: utf-8 -*-
# (c) 2020, John Westcott IV <john.westcott.iv@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'}
DOCUMENTATION = '''
---
module: instance_group
author: "John Westcott IV (@john-westcott-iv)"
version_added: "4.0.0"
short_description: create, update, or destroy Automation Platform Controller instance groups.
description:
- Create, update, or destroy Automation Platform Controller instance groups. See
U(https://www.ansible.com/tower) for an overview.
options:
name:
description:
- Name of this instance group.
required: True
type: str
new_name:
description:
- Setting this option will change the existing name (looked up via the name field.
type: str
credential:
description:
- Credential to authenticate with Kubernetes or OpenShift. Must be of type "Kubernetes/OpenShift API Bearer Token".
required: False
type: str
is_container_group:
description:
- Signifies that this InstanceGroup should act as a ContainerGroup. If no credential is specified, the underlying Pod's ServiceAccount will be used.
required: False
type: bool
default: False
policy_instance_percentage:
description:
- Minimum percentage of all instances that will be automatically assigned to this group when new instances come online.
required: False
type: int
default: '0'
policy_instance_minimum:
description:
- Static minimum number of Instances that will be automatically assign to this group when new instances come online.
required: False
type: int
default: '0'
policy_instance_list:
description:
- List of exact-match Instances that will be assigned to this group
required: False
type: list
elements: str
pod_spec_override:
description:
- A custom Kubernetes or OpenShift Pod specification.
required: False
type: str
instances:
description:
- The instances associated with this instance_group
required: False
type: list
elements: str
state:
description:
- Desired state of the resource.
choices: ["present", "absent"]
default: "present"
type: str
extends_documentation_fragment: awx.awx.auth
'''
EXAMPLES = '''
'''
from ..module_utils.controller_api import ControllerAPIModule
def main():
# Any additional arguments that are not fields of the item can be added here
argument_spec = dict(
name=dict(required=True),
new_name=dict(),
credential=dict(),
is_container_group=dict(type='bool', default=False),
policy_instance_percentage=dict(type='int', default='0'),
policy_instance_minimum=dict(type='int', default='0'),
policy_instance_list=dict(type='list', elements='str'),
pod_spec_override=dict(),
instances=dict(required=False, type="list", elements='str', default=None),
state=dict(choices=['present', 'absent'], default='present'),
)
# Create a module for ourselves
module = ControllerAPIModule(argument_spec=argument_spec)
# Extract our parameters
name = module.params.get('name')
new_name = module.params.get("new_name")
credential = module.params.get('credential')
is_container_group = module.params.get('is_container_group')
policy_instance_percentage = module.params.get('policy_instance_percentage')
policy_instance_minimum = module.params.get('policy_instance_minimum')
policy_instance_list = module.params.get('policy_instance_list')
pod_spec_override = module.params.get('pod_spec_override')
instances = module.params.get('instances')
state = module.params.get('state')
# Attempt to look up an existing item based on the provided data
existing_item = module.get_one('instance_groups', name_or_id=name)
if state == 'absent':
# If the state was absent we can let the module delete it if needed, the module will handle exiting from this
module.delete_if_needed(existing_item)
# Attempt to look up the related items the user specified (these will fail the module if not found)
credential_id = None
if credential:
credential_id = module.resolve_name_to_id('credentials', credential)
instances_ids = None
if instances is not None:
instances_ids = []
for item in instances:
instances_ids.append(module.resolve_name_to_id('instances', item))
# Create the data that gets sent for create and update
new_fields = {}
new_fields['name'] = new_name if new_name else (module.get_item_name(existing_item) if existing_item else name)
if credential is not None:
new_fields['credential'] = credential_id
if is_container_group is not None:
new_fields['is_container_group'] = is_container_group
if policy_instance_percentage is not None:
new_fields['policy_instance_percentage'] = policy_instance_percentage
if policy_instance_minimum is not None:
new_fields['policy_instance_minimum'] = policy_instance_minimum
if policy_instance_list is not None:
new_fields['policy_instance_list'] = policy_instance_list
if pod_spec_override is not None:
new_fields['pod_spec_override'] = pod_spec_override
# If the state was present and we can let the module build or update the existing item, this will return on its own
module.create_or_update_if_needed(
existing_item,
new_fields,
endpoint='instance_groups',
item_type='instance_group',
associations={
'instances': instances_ids,
},
)
if __name__ == '__main__':
main()
| 36.162651 | 156 | 0.695819 |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'}
DOCUMENTATION = '''
---
module: instance_group
author: "John Westcott IV (@john-westcott-iv)"
version_added: "4.0.0"
short_description: create, update, or destroy Automation Platform Controller instance groups.
description:
- Create, update, or destroy Automation Platform Controller instance groups. See
U(https://www.ansible.com/tower) for an overview.
options:
name:
description:
- Name of this instance group.
required: True
type: str
new_name:
description:
- Setting this option will change the existing name (looked up via the name field.
type: str
credential:
description:
- Credential to authenticate with Kubernetes or OpenShift. Must be of type "Kubernetes/OpenShift API Bearer Token".
required: False
type: str
is_container_group:
description:
- Signifies that this InstanceGroup should act as a ContainerGroup. If no credential is specified, the underlying Pod's ServiceAccount will be used.
required: False
type: bool
default: False
policy_instance_percentage:
description:
- Minimum percentage of all instances that will be automatically assigned to this group when new instances come online.
required: False
type: int
default: '0'
policy_instance_minimum:
description:
- Static minimum number of Instances that will be automatically assign to this group when new instances come online.
required: False
type: int
default: '0'
policy_instance_list:
description:
- List of exact-match Instances that will be assigned to this group
required: False
type: list
elements: str
pod_spec_override:
description:
- A custom Kubernetes or OpenShift Pod specification.
required: False
type: str
instances:
description:
- The instances associated with this instance_group
required: False
type: list
elements: str
state:
description:
- Desired state of the resource.
choices: ["present", "absent"]
default: "present"
type: str
extends_documentation_fragment: awx.awx.auth
'''
EXAMPLES = '''
'''
from ..module_utils.controller_api import ControllerAPIModule
def main():
# Any additional arguments that are not fields of the item can be added here
argument_spec = dict(
name=dict(required=True),
new_name=dict(),
credential=dict(),
is_container_group=dict(type='bool', default=False),
policy_instance_percentage=dict(type='int', default='0'),
policy_instance_minimum=dict(type='int', default='0'),
policy_instance_list=dict(type='list', elements='str'),
pod_spec_override=dict(),
instances=dict(required=False, type="list", elements='str', default=None),
state=dict(choices=['present', 'absent'], default='present'),
)
# Create a module for ourselves
module = ControllerAPIModule(argument_spec=argument_spec)
# Extract our parameters
name = module.params.get('name')
new_name = module.params.get("new_name")
credential = module.params.get('credential')
is_container_group = module.params.get('is_container_group')
policy_instance_percentage = module.params.get('policy_instance_percentage')
policy_instance_minimum = module.params.get('policy_instance_minimum')
policy_instance_list = module.params.get('policy_instance_list')
pod_spec_override = module.params.get('pod_spec_override')
instances = module.params.get('instances')
state = module.params.get('state')
# Attempt to look up an existing item based on the provided data
existing_item = module.get_one('instance_groups', name_or_id=name)
if state == 'absent':
# If the state was absent we can let the module delete it if needed, the module will handle exiting from this
module.delete_if_needed(existing_item)
# Attempt to look up the related items the user specified (these will fail the module if not found)
credential_id = None
if credential:
credential_id = module.resolve_name_to_id('credentials', credential)
instances_ids = None
if instances is not None:
instances_ids = []
for item in instances:
instances_ids.append(module.resolve_name_to_id('instances', item))
# Create the data that gets sent for create and update
new_fields = {}
new_fields['name'] = new_name if new_name else (module.get_item_name(existing_item) if existing_item else name)
if credential is not None:
new_fields['credential'] = credential_id
if is_container_group is not None:
new_fields['is_container_group'] = is_container_group
if policy_instance_percentage is not None:
new_fields['policy_instance_percentage'] = policy_instance_percentage
if policy_instance_minimum is not None:
new_fields['policy_instance_minimum'] = policy_instance_minimum
if policy_instance_list is not None:
new_fields['policy_instance_list'] = policy_instance_list
if pod_spec_override is not None:
new_fields['pod_spec_override'] = pod_spec_override
# If the state was present and we can let the module build or update the existing item, this will return on its own
module.create_or_update_if_needed(
existing_item,
new_fields,
endpoint='instance_groups',
item_type='instance_group',
associations={
'instances': instances_ids,
},
)
if __name__ == '__main__':
main()
| true | true |
f7f77101cd59393b0ea89ebff088b0aa3d848f89 | 14,352 | py | Python | src/anygen/__init__.py | kshpytsya/anygen | 418d5d98550bc305514ef26e925cf5c0e0846c59 | [
"MIT"
] | null | null | null | src/anygen/__init__.py | kshpytsya/anygen | 418d5d98550bc305514ef26e925cf5c0e0846c59 | [
"MIT"
] | null | null | null | src/anygen/__init__.py | kshpytsya/anygen | 418d5d98550bc305514ef26e925cf5c0e0846c59 | [
"MIT"
] | null | null | null | import c3linearize as _c3linearize
import collections as _collections
import jinja2 as _jinja2
import json as _json
import pathlib as _pathlib
import pkg_resources as _pkg_resources
import ruamel.yaml as _yaml
from ruamel.yaml import YAML as _YAML
import runpy as _runpy
import subprocess as _subprocess
import sys as _sys
import yaql as _yaql
from . import scanextras as _scanextras
from .obj import Obj as _Obj
from .taskflow import TaskFlow as _TaskFlow
try:
__version__ = _pkg_resources.get_distribution(__name__).version
except: # noqa # pragma: no cover
pass
ELIDE = object()
class TaggedStr(str):
def __new__(cls, s, **kw):
self = super().__new__(cls, s)
self.__dict__ = kw
return self
class TemplateResultStr(TaggedStr):
pass
def _which(path, name):
for path_entry in path:
path_name = _pathlib.Path(path_entry) / name
if path_name.exists():
return path_name
return None
def _checked_which(path, name):
result = _which(path, name)
if result is None:
raise FileNotFoundError(name, path)
return result
class Anygen:
def __init__(self, produce_func):
self._produce_func = produce_func
def produce(self, *args, **kw):
return self._produce_func(args + (kw,))
def _init_task_init(ctx):
ctx.yaql = ctx.inp.yaql
ctx.taskflow = _TaskFlow()
ctx.extras = _collections.defaultdict(dict)
for k, v in ctx.inp.extras.items():
ctx.extras[k].update(v)
def task(produce_ctx):
produce_ctx.yaql_ctx = produce_ctx.inp.yaql_ctx
produce_ctx.yaql_ctx["inp"] = ctx.yaql.expr.merge_dict_list.evaluate(
context=ctx.yaql.ctx.create_child_context(),
data=produce_ctx.inp.inp
)
produce_ctx.yaql_ctx["out"] = {}
ctx.taskflow.add_task("init", func=task)
def _init_task_load_yamls(ctx):
suffix = "anygen.yml"
COMBINED = object()
ROOT = object()
loaded = {}
yaml_loader = _YAML(typ='safe', pure=True)
def load_list(classes):
for i in classes:
load(i)
def load(class_):
nonlocal loaded
if class_ in loaded:
return
path_name = _checked_which(ctx.inp.path, class_ + "." + suffix)
yaml = yaml_loader.load(path_name)
extends = yaml.get("extends", [])
# TODO proper error
assert isinstance(extends, list)
loaded[class_] = _Obj(path_name=path_name, yaml=yaml, extends=extends)
load_list(extends)
def load_root():
path_name = _which(ctx.inp.path, suffix)
if path_name is None:
return
yaml = yaml_loader.load(path_name)
if "extends" in yaml:
raise RuntimeError("root class cannot have 'extends'")
loaded[ROOT] = _Obj(path_name=path_name, yaml=yaml)
load_list(ctx.inp.classes)
load_root()
if ROOT in loaded:
bases = [ROOT]
else:
bases = []
def bases_func(class_):
if class_ is COMBINED:
return ctx.inp.classes + bases
if class_ is ROOT:
return []
return list(loaded[class_].extends) + bases
dep_graph = _c3linearize.build_graph(COMBINED, bases_func)
c3linearization = _c3linearize.linearize(dep_graph, heads=[COMBINED])[COMBINED]
assert c3linearization.pop(0) is COMBINED
ctx.classes = list(reversed([loaded[i] for i in c3linearization]))
for class_ in ctx.classes:
class_.yaql_prefix = class_.yaml.get("marks", {}).get("yaql", "=")
class_.elideable_key_suffix = class_.yaml.get("marks", {}).get("elide", "?")
class_.merge_key_suffix = class_.yaml.get("marks", {}).get("merge", "+")
class_.filter_key_sep = class_.yaml.get("marks", {}).get("filter", "|")
def _init_task_merge_yaml_consts(ctx):
ctx.yaql.ctx0 = ctx.yaql.expr.merge_yaml_consts.evaluate(context=ctx.yaql.ctx, data=ctx.classes)
ctx.yaql.ctx = ctx.yaql.ctx0.create_child_context()
def _init_task_py_deps(ctx):
missing_requires = set()
for class_ in ctx.classes:
for req_str in class_.yaml.get('py_requires', []):
req = _pkg_resources.Requirement.parse(req_str)
try:
_pkg_resources.working_set.resolve([req])
except _pkg_resources.DistributionNotFound:
missing_requires.add(req)
if missing_requires:
if _sys.base_prefix == _sys.prefix:
raise RuntimeError(
"missing Python requirements and not running in venv -- will not try to autoinstall",
list(missing_requires)
)
_subprocess.check_call(
[_pathlib.Path(_sys.executable).parent / "pip", "install"] +
[str(i) for i in missing_requires]
)
def _init_task_load_plugins(ctx):
extras = ctx.extras
origins = _collections.defaultdict(list)
for entry_point in _pkg_resources.iter_entry_points("anygen", "extras"):
these_extras = entry_point.load()
for k1, v1 in these_extras.items():
for k2, v2 in v1.items():
origins[(k1, k2)].append(str(entry_point))
extras[k1][k2] = v2
dups = []
for k, these_origins in origins.items():
if len(these_origins) > 1:
dups.append(('%s_%s' % k, these_origins))
if dups:
raise RuntimeError(
"conflicting plugins installed. Some 'extras' are defined in multiple plugins",
dups
)
def _init_task_load_py(ctx):
extras = ctx.extras
for class_ in ctx.classes:
py_fname = class_.path_name.with_suffix(".py")
if not py_fname.exists():
continue
py_dict = _runpy.run_path(py_fname)
these_extras = _scanextras.scan(py_dict)
for k1, v1 in these_extras.items():
for k2, v2 in v1.items():
extras[k1][k2] = v2
def _init_task_setup_yaql_extras(ctx):
for k, v in ctx.extras["yaql"].items():
ctx.yaql.ctx.register_function(_yaql.language.specs.name(k)(v))
def _init_task_setup_jinja(ctx):
jinja_env = ctx.jinja_env = _jinja2.Environment(
loader=_jinja2.ChoiceLoader(
[_jinja2.DictLoader(class_.yaml.get("templates", {})) for class_ in reversed(ctx.classes)] +
[_jinja2.FileSystemLoader(ctx.inp.path)]
),
keep_trailing_newline=True
)
for k, v in ctx.extras["jinjaglobals"].items():
jinja_env.globals[k] = v
for k, v in ctx.extras["jinjafilter"].items():
jinja_env.filters[k] = v
for k, v in ctx.extras["jinjatest"].items():
jinja_env.tests[k] = v
@_yaql.language.specs.name("template")
def yaql_template(name, **kw):
return TemplateResultStr(jinja_env.get_template(name).render(**kw), name=name)
ctx.yaql.ctx.register_function(yaql_template)
def yaql_ctx_to_str(ctx):
if ctx is None:
return '*'
return str(dict((k, ctx.get_data(k)) for k in ctx.keys())) + ' | ' + yaql_ctx_to_str(ctx.parent)
def _init_task_prepare(ctx):
preparers = []
for class_ in ctx.classes:
prepare_exprs = class_.yaml.get("prepare", [])
if isinstance(prepare_exprs, str):
prepare_exprs = [prepare_exprs]
for expr in prepare_exprs:
preparers.append(ctx.yaql.engine(expr))
def task(produce_ctx):
# print(yaql_ctx_to_str(produce_ctx.yaql_ctx))
for i in preparers:
produce_ctx.yaql_ctx = i.evaluate(context=produce_ctx.yaql_ctx, data=None)
# print(yaql_ctx_to_str(produce_ctx.yaql_ctx))
ctx.taskflow.add_task("prepare", func=task, after=["init"])
def _recursive_yaql(ctx, class_, data):
def process_dict_item(k, v):
pipeline_tail = []
for suffix, yaql_filter in [
(class_.elideable_key_suffix, 'elide'),
(class_.merge_key_suffix, 'merge')
]:
if k.endswith(suffix):
k = k[:-len(suffix)]
pipeline_tail.append(yaql_filter)
k, *pipeline = k.split(class_.filter_key_sep)
pipeline.extend(reversed(pipeline_tail))
pipeline = [ctx.yaql.engine(i + '($)') for i in pipeline]
def produce(yaql_ctx):
result = v(yaql_ctx)
for i in pipeline:
result = i.evaluate(context=ctx.yaql.ctx, data=result)
return result
return k, produce
def recursive_elide(data):
if isinstance(data, dict):
return dict((k, recursive_elide(v)) for k, v in data.items() if v is not ELIDE)
elif isinstance(data, list):
return list(recursive_elide(i) for i in data if i is not ELIDE)
else:
return data
def recurse(data):
if isinstance(data, str):
if data.startswith(class_.yaql_prefix):
expr = ctx.yaql.engine(data[len(class_.yaql_prefix):])
return lambda yaql_ctx: recursive_elide(expr.evaluate(context=yaql_ctx))
else:
return lambda yaql_ctx: data
elif isinstance(data, dict):
items = list(process_dict_item(k, recurse(v)) for k, v in data.items())
return lambda yaql_ctx: dict(
(k, v)
for k, cb in items
for v in (cb(yaql_ctx),)
if v is not ELIDE
)
elif isinstance(data, list):
items = list(recurse(i) for i in data)
return lambda yaql_ctx: list(
v
for cb in items
for v in (cb(yaql_ctx),)
if v is not ELIDE
)
else:
return lambda yaql_ctx: data
return recurse(data)
def _yaql_let(yaql_ctx, *args, **kw):
yaql_ctx = yaql_ctx.create_child_context()
for i, v in enumerate(args, 1):
yaql_ctx[str(i)] = v
for k, v in kw.items():
yaql_ctx[k] = v
return yaql_ctx
def _init_task_fragments(ctx):
fragments = set()
for class_ in reversed(ctx.classes):
for k, v in class_.yaml.get("fragments", {}).items():
if k in fragments:
continue
fragments.add(k)
def one(k, v):
frag_func = _recursive_yaql(ctx, class_, v)
@_yaql.language.specs.name(k)
def wrapper(*args, **kw):
return frag_func(_yaql_let(ctx.yaql.ctx0, *args, **kw))
ctx.yaql.ctx0.register_function(wrapper)
one(k, v)
def _init_task_produce(ctx):
producers = [lambda yaql_ctx: yaql_ctx.get_data("out")] + [
_recursive_yaql(ctx, class_, {"produce" + suffix: data})
for class_ in ctx.classes
for suffix in ['', class_.merge_key_suffix]
for data in (class_.yaml.get("produce" + suffix, None),)
if data is not None
]
def task(produce_ctx):
produce_ctx.out = ctx.yaql.expr.merge_dict_list.evaluate(
context=ctx.yaql.ctx.create_child_context(),
data=[i(produce_ctx.yaql_ctx) for i in producers]
)["produce"]
ctx.taskflow.add_task("produce", func=task, after=["prepare"])
def _init_task_result(ctx):
def produce(inp):
return ctx.taskflow.run(_Obj(
yaql_ctx=ctx.yaql.ctx.create_child_context(),
inp=inp
))
ctx.out = produce
class _FunctionRegistry:
def __init__(self):
self.functions = []
def __call__(self, f):
self.functions.append(f)
return f
def fill_context(self, yaql_ctx):
for f in self.functions:
yaql_ctx.register_function(f)
_std_function_registry = _FunctionRegistry()
@_std_function_registry
def elide(x):
if x is None or x == [] or x == {}:
return ELIDE
else:
return x
def _register_std_functions():
@_std_function_registry
def to_yaml(data):
return _yaml.dump(data, Dumper=_yaml.RoundTripDumper)
@_std_function_registry
def to_json(data):
return _json.dumps(data, sort_keys=True)
_register_std_functions()
_YAQL_PREPARE_CTX = [
"def(merge0, $.aggregate($1.merge_with({''=>$2}), {}).get(''))",
"def(merge, merge0(merge0($)))"
]
class AnygenEngine:
def __init__(self):
self._taskflow = _TaskFlow()
self._yaql_engine = \
_yaql.YaqlFactory(allow_delegates=True) \
.create(
options={
# 'yaql.convertInputData': False
'yaql.convertInputData': True
})
self._yaql_ctx = _yaql.create_context(
convention=_yaql.language.conventions.PythonConvention(),
delegates=True
)
self._yaql_expr = _Obj(dict((k, self._yaql_engine(v)) for k, v in [
("merge_yaml_consts", "call(let, [none], $.aggregate($1.merge_with($2.yaml.get(const, {})), {}))"),
("merge_dict_list", "$.aggregate($1.merge_with($2), {})"),
]))
_std_function_registry.fill_context(self._yaql_ctx)
for i in _YAQL_PREPARE_CTX:
self._yaql_ctx = self._yaql_engine(i).evaluate(context=self._yaql_ctx, data=None)
self._taskflow.add_tasks([
('init', _init_task_init),
('load_yamls', _init_task_load_yamls),
('merge_yaml_consts', _init_task_merge_yaml_consts),
('py_deps', _init_task_py_deps),
('load_plugins', _init_task_load_plugins),
('load_py', _init_task_load_py),
('setup_yaql_extras', _init_task_setup_yaql_extras),
('setup_jinja', _init_task_setup_jinja),
('fragments', _init_task_fragments),
('prepare', _init_task_prepare),
('produce', _init_task_produce),
('result', _init_task_result),
])
def create(
self,
*,
path,
classes,
extras=None
):
return Anygen(self._taskflow.run(_Obj(
yaql=_Obj(
engine=self._yaql_engine,
ctx=self._yaql_ctx.create_child_context(),
expr=self._yaql_expr,
),
path=path,
classes=classes,
extras=extras or {}
)))
_yaql.yaqlization.yaqlize(_Obj)
_yaql.yaqlization.yaqlize(TaggedStr)
| 28.877264 | 111 | 0.604236 | import c3linearize as _c3linearize
import collections as _collections
import jinja2 as _jinja2
import json as _json
import pathlib as _pathlib
import pkg_resources as _pkg_resources
import ruamel.yaml as _yaml
from ruamel.yaml import YAML as _YAML
import runpy as _runpy
import subprocess as _subprocess
import sys as _sys
import yaql as _yaql
from . import scanextras as _scanextras
from .obj import Obj as _Obj
from .taskflow import TaskFlow as _TaskFlow
try:
__version__ = _pkg_resources.get_distribution(__name__).version
except: = object()
class TaggedStr(str):
def __new__(cls, s, **kw):
self = super().__new__(cls, s)
self.__dict__ = kw
return self
class TemplateResultStr(TaggedStr):
pass
def _which(path, name):
for path_entry in path:
path_name = _pathlib.Path(path_entry) / name
if path_name.exists():
return path_name
return None
def _checked_which(path, name):
result = _which(path, name)
if result is None:
raise FileNotFoundError(name, path)
return result
class Anygen:
def __init__(self, produce_func):
self._produce_func = produce_func
def produce(self, *args, **kw):
return self._produce_func(args + (kw,))
def _init_task_init(ctx):
ctx.yaql = ctx.inp.yaql
ctx.taskflow = _TaskFlow()
ctx.extras = _collections.defaultdict(dict)
for k, v in ctx.inp.extras.items():
ctx.extras[k].update(v)
def task(produce_ctx):
produce_ctx.yaql_ctx = produce_ctx.inp.yaql_ctx
produce_ctx.yaql_ctx["inp"] = ctx.yaql.expr.merge_dict_list.evaluate(
context=ctx.yaql.ctx.create_child_context(),
data=produce_ctx.inp.inp
)
produce_ctx.yaql_ctx["out"] = {}
ctx.taskflow.add_task("init", func=task)
def _init_task_load_yamls(ctx):
suffix = "anygen.yml"
COMBINED = object()
ROOT = object()
loaded = {}
yaml_loader = _YAML(typ='safe', pure=True)
def load_list(classes):
for i in classes:
load(i)
def load(class_):
nonlocal loaded
if class_ in loaded:
return
path_name = _checked_which(ctx.inp.path, class_ + "." + suffix)
yaml = yaml_loader.load(path_name)
extends = yaml.get("extends", [])
assert isinstance(extends, list)
loaded[class_] = _Obj(path_name=path_name, yaml=yaml, extends=extends)
load_list(extends)
def load_root():
path_name = _which(ctx.inp.path, suffix)
if path_name is None:
return
yaml = yaml_loader.load(path_name)
if "extends" in yaml:
raise RuntimeError("root class cannot have 'extends'")
loaded[ROOT] = _Obj(path_name=path_name, yaml=yaml)
load_list(ctx.inp.classes)
load_root()
if ROOT in loaded:
bases = [ROOT]
else:
bases = []
def bases_func(class_):
if class_ is COMBINED:
return ctx.inp.classes + bases
if class_ is ROOT:
return []
return list(loaded[class_].extends) + bases
dep_graph = _c3linearize.build_graph(COMBINED, bases_func)
c3linearization = _c3linearize.linearize(dep_graph, heads=[COMBINED])[COMBINED]
assert c3linearization.pop(0) is COMBINED
ctx.classes = list(reversed([loaded[i] for i in c3linearization]))
for class_ in ctx.classes:
class_.yaql_prefix = class_.yaml.get("marks", {}).get("yaql", "=")
class_.elideable_key_suffix = class_.yaml.get("marks", {}).get("elide", "?")
class_.merge_key_suffix = class_.yaml.get("marks", {}).get("merge", "+")
class_.filter_key_sep = class_.yaml.get("marks", {}).get("filter", "|")
def _init_task_merge_yaml_consts(ctx):
ctx.yaql.ctx0 = ctx.yaql.expr.merge_yaml_consts.evaluate(context=ctx.yaql.ctx, data=ctx.classes)
ctx.yaql.ctx = ctx.yaql.ctx0.create_child_context()
def _init_task_py_deps(ctx):
missing_requires = set()
for class_ in ctx.classes:
for req_str in class_.yaml.get('py_requires', []):
req = _pkg_resources.Requirement.parse(req_str)
try:
_pkg_resources.working_set.resolve([req])
except _pkg_resources.DistributionNotFound:
missing_requires.add(req)
if missing_requires:
if _sys.base_prefix == _sys.prefix:
raise RuntimeError(
"missing Python requirements and not running in venv -- will not try to autoinstall",
list(missing_requires)
)
_subprocess.check_call(
[_pathlib.Path(_sys.executable).parent / "pip", "install"] +
[str(i) for i in missing_requires]
)
def _init_task_load_plugins(ctx):
extras = ctx.extras
origins = _collections.defaultdict(list)
for entry_point in _pkg_resources.iter_entry_points("anygen", "extras"):
these_extras = entry_point.load()
for k1, v1 in these_extras.items():
for k2, v2 in v1.items():
origins[(k1, k2)].append(str(entry_point))
extras[k1][k2] = v2
dups = []
for k, these_origins in origins.items():
if len(these_origins) > 1:
dups.append(('%s_%s' % k, these_origins))
if dups:
raise RuntimeError(
"conflicting plugins installed. Some 'extras' are defined in multiple plugins",
dups
)
def _init_task_load_py(ctx):
extras = ctx.extras
for class_ in ctx.classes:
py_fname = class_.path_name.with_suffix(".py")
if not py_fname.exists():
continue
py_dict = _runpy.run_path(py_fname)
these_extras = _scanextras.scan(py_dict)
for k1, v1 in these_extras.items():
for k2, v2 in v1.items():
extras[k1][k2] = v2
def _init_task_setup_yaql_extras(ctx):
for k, v in ctx.extras["yaql"].items():
ctx.yaql.ctx.register_function(_yaql.language.specs.name(k)(v))
def _init_task_setup_jinja(ctx):
jinja_env = ctx.jinja_env = _jinja2.Environment(
loader=_jinja2.ChoiceLoader(
[_jinja2.DictLoader(class_.yaml.get("templates", {})) for class_ in reversed(ctx.classes)] +
[_jinja2.FileSystemLoader(ctx.inp.path)]
),
keep_trailing_newline=True
)
for k, v in ctx.extras["jinjaglobals"].items():
jinja_env.globals[k] = v
for k, v in ctx.extras["jinjafilter"].items():
jinja_env.filters[k] = v
for k, v in ctx.extras["jinjatest"].items():
jinja_env.tests[k] = v
@_yaql.language.specs.name("template")
def yaql_template(name, **kw):
return TemplateResultStr(jinja_env.get_template(name).render(**kw), name=name)
ctx.yaql.ctx.register_function(yaql_template)
def yaql_ctx_to_str(ctx):
if ctx is None:
return '*'
return str(dict((k, ctx.get_data(k)) for k in ctx.keys())) + ' | ' + yaql_ctx_to_str(ctx.parent)
def _init_task_prepare(ctx):
preparers = []
for class_ in ctx.classes:
prepare_exprs = class_.yaml.get("prepare", [])
if isinstance(prepare_exprs, str):
prepare_exprs = [prepare_exprs]
for expr in prepare_exprs:
preparers.append(ctx.yaql.engine(expr))
def task(produce_ctx):
for i in preparers:
produce_ctx.yaql_ctx = i.evaluate(context=produce_ctx.yaql_ctx, data=None)
ctx.taskflow.add_task("prepare", func=task, after=["init"])
def _recursive_yaql(ctx, class_, data):
def process_dict_item(k, v):
pipeline_tail = []
for suffix, yaql_filter in [
(class_.elideable_key_suffix, 'elide'),
(class_.merge_key_suffix, 'merge')
]:
if k.endswith(suffix):
k = k[:-len(suffix)]
pipeline_tail.append(yaql_filter)
k, *pipeline = k.split(class_.filter_key_sep)
pipeline.extend(reversed(pipeline_tail))
pipeline = [ctx.yaql.engine(i + '($)') for i in pipeline]
def produce(yaql_ctx):
result = v(yaql_ctx)
for i in pipeline:
result = i.evaluate(context=ctx.yaql.ctx, data=result)
return result
return k, produce
def recursive_elide(data):
if isinstance(data, dict):
return dict((k, recursive_elide(v)) for k, v in data.items() if v is not ELIDE)
elif isinstance(data, list):
return list(recursive_elide(i) for i in data if i is not ELIDE)
else:
return data
def recurse(data):
if isinstance(data, str):
if data.startswith(class_.yaql_prefix):
expr = ctx.yaql.engine(data[len(class_.yaql_prefix):])
return lambda yaql_ctx: recursive_elide(expr.evaluate(context=yaql_ctx))
else:
return lambda yaql_ctx: data
elif isinstance(data, dict):
items = list(process_dict_item(k, recurse(v)) for k, v in data.items())
return lambda yaql_ctx: dict(
(k, v)
for k, cb in items
for v in (cb(yaql_ctx),)
if v is not ELIDE
)
elif isinstance(data, list):
items = list(recurse(i) for i in data)
return lambda yaql_ctx: list(
v
for cb in items
for v in (cb(yaql_ctx),)
if v is not ELIDE
)
else:
return lambda yaql_ctx: data
return recurse(data)
def _yaql_let(yaql_ctx, *args, **kw):
yaql_ctx = yaql_ctx.create_child_context()
for i, v in enumerate(args, 1):
yaql_ctx[str(i)] = v
for k, v in kw.items():
yaql_ctx[k] = v
return yaql_ctx
def _init_task_fragments(ctx):
fragments = set()
for class_ in reversed(ctx.classes):
for k, v in class_.yaml.get("fragments", {}).items():
if k in fragments:
continue
fragments.add(k)
def one(k, v):
frag_func = _recursive_yaql(ctx, class_, v)
@_yaql.language.specs.name(k)
def wrapper(*args, **kw):
return frag_func(_yaql_let(ctx.yaql.ctx0, *args, **kw))
ctx.yaql.ctx0.register_function(wrapper)
one(k, v)
def _init_task_produce(ctx):
producers = [lambda yaql_ctx: yaql_ctx.get_data("out")] + [
_recursive_yaql(ctx, class_, {"produce" + suffix: data})
for class_ in ctx.classes
for suffix in ['', class_.merge_key_suffix]
for data in (class_.yaml.get("produce" + suffix, None),)
if data is not None
]
def task(produce_ctx):
produce_ctx.out = ctx.yaql.expr.merge_dict_list.evaluate(
context=ctx.yaql.ctx.create_child_context(),
data=[i(produce_ctx.yaql_ctx) for i in producers]
)["produce"]
ctx.taskflow.add_task("produce", func=task, after=["prepare"])
def _init_task_result(ctx):
def produce(inp):
return ctx.taskflow.run(_Obj(
yaql_ctx=ctx.yaql.ctx.create_child_context(),
inp=inp
))
ctx.out = produce
class _FunctionRegistry:
def __init__(self):
self.functions = []
def __call__(self, f):
self.functions.append(f)
return f
def fill_context(self, yaql_ctx):
for f in self.functions:
yaql_ctx.register_function(f)
_std_function_registry = _FunctionRegistry()
@_std_function_registry
def elide(x):
if x is None or x == [] or x == {}:
return ELIDE
else:
return x
def _register_std_functions():
@_std_function_registry
def to_yaml(data):
return _yaml.dump(data, Dumper=_yaml.RoundTripDumper)
@_std_function_registry
def to_json(data):
return _json.dumps(data, sort_keys=True)
_register_std_functions()
_YAQL_PREPARE_CTX = [
"def(merge0, $.aggregate($1.merge_with({''=>$2}), {}).get(''))",
"def(merge, merge0(merge0($)))"
]
class AnygenEngine:
def __init__(self):
self._taskflow = _TaskFlow()
self._yaql_engine = \
_yaql.YaqlFactory(allow_delegates=True) \
.create(
options={
'yaql.convertInputData': True
})
self._yaql_ctx = _yaql.create_context(
convention=_yaql.language.conventions.PythonConvention(),
delegates=True
)
self._yaql_expr = _Obj(dict((k, self._yaql_engine(v)) for k, v in [
("merge_yaml_consts", "call(let, [none], $.aggregate($1.merge_with($2.yaml.get(const, {})), {}))"),
("merge_dict_list", "$.aggregate($1.merge_with($2), {})"),
]))
_std_function_registry.fill_context(self._yaql_ctx)
for i in _YAQL_PREPARE_CTX:
self._yaql_ctx = self._yaql_engine(i).evaluate(context=self._yaql_ctx, data=None)
self._taskflow.add_tasks([
('init', _init_task_init),
('load_yamls', _init_task_load_yamls),
('merge_yaml_consts', _init_task_merge_yaml_consts),
('py_deps', _init_task_py_deps),
('load_plugins', _init_task_load_plugins),
('load_py', _init_task_load_py),
('setup_yaql_extras', _init_task_setup_yaql_extras),
('setup_jinja', _init_task_setup_jinja),
('fragments', _init_task_fragments),
('prepare', _init_task_prepare),
('produce', _init_task_produce),
('result', _init_task_result),
])
def create(
self,
*,
path,
classes,
extras=None
):
return Anygen(self._taskflow.run(_Obj(
yaql=_Obj(
engine=self._yaql_engine,
ctx=self._yaql_ctx.create_child_context(),
expr=self._yaql_expr,
),
path=path,
classes=classes,
extras=extras or {}
)))
_yaql.yaqlization.yaqlize(_Obj)
_yaql.yaqlization.yaqlize(TaggedStr)
| true | true |
f7f7715cde2a7388f587cf7db9ed983c764367e2 | 858 | py | Python | examples/units/bar_unit_demo.py | SoftwareDev/mat-plot-lib | abaf94859d5ef6e653a4d8a7ce2c59cea1724a57 | [
"MIT",
"BSD-3-Clause"
] | 16 | 2016-06-14T19:45:35.000Z | 2020-11-30T19:02:58.000Z | lib/mpl_examples/units/bar_unit_demo.py | yingkailiang/matplotlib | 255a79b106c98c1904489afe6a754e4d943179d6 | [
"MIT",
"BSD-3-Clause"
] | 7 | 2015-05-08T19:36:25.000Z | 2015-06-30T15:32:17.000Z | lib/mpl_examples/units/bar_unit_demo.py | yingkailiang/matplotlib | 255a79b106c98c1904489afe6a754e4d943179d6 | [
"MIT",
"BSD-3-Clause"
] | 6 | 2015-06-05T03:34:06.000Z | 2022-01-25T09:07:10.000Z | #!/usr/bin/env python
import numpy as np
from basic_units import cm, inch
import matplotlib.pyplot as plt
N = 5
menMeans = (150*cm, 160*cm, 146*cm, 172*cm, 155*cm)
menStd = ( 20*cm, 30*cm, 32*cm, 10*cm, 20*cm)
fig, ax = plt.subplots()
ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars
p1 = ax.bar(ind, menMeans, width, color='r', bottom=0*cm, yerr=menStd)
womenMeans = (145*cm, 149*cm, 172*cm, 165*cm, 200*cm)
womenStd = (30*cm, 25*cm, 20*cm, 31*cm, 22*cm)
p2 = ax.bar(ind+width, womenMeans, width, color='y', bottom=0*cm, yerr=womenStd)
ax.set_title('Scores by group and gender')
ax.set_xticks(ind+width)
ax.set_xticklabels( ('G1', 'G2', 'G3', 'G4', 'G5') )
ax.legend( (p1[0], p2[0]), ('Men', 'Women') )
ax.yaxis.set_units(inch)
ax.autoscale_view()
#plt.savefig('barchart_demo')
plt.show()
| 26.8125 | 80 | 0.651515 |
import numpy as np
from basic_units import cm, inch
import matplotlib.pyplot as plt
N = 5
menMeans = (150*cm, 160*cm, 146*cm, 172*cm, 155*cm)
menStd = ( 20*cm, 30*cm, 32*cm, 10*cm, 20*cm)
fig, ax = plt.subplots()
ind = np.arange(N)
width = 0.35
p1 = ax.bar(ind, menMeans, width, color='r', bottom=0*cm, yerr=menStd)
womenMeans = (145*cm, 149*cm, 172*cm, 165*cm, 200*cm)
womenStd = (30*cm, 25*cm, 20*cm, 31*cm, 22*cm)
p2 = ax.bar(ind+width, womenMeans, width, color='y', bottom=0*cm, yerr=womenStd)
ax.set_title('Scores by group and gender')
ax.set_xticks(ind+width)
ax.set_xticklabels( ('G1', 'G2', 'G3', 'G4', 'G5') )
ax.legend( (p1[0], p2[0]), ('Men', 'Women') )
ax.yaxis.set_units(inch)
ax.autoscale_view()
plt.show()
| true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.