from unittest import mock

from geo_garry import distance, polygons, Coordinates

def test_distance_calculator():
    service = distance.DistanceCalculatorAbstract(polygon=polygons.MKAD_POLYGON)

    with mock.patch.object(service, 'calc_distance', return_value=100500) as calc_mock:
        inside_mkad = Coordinates(latitude=55.6892209716432, longitude=37.752854389528585)
        assert service.get_distance(inside_mkad) == 0
        calc_mock.assert_not_called()

    with mock.patch.object(service, 'calc_distance', return_value=100590.1234) as calc_mock:
        outside_mkad = Coordinates(latitude=50.4254225, longitude=36.9020654)
        assert service.get_distance(outside_mkad) == 101
        calc_mock.assert_called_once_with(outside_mkad)

    with mock.patch.object(service, 'calc_distance', return_value=63) as calc_mock:
        outside_mkad = Coordinates(latitude=50.4254225, longitude=36.9020654)
        assert service.get_distance(outside_mkad) == 1
        calc_mock.assert_called_once_with(outside_mkad)

@mock.patch('geo_garry.gmaps.api.GoogleMapsApi')
def test_nearest_exits_calculator(api_mock):
    api_mock.get_distance_from_points.return_value = 5900

    service = distance.NearestExitsGoogleDistanceCalculator(
        api=api_mock,
        polygon=polygons.MKAD_POLYGON,
        exits_coordinates=distance.MKAD_EXITS_COORDINATES,
        exits_tree=distance.MKAD_TREE,
    )

    coords = Coordinates(123.10, 123.10)
    assert service.calc_distance(coords) == 5900
    api_mock.get_distance_from_points.assert_called_once_with([
        (55.82543390489343, 37.83464260085545),
        (55.82959228057486, 37.82861019557688),
        (55.8138082895938, 37.83884777073161),
        (55.81012946042399, 37.83951226232321),
        (55.80418173177062, 37.83998433110984),
        (55.802423269353746, 37.840209636667076),
        (55.77682626803085, 37.84269989967345)
    ], (123.10, 123.10))
    api_mock.get_distance_from_points.reset_mock()
    coords = Coordinates(153.10, 173.10)
    service.calc_distance(coords)
    api_mock.get_distance_from_points.assert_called_once_with([
        (55.82543390489343, 37.83464260085545),
        (55.82959228057486, 37.82861019557688),
        (55.8138082895938, 37.83884777073161),
        (55.81012946042399, 37.83951226232321),
        (55.80418173177062, 37.83998433110984),
        (55.802423269353746, 37.840209636667076),
        (55.77682626803085, 37.84269989967345)
    ], (153.10, 173.10))

@mock.patch('geo_garry.gmaps.api.GoogleMapsApi')
def test_polygon_center(api_mock):
    api_mock.get_driving_path.return_value = [
        {'distance': {'text': '68 m', 'value': 68},
         'duration': {'text': '1 min', 'value': 12},
         'end_location': {'lat': 59.9494407, 'lng': 30.3051397},
         'start_location': {'lat': 59.950025, 'lng': 30.3049966},
         'travel_mode': 'DRIVING'},
        {'distance': {'text': '0.9 km', 'value': 911},
         'duration': {'text': '3 mins', 'value': 181},
         'end_location': {'lat': 59.95240949999999, 'lng': 30.2904161},
         'start_location': {'lat': 59.9494407, 'lng': 30.3051397},
         'travel_mode': 'DRIVING'},
        {'distance': {'text': '0.3 km', 'value': 256},
         'duration': {'text': '1 min', 'value': 48},
         'end_location': {'lat': 59.95395199999999, 'lng': 30.2870172},
         'start_location': {'lat': 59.95240949999999, 'lng': 30.2904161},
         'travel_mode': 'DRIVING'},
        {'distance': {'text': '1.2 km', 'value': 1171},
         'duration': {'text': '2 mins', 'value': 97},
         'end_location': {'lat': 59.96126159999999, 'lng': 30.2720644},
         'start_location': {'lat': 59.95395199999999, 'lng': 30.2870172},
         'travel_mode': 'DRIVING'},
        {'distance': {'text': '1.1 km', 'value': 1128},
         'duration': {'text': '2 mins', 'value': 92},
         'end_location': {'lat': 59.9529837, 'lng': 30.2661487},
         'start_location': {'lat': 59.96126159999999, 'lng': 30.2720644},
         'travel_mode': 'DRIVING'},
        {'distance': {'text': '0.2 km', 'value': 155},
         'duration': {'text': '1 min', 'value': 34},
         'end_location': {'lat': 59.9539901, 'lng': 30.266071},
         'start_location': {'lat': 59.9529837, 'lng': 30.2661487},
         'travel_mode': 'DRIVING'},
        {'distance': {'text': '2.6 km', 'value': 2633},
         'duration': {'text': '2 mins', 'value': 145},
         'end_location': {'lat': 59.9618416, 'lng': 30.2237484},
         'start_location': {'lat': 59.9539901, 'lng': 30.266071},
         'travel_mode': 'DRIVING'},
        {'distance': {'text': '14.2 km', 'value': 14150},
         'duration': {'text': '9 mins', 'value': 535},
         'end_location': {'lat': 60.0594314, 'lng': 30.1433647},
         'start_location': {'lat': 59.9618416, 'lng': 30.2237484},
         'travel_mode': 'DRIVING'},
        {'distance': {'text': '0.9 km', 'value': 888},
         'duration': {'text': '1 min', 'value': 59},
         'end_location': {'lat': 60.05786469999999, 'lng': 30.1353269},
         'start_location': {'lat': 60.0594314, 'lng': 30.1433647},
         'travel_mode': 'DRIVING'},
        {'distance': {'text': '23.9 km', 'value': 23930},
         'duration': {'text': '14 mins', 'value': 843},
         'end_location': {'lat': 60.0135102, 'lng': 29.71841319999999},
         'start_location': {'lat': 60.05786469999999, 'lng': 30.1353269},
         'travel_mode': 'DRIVING'},
        {'distance': {'text': '0.3 km', 'value': 283},
         'duration': {'text': '1 min', 'value': 22},
         'end_location': {'lat': 60.01416589999999, 'lng': 29.7167109},
         'start_location': {'lat': 60.0135102, 'lng': 29.71841319999999},
         'travel_mode': 'DRIVING'},
        {'distance': {'text': '3.0 km', 'value': 3017},
         'duration': {'text': '4 mins', 'value': 253},
         'end_location': {'lat': 60.0012631, 'lng': 29.762545},
         'start_location': {'lat': 60.01416589999999, 'lng': 29.7167109},
         'travel_mode': 'DRIVING'},
        {'distance': {'text': '0.4 km', 'value': 388},
         'duration': {'text': '1 min', 'value': 40},
         'end_location': {'lat': 59.9980647, 'lng': 29.7597875},
         'start_location': {'lat': 60.0012631, 'lng': 29.762545},
         'travel_mode': 'DRIVING'},
        {'distance': {'text': '0.4 km', 'value': 382},
         'duration': {'text': '1 min', 'value': 70},
         'end_location': {'lat': 59.9966984, 'lng': 29.7660179},
         'start_location': {'lat': 59.9980647, 'lng': 29.7597875},
         'travel_mode': 'DRIVING'},
        {'distance': {'text': '88 m', 'value': 88},
         'duration': {'text': '1 min', 'value': 19},
         'end_location': {'lat': 59.9959712, 'lng': 29.7653955},
         'start_location': {'lat': 59.9966984, 'lng': 29.7660179},
         'travel_mode': 'DRIVING'},
        {'distance': {'text': '9 m', 'value': 9},
         'duration': {'text': '1 min', 'value': 2},
         'end_location': {'lat': 59.9959303, 'lng': 29.7655452},
         'start_location': {'lat': 59.9959712, 'lng': 29.7653955},
         'travel_mode': 'DRIVING'},
    ]
    service = distance.PolygonCenterGoogleDistanceCalculator(
        api=api_mock,
        polygon=distance.KAD_POLYGON,
        center=distance.KAD_CENTER,
    )
    assert round(service.calc_distance(
        Coordinates(latitude=59.991988, longitude=29.775469),
    )) == 35823
    api_mock.get_driving_path.assert_called_once_with(distance.KAD_CENTER.as_tuple(), (59.991988, 29.775469))

@mock.patch('geo_garry.distance.DistanceCalculatorAbstract.calc_distance')
def test_cacheable_calculator(calc_mock):
    storage_mock = mock.Mock(get=mock.Mock(return_value=12345))
    service = distance.CachedDistanceCalculator(storage=storage_mock, polygon=polygons.MKAD_POLYGON)
    outside_mkad = Coordinates(latitude=50.4254225, longitude=36.9020654)
    assert service.get_distance(outside_mkad) == 12
    storage_mock.get.assert_called_once_with('distance:50.4254225,36.9020654')
    calc_mock.assert_not_called()

    calc_mock.return_value = 12345
    storage_mock = mock.Mock(get=mock.Mock(return_value=None))
    service = distance.CachedDistanceCalculator(storage=storage_mock, polygon=polygons.MKAD_POLYGON)
    assert service.get_distance(outside_mkad) == 12
    storage_mock.set.assert_called_once_with('distance:50.4254225,36.9020654', '12345', ex=60*60*24*30)
    calc_mock.assert_called_once_with(outside_mkad)

@mock.patch('geo_garry.distance.NearestExitsGoogleDistanceCalculator.calc_distance')
def test_mkad_calculator(calc_mock):
    storage_mock = mock.Mock(get=mock.Mock(return_value=12345))
    service = distance.MkadDistanceCalculator(storage=storage_mock, gmaps_client=mock.Mock())
    outside_mkad = Coordinates(latitude=50.4254225, longitude=36.9020654)
    assert service.get_distance(outside_mkad) == 12
    storage_mock.get.assert_called_once_with('distance:50.4254225,36.9020654')
    calc_mock.assert_not_called()

    calc_mock.return_value = 12345
    storage_mock = mock.Mock(get=mock.Mock(return_value=None))
    service = distance.MkadDistanceCalculator(storage=storage_mock, gmaps_client=mock.Mock())
    assert service.get_distance(outside_mkad) == 12
    storage_mock.set.assert_called_once_with('distance:50.4254225,36.9020654', '12345', ex=60*60*24*30)
    calc_mock.assert_called_once_with(outside_mkad)

@mock.patch('geo_garry.distance.PolygonCenterGoogleDistanceCalculator.calc_distance')
def test_kad_calculator(calc_mock):
    storage_mock = mock.Mock(get=mock.Mock(return_value=12345))
    service = distance.KadDistanceCalculator(storage=storage_mock, gmaps_client=mock.Mock())
    outside_kad = Coordinates(latitude=59.991988, longitude=29.775469)
    assert service.get_distance(outside_kad) == 12
    storage_mock.get.assert_called_once_with('distance:59.991988,29.775469')
    calc_mock.assert_not_called()

    calc_mock.return_value = 12345
    storage_mock = mock.Mock(get=mock.Mock(return_value=None))
    service = distance.KadDistanceCalculator(storage=storage_mock, gmaps_client=mock.Mock())
    assert service.get_distance(outside_kad) == 12
    storage_mock.set.assert_called_once_with('distance:59.991988,29.775469', '12345', ex=60*60*24*30)
    calc_mock.assert_called_once_with(outside_kad)


import numpy as np
import matplotlib.pyplot as plt
from sklearn.mixture import GaussianMixture as GMM
from scipy.stats import multivariate_normal

#loads data
data = np.genfromtxt('vowdata_nohead.dat', dtype='U16')
identifiers = data[:, 0]
data = data[:, 2:7].astype(np.int)  # pulls out 'steady state' values for the vowels

vowels = ['ae', 'ah', 'aw', 'eh', 'er', 'ei', 'ih', 'iy', 'oa', 'oo', 'uh', 'uw']

#distributes tarining and testing data
N_train = 70
N_test = 69
N_all = N_train + N_test

train_index = []
test_index = []

for vowel in vowels:
    index = np.flatnonzero(np.core.defchararray.find(identifiers, vowel) != -1)
    train_index.extend(index[:N_train])
    test_index.extend(index[N_train:])

train_set = data[train_index]
test_set = data[test_index]

#put data into dictionary and creates answersheats
data_dict = dict()

for i in range(12):
	data_dict[vowels[i]] = data[i*N_all:(i+1)*N_all, :]

correct_train = np.asarray([i for i in range(12) for _ in range(N_train)])
correct_test = np.asarray([i for i in range(12) for _ in range(N_test)])

def mean(m):
    mean = m.mean(axis=0)
    return mean

def cov(m, diagonal=True):
    c = np.dot((m - m.mean(axis=0)).T, (m - m.mean(axis=0))) / (len(m) - 1)
    if diagonal:
        c = np.diag(np.diag(c))
    return c

# makes predictions given pdfs
def predict(dist, x):
	vowel_probabilities = np.zeros((len(vowels), len(x)))

	for i in range(len(vowels)):
		vowel_probabilities[i] = dist[vowels[i]](x)
	return np.argmax(vowel_probabilities, axis=0)

def error_rate(N, m):
    e = np.sum(m) - np.trace(m)
    print("#feil:", e)
    return e / N*100

#prints confusion matrix and error rate
def confuse(pred, corr, label=''):
	conf = np.zeros((12, 12))
	for i, j in zip(pred, corr):
		conf[i, j] += 1
	print(label, 'confusion:\n', conf)

	print("%s error: %.2f%%" % (label, error_rate(pred.shape[0], conf)))

# GAUSS (=GMM1) full cov

#train
distributions = dict()
for v in vowels:
	distributions[v] = multivariate_normal(mean(data_dict[v]),cov(data_dict[v], diagonal=False)).pdf

#predict
predicted_vowel_indices_test = predict(distributions, test_set)
#print confusion
confuse(predicted_vowel_indices_test, correct_test, 'full covar')

# GAUSS (=GMM1) diag cov

distributions = dict()
for v in vowels:
	distributions[v] = multivariate_normal(mean(data_dict[v]),cov(data_dict[v], diagonal=True)).pdf

predicted_vowel_indices_test = predict(distributions, test_set)
confuse(predicted_vowel_indices_test, correct_test, 'diag covar')

# GMM2

distributions = dict()
for v in vowels:
	gmm = GMM(2, 'diag') # 2 mixtures, cov-type diagonal
	gmm.fit(data_dict[v])
	distributions[v] = gmm.score_samples

pred = predict(distributions, test_set)
confuse(pred, correct_test, 'GMM2')

# GMM3

distributions = dict()
for v in vowels:
	gmm = GMM(3, 'diag')  # 3 mixtures, cov-type diag
	gmm.fit(data_dict[v])
	distributions[v] = gmm.score_samples

pred = predict(distributions, train_set)
confuse(pred, correct_test, 'GMM3')


# write a python program to create a dictionary that contains three dictionaries (nested).
item={"brand":{"model":2022,"price":5000,
       "rate":{"class":12,"subject":"maths",
       "mobile":{"locatio":"rewa","mail":"gaurav@gmail"}}}}
for i in item:
    if type(item[i]) is dict:
        for k in item[i]:
            print(k,' ',item[i])
print(item)


import tensorflow as tf
import glob
import os

# 形成文件名列表
image_filenames = glob.glob('E:/tensorflow/catdog/train/*.jpg')

# 推导出label列表
labels = list(map(lambda x:x.split('\\')[1].split('.')[0], image_filenames))

# 独热编码
train_label = [[1, 0] if x == 'cat' else [0, 1] for x in labels]

# 对照片目录的队列进行读取，形成了两个队列: 文件名、label
image_queue = tf.train.slice_input_producer([image_filenames, train_label])

# 解码
image_ = tf.read_file(image_queue[0])
image = tf.image.decode_jpeg(image_, channels=3)

# 将照片转换为灰度照片，channels = 1, 加快计算速度
grey_image = tf.image.rgb_to_grayscale(image)
# 统一照片大小
resize_image = tf.image.resize_images(grey_image, (200, 200))
# reshape
resize_image = tf.reshape(resize_image, [200, 200, 1])

# 标准化，加快CNN网络的训练过程
new_image = tf.image.per_image_standardization(resize_image)

# batch
batch_size = 60

# 形成batch使用， 一次读入130张， 加快速度
capacity = 10 + 2 * batch_size

# 形成批次
image_batch, label_batch = tf.train.batch([new_image, image_queue[1]], batch_size=batch_size, capacity=capacity)

# 第一层
conv2d_1 = tf.contrib.layers.convolution2d(
    image_batch,
    num_outputs=32,
    weights_initializer=tf.truncated_normal_initializer(stddev=0.001),
    kernel_size=(5, 5),
    activation_fn=tf.nn.relu,
    stride=(1, 1),
    padding='SAME',
    trainable=True
)

pool_1 = tf.nn.max_pool(conv2d_1,
                        # [0]：batch; [3]: channel, 一般设置为1， [1]\[2]: 对哪个部位进行运算
                        ksize=[1, 3, 3, 1],
                        # 跨度: 2 * 2
                        strides=[1, 2, 2, 1],
                        padding='SAME')

conv2d_2 = tf.contrib.layers.convolution2d(
    pool_1,
    num_outputs=32,
    weights_initializer=tf.truncated_normal_initializer(stddev=0.01),
    kernel_size=(5, 5),
    activation_fn=tf.nn.relu,
    stride=(1, 1),
    padding='SAME',
    trainable=True
)

pool_2 = tf.nn.max_pool(conv2d_2,
                        ksize=[1, 3, 3, 1],
                        strides=[1, 2, 2, 1],
                        padding='SAME')

conv2d_3 = tf.contrib.layers.convolution2d(
    pool_2,
    num_outputs=64,
    weights_initializer=tf.truncated_normal_initializer(stddev=0.01),
    kernel_size=(5, 5),
    activation_fn=tf.nn.relu,
    stride=(1, 1),
    padding='SAME',
    trainable=True
)

pool_3 = tf.nn.max_pool(conv2d_3,
                        ksize=[1, 3, 3, 1],
                        strides=[1, 2, 2, 1],
                        padding='SAME')

# 扁平化
pool3_flat = tf.reshape(pool_3, [-1, 25 * 25 * 64])

fc_1 = tf.contrib.layers.fully_connected(
    pool3_flat,
    1024,
    weights_initializer=tf.truncated_normal_initializer(stddev=0.1),
    activation_fn=tf.nn.relu
)

fc_2 = tf.contrib.layers.fully_connected(
    fc_1,
    192,
    weights_initializer=tf.truncated_normal_initializer(stddev=0.1),
    activation_fn=tf.nn.relu
)

out_w1 = tf.Variable(tf.truncated_normal([192, 2]))
out_b1 = tf.Variable(tf.truncated_normal([2]))
comb_out = tf.matmul(fc_2, out_w1) + out_b1
pred = tf.sigmoid(comb_out)

label_batch = tf.cast(label_batch, tf.float32)

loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=label_batch, logits=comb_out))

train_step = tf.train.AdamOptimizer(0.0001).minimize(loss)

predicted = tf.cast(pred > 0.5, tf.float32)
accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, label_batch), tf.float32))

ckpt = tf.train.get_checkpoint_state(os.path.dirname('./ck/'))
saver = tf.train.Saver()
sess = tf.Session()
# 初始化参数
sess.run(tf.global_variables_initializer())
saver.restore(sess, ckpt.model_checkpoint_path)

# 控制队列
coord = tf.train.Coordinator()
# 启动队列
threads = tf.train.start_queue_runners(coord=coord, sess=sess)

# 训练3000步:
for step in range(2000, 3000):
    sess.run(train_step)
    if step % 100 == 0:
        res = sess.run([loss, accuracy])
        print(step, res)
        saver.save(sess, './ck/CK_L8_catdog', global_step=step)
coord.request_stop()
coord.join(threads)

sess.close()


import importlib

import spacy
from tqdm import tqdm
from utils import convert_word_idx_to_char_idx

class FactualFactorExtractor:
    def __init__(self, fact_extractor='en_core_web_trf', use_gpu=False, device=0):

        if use_gpu:
            spacy.require_gpu(device)

        # load nlp tool
        # it can be loaded by "import en_core_web_trf" or "spacy.load('en_core_web_trf')"
        try:
            module = importlib.import_module(fact_extractor)
            self.nlp = module.load()
        except ImportError:
            self.nlp = spacy.load(fact_extractor)

    def extract_factual_factors(self,
                                documents,
                                summaries,
                                granularity='sentence',
                                use_tqdm=True):
        """
        1. Split sentences by SpaCy in order to match the index in entities or nouns extracted by it.
        2. Extract factual factors from summary by SpaCy.
        """

        processed_data = []

        if use_tqdm:
            bar = tqdm(list(zip(documents, summaries)), desc=f'Extracting factual factors', ncols=150)
        else:
            print(f'Extracting factual factors from {len(documents)} samples...')
            bar = list(zip(documents, summaries))

        # process each pair of document and summary
        for i, (r_document, r_summary) in enumerate(bar):

            document = ' '.join(list(filter(lambda x: x, r_document.split(' '))))
            summary = ' '.join(list(filter(lambda x: x, r_summary.split(' '))))

            seg_document = [word.text for word in self.nlp(document)]

            bias = 0  # sentence bias
            summary_sentences = []
            summary_entities = []
            summary_nouns = []

            if granularity == 'sentence':
                seg_sentences = self.nlp(summary).sents
            else:
                seg_sentences = [self.nlp(summary)]

            for seg_sentence in seg_sentences:
                seg_summary_sentence = [word.text for word in seg_sentence]
                entities = [{'text': ent.text,
                             'start': ent.start - bias,
                             'end': ent.end - bias} for ent in seg_sentence.ents]
                nouns = [{'text': noun_chunk.text,
                          'start': noun_chunk.start - bias,
                          'end': noun_chunk.end - bias} for noun_chunk in
                         seg_sentence.noun_chunks]
                bias += len(seg_summary_sentence)

                # convert the word indices to char indices
                # 'I am a good man.' (good, 3, 4) to (good, 7, 11)
                entities = convert_word_idx_to_char_idx(seg_summary_sentence, entities)
                nouns = convert_word_idx_to_char_idx(seg_summary_sentence, nouns)

                summary_sentences.append(' '.join(seg_summary_sentence))    # merge to a string
                summary_entities.append(entities)
                summary_nouns.append(nouns)

            processed_data.append({
                'document': ' '.join(seg_document),
                'summary_sentences': summary_sentences,
                'summary_entities': summary_entities,
                'summary_nouns': summary_nouns
            })

        return processed_data

    def mixture_factual_factors(self, factors1, factors2):
        """
        Drop out the factors2's factors which overlap factors1's factors.
        """
        candidate_factors = []

        for j in range(len(factors2)):
            for i in range(len(factors1)):
                if i == 0:
                    if factors2[j]['end'] <= factors1[i]['start']:
                        candidate_factors.append(factors2[j])
                        break
                else:
                    if factors2[j]['start'] >= factors1[i - 1]['end'] and factors2[j]['end'] <= factors1[i]['start']:
                        candidate_factors.append(factors2[j])
                        break

            if factors1 and factors2[j]['start'] >= factors1[-1]['end']:
                candidate_factors.extend(factors2[j:])
                break

        if not factors1:
            factors = factors2
        else:
            factors = factors1 + candidate_factors
            factors = list(sorted(factors, key=lambda x: x['start']))

        return factors

    def select_factual_factors(self, entities, nouns, selection):

        if selection == 'entity':
            return entities
        elif selection == 'noun':
            return nouns
        elif selection == 'noun_first':
            return self.mixture_factual_factors(nouns, entities)
        else:
            return self.mixture_factual_factors(entities, nouns)

    def block(self, factors, k):
        blocks = []
        block = []
        for factor in factors:
            block.append(factor)
            if len(block) == k:
                blocks.append(block)
                block = []

        if block:
            blocks.append(block)

        return blocks

    def block_factual_factors(self, data, k, selection, use_tqdm):

        processed_data = []

        if use_tqdm:
            bar = tqdm(data, desc=f'Blocking factual factors by k={k}', ncols=150)
        else:
            print(f'Blocking factual factors by k={k} from {len(data)} samples...')
            bar = data

        for i, sample in enumerate(bar):
            for j, (sentence, entities, nouns) in enumerate(
                    zip(sample['summary_sentences'], sample['summary_entities'], sample['summary_nouns'])):
                factors = self.select_factual_factors(entities, nouns, selection)
                factors = self.block(factors, k)
                factors = factors if factors else [[]]

                for sub_factors in factors:
                    processed_data.append({
                        'sample_id': i,
                        'sentence_id': j,
                        'document': sample['document'],
                        'summary': sentence,
                        'factors': sub_factors
                    })

        return processed_data

    def extract(self,
                documents,
                summaries,
                k,
                granularity,
                selection,
                use_tqdm):
        """
        1. Extract factual factors from summary.
        2. Block the samples by k.
        """
        processed_data = self.extract_factual_factors(documents, summaries, granularity, use_tqdm)
        processed_data = self.block_factual_factors(processed_data, k, selection, use_tqdm)

        return processed_data


__author__ = ' abhinil'

from flask import Flask, render_template, request, g
from flask import Markup
from plotly.offline import plot
from scipy.stats import uniform, norm, expon
import pandas as pd
import math
import plotly.express as px
import time

app = Flask(__name__)

def UniformDist(mean, stddev):
    sum1 = mean*2 #a+b
    variance = stddev**2
    diff1 = math.sqrt(variance*12) #b-a
    b = (sum1 + diff1)/2
    a = (sum1 - b)

    #configs
    n = 10000
    start = a
    width = b-a
    data_uniform = uniform.rvs(size=n, loc = start, scale=width)
    df = pd.DataFrame(data_uniform, columns = ['y'])
    return df

def NormalDist(mean, stddev):
    n = 10000
    data_normal = norm.rvs(size=n, loc = mean, scale=stddev)
    df = pd.DataFrame(data_normal, columns = ['y'])
    return df

def ExpDist(mean, stddev):
    lam = stddev
    e = mean - lam
    n = 10000
    data_normal = expon.rvs(size=n, loc = e, scale=lam)
    df = pd.DataFrame(data_normal, columns = ['y'])
    return df

def graph(x1, x2):
    fig = plot(px.pie(values=[x1, x2], names=["Simul Time", "Network Overhead"]), output_type='div')
    return fig
end = 0
start = 0
@app.before_request
def before_request():
    g.request_start_time = time.time()
    g.request_p = lambda: ""
    g.request_time = lambda: ""
    g.request_graph = lambda x1, x2: ""
    g.st = 0
    g.nt = lambda: int(0)

p = 0
@app.route('/')
def DistSimul():
    return render_template('DistSimul.html')
@app.route('/result', methods = ['POST'])
def result():
    t = request.values.get('t', 0)
    time.sleep(float(t))
    try:
        mean = float(request.form.get('mean'))
        stddev = float(request.form.get('stddev'))
        type = request.form.get('distribution-type')
    except:
        return render_template('DistSimul.html', ex = "Please enter values in all fields and in correct data types! ")
    start = time.time()

    if(type == "Uniform"):
        df = UniformDist(mean, stddev)
    elif(type == "Normal"):
        df = NormalDist(mean, stddev)
    else:
        df = ExpDist(mean, stddev)

    my_plot_div = plot(px.histogram(df, nbins=200, title = str(type)+ " distribution"), output_type='div')

    end = time.time()

    g.request_p = lambda: "%.5f ms" % ((time.time() - g.request_start_time - end + start)*1000)
    g.request_time = lambda: "%.5f ms" % ((time.time() - g.request_start_time)*1000)
    g.request_graph = lambda x1, x2: Markup(graph(x1, x2))

    g.st = (end- start)*1000
    g.nt = lambda: ((time.time() - g.request_start_time)*1000)
    return render_template('DistSimul.html', placeholder=Markup(my_plot_div), t1 = "{:.3f}".format((end- start)*1000)+" ms" , t = (end-start)*1000)

if __name__ == '__main__':
    app.run(debug=True, host = '0.0.0.0', port = 4000)


from sys import stdin
getc = stdin.readline
TC = int(getc())
for i in range(TC):
    if i > 0: print()
    D = int(getc())
    db = []
    for _ in range(D):
        make, L, H = getc().split()
        db.append((make, int(L), int(H)))
    Q = int(getc())
    for _ in range(Q):
        count = 0
        price = int(getc())
        for m, l, h in db:
            if price <= h and price >= l:
                if count == 0:
                    name = m
                count += 1
                if count > 1:
                    break
        if count == 1:
            print(name)
        else:
            print('UNDETERMINED')


import ctypes
import os
import sys
from abc import abstractmethod
from contextlib import contextmanager
from dataclasses import dataclass

build_dir = os.environ.get("KERNEL_EXPLORER_BUILD_DIR", None)
if build_dir is None:
    raise ValueError("Environment variable KERNEL_EXPLORER_BUILD_DIR is required")

if not os.path.exists(build_dir):
    raise ValueError(f"KERNEL_EXPLORER_BUILD_DIR ({build_dir}) points to nonexistent path")

# onnxruntime_pybind11_state and kernel_explorer
sys.path.insert(0, build_dir)

# pylint: disable=wrong-import-position
import onnxruntime_pybind11_state  # noqa: E402

# We need to call some functions to properly initialize so pointers in the library
available_providers = onnxruntime_pybind11_state.get_available_providers()

build_dir = os.path.realpath(build_dir)
search_paths = [build_dir]

# As Kernel Explorer makes use of utility functions in ONNXRuntime, we dlopen all relevant libraries to bring required
# symbols into global namespace, so that we don't need to worry about linking.
library_files_to_load = [
    "onnxruntime_pybind11_state.so",
    "libonnxruntime_providers_shared.so",
]
if "CUDAExecutionProvider" in available_providers:
    library_files_to_load.append("libonnxruntime_providers_cuda.so")
if "ROCMExecutionProvider" in available_providers:
    library_files_to_load.append("libonnxruntime_providers_rocm.so")

library_to_load = []

for lib in library_files_to_load:
    for prefix in search_paths:
        path = os.path.join(prefix, lib)
        if os.path.exists(path):
            library_to_load.append(path)
            continue

        raise OSError(f"cannot found {lib}")

# use RTLD_GLOBAL to bring all symbols to global name space
libraries = [ctypes.CDLL(lib_path, mode=ctypes.RTLD_GLOBAL) for lib_path in library_to_load]

# pylint: disable=wrong-import-position, disable=unused-import
import _kernel_explorer  # noqa: E402, F401

# pylint: disable=wrong-import-position, disable=unused-import, disable=wildcard-import
from _kernel_explorer import *  # noqa: F403, E402

# Benchmark Reporter
@dataclass
class MetricBase:
    name: str
    dtype: str
    milliseconds_duration: float

    def __lt__(self, other):
        if "Tunable" in self.name or other.duration < 0:
            return True
        if "Tunable" in other.name or self.duration < 0:
            return False

        return self.duration < other.duration

    @property
    def duration(self):
        return self.milliseconds_duration * 1000

    @abstractmethod
    def report(self) -> str:
        raise NotImplementedError()

@dataclass
class ComputeMetric(MetricBase):
    FLOPs: int

    @property
    def tflops(self):
        return self.FLOPs * 1e6 / self.duration / 1e12

@dataclass
class BandwidthMetric(MetricBase):
    bytes: int

    @property
    def gbps(self):
        return self.bytes * 1e6 / self.duration / 1e9

@dataclass
class ComputeAndBandwidthMetric(ComputeMetric, BandwidthMetric):
    pass

class InstanceBenchmarkReporter:
    def __init__(self):
        self.sort = False
        self.reporters = []

    def set_sort(self, sort):
        self.sort = sort

    def make_report(self):
        self.reporters.sort()
        for item in self.reporters:
            print(item.report())
        self.reporters.clear()

    def receive(self, status):
        self.reporters.append(status)
        if not self.sort:
            self.make_report()

_reporter = InstanceBenchmarkReporter()

@contextmanager
def benchmark(sort):
    _reporter.set_sort(sort)
    try:
        yield
    finally:
        _reporter.make_report()

def report(status):
    _reporter.receive(status)


__title__ = "FemInputWriterCcx"
__author__ = "Przemo Firszt, Bernd Hahnebach"
__url__ = "http://www.freecadweb.org"

## \addtogroup FEM
#  @{

import FreeCAD
import os
import sys
import time
import FemMeshTools
import FemInputWriter

class FemInputWriterCcx(FemInputWriter.FemInputWriter):
    def __init__(self,
                 analysis_obj, solver_obj,
                 mesh_obj, matlin_obj, matnonlin_obj,
                 fixed_obj, displacement_obj,
                 contact_obj, planerotation_obj, transform_obj,
                 selfweight_obj, force_obj, pressure_obj,
                 temperature_obj, heatflux_obj, initialtemperature_obj,
                 beamsection_obj, shellthickness_obj,
                 analysis_type=None, dir_name=None
                 ):

        FemInputWriter.FemInputWriter.__init__(
            self,
            analysis_obj, solver_obj,
            mesh_obj, matlin_obj, matnonlin_obj,
            fixed_obj, displacement_obj,
            contact_obj, planerotation_obj, transform_obj,
            selfweight_obj, force_obj, pressure_obj,
            temperature_obj, heatflux_obj, initialtemperature_obj,
            beamsection_obj, shellthickness_obj,
            analysis_type, dir_name)
        self.main_file_name = self.mesh_object.Name + '.inp'
        self.file_name = self.dir_name + '/' + self.main_file_name
        print('FemInputWriterCcx --> self.dir_name  -->  ' + self.dir_name)
        print('FemInputWriterCcx --> self.main_file_name  -->  ' + self.main_file_name)
        print('FemInputWriterCcx --> self.file_name  -->  ' + self.file_name)

    def write_calculix_input_file(self):
        if self.solver_obj.SplitInputWriter is True:
            self.write_calculix_splitted_input_file()
        else:
            self.write_calculix_one_input_file()
        return self.file_name

    def write_calculix_one_input_file(self):
        timestart = time.clock()
        self.femmesh.writeABAQUS(self.file_name)

        # reopen file with "append" and add the analysis definition
        inpfile = open(self.file_name, 'a')
        inpfile.write('\n\n')

        # node and element sets
        self.write_element_sets_material_and_femelement_type(inpfile)
        if self.fixed_objects:
            self.write_node_sets_constraints_fixed(inpfile)
        if self.displacement_objects:
            self.write_node_sets_constraints_displacement(inpfile)
        if self.planerotation_objects:
            self.write_node_sets_constraints_planerotation(inpfile)
        if self.contact_objects:
            self.write_surfaces_contraints_contact(inpfile)
        if self.transform_objects:
            self.write_node_sets_constraints_transform(inpfile)
        if self.analysis_type == "thermomech" and self.temperature_objects:
            self.write_node_sets_constraints_temperature(inpfile)

        # materials and fem element types
        self.write_materials(inpfile)
        if self.analysis_type == "thermomech" and self.initialtemperature_objects:
            self.write_constraints_initialtemperature(inpfile)
        self.write_femelementsets(inpfile)

        # constraints independent from steps
        if self.planerotation_objects:
            self.write_constraints_planerotation(inpfile)
        if self.contact_objects:
            self.write_constraints_contact(inpfile)
        if self.transform_objects:
            self.write_constraints_transform(inpfile)

        # step begin
        self.write_step_begin(inpfile)

        # constraints depend on step used in all analysis types
        if self.fixed_objects:
            self.write_constraints_fixed(inpfile)
        if self.displacement_objects:
            self.write_constraints_displacement(inpfile)

        # constraints depend on step and depending on analysis type
        if self.analysis_type == "frequency":
            pass
        elif self.analysis_type == "static":
            if self.selfweight_objects:
                self.write_constraints_selfweight(inpfile)
            if self.force_objects:
                self.write_constraints_force(inpfile)
            if self.pressure_objects:
                self.write_constraints_pressure(inpfile)
        elif self.analysis_type == "thermomech":
            if self.selfweight_objects:
                self.write_constraints_selfweight(inpfile)
            if self.force_objects:
                self.write_constraints_force(inpfile)
            if self.pressure_objects:
                self.write_constraints_pressure(inpfile)
            if self.temperature_objects:
                self.write_constraints_temperature(inpfile)
            if self.heatflux_objects:
                self.write_constraints_heatflux(inpfile)

        # output and step end
        self.write_outputs_types(inpfile)
        self.write_step_end(inpfile)

        # footer
        self.write_footer(inpfile)
        inpfile.close()
        print("Writing time input file: " + str(time.clock() - timestart) + ' \n')

    def write_calculix_splitted_input_file(self):
        timestart = time.clock()

        # reopen file with "append" and add the analysis definition
        # first open file with "write" to ensure that each new iteration of writing of inputfile starts in new file
        # first open file with "write" to ensure that the .writeABAQUS also writes in inputfile
        inpfileMain = open(self.file_name, 'w')
        inpfileMain.close
        inpfileMain = open(self.file_name, 'a')
        inpfileMain.write('\n\n')

        # write nodes and elements
        name = self.file_name[:-4]
        include_name = self.main_file_name[:-4]

        inpfileNodesElem = open(name + "_Node_Elem_sets.inp", 'w')
        self.femmesh.writeABAQUS(name + "_Node_Elem_sets.inp")
        inpfileNodesElem.close
        inpfileMain.write('\n***********************************************************\n')
        inpfileMain.write('**Nodes and Elements\n')
        inpfileMain.write('** written by femmesh.writeABAQUS\n')
        inpfileMain.write('*INCLUDE,INPUT=' + include_name + "_Node_Elem_sets.inp \n")

        # create seperate inputfiles for each node set or constraint
        if self.fixed_objects or self.displacement_objects or self.planerotation_objects:
            inpfileNodes = open(name + "_Node_sets.inp", 'w')
        if self.analysis_type == "thermomech" and self.temperature_objects:
            inpfileNodeTemp = open(name + "_Node_Temp.inp", 'w')
        if self.force_objects:
            inpfileForce = open(name + "_Node_Force.inp", 'w')
        if self.pressure_objects:
            inpfilePressure = open(name + "_Pressure.inp", 'w')
        if self.analysis_type == "thermomech" and self.heatflux_objects:
            inpfileHeatflux = open(name + "_Node_Heatlfux.inp", 'w')
        if self.contact_objects:
            inpfileContact = open(name + "_Surface_Contact.inp", 'w')
        if self.transform_objects:
            inpfileTransform = open(name + "_Node_Transform.inp", 'w')

        # node and element sets
        self.write_element_sets_material_and_femelement_type(inpfileMain)
        if self.fixed_objects:
            self.write_node_sets_constraints_fixed(inpfileNodes)
        if self.displacement_objects:
            self.write_node_sets_constraints_displacement(inpfileNodes)
        if self.planerotation_objects:
            self.write_node_sets_constraints_planerotation(inpfileNodes)
        if self.contact_objects:
            self.write_surfaces_contraints_contact(inpfileContact)
        if self.transform_objects:
            self.write_node_sets_constraints_transform(inpfileTransform)

        # write commentary and include statement for static case node sets
        inpfileMain.write('\n***********************************************************\n')
        inpfileMain.write('**Node sets for constraints\n')
        inpfileMain.write('** written by write_node_sets_constraints_fixed\n')
        inpfileMain.write('** written by write_node_sets_constraints_displacement\n')
        inpfileMain.write('** written by write_node_sets_constraints_planerotation\n')
        if self.fixed_objects or self.displacement_objects or self.planerotation_objects:
            inpfileMain.write('*INCLUDE,INPUT=' + include_name + "_Node_sets.inp \n")

        inpfileMain.write('\n***********************************************************\n')
        inpfileMain.write('** Surfaces for contact constraint\n')
        inpfileMain.write('** written by write_surfaces_contraints_contact\n')
        if self.contact_objects:
            inpfileMain.write('*INCLUDE,INPUT=' + include_name + "_Surface_Contact.inp \n")

        inpfileMain.write('\n***********************************************************\n')
        inpfileMain.write('** Node sets for transform constraint\n')
        inpfileMain.write('** written by write_node_sets_constraints_transform\n')
        if self.transform_objects:
            inpfileMain.write('*INCLUDE,INPUT=' + include_name + "_Node_Transform.inp \n")

        if self.analysis_type == "thermomech" and self.temperature_objects:
            self.write_node_sets_constraints_temperature(inpfileNodeTemp)

        # include seperately written temperature constraint in input file
        if self.analysis_type == "thermomech":
            inpfileMain.write('\n***********************************************************\n')
            inpfileMain.write('**Node sets for temperature constraint\n')
            inpfileMain.write('** written by write_node_sets_constraints_temperature\n')
            if self.temperature_objects:
                inpfileMain.write('*INCLUDE,INPUT=' + include_name + "_Node_Temp.inp \n")

        # materials and fem element types
        self.write_materials(inpfileMain)
        if self.analysis_type == "thermomech" and self.initialtemperature_objects:
            self.write_constraints_initialtemperature(inpfileMain)
        self.write_femelementsets(inpfileMain)

        # constraints independent from steps
        if self.planerotation_objects:
            self.write_constraints_planerotation(inpfileMain)
        if self.contact_objects:
            self.write_constraints_contact(inpfileMain)
        if self.transform_objects:
            self.write_constraints_transform(inpfileMain)

        # step begin
        self.write_step_begin(inpfileMain)

        # constraints depend on step used in all analysis types
        if self.fixed_objects:
            self.write_constraints_fixed(inpfileMain)
        if self.displacement_objects:
            self.write_constraints_displacement(inpfileMain)

        # constraints depend on step and depending on analysis type
        if self.analysis_type == "frequency":
            pass
        elif self.analysis_type == "static":
            if self.selfweight_objects:
                self.write_constraints_selfweight(inpfileMain)
            if self.force_objects:
                self.write_constraints_force(inpfileForce)
            if self.pressure_objects:
                self.write_constraints_pressure(inpfilePressure)
        elif self.analysis_type == "thermomech":
            if self.selfweight_objects:
                self.write_constraints_selfweight(inpfileMain)
            if self.force_objects:
                self.write_constraints_force(inpfileForce)
            if self.pressure_objects:
                self.write_constraints_pressure(inpfilePressure)
            if self.temperature_objects:
                self.write_constraints_temperature(inpfileMain)
            if self.heatflux_objects:
                self.write_constraints_heatflux(inpfileHeatflux)

        # include seperately written constraints in input file
        inpfileMain.write('\n***********************************************************\n')
        inpfileMain.write('** Node loads\n')
        inpfileMain.write('** written by write_constraints_force\n')
        if self.force_objects:
            inpfileMain.write('*INCLUDE,INPUT=' + include_name + "_Node_Force.inp \n")

        inpfileMain.write('\n***********************************************************\n')
        inpfileMain.write('** Element + CalculiX face + load in [MPa]\n')
        inpfileMain.write('** written by write_constraints_pressure\n')
        if self.pressure_objects:
            inpfileMain.write('*INCLUDE,INPUT=' + include_name + "_Pressure.inp \n")

        if self.analysis_type == "thermomech":
            inpfileMain.write('\n***********************************************************\n')
            inpfileMain.write('** Convective heat transfer (heat flux)\n')
            inpfileMain.write('** written by write_constraints_heatflux\n')
            if self.heatflux_objects:
                inpfileMain.write('*INCLUDE,INPUT=' + include_name + "_Node_Heatlfux.inp \n")

        # output and step end
        self.write_outputs_types(inpfileMain)
        self.write_step_end(inpfileMain)

        # footer
        self.write_footer(inpfileMain)
        inpfileMain.close()
        print("Writing time input file: " + str(time.clock() - timestart) + ' \n')

    def write_element_sets_material_and_femelement_type(self, f):
        f.write('\n***********************************************************\n')
        f.write('** Element sets for materials and FEM element type (solid, shell, beam)\n')
        f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name))
        if len(self.material_objects) == 1:
            if self.beamsection_objects and len(self.beamsection_objects) == 1:          # single mat, single beam
                self.get_ccx_elsets_single_mat_single_beam()
            elif self.beamsection_objects and len(self.beamsection_objects) > 1:         # single mat, multiple beams
                self.get_ccx_elsets_single_mat_multiple_beam()
            elif self.shellthickness_objects and len(self.shellthickness_objects) == 1:  # single mat, single shell
                self.get_ccx_elsets_single_mat_single_shell()
            elif self.shellthickness_objects and len(self.shellthickness_objects) > 1:   # single mat, multiple shells
                self.get_ccx_elsets_single_mat_multiple_shell()
            else:                                                                        # single mat, solid
                self.get_ccx_elsets_single_mat_solid()
        else:
            if self.beamsection_objects and len(self.beamsection_objects) == 1:         # multiple mats, single beam
                self.get_ccx_elsets_multiple_mat_single_beam()
            elif self.beamsection_objects and len(self.beamsection_objects) > 1:        # multiple mats, multiple beams
                self.get_ccx_elsets_multiple_mat_multiple_beam()
            elif self.shellthickness_objects and len(self.shellthickness_objects) == 1:   # multiple mats, single shell
                self.get_ccx_elsets_multiple_mat_single_shell()
            elif self.shellthickness_objects and len(self.shellthickness_objects) > 1:  # multiple mats, multiple shells
                self.get_ccx_elsets_multiple_mat_multiple_shell()
            else:                                                                       # multiple mats, solid
                self.get_ccx_elsets_multiple_mat_solid()
        for ccx_elset in self.ccx_elsets:
            f.write('*ELSET,ELSET=' + ccx_elset['ccx_elset_name'] + '\n')
            if ccx_elset['ccx_elset']:
                if ccx_elset['ccx_elset'] == self.ccx_eall:
                    f.write(self.ccx_eall + '\n')
                else:
                    for elid in ccx_elset['ccx_elset']:
                        f.write(str(elid) + ',\n')
            else:
                f.write('**No elements found for these objects\n')

    def write_node_sets_constraints_fixed(self, f):
        # get nodes
        self.get_constraints_fixed_nodes()
        # write nodes to file
        f.write('\n***********************************************************\n')
        f.write('** Node set for fixed constraint\n')
        f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name))
        for femobj in self.fixed_objects:  # femobj --> dict, FreeCAD document object is femobj['Object']
            f.write('*NSET,NSET=' + femobj['Object'].Name + '\n')
            for n in femobj['Nodes']:
                f.write(str(n) + ',\n')

    def write_node_sets_constraints_displacement(self, f):
        # get nodes
        self.get_constraints_displacement_nodes()
        # write nodes to file
        f.write('\n***********************************************************\n')
        f.write('** Node sets for prescribed displacement constraint\n')
        f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name))
        for femobj in self.displacement_objects:  # femobj --> dict, FreeCAD document object is femobj['Object']
            f.write('*NSET,NSET=' + femobj['Object'].Name + '\n')
            for n in femobj['Nodes']:
                f.write(str(n) + ',\n')

    def write_node_sets_constraints_planerotation(self, f):
        # get nodes
        self.get_constraints_planerotation_nodes()
        # write nodes to file
        if not self.femnodes_mesh:
            self.femnodes_mesh = self.femmesh.Nodes
        f.write('\n***********************************************************\n')
        f.write('** Node set for plane rotation constraint\n')
        f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name))
        # info about self.constraint_conflict_nodes:
        # is used to check if MPC and constraint fixed and constraint displacement share same nodes,
        # because MPC's and constriants fixed an constraints displacement can't share same nodes.
        # thus call write_node_sets_constraints_planerotation has to be after constraint fixed and constraint displacement
        for femobj in self.planerotation_objects:  # femobj --> dict, FreeCAD document object is femobj['Object']
            l_nodes = femobj['Nodes']
            fric_obj = femobj['Object']
            f.write('*NSET,NSET=' + fric_obj.Name + '\n')
            # Code to extract nodes and coordinates on the PlaneRotation support face
            nodes_coords = []
            for node in l_nodes:
                nodes_coords.append((node, self.femnodes_mesh[node].x, self.femnodes_mesh[node].y, self.femnodes_mesh[node].z))
            node_planerotation = FemMeshTools.get_three_non_colinear_nodes(nodes_coords)
            for i in range(len(l_nodes)):
                if l_nodes[i] not in node_planerotation:
                    node_planerotation.append(l_nodes[i])
            MPC_nodes = []
            for i in range(len(node_planerotation)):
                cnt = 0
                for j in range(len(self.constraint_conflict_nodes)):
                    if node_planerotation[i] == self.constraint_conflict_nodes[j]:
                        cnt = cnt + 1
                if cnt == 0:
                    MPC = node_planerotation[i]
                    MPC_nodes.append(MPC)
            for i in range(len(MPC_nodes)):
                f.write(str(MPC_nodes[i]) + ',\n')

    def write_surfaces_contraints_contact(self, f):
        # get surface nodes and write them to file
        f.write('\n***********************************************************\n')
        f.write('** Surfaces for contact constraint\n')
        f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name))
        obj = 0
        for femobj in self.contact_objects:  # femobj --> dict, FreeCAD document object is femobj['Object']
            contact_obj = femobj['Object']
            cnt = 0
            obj = obj + 1
            for o, elem_tup in contact_obj.References:
                for elem in elem_tup:
                    ref_shape = o.Shape.getElement(elem)
                    cnt = cnt + 1
                    if ref_shape.ShapeType == 'Face':
                        if cnt == 1:
                            name = "DEP" + str(obj)
                        else:
                            name = "IND" + str(obj)
                        f.write('*SURFACE, NAME =' + name + '\n')
                        v = self.mesh_object.FemMesh.getccxVolumesByFace(ref_shape)
                        for i in v:
                            f.write("{},S{}\n".format(i[0], i[1]))

    def write_node_sets_constraints_transform(self, f):
        # get nodes
        self.get_constraints_transform_nodes()
        # write nodes to file
        f.write('\n***********************************************************\n')
        f.write('** Node sets for transform constraint\n')
        f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name))
        for femobj in self.transform_objects:  # femobj --> dict, FreeCAD document object is femobj['Object']
            trans_obj = femobj['Object']
            if trans_obj.TransformType == "Rectangular":
                f.write('*NSET,NSET=Rect' + trans_obj.Name + '\n')
            elif trans_obj.TransformType == "Cylindrical":
                f.write('*NSET,NSET=Cylin' + trans_obj.Name + '\n')
            for n in femobj['Nodes']:
                f.write(str(n) + ',\n')

    def write_node_sets_constraints_temperature(self, f):
        # get nodes
        self.get_constraints_temperature_nodes()
        # write nodes to file
        f.write('\n***********************************************************\n')
        f.write('** Node sets for temperature constraints\n')
        f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name))
        for femobj in self.temperature_objects:  # femobj --> dict, FreeCAD document object is femobj['Object']
            f.write('*NSET,NSET=' + femobj['Object'].Name + '\n')
            for n in femobj['Nodes']:
                f.write(str(n) + ',\n')

    def write_materials(self, f):
        f.write('\n***********************************************************\n')
        f.write('** Materials\n')
        f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name))
        f.write('** Young\'s modulus unit is MPa = N/mm2\n')
        if self.analysis_type == "frequency" or self.selfweight_objects or (self.analysis_type == "thermomech" and not self.solver_obj.ThermoMechSteadyState):
            f.write('** Density\'s unit is t/mm^3\n')
        if self.analysis_type == "thermomech":
            f.write('** Thermal conductivity unit is kW/mm/K = t*mm/K*s^3\n')
            f.write('** Specific Heat unit is kJ/t/K = mm^2/s^2/K\n')
        for femobj in self.material_objects:  # femobj --> dict, FreeCAD document object is femobj['Object']
            mat_obj = femobj['Object']
            mat_info_name = mat_obj.Material['Name']
            mat_name = mat_obj.Name
            # get material properties, Currently in SI units: M/kg/s/Kelvin
            YM = FreeCAD.Units.Quantity(mat_obj.Material['YoungsModulus'])
            YM_in_MPa = float(YM.getValueAs('MPa'))
            PR = float(mat_obj.Material['PoissonRatio'])
            if self.analysis_type == "frequency" or self.selfweight_objects or (self.analysis_type == "thermomech" and not self.solver_obj.ThermoMechSteadyState):
                density = FreeCAD.Units.Quantity(mat_obj.Material['Density'])
                density_in_tonne_per_mm3 = float(density.getValueAs('t/mm^3'))
            if self.analysis_type == "thermomech":
                TC = FreeCAD.Units.Quantity(mat_obj.Material['ThermalConductivity'])
                TC_in_WmK = float(TC.getValueAs('W/m/K'))  # SvdW: Add factor to force units to results' base units of t/mm/s/K - W/m/K results in no factor needed
                TEC = FreeCAD.Units.Quantity(mat_obj.Material['ThermalExpansionCoefficient'])
                TEC_in_mmK = float(TEC.getValueAs('mm/mm/K'))
                SH = FreeCAD.Units.Quantity(mat_obj.Material['SpecificHeat'])
                SH_in_JkgK = float(SH.getValueAs('J/kg/K')) * 1e+06  # SvdW: Add factor to force units to results' base units of t/mm/s/K
            # write material properties
            f.write('** FreeCAD material name: ' + mat_info_name + '\n')
            f.write('*MATERIAL, NAME=' + mat_name + '\n')
            f.write('*ELASTIC\n')
            f.write('{0:.0f}, {1:.3f}\n'.format(YM_in_MPa, PR))
            if self.analysis_type == "frequency" or self.selfweight_objects or (self.analysis_type == "thermomech" and not self.solver_obj.ThermoMechSteadyState):
                f.write('*DENSITY\n')
                f.write('{0:.3e}\n'.format(density_in_tonne_per_mm3))
            if self.analysis_type == "thermomech":
                f.write('*CONDUCTIVITY\n')
                f.write('{0:.3f}\n'.format(TC_in_WmK))
                f.write('*EXPANSION\n')
                f.write('{0:.3e}\n'.format(TEC_in_mmK))
                f.write('*SPECIFIC HEAT\n')
                f.write('{0:.3e}\n'.format(SH_in_JkgK))
            # nonlinear material properties
            if self.solver_obj.MaterialNonlinearity == 'nonlinear':
                for femobj in self.material_nonlinear_objects:  # femobj --> dict, FreeCAD document object is femobj['Object']
                    nl_mat_obj = femobj['Object']
                    if nl_mat_obj.LinearBaseMaterial == mat_obj:
                        if nl_mat_obj.MaterialModelNonlinearity == "simple hardening":
                            f.write('*PLASTIC\n')
                            f.write(nl_mat_obj.YieldPoint1 + '\n')
                            f.write(nl_mat_obj.YieldPoint2 + '\n')
                    f.write('\n')

    def write_constraints_initialtemperature(self, f):
        f.write('\n***********************************************************\n')
        f.write('** Initial temperature constraint\n')
        f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name))
        f.write('*INITIAL CONDITIONS,TYPE=TEMPERATURE\n')
        for itobj in self.initialtemperature_objects:  # Should only be one
            inittemp_obj = itobj['Object']
            f.write('Nall,{}\n'.format(inittemp_obj.initialTemperature))  # OvG: Initial temperature

    def write_femelementsets(self, f):
        f.write('\n***********************************************************\n')
        f.write('** Sections\n')
        f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name))
        for ccx_elset in self.ccx_elsets:
            if ccx_elset['ccx_elset']:
                if 'beamsection_obj'in ccx_elset:  # beam mesh
                    beamsec_obj = ccx_elset['beamsection_obj']
                    elsetdef = 'ELSET=' + ccx_elset['ccx_elset_name'] + ', '
                    material = 'MATERIAL=' + ccx_elset['mat_obj_name']
                    if beamsec_obj.SectionType == 'Rectangular':
                        height = beamsec_obj.RectHeight.getValueAs('mm')
                        width = beamsec_obj.RectWidth.getValueAs('mm')
                        section_type = ', SECTION=RECT'
                        setion_geo = str(height) + ', ' + str(width) + '\n'
                        setion_def = '*BEAM SECTION, ' + elsetdef + material + section_type + '\n'
                    elif beamsec_obj.SectionType == 'Circular':
                        radius = 0.5 * beamsec_obj.CircDiameter.getValueAs('mm')
                        section_type = ', SECTION=CIRC'
                        setion_geo = str(radius) + '\n'
                        setion_def = '*BEAM SECTION, ' + elsetdef + material + section_type + '\n'
                    elif beamsec_obj.SectionType == 'Pipe':
                        radius = 0.5 * beamsec_obj.PipeDiameter.getValueAs('mm')
                        thickness = beamsec_obj.PipeThickness.getValueAs('mm')
                        section_type = ', SECTION=PIPE'
                        setion_geo = str(radius) + ', ' + str(thickness) + '\n'
                        setion_def = '*BEAM GENERAL SECTION, ' + elsetdef + material + section_type + '\n'
                    f.write(setion_def)
                    f.write(setion_geo)
                elif 'shellthickness_obj'in ccx_elset:  # shell mesh
                    shellth_obj = ccx_elset['shellthickness_obj']
                    elsetdef = 'ELSET=' + ccx_elset['ccx_elset_name'] + ', '
                    material = 'MATERIAL=' + ccx_elset['mat_obj_name']
                    setion_def = '*SHELL SECTION, ' + elsetdef + material + '\n'
                    setion_geo = str(shellth_obj.Thickness.getValueAs('mm')) + '\n'
                    f.write(setion_def)
                    f.write(setion_geo)
                else:  # solid mesh
                    elsetdef = 'ELSET=' + ccx_elset['ccx_elset_name'] + ', '
                    material = 'MATERIAL=' + ccx_elset['mat_obj_name']
                    setion_def = '*SOLID SECTION, ' + elsetdef + material + '\n'
                    f.write(setion_def)

    def write_step_begin(self, f):
        f.write('\n***********************************************************\n')
        f.write('** At least one step is needed to run an CalculiX analysis of FreeCAD\n')
        f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name))
        # STEP line
        step = '*STEP'
        if self.solver_obj.GeometricalNonlinearity == "nonlinear":
            if self.analysis_type == 'static' or self.analysis_type == 'thermomech':
                step += ', NLGEOM'   # https://www.comsol.com/blogs/what-is-geometric-nonlinearity/
            elif self.analysis_type == 'frequency':
                print('Analysis type frequency and geometrical nonlinear analyis are not allowed together, linear is used instead!')
        if self.solver_obj.IterationsThermoMechMaximum:
            if self.analysis_type == 'thermomech':
                step += ', INC=' + str(self.solver_obj.IterationsThermoMechMaximum)
            elif self.analysis_type == 'static' or self.analysis_type == 'frequency':
                pass  # not supported for stati and frequency,  ... really ?
        # write step line
        f.write(step + '\n')
        # CONTROLS line
        # all analyis types, ... really in frequency too?!?
        if self.solver_obj.IterationsControlParameterTimeUse:
            f.write('*CONTROLS, PARAMETERS=TIME INCREMENTATION\n')
            f.write(self.solver_obj.IterationsControlParameterIter + '\n')
            f.write(self.solver_obj.IterationsControlParameterCutb + '\n')
        # ANALYSIS type line
        # analysis line --> analysis type
        if self.analysis_type == 'static':
            analysis_type = '*STATIC'
        elif self.analysis_type == 'frequency':
            analysis_type = '*FREQUENCY'
        elif self.analysis_type == 'thermomech':
            analysis_type = '*COUPLED TEMPERATURE-DISPLACEMENT'
        # analysis line --> solver type
        if self.solver_obj.MatrixSolverType == "default":
            pass
        elif self.solver_obj.MatrixSolverType == "spooles":
            analysis_type += ', SOLVER=SPOOLES'
        elif self.solver_obj.MatrixSolverType == "iterativescaling":
            analysis_type += ', SOLVER=ITERATIVE SCALING'
        elif self.solver_obj.MatrixSolverType == "iterativecholesky":
            analysis_type += ', SOLVER=ITERATIVE CHOLESKY'
        # analysis line --> user defined incrementations --> parameter DIRECT
        if self.solver_obj.IterationsUserDefinedIncrementations:
            if self.analysis_type == 'static':  # it would be possible in thermomech too IMHO (bernd)
                analysis_type += ', DIRECT'
            elif self.analysis_type == 'thermomech':
                print('IterationsUserDefinedIncrementations not implemented for thermomech at the moment')
            elif self.analysis_type == 'frequency':
                print('Analysis type frequency and IterationsUserDefinedIncrementations are not allowed together, it is ignored')
        # analysis line --> steadystate --> thermomech only
        if self.solver_obj.ThermoMechSteadyState:
            if self.analysis_type == 'thermomech':
                analysis_type += ', STEADY STATE'
                self.solver_obj.TimeInitialStep = 1.0  # Set time to 1 and ignore user inputs for steady state
                self.solver_obj.TimeEnd = 1.0
            elif self.analysis_type == 'static' or self.analysis_type == 'frequency':
                pass  # not supported for static and frequency!
        # ANALYSIS paramter line
        analysis_parameter = ''
        if self.analysis_type == 'static':
            if self.solver_obj.IterationsUserDefinedIncrementations:
                analysis_parameter = self.solver_obj.IterationsUserDefinedTimeStepLength
        elif self.analysis_type == 'frequency':
            analysis_parameter = '{},{},{}\n'.format(self.solver_obj.EigenmodesCount, self.solver_obj.EigenmodeLowLimit, self.solver_obj.EigenmodeHighLimit)
        elif self.analysis_type == 'thermomech':
            analysis_parameter = '{},{}'.format(self.solver_obj.TimeInitialStep, self.solver_obj.TimeEnd)  # OvG: 1.0 increment, total time 1 for steady state will cut back automatically
        # write analysis type line, analysis parameter line
        f.write(analysis_type + '\n')
        f.write(analysis_parameter + '\n')

    def write_constraints_fixed(self, f):
        f.write('\n***********************************************************\n')
        f.write('** Fixed Constraints\n')
        f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name))
        for femobj in self.fixed_objects:  # femobj --> dict, FreeCAD document object is femobj['Object']
            fix_obj_name = femobj['Object'].Name
            f.write('*BOUNDARY\n')
            f.write(fix_obj_name + ',1\n')
            f.write(fix_obj_name + ',2\n')
            f.write(fix_obj_name + ',3\n')
            if self.beamsection_objects or self.shellthickness_objects:
                f.write(fix_obj_name + ',4\n')
                f.write(fix_obj_name + ',5\n')
                f.write(fix_obj_name + ',6\n')
            f.write('\n')

    def write_constraints_displacement(self, f):
        f.write('\n***********************************************************\n')
        f.write('** Displacement constraint applied\n')
        f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name))
        for femobj in self.displacement_objects:  # femobj --> dict, FreeCAD document object is femobj['Object']
            disp_obj = femobj['Object']
            disp_obj_name = disp_obj.Name
            f.write('*BOUNDARY\n')
            if disp_obj.xFix:
                f.write(disp_obj_name + ',1\n')
            elif not disp_obj.xFree:
                f.write(disp_obj_name + ',1,1,' + str(disp_obj.xDisplacement) + '\n')
            if disp_obj.yFix:
                f.write(disp_obj_name + ',2\n')
            elif not disp_obj.yFree:
                f.write(disp_obj_name + ',2,2,' + str(disp_obj.yDisplacement) + '\n')
            if disp_obj.zFix:
                f.write(disp_obj_name + ',3\n')
            elif not disp_obj.zFree:
                f.write(disp_obj_name + ',3,3,' + str(disp_obj.zDisplacement) + '\n')

            if self.beamsection_objects or self.shellthickness_objects:
                if disp_obj.rotxFix:
                    f.write(disp_obj_name + ',4\n')
                elif not disp_obj.rotxFree:
                    f.write(disp_obj_name + ',4,4,' + str(disp_obj.xRotation) + '\n')
                if disp_obj.rotyFix:
                    f.write(disp_obj_name + ',5\n')
                elif not disp_obj.rotyFree:
                    f.write(disp_obj_name + ',5,5,' + str(disp_obj.yRotation) + '\n')
                if disp_obj.rotzFix:
                    f.write(disp_obj_name + ',6\n')
                elif not disp_obj.rotzFree:
                    f.write(disp_obj_name + ',6,6,' + str(disp_obj.zRotation) + '\n')
        f.write('\n')

    def write_constraints_contact(self, f):
        f.write('\n***********************************************************\n')
        f.write('** Contact Constraints\n')
        f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name))
        obj = 0
        for femobj in self.contact_objects:  # femobj --> dict, FreeCAD document object is femobj['Object']
            obj = obj + 1
            contact_obj = femobj['Object']
            f.write('*CONTACT PAIR, INTERACTION=INT' + str(obj) + ',TYPE=SURFACE TO SURFACE\n')
            ind_surf = "IND" + str(obj)
            dep_surf = "DEP" + str(obj)
            f.write(dep_surf + ',' + ind_surf + '\n')
            f.write('*SURFACE INTERACTION, NAME=INT' + str(obj) + '\n')
            f.write('*SURFACE BEHAVIOR,PRESSURE-OVERCLOSURE=LINEAR\n')
            slope = contact_obj.Slope
            f.write(str(slope) + ' \n')
            friction = contact_obj.Friction
            if friction > 0:
                f.write('*FRICTION \n')
                stick = (slope / 10.0)
                f.write(str(friction) + ', ' + str(stick) + ' \n')

    def write_constraints_planerotation(self, f):
        f.write('\n***********************************************************\n')
        f.write('** PlaneRotation Constraints\n')
        f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name))
        for femobj in self.planerotation_objects:  # femobj --> dict, FreeCAD document object is femobj['Object']
            fric_obj_name = femobj['Object'].Name
            f.write('*MPC\n')
            f.write('PLANE,' + fric_obj_name + '\n')

    def write_constraints_transform(self, f):
        f.write('\n***********************************************************\n')
        f.write('** Transform Constaints\n')
        f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name))
        for trans_object in self.transform_objects:
            trans_obj = trans_object['Object']
            if trans_obj.TransformType == "Rectangular":
                f.write('*TRANSFORM, NSET=Rect' + trans_obj.Name + ', TYPE=R\n')
                coords = FemMeshTools.get_rectangular_coords(trans_obj)
                f.write(coords + '\n')
            elif trans_obj.TransformType == "Cylindrical":
                f.write('*TRANSFORM, NSET=Cylin' + trans_obj.Name + ', TYPE=C\n')
                coords = FemMeshTools.get_cylindrical_coords(trans_obj)
                f.write(coords + '\n')

    def write_constraints_selfweight(self, f):
        f.write('\n***********************************************************\n')
        f.write('** Self weight Constraint\n')
        f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name))
        for femobj in self.selfweight_objects:  # femobj --> dict, FreeCAD document object is femobj['Object']
            selwei_obj_name = femobj['Object'].Name
            f.write('** ' + selwei_obj_name + '\n')
            f.write('*DLOAD\n')
            f.write('Eall,GRAV,9810,0,0,-1\n')
            f.write('\n')
        # grav (erdbeschleunigung) is equal for all elements
        # should be only one constraint
        # different elment sets for different density are written in the material element sets allready

    def write_constraints_force(self, f):
        # check shape type of reference shape and get node loads
        self.get_constraints_force_nodeloads()
        # write node loads to file
        f.write('\n***********************************************************\n')
        f.write('** Node loads Constraints\n')
        f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name))
        f.write('*CLOAD\n')
        for femobj in self.force_objects:  # femobj --> dict, FreeCAD document object is femobj['Object']
            frc_obj_name = femobj['Object'].Name
            direction_vec = femobj['Object'].DirectionVector
            f.write('** ' + frc_obj_name + '\n')
            for ref_shape in femobj['NodeLoadTable']:
                f.write('** ' + ref_shape[0] + '\n')
                for n in sorted(ref_shape[1]):
                    node_load = ref_shape[1][n]
                    if (direction_vec.x != 0.0):
                        v1 = "{:.13E}".format(direction_vec.x * node_load)
                        f.write(str(n) + ',1,' + v1 + '\n')
                    if (direction_vec.y != 0.0):
                        v2 = "{:.13E}".format(direction_vec.y * node_load)
                        f.write(str(n) + ',2,' + v2 + '\n')
                    if (direction_vec.z != 0.0):
                        v3 = "{:.13E}".format(direction_vec.z * node_load)
                        f.write(str(n) + ',3,' + v3 + '\n')
                f.write('\n')
            f.write('\n')

    def write_constraints_pressure(self, f):
        # get the faces and face numbers
        self.get_constraints_pressure_faces()
        # write face loads to file
        f.write('\n***********************************************************\n')
        f.write('** Element + CalculiX face + load in [MPa]\n')
        f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name))
        for femobj in self.pressure_objects:  # femobj --> dict, FreeCAD document object is femobj['Object']
            prs_obj = femobj['Object']
            rev = -1 if prs_obj.Reversed else 1
            f.write('*DLOAD\n')
            for ref_shape in femobj['PressureFaces']:
                f.write('** ' + ref_shape[0] + '\n')
                for face, fno in ref_shape[1]:
                    f.write("{},P{},{}\n".format(face, fno, rev * prs_obj.Pressure))

    def write_constraints_temperature(self, f):
        f.write('\n***********************************************************\n')
        f.write('** Fixed temperature constraint applied\n')
        f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name))
        for ftobj in self.temperature_objects:
            fixedtemp_obj = ftobj['Object']
            NumberOfNodes = len(ftobj['Nodes'])
            if fixedtemp_obj.ConstraintType == "Temperature":
                f.write('*BOUNDARY\n')
                f.write('{},11,11,{}\n'.format(fixedtemp_obj.Name, fixedtemp_obj.Temperature))
                f.write('\n')
            elif fixedtemp_obj.ConstraintType == "CFlux":
                f.write('*CFLUX\n')
                f.write('{},11,{}\n'.format(fixedtemp_obj.Name, fixedtemp_obj.CFlux * 0.001 / NumberOfNodes))
                f.write('\n')

    def write_constraints_heatflux(self, f):
        f.write('\n***********************************************************\n')
        f.write('** Heatflux constraints\n')
        f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name))
        for hfobj in self.heatflux_objects:
            heatflux_obj = hfobj['Object']
            if heatflux_obj.ConstraintType == "Convection":
                f.write('*FILM\n')
                for o, elem_tup in heatflux_obj.References:
                    for elem in elem_tup:
                        ho = o.Shape.getElement(elem)
                        if ho.ShapeType == 'Face':
                            v = self.mesh_object.FemMesh.getccxVolumesByFace(ho)
                            f.write("** Heat flux on face {}\n".format(elem))
                            for i in v:
                                f.write("{},F{},{},{}\n".format(i[0], i[1], heatflux_obj.AmbientTemp, heatflux_obj.FilmCoef * 0.001))  # SvdW add factor to force heatflux to units system of t/mm/s/K # OvG: Only write out the VolumeIDs linked to a particular face
            elif heatflux_obj.ConstraintType == "DFlux":
                f.write('*DFLUX\n')
                for o, elem_tup in heatflux_obj.References:
                    for elem in elem_tup:
                        ho = o.Shape.getElement(elem)
                        if ho.ShapeType == 'Face':
                            v = self.mesh_object.FemMesh.getccxVolumesByFace(ho)
                            f.write("** Heat flux on face {}\n".format(elem))
                            for i in v:
                                f.write("{},S{},{}\n".format(i[0], i[1], heatflux_obj.DFlux * 0.001))

    def write_outputs_types(self, f):
        f.write('\n***********************************************************\n')
        f.write('** Outputs --> frd file\n')
        f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name))
        if self.beamsection_objects or self.shellthickness_objects:
            f.write('*NODE FILE, OUTPUT=2d\n')
        else:
            f.write('*NODE FILE\n')
        if self.analysis_type == "thermomech":  # MPH write out nodal temperatures if thermomechanical
            f.write('U, NT\n')
        else:
            f.write('U\n')
        f.write('*EL FILE\n')
        f.write('S, E\n')
        f.write('** outputs --> dat file\n')
        f.write('*NODE PRINT , NSET=Nall \n')
        f.write('U \n')
        f.write('*EL PRINT , ELSET=Eall \n')
        f.write('S \n')

    def write_step_end(self, f):
        f.write('\n***********************************************************\n')
        f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name))
        f.write('*END STEP \n')

    def write_footer(self, f):
        f.write('\n***********************************************************\n')
        f.write('** CalculiX Input file\n')
        f.write('** written by {} function\n'.format(sys._getframe().f_code.co_name))
        f.write('**   written by    --> FreeCAD ' + self.fc_ver[0] + '.' + self.fc_ver[1] + '.' + self.fc_ver[2] + '\n')
        f.write('**   written on    --> ' + time.ctime() + '\n')
        f.write('**   file name     --> ' + os.path.basename(FreeCAD.ActiveDocument.FileName) + '\n')
        f.write('**   analysis name --> ' + self.analysis.Name + '\n')
        f.write('**\n')
        f.write('**\n')
        f.write('**\n')
        f.write('**   Units\n')
        f.write('**\n')
        f.write('**   Geometry (mesh data)        --> mm\n')
        f.write("**   Materials (Young's modulus) --> N/mm2 = MPa\n")
        f.write('**   Loads (nodal loads)         --> N\n')
        f.write('**\n')

    # self.ccx_elsets = [ {
    #                        'beamsection_obj' : 'beamsection_obj'       if exists
    #                        'shellthickness_obj' : shellthickness_obj'  if exists
    #                        'ccx_elset' : [e1, e2, e3, ... , en] or string self.ccx_eall
    #                        'ccx_elset_name' : 'ccx_identifier_elset'
    #                        'mat_obj_name' : 'mat_obj.Name'
    #                        'ccx_mat_name' : 'mat_obj.Material['Name']'   !!! not unique !!!
    #                     },
    #                     {}, ... , {} ]
    def get_ccx_elsets_single_mat_single_beam(self):
        mat_obj = self.material_objects[0]['Object']
        beamsec_obj = self.beamsection_objects[0]['Object']
        ccx_elset = {}
        ccx_elset['beamsection_obj'] = beamsec_obj
        ccx_elset['ccx_elset'] = self.ccx_eall
        ccx_elset['ccx_elset_name'] = get_ccx_elset_beam_name(mat_obj.Name, beamsec_obj.Name)
        ccx_elset['mat_obj_name'] = mat_obj.Name
        ccx_elset['ccx_mat_name'] = mat_obj.Material['Name']
        self.ccx_elsets.append(ccx_elset)

    def get_ccx_elsets_single_mat_single_shell(self):
        mat_obj = self.material_objects[0]['Object']
        shellth_obj = self.shellthickness_objects[0]['Object']
        ccx_elset = {}
        ccx_elset['shellthickness_obj'] = shellth_obj
        ccx_elset['ccx_elset'] = self.ccx_eall
        ccx_elset['ccx_elset_name'] = get_ccx_elset_shell_name(mat_obj.Name, shellth_obj.Name)
        ccx_elset['mat_obj_name'] = mat_obj.Name
        ccx_elset['ccx_mat_name'] = mat_obj.Material['Name']
        self.ccx_elsets.append(ccx_elset)

    def get_ccx_elsets_single_mat_solid(self):
        mat_obj = self.material_objects[0]['Object']
        ccx_elset = {}
        ccx_elset['ccx_elset'] = self.ccx_eall
        ccx_elset['ccx_elset_name'] = get_ccx_elset_solid_name(mat_obj.Name)
        ccx_elset['mat_obj_name'] = mat_obj.Name
        ccx_elset['ccx_mat_name'] = mat_obj.Material['Name']
        self.ccx_elsets.append(ccx_elset)

    def get_ccx_elsets_single_mat_multiple_beam(self):
        if not self.femelement_table:
            self.femelement_table = FemMeshTools.get_femelement_table(self.femmesh)
        mat_obj = self.material_objects[0]['Object']
        FemMeshTools.get_femelement_sets(self.femmesh, self.femelement_table, self.beamsection_objects)
        for beamsec_data in self.beamsection_objects:
            beamsec_obj = beamsec_data['Object']
            ccx_elset = {}
            ccx_elset['beamsection_obj'] = beamsec_obj
            ccx_elset['ccx_elset'] = beamsec_data['FEMElements']
            ccx_elset['ccx_elset_name'] = get_ccx_elset_beam_name(mat_obj.Name, beamsec_obj.Name, None, beamsec_data['ShortName'])
            ccx_elset['mat_obj_name'] = mat_obj.Name
            ccx_elset['ccx_mat_name'] = mat_obj.Material['Name']
            self.ccx_elsets.append(ccx_elset)

    def get_ccx_elsets_single_mat_multiple_shell(self):
        if not self.femelement_table:
            self.femelement_table = FemMeshTools.get_femelement_table(self.femmesh)
        mat_obj = self.material_objects[0]['Object']
        FemMeshTools.get_femelement_sets(self.femmesh, self.femelement_table, self.shellthickness_objects)
        for shellth_data in self.shellthickness_objects:
            shellth_obj = shellth_data['Object']
            ccx_elset = {}
            ccx_elset['shellthickness_obj'] = shellth_obj
            ccx_elset['ccx_elset'] = shellth_data['FEMElements']
            ccx_elset['ccx_elset_name'] = get_ccx_elset_shell_name(mat_obj.Name, shellth_obj.Name, None, shellth_data['ShortName'])
            ccx_elset['mat_obj_name'] = mat_obj.Name
            ccx_elset['ccx_mat_name'] = mat_obj.Material['Name']
            self.ccx_elsets.append(ccx_elset)

    def get_ccx_elsets_multiple_mat_single_beam(self):
        if not self.femelement_table:
            self.femelement_table = FemMeshTools.get_femelement_table(self.femmesh)
        beamsec_obj = self.beamsection_objects[0]['Object']
        FemMeshTools.get_femelement_sets(self.femmesh, self.femelement_table, self.material_objects)
        for mat_data in self.material_objects:
            mat_obj = mat_data['Object']
            ccx_elset = {}
            ccx_elset['beamsection_obj'] = beamsec_obj
            ccx_elset['ccx_elset'] = mat_data['FEMElements']
            ccx_elset['ccx_elset_name'] = get_ccx_elset_beam_name(mat_obj.Name, beamsec_obj.Name, mat_data['ShortName'])
            ccx_elset['mat_obj_name'] = mat_obj.Name
            ccx_elset['ccx_mat_name'] = mat_obj.Material['Name']
            self.ccx_elsets.append(ccx_elset)

    def get_ccx_elsets_multiple_mat_single_shell(self):
        if not self.femelement_table:
            self.femelement_table = FemMeshTools.get_femelement_table(self.femmesh)
        shellth_obj = self.shellthickness_objects[0]['Object']
        FemMeshTools.get_femelement_sets(self.femmesh, self.femelement_table, self.material_objects)
        for mat_data in self.material_objects:
            mat_obj = mat_data['Object']
            ccx_elset = {}
            ccx_elset['shellthickness_obj'] = shellth_obj
            ccx_elset['ccx_elset'] = mat_data['FEMElements']
            ccx_elset['ccx_elset_name'] = get_ccx_elset_shell_name(mat_obj.Name, shellth_obj.Name, mat_data['ShortName'])
            ccx_elset['mat_obj_name'] = mat_obj.Name
            ccx_elset['ccx_mat_name'] = mat_obj.Material['Name']
            self.ccx_elsets.append(ccx_elset)

    def get_ccx_elsets_multiple_mat_solid(self):
        all_found = False
        if self.femmesh.GroupCount:
            all_found = FemMeshTools.get_femelement_sets_from_group_data(self.femmesh, self.material_objects)
            print(all_found)
        if all_found is False:
            if not self.femelement_table:
                self.femelement_table = FemMeshTools.get_femelement_table(self.femmesh)
            # we gone use the binary search for get_femelements_by_femnodes(), thus we need the parameter values self.femnodes_ele_table
            if not self.femnodes_mesh:
                self.femnodes_mesh = self.femmesh.Nodes
            if not self.femnodes_ele_table:
                self.femnodes_ele_table = FemMeshTools.get_femnodes_ele_table(self.femnodes_mesh, self.femelement_table)
            FemMeshTools.get_femelement_sets(self.femmesh, self.femelement_table, self.material_objects, self.femnodes_ele_table)
        for mat_data in self.material_objects:
            mat_obj = mat_data['Object']
            ccx_elset = {}
            ccx_elset['ccx_elset'] = mat_data['FEMElements']
            ccx_elset['ccx_elset_name'] = get_ccx_elset_solid_name(mat_obj.Name, None, mat_data['ShortName'])
            ccx_elset['mat_obj_name'] = mat_obj.Name
            ccx_elset['ccx_mat_name'] = mat_obj.Material['Name']
            self.ccx_elsets.append(ccx_elset)

    def get_ccx_elsets_multiple_mat_multiple_beam(self):
        if not self.femelement_table:
            self.femelement_table = FemMeshTools.get_femelement_table(self.femmesh)
        FemMeshTools.get_femelement_sets(self.femmesh, self.femelement_table, self.beamsection_objects)
        FemMeshTools.get_femelement_sets(self.femmesh, self.femelement_table, self.material_objects)
        for beamsec_data in self.beamsection_objects:
            beamsec_obj = beamsec_data['Object']
            for mat_data in self.material_objects:
                mat_obj = mat_data['Object']
                ccx_elset = {}
                ccx_elset['beamsection_obj'] = beamsec_obj
                elemids = []
                for elemid in beamsec_data['FEMElements']:
                    if elemid in mat_data['FEMElements']:
                        elemids.append(elemid)
                ccx_elset['ccx_elset'] = elemids
                ccx_elset['ccx_elset_name'] = get_ccx_elset_beam_name(mat_obj.Name, beamsec_obj.Name, mat_data['ShortName'], beamsec_data['ShortName'])
                ccx_elset['mat_obj_name'] = mat_obj.Name
                ccx_elset['ccx_mat_name'] = mat_obj.Material['Name']
                self.ccx_elsets.append(ccx_elset)

    def get_ccx_elsets_multiple_mat_multiple_shell(self):
        if not self.femelement_table:
            self.femelement_table = FemMeshTools.get_femelement_table(self.femmesh)
        FemMeshTools.get_femelement_sets(self.femmesh, self.femelement_table, self.shellthickness_objects)
        FemMeshTools.get_femelement_sets(self.femmesh, self.femelement_table, self.material_objects)
        for shellth_data in self.shellthickness_objects:
            shellth_obj = shellth_data['Object']
            for mat_data in self.material_objects:
                mat_obj = mat_data['Object']
                ccx_elset = {}
                ccx_elset['shellthickness_obj'] = shellth_obj
                elemids = []
                for elemid in shellth_data['FEMElements']:
                    if elemid in mat_data['FEMElements']:
                        elemids.append(elemid)
                ccx_elset['ccx_elset'] = elemids
                ccx_elset['ccx_elset_name'] = get_ccx_elset_shell_name(mat_obj.Name, shellth_obj.Name, mat_data['ShortName'], shellth_data['ShortName'])
                ccx_elset['mat_obj_name'] = mat_obj.Name
                ccx_elset['ccx_mat_name'] = mat_obj.Material['Name']
                self.ccx_elsets.append(ccx_elset)

# Helpers
def get_ccx_elset_beam_name(mat_name, beamsec_name, mat_short_name=None, beamsec_short_name=None):
    if not mat_short_name:
        mat_short_name = 'Mat0'
    if not beamsec_short_name:
        beamsec_short_name = 'Beam0'
    if len(mat_name + beamsec_name) > 20:   # max identifier lenght in CalculiX for beam elsets
        return mat_short_name + beamsec_short_name
    else:
        return mat_name + beamsec_name

def get_ccx_elset_shell_name(mat_name, shellth_name, mat_short_name=None, shellth_short_name=None):
    if not mat_short_name:
        mat_short_name = 'Mat0'
    if not shellth_short_name:
        shellth_short_name = 'Shell0'
    if len(mat_name + shellth_name) > 80:   # standard max identifier lenght in CalculiX
        return mat_short_name + shellth_short_name
    else:
        return mat_name + shellth_name

def get_ccx_elset_solid_name(mat_name, solid_name=None, mat_short_name=None):
    if not solid_name:
        solid_name = 'Solid'
    if not mat_short_name:
        mat_short_name = 'Mat0'
    if len(mat_name + solid_name) > 80:   # standard max identifier lenght in CalculiX
        return mat_short_name + solid_name
    else:
        return mat_name + solid_name

#  @}


# example invocation
# python article_finder.py --file ol_dump_2022-06-06.txt.gz

from olclient.bots import AbstractBotJob
import gzip
import re

class Job_The(AbstractBotJob):
    pattern = re.compile(r"^([\w ,]*), ?([a-zA-Z]{1,4})$")

    def needs_fixing(self, edition_title: str) -> bool:
        return True if(self.pattern.search(edition_title)) else False

    def find_article(self, edition_title: str) -> str:
        match = self.pattern.search(edition_title)

        return match.group(2)

    def run(self) -> None:
        self.dry_run_declaration()

        with gzip.open(self.args.file, 'rb') as file:
            for row in file:
                row, json_data = self.process_row(row)
                if not ( json_data['type']['key'] == '/type/edition' or json_data['type']['key'] == '/type/work' ):
                    continue
                title = json_data.get('title') if json_data.get('title') else '' # title or ''
                if not self.needs_fixing(title):
                    continue

                self.logger.info(self.find_article(title))

if __name__ == "__main__":
    job = Job_The()

    try:
        job.run()
    except Exception as e:
        job.logger.exception("")
        raise e


#!/usr/bin/python

def fib_r(x) :
    if (x <= 2):
        return 1
    return fib_r(x-1) + fib_r(x-2)

def fib_i(x) :
    a = 1
    b = 1
    fib = 1
    i = 2
    while i < x:
        fib = a +b
        a = b
        b = fib
        i+=1

    return fib

x = 40

for i in range (0,41):
    import time
    start = time.time()
    k = str(fib_r(i))
    #print(k)
    #print("Fib of " + str(i) + " = " + str(fib_r(i)))
    endR = time.time()
    print((endR - start)*1000)

print("---------------------")

for j in range (0,41):
    import time
    start = time.time()
    l = str(fib_i(j))
    #print(l)
    #print ("Fib of " + str(j) + " = " + str(fib_i(j)))
    endI = time.time()
    print((endI - start)*1000)

CO322-Data Structures and Algorithms/Lab1- run time of an algorithm/fib.py


"""
script info:
name: resursion 递归
"""

import sys

def recursionSum(l: list) -> int:
    """
    list sum implemented by recursion
    递归实现进制转换
    Args:
        l: list 待求和的元素

    Returns:
        sum: int
    """
    if len(l) == 1:
        return l[0]
    else:
        return l[0] + recursionSum(l[1:])

def binHexOct(n: int, base: int) -> str:
    """
    number system transformation implemented by recursion
    递归实现进制转换
    Args:
        n: number 待转换数字
        base: 进制转换基

    Returns:
        进制转换结果 str
    """
    convert_string = '0123456789'
    if base > 10:
        convert_string = '0123456789ABCDEF'

    if n < base:
        return convert_string[n]  # str
    else:
        return binHexOct(n // base, base) + convert_string[n % base]  # 因为返回的str 所以可以用+进行拼接

def fractalTree(branch_len: int):
    """
    fractal tree
    分型树
    Args:
        branch_len:

    Returns:

    """
    if branch_len > 5:
        t.forward(branch_len)
        t.right(20)
        fractalTree(branch_len - 15)
        t.left(40)
        fractalTree(branch_len - 15)
        t.right(20)
        t.backward(branch_len)

def hanoi():
    """
    tower of hanoi implemented by recursion
    递归实现汉诺塔
    Returns:

    """

    def moveTower(height, fromPole, withPole, toPole):
        if height >= 1:
            moveTower(height - 1, fromPole, toPole, withPole)
            moveDisk(height, fromPole, toPole)
            moveTower(height - 1, withPole, fromPole, toPole)

    def moveDisk(disk, fromPole, toPole):
        print(f'moving disk[{disk}] from {fromPole} to {toPole}')

    moveTower(3, '#1', '#2', '#3')

if __name__ == '__main__':
    print(__doc__)

    print(sys.getrecursionlimit())
    # print(sys.setrecursionlimit()) # 设置递归栈最大深度

    # 递归求解 数列求和
    print(recursionSum([1, 3, 5, 7, 9]))

    # 进制转换
    print(binHexOct(123456, 16))

    # import turtle
    #
    # t = turtle.Turtle()
    # t.left(90)
    # t.penup()
    # t.backward(100)
    # t.pendown()
    # t.pencolor('green')
    # t.pensize(3)
    # fractalTree(75)
    # t.hideturtle()
    # turtle.done()

    hanoi()


# -*- coding: utf-8 -*-
import logging
import base64
import time
import json
from datetime import date,datetime,timedelta
from dateutil.relativedelta import relativedelta
from odoo.modules.module import get_module_resource
from odoo import _, api, fields, models, exceptions
from odoo.exceptions import Warning, UserError, ValidationError
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
from odoo.tools.misc import get_lang

class InheritedSaleOrder(models.Model):
    _inherit = 'sale.order'

    practice_id = fields.Many2one(
        'res.partner',
        # required=True,
        domain=[('is_company','=',True)],
        string="Practice"
        )
    practitioner_id = fields.Many2one(
        'res.partner',
        # required=True,
        domain=[('is_practitioner','=',True)],
        string="Practitioner"
        )
    patient_id = fields.Many2one(
        "pod.patient",
        # required=True,
        states={"draft": [("readonly", False)], "done": [("readonly", True)]}
    )

    # patient_id = fields.Char(related='prescription_order_id.patient_id.name')

    prescription_order_id = fields.Many2one('pod.prescription.order', readonly=False)
    prescription_order_lines = fields.One2many('pod.prescription.order.line', 'prescription_order_id', readonly=False)

    @api.onchange('partner_id', 'practitioner_id')
    def onchange_set_domain_partner_practitioner(self):
        if self.partner_id and not self.practitioner_id:
            self.practitioner_id = self.partner_id.practitioner_id
        if self.practitioner_id and not self.patient_id:
            # Set patient_id based on practitioner_id
            self.patient_id = self.practitioner_id.patient_id
    # @api.onchange('partner_id', 'practitioner_id')
    # def _onchange_partner_practitioner(self):
    #     if self.partner_id:
    #         self.practitioner_id = False
    #         self.patient_id = False

    #     if self.practitioner_id:
    #         self.patient_id = False

    @api.onchange("product_id")
    def product_id_change(self):
        res = super(InheritedSaleOrder, self).product_id_change()
        if self.product_id:
            product = self.product_id.with_context(lang=self.order_id.partner_id.lang)
            if product.variant_description:
                self.name = product.variant_description
        return res

class SaleOrderLine(models.Model):
    _inherit = "sale.order.line"

    @api.onchange("product_id")
    def product_id_change(self):
        res = super(SaleOrderLine, self).product_id_change()
        if self.product_id:
            product = self.product_id.with_context(lang=self.order_id.partner_id.lang)
            if product.variant_description:
                self.name = product.variant_description
        return res


from collections import defaultdict

keypad_codes = ["2", "2", "2", "3", "3", "3", "4", "4", "4", "5", "5", "5", "6", "6", "6", "7", "7", "7", "7", "8", "8", "8", "9", "9", "9", "9"]
""""
for i in range(2,10):
    repetitions = 4 if i in (7,9) else 3
    aux = [i]*repetitions
    keypad_codes.extend(aux)
"""
(n, q) = input().split(" ")
n = int(n)
q = int(q)
#print(keypad_codes)

dc = {}

for i in range(n):
    identifier = input()
    identifier_str = ""
    for letter in identifier:
        identifier_str += keypad_codes[ord(letter) - ord('a')]
    try:
        dc[identifier_str] += 1
    except KeyError:
        dc[identifier_str] = 1

codes = []
for i in range(q):
    code = input()
    try:
        print(dc[code])
    except KeyError:
        print(0)


import logzero
from logzero import logger
from pathlib import Path
import yaml
from datetime import datetime

class Logger:
    '''
    ロガークラス
    '''

    def __init__(self, debug_flg):

        # ディレクトリ
        cwd = Path.cwd()

        # 設定ファイル読み込み
        with open(Path(cwd, 'config', 'config.yml'), encoding='utf-8') as f:
            config = yaml.safe_load(f)

        # 日付取得
        dt_now = datetime.now()
        exec_ymd = dt_now.strftime('%Y%m%d')

        # 出力レベルの設定
        if config['FLAG']['debug'] or debug_flg:
            logzero.loglevel(10)
        else:
            logzero.loglevel(20)

        # ファイル出力
        if config['LOG']['path']:
            log_file_path = config['LOG']['path']
        else:
            log_file_path = str(Path(cwd, 'logs'))

        log_file_name = config['LOG']['name']

        # ファイル作成
        with open(str(Path(log_file_path, exec_ymd))+'_'+log_file_name, 'w', encoding='shift-jis'):
            pass

        logzero.logfile(Path(log_file_path, exec_ymd+'_'+log_file_name))

    # debug
    def debug(self, msg, *args, **kwargs):
        logger.debug(msg, *args, **kwargs)

    # info
    def info(self, msg, *args, **kwargs):
        logger.info(msg, *args, **kwargs)

    # warning
    def warning(self, msg, *args, **kwargs):
        logger.warning(msg, *args, **kwargs)

    # error
    def error(self, msg, *args, **kwargs):
        logger.error(msg, *args, **kwargs)


"Модул  MAIN"

import window, os, pygame,level0

try:
    os.system('clear')  #Линукс
except KeyError:
    os.system('cls')    #Виндовс

win = window.createWindow(800,600,'Мистическая башня')
#screen = window.createScreen(800,600)
screen = pygame.Surface((800,600))

level0.gameRun(True,win,screen,(146,205,255))