import os
import re

def open_file(file):
    absolute_path = os.path.dirname(os.path.abspath(__file__))
    absolute_path = absolute_path + '\\'
    file_path = absolute_path + file
    input_file = open(file_path, "r")
    return input_file

class Computer:
    def __init__(self):

        self.registers = {'a': 0, 'b': 0, 'c': 0, 'd': 0}
        self.ip = 0

    def cpy(self, x, y):

        self.registers[y] = x
        self.ip += 1

    def inc(self, x):
        val = self.registers[x]
        self.registers[x] += 1
        self.ip += 1

    def dec(self, x):
        val = self.registers[x]
        self.registers[x] -= 1
        self.ip += 1
        if x == 'd':
            print(self.registers['d'])

    def jnz(self, x, y):
        if not (x == 0):
            self.ip += y
        else:
            self.ip += 1

    def execute_instruction(self, instruction_string):
        cpy_reg_re = re.compile(r"cpy (\w) (\w)")
        cpy_int_re = re.compile(r"cpy (\d+) (\w)")
        inc_re = re.compile(r"inc (\w)")
        dec_re = re.compile(r"dec (\w)")
        jnz_re = re.compile(r"jnz (\w) (-*\d+)")
        jnz_int_re = re.compile(r"jnz (\d+) (-*\d+)")

        # print(self.ip, ": [a:", self.registers['a'], ", b:", self.registers['b'], ", c:", self.registers['c'], ", d:", self.registers['d'], "] - ", instruction_string)
        match = cpy_int_re.search(instruction_string)
        if (match):
            self.cpy(int(match.group(1)), match.group(2))
            return

        match = cpy_reg_re.search(instruction_string)
        if (match):
            self.cpy(self.registers[match.group(1)], match.group(2))
            return

        match = inc_re.search(instruction_string)
        if (match):
            self.inc(match.group(1))
            return

        match = dec_re.search(instruction_string)
        if (match):
            self.dec(match.group(1))
            return

        match = jnz_int_re.search(instruction_string)
        if (match):
            self.jnz(int(match.group(1)), int(match.group(2)))
            return

        match = jnz_re.search(instruction_string)
        if (match):
            self.jnz(self.registers[match.group(1)], int(match.group(2)))
            return

        assert (False)

    def execute_program(self, program):
        instructions = program.splitlines()
        while 0 <= self.ip < len(instructions):
            self.execute_instruction(instructions[self.ip])

test_program = """\
cpy 41 a
inc a
inc a
dec a
jnz a 2
dec a"""

real_program = """\
cpy 1 a
cpy 1 b
cpy 26 d
jnz c 2
jnz 1 5
cpy 7 c
inc d
dec c
jnz c -2
cpy a c
inc a
dec b
jnz b -2
cpy c b
dec d
jnz d -6
cpy 19 c
cpy 11 d
inc a
dec d
jnz d -2
dec c
jnz c -5"""

real_program_2 = """\
cpy 1 c
cpy 1 a
cpy 1 b
cpy 26 d
jnz c 2
jnz 1 5
cpy 7 c
inc d
dec c
jnz c -2
cpy a c
inc a
dec b
jnz b -2
cpy c b
dec d
jnz d -6
cpy 19 c
cpy 11 d
inc a
dec d
jnz d -2
dec c
jnz c -5"""

def test():
    computer = Computer()
    computer.execute_program(test_program)
    print(computer.registers)
    return computer.registers['a']

def run():
    computer = Computer()
    computer.execute_program(real_program)
    print(computer.registers['a'])

def run_part2():
    computer = Computer()
    computer.execute_program(real_program_2)
    print(computer.registers['a'])

assert (test() == 42)
run_part2()


import os
import time
import pandas as pd
from datetime import datetime
import progressbar
import logging
import numexpr as ne

logger = logging.getLogger(__name__)

"""
This class provides the functionality to load trajectory data into
cBLUE.  Currently, the sbet files are expected to be ASCII files
that are exported from Applanix's PosPac software.
"""

class Sbet:
    def __init__(self, sbet_dir, sensor_name):
        """
        The data from all of the loaded sbet files are represented by
        a single Sbet object.  When the Sbet class is instantiated,
        the sbet object does not contain any sbet data.  The data
        are "loaded" (assigned to a field of the sbet object) when
        the user clicks the 'Load Sbet Data' button.
        :param str sbet_dir: directory contained trajectory files
        """

        self.sbet_dir = sbet_dir

        self.sensor_name = sensor_name

        self.sbet_files = sorted(
            [
                os.path.join(sbet_dir, f)
                for f in os.listdir(sbet_dir)
                if f.endswith(".txt")
            ]
        )

        self.data = None
        self.SECS_PER_GPS_WK = 7 * 24 * 60 * 60  # 604800 sec
        self.SECS_PER_DAY = 24 * 60 * 60  # 86400 sec
        self.GPS_EPOCH = datetime(1980, 1, 6, 0, 0, 0)
        self.GPS_ADJUSTED_OFFSET = 1e9

    @staticmethod
    def get_sbet_date(sbet):
        """parses year, month, and day from ASCII sbet filename

        :param str sbet: ASCII sbet filename
        :return: List[int]
        """
        sbet_path = os.path.normpath(sbet)
        sbet_parts = os.path.split(sbet_path)

        sbet_name = sbet_parts[-1]
        logger.sbet(f"SBET Name : {sbet_name}")
        year = int(sbet_name[0:4])
        month = int(sbet_name[4:6])
        day = int(sbet_name[6:8])
        sbet_date = [year, month, day]
        return sbet_date

    def gps_sow_to_gps_adj(self, gps_date, gps_wk_sec):
        """converts GPS seconds-of-week timestamp to GPS adjusted standard time

        In the case that the timestamps in the sbet files are GPS week seconds,
        this method is called to convert the timestamps to GPS adjusted standard
        time, which is what the las file timestamps are.  The timestamps in the
        sbet and las files need to be the same format, because the merging process
        merges the data in the sbet and las files based on timestamps.

        :param ? gps_date: [year, month, day]
        :param ? gps_wk_sec: GPS seconds-of-week timestamp
        :return: float
        """

        logger.sbet("converting GPS week seconds to GPS adjusted standard time..."),

        year = gps_date[0]
        month = gps_date[1]
        day = gps_date[2]

        sbet_date = datetime(year, month, day)
        dt = sbet_date - self.GPS_EPOCH
        gps_wk = int((dt.days * self.SECS_PER_DAY + dt.seconds) / self.SECS_PER_GPS_WK)
        gps_time = gps_wk * self.SECS_PER_GPS_WK + gps_wk_sec
        gps_time_adj = gps_time - self.GPS_ADJUSTED_OFFSET

        return gps_time_adj

    def check_if_sow(self, time):
        logger.sbet("checking if timestamps are GPS week seconds...")
        if time <= self.SECS_PER_GPS_WK:
            return True
        else:
            return False

    def build_sbets_data(self):
        """builds 1 pandas dataframe from all ASCII sbet files

        :return: pandas dataframe

        The following table lists the contents of the returned pandas sbet dataframe:

        =====   =============================================================
        Index   description
        =====   =============================================================
        0       timestamp (GPS seconds-of-week or GPS standard adjusted time)
        1       longitude
        2       latitude
        3       X (easting)
        4       Y (northing)
        5       Z (ellipsoid height)
        6       roll
        7       pitch
        8       heading
        9       standard deviation X
        10      standard deviation Y
        11      standard deviation Z
        12      standard deviation roll
        13      standard deviation pitch
        14      standard deviation heading
        =====   =============================================================
        """

        sbets_df = pd.DataFrame()
        header_sbet = [
            "time",
            "lon",
            "lat",
            "X",
            "Y",
            "Z",
            "roll",
            "pitch",
            "heading",
            "stdX",
            "stdY",
            "stdZ",
            "stdroll",
            "stdpitch",
            "stdheading",
        ]
        # Used for holding processed SBET data if this is the PILLS sensor
        modified_sbet_file = "modified_pills_sbet.txt"

        print(r"Loading trajectory files...")
        logger.sbet("loading {} trajectory files...".format(len(self.sbet_files)))
        for sbet in progressbar.progressbar(
            sorted(self.sbet_files), redirect_stdout=True
        ):
            logger.sbet("-" * 50)
            logger.sbet("{}...".format(os.path.split(sbet)[-1]))
            sbet_date = self.get_sbet_date(sbet)

            # If this is the PILLS sensor, pre-process the sbet data
            if(self.sensor_name == "PILLS or RAMMS"):
                logger.sbet("PILLS or RAMMS Sensor, pre-processing sbet file")
                self.preprocess_pills_sbet(sbet, modified_sbet_file)
                # Reassign the SBET file name to the modified file
                sbet = modified_sbet_file

            sbet_df = pd.read_csv(
                sbet,
                skip_blank_lines=True,
                engine="c",
                delim_whitespace=True,
                header=None,
                names=header_sbet,
                index_col=False,
            )
            logger.sbet("({} trajectory points)".format(sbet_df.shape[0]))

            is_sow = self.check_if_sow(sbet_df["time"][0])
            if is_sow:
                gps_time_adj = self.gps_sow_to_gps_adj(sbet_date, sbet_df["time"])
                sbet_df["time"] = gps_time_adj

            sbets_df = sbets_df.append(sbet_df, ignore_index=True)

        sbets_data = sbets_df.sort_values(["time"], ascending=[1])

        #If this was the PILLS sensor and we created a modified SBET file.
        #   Then clean up by deleting the modified_pills_sbet.txt
        if os.path.isfile(modified_sbet_file):
            logger.sbet("Cleaning up Modified SBET file")
            os.remove(modified_sbet_file)

        return sbets_data

    def set_data(self):
        """populates Sbet object's data field with pandas dataframe (when user
        presses the "Load Trajectory File(s)" button)

        :return: n/a
        """

        sbet_tic = time.process_time()
        self.data = self.build_sbets_data()  # df
        sbet_toc = time.process_time()
        logger.sbet(
            "It took {:.1f} mins to load the trajectory data.".format(
                (sbet_toc - sbet_tic) / 60
            )
        )

    def get_tile_data(self, north, south, east, west):
        """queries the sbet data points that lie within the given las tile bounding coordinates

        One pandas dataframe is created from all of the loaded ASCII sbet files,
        but as each las tile is processed, only the sbet data located within the
        las tile limits are sent to the calc_tpu() method.

        To account for las tiles that contain data points from a las flight line
        whose corresponding trajectory data falls outside of the las tile extents,
        a buffer is added to the bounds of the tile when retreiving the
        trajectory data.

        :param float north: northern limit of las tile
        :param float south: southern limit of las tile
        :param float east: eastern limit of las tile
        :param float west: western limit of las tile
        :return: pandas dataframe
        """

        buff = 500  # meters

        x = self.data.X.values
        y = self.data.Y.values

        north += buff
        south -= buff
        east += buff
        west -= buff

        # using numexpr for accelerating computations of large arrays
        data = self.data[
            ne.evaluate("(y >= south) & (y <= north) & (x >= west) & (x <= east)")
        ]

        return data

    def preprocess_pills_sbet(self, sbet_file, modified_sbet_file):
        """Pre-process the given PILLS SBET data into the expected cBLUE format so that build_sbets_data()
            will run as expected.

            The PILLS SBET file has a varying number of lines of text describing the data in the file preceeding the SBET data.
            The PILLS SBET data has 20 columns in the order:
                TIME, DISTANCE, EASTING, NORTHING, ELLIPSOID HEIGHT, LATITUDE, LONGITUDE,
                ELLIPSOID HEIGHT, ROLL, PITCH, HEADING, EAST VELOCITY, NORTH VELOCITY,
                UP VELOCITY, EAST SD, NORTH SD, HEIGHT SD, ROLL SD, PITCH SD, HEADING SD

            build_sbets_data() expects for the data to have 15 columns in the order:
                timestamp (GPS seconds-of-week or GPS standard adjusted time), longitude, latitude,
                X (easting), Y (northing), Z (ellipsoid height), roll, pitch, heading, standard deviation X,
                standard deviation Y, standard deviation Z, standard deviation roll, standard deviation pitch,
                standard deviation heading

            The heading text is removed from the file. The 5 unneeded columns are dropped from the table.
            The column order is rearranged to match the expected order in build_sbets_data().

            The processed data is then written to the modified_sbet_file.

            :param string sbet_file: SBET File name selected by the user
            :param string modified_sbet_fil: File name that the processed SBET data will be written to
        """
        # The first 26-28 rows of a PILLS sbet file are descrptions of the data.
        #   Drop the first 100 lines (header lines and time when plane is on the ground)
        #   to ensure that all extra header lines are dropped.
        n = 100

        # List of column indicies to drop from the PILLS sbet file
        drop_columns = [1, 7, 11, 12, 13]
        # Column index to reorder the sbet columns after the unneeded columns have been dropped
        # Time, Longitude, Latitude, X(Easting), Y(Northing), Z(Ellipsoid Height), Roll, Pitch, Heading,
        #   stdx(East SD), stdy(North SD), stdz(Height SD), stdroll(Roll SD), stdpitch(Pitch SD), stdheading(Heading SD)
        new_order = [0, 5, 4, 1, 2, 3, 6, 7, 8, 9, 10, 11, 12, 13, 14]

        # We want to get rid of the first 26 lines of the file
        # open the sbet file with read and write permissions
        with open(sbet_file, 'r') as fp:
            #read in the lines of the sbet file
            lines = fp.readlines()

            with open(modified_sbet_file, 'w') as modified_fp:
                #write the lines to the modified file without the first 26 lines
                modified_fp.writelines(lines[n:])

                modified_fp.close()

            fp.close()

        # Read in the sbet_file and save it to a DataFrame
        sbet_df = pd.read_csv(modified_sbet_file, delim_whitespace=True, header=None, index_col=False)

        # logger.sbet(f"sbet df: {sbet_df}")

        # Drop the unneeded columns
        new_sbet_df = sbet_df.drop(sbet_df.columns[drop_columns], axis = 1)

        #Rename column labels to make it easier to reorder them
        new_sbet_df.columns = range(0,15)

        # logger.sbet(f"sbet dropped columns: {new_sbet_df}")

        # Rearrange the column order to match expected column order
        new_sbet_df = new_sbet_df.reindex(new_order, axis =1)

        # logger.sbet(f"sbet rearranged: {new_sbet_df}")

        # Write the processed data to the modified sbet file
        new_sbet_df.to_csv(modified_sbet_file, index=False, index_label=False, sep=" ", header=False)


import csv, json, xlrd

def csvParse(csvfile):
    # Open the CSV
    f = open( csvfile, 'rU' )
        # Change each fieldname to the appropriate field name.
    reader = csv.DictReader( f, fieldnames = ( "Protocol","Source Port","Destination Port","Source IP", "Destination IP", "Source MAC", "Destination MAC", "segment ID", "Frame name", "Frame ID", "segment name", "packet ID", "Receivers"))
    framenames = []
    store = []
    # Store frame names in a list
    for row in reader:
        frame= {"FrameName":row["Frame name"],
        "FrameID": row["Frame ID"],
        "protocol": row["Protocol"],
        "segments":[]}
        if row["Frame name"] not in framenames:
            framenames.append(row["Frame name"])
            store.append(frame)

    # Create Objects for Frames, segments and packets
    segment = {"segmentName":""}
    for frame in store:
        f = open( csvfile, 'rU' )
        reader = csv.DictReader( f, fieldnames = ( "Protocol","Source Port","Destination Port","Source IP", "Destination IP", "Source MAC", "Destination MAC", "segment ID","Frame name", "Frame ID", "segment name", "packet ID", "Receivers"))
        for row in reader:
            if frame["FrameName"] == row["Frame name"]:
                if segment["segmentName"] != row["segment name"]:
                    segment = {
                        "segmentID":row["segment ID"],
                        "segmentName": row["segment name"],
                        "srcPort":row["Source Port"],
                        "destPort":row["Destination Port"],
                        "packets":[{
                            "packetID":row["packet ID"],
                            "Receivers":row["Receivers"],
                            "destIP":row["Destination IP"],
                            "destMAC":row["Destination MAC"],
                            "srcIP": row["Source IP"],
                            "srcMAC":row["Source MAC"]
                            }]
                        }
                    frame["segments"].append(segment)
                else:
                    packet = {
                        "packetID":row["packet ID"],
                        "Receivers":row["Receivers"],
                        "destIP":row["Destination IP"],
                        "destMAC":row["Destination MAC"],
                        "srcIP": row["Source IP"],
                        "srcMAC":row["Source MAC"]
                        }
                    segment["packets"].append(packet)

    # Parse the CSV into JSON
    out = json.dumps(store, indent=4)
    # Save the JSON
    f = open( 'data.json', 'w')
    f.write(out)

def xlsParse(xlsfile):
    store = []  #List of objects to be parsed into json file
    framenames = []
    book = xlrd.open_workbook(xlsfile)
    sh1 = book.sheet_by_index(0)

    for rx in range(1, sh1.nrows):
        if sh1.row(rx)[8].value not in framenames:
            framenames.append(sh1.row(rx)[8].value)
            frame = {"frameName": sh1.row(rx)[8].value,
               "frameID": sh1.row(rx)[9].value,
               "protocol": sh1.row(rx)[0].value,
               "segments":[]
               }
            store.append(frame)

    segment = {"segmentName":""}
    for frame in store:
        for rx in range(1, sh1.nrows):
            if frame["frameName"] == sh1.row(rx)[8].value:
                if segment["segmentName"] != sh1.row(rx)[10].value:
                    segment = {
                    "segmentID":sh1.row(rx)[7].value,
                    "segmentName": sh1.row(rx)[10].value,
                    "srcPort":int(sh1.row(rx)[1].value),
                    "destPort":int(sh1.row(rx)[2].value),
                    "packets":[{
                        "packetID":sh1.row(rx)[11].value,
                        "Receivers":sh1.row(rx)[12].value,
                        "srcMAC": sh1.row(rx)[5].value,
                        "srcIP": sh1.row(rx)[3].value,
                        "destIP":sh1.row(rx)[4].value,
                        "destMAC":sh1.row(rx)[6].value
                        }]
                    }
                    frame["segments"].append(segment)
                else:
                    packet = {
                    "packetID":sh1.row(rx)[11].value,
                    "Receivers":sh1.row(rx)[12].value,
                    "srcMAC": sh1.row(rx)[5].value,
                    "srcIP": sh1.row(rx)[3].value,
                    "destIP":sh1.row(rx)[4].value,
                    "destMAC":sh1.row(rx)[6].value
                    }
                    segment["packets"].append(packet)

    # Parse the XLS into JSON
    out = json.dumps(store, indent=4)
    # Save the JSON
    f = open( 'xlsdata.json', 'w')
    f.write(out)

csvParse('dataset.csv')

xlsParse('dataset.xls')


from scipy.integrate._ivp.radau import T
from double_pendulum import DoublePendulum
import numpy as np
import pytest

@pytest.mark.parametrize(
    "theta1, theta2, expected",
    [
        (  0,   0,            0),
        (  0, 0.5,  3.386187037),
        (0.5,   0, -7.678514423),
        (0.5, 0.5, -4.703164534),
    ]
)
def test_domega1_dt(theta1, theta2, expected):
    dp = DoublePendulum()
    t = 0
    y = (theta1, 0.25, theta2, 0.15)
    dtheta1_dt, domega1_dt, _, _ = dp(t, y)
    assert np.isclose(dtheta1_dt, 0.25)
    assert np.isclose(domega1_dt, expected)

@pytest.mark.parametrize(
    "theta1, theta2, expected",
    [
        (  0,   0,          0.0),
        (  0, 0.5, -7.704787325),
        (0.5,   0,  6.768494455),
        (0.5, 0.5,          0.0),
    ],
)
def test_domega2_dt(theta1, theta2, expected):
    dp = DoublePendulum()
    t = 0
    y = (theta1, 0.25, theta2, 0.15)
    _, _, dtheta2_dt, domega2_dt = dp(t, y)
    assert np.isclose(dtheta2_dt, 0.15)
    assert np.isclose(domega2_dt, expected)

def test_DoublePendulum_at_origin_with_angular_velocity():
    """Testing that the pendulum moves from angle 0,0 when given an initial speed
    """
    pend = DoublePendulum()
    y = (0, 0.25, 0, 0.15)
    pend.solve(y,10,0.1)

    assert pend.Etotal.all() > 0

def test_DoublePendulum_empty_attribute():
    """Testing for empty attributes
    """
    pend = DoublePendulum()
    with pytest.raises(Exception):
        pend.theta1
        pend.theta2
        pend.vx1
        pend.vx2
        pend.vy1
        pend.vy2
        pend.P
        pend.K
        pend.Etotal
        pend.t

def test_DoublePendulum_no_direct_attribute_access():
    theta1 = 90
    theta2 = 180
    omega1 = 0
    omega2 = 0
    y = (theta1, omega1, theta2, omega2)

    pend = DoublePendulum()
    pend.solve(y,10,0.1)
    with pytest.raises(AttributeError):
        pend.__theta1
        pend.__theta2
        pend.__vx1
        pend.__vx2
        pend.__vy1
        pend.__vy2
        pend.__P
        pend.__K
        pend.__Etotal
        pend.__t


__id__        = "$Id$"
__version__   = "$Revision$"
__date__      = "$Date$"
__copyright__ = "Copyright (c) 2019 Igalia, S.L."
__license__   = "LGPL"

from orca import debug
from orca import focus_manager
from orca.scripts import default

from .script_utilities import Utilities

_focusManager = focus_manager.getManager()

class Script(default.Script):

    def __init__(self, app):
        """Creates a new script for the given application."""

        super().__init__(app)

    def getUtilities(self):
        """Returns the utilities for this script."""

        return Utilities(self)

    def forceScriptActivation(self, event):
        """Allows scripts to insist that they should become active."""

        if self.utilities.isSwitcherSelectionChangeEventType(event):
            return True

        return super().forceScriptActivation(event)

    def _handleSwitcherEvent(self, event):
        """Presents the currently selected item, if appropriate."""

        if not self.utilities.isSwitcherContainer(event.source):
            msg = "SWITCHER: Event is not from switcher container"
            debug.printMessage(debug.LEVEL_INFO, msg, True)
            return False

        if not self.utilities.isSwitcherSelectionChangeEventType(event):
            msg = "SWITCHER: Not treating event as selection change."
            debug.printMessage(debug.LEVEL_INFO, msg, True)
            return True

        msg = "SWITCHER: Treating event as selection change"
        debug.printMessage(debug.LEVEL_INFO, msg, True)

        self.presentationInterrupt()
        _focusManager.set_active_window(self.utilities.topLevelObject(event.source))
        _focusManager.set_locus_of_focus(event, event.source, False)
        self.presentMessage(self.utilities.getSelectionName(event.source),
                            resetStyles=False, force=True)
        return True

    def onFocusedChanged(self, event):
        """Callback for object:state-changed:focused accessibility events."""

        if self._handleSwitcherEvent(event):
            return

        super().onFocusedChanged(event)

    def onNameChanged(self, event):
        """Callback for object:property-change:accessible-name events."""

        if self._handleSwitcherEvent(event):
            return

        super().onNameChanged(event)

    def onSelectedChanged(self, event):
        """Callback for object:state-changed:selected accessibility events."""

        if self._handleSwitcherEvent(event):
            return

        super().onSelectedChanged(event)

    def onSelectionChanged(self, event):
        """Callback for object:selection-changed accessibility events."""

        if self._handleSwitcherEvent(event):
            return

        super().onSelectionChanged(event)

    def onShowingChanged(self, event):
        """Callback for object:state-changed:showing accessibility events."""

        if self._handleSwitcherEvent(event):
            return

        super().onShowingChanged(event)

    def onCaretMoved(self, event):
        """Callback for object:text-caret-moved accessibility events."""

        if self._handleSwitcherEvent(event):
            return

        super().onCaretMoved(event)

    def onTextDeleted(self, event):
        """Callback for object:text-changed:delete accessibility events."""

        if self._handleSwitcherEvent(event):
            return

        super().onTextDeleted(event)

    def onTextInserted(self, event):
        """Callback for object:text-changed:insert accessibility events."""

        if self._handleSwitcherEvent(event):
            return

        super().onTextInserted(event)


#!/data/venv/hdp-env/bin python
# -*- coding: utf8 -*-
'''
@Author: xiangfu shi
@Contact: xfu_shi@163.com
@Time: 2019/12/22 9:05 PM
'''
import  tensorflow as tf
from model_brain import  BaseModel
'''DNN demo'''
class DNN(BaseModel):
    '''DNN model 最简单的dnn结构'''
    def __init__(self, features, labels, params, mode):
        super(DNN,self).__init__(features, labels, params, mode)
        _,self.Deep_Features = self._get_feature_embedding
        with tf.variable_scope('Embedding_Module'):
            self.embedding_layer = self.get_input_layer(self.Deep_Features)
        with tf.variable_scope('DNN_Module'):
            self.logits = self._model_fn

    @property
    def _model_fn(self):
        '''DNN model'''
        with tf.variable_scope('fc_net'):
            logits = self.fc_net(self.embedding_layer,1)
        return logits


#                             -*- Mode: Python -*-
# Sequence.py
#

import sys

from . import common as uc

class RefSeq:
    """Reference path object that contains information on
    sequence, sequence name, kmers and kmer indices.

    Attributes
    ---------
    seq : str
        Reference sequence from fasta file.
    k : int
        K-mer size.
    first_kmer : str
        First kmer in seq.
    last_kmer : str
        Last kmer in seq.
    name : str
        Path name.
    ref_mer : list
        List of kmers found in seq.

    Methods
    -------
    set_index
    """

    def __init__(self, seq, name, k):

        self.seq = seq
        self.k = k

        self.first_kmer = self.seq[0:self.k]
        self.last_kmer = self.seq[-self.k:]

        self.name = name

        self.ref_mer = uc.get_ref_kmer(seq, self.name, self.k)

        assert len(self.ref_mer)

    def set_index(self, kmer):
        """"""

        self.seq_index = tuple([kmer.index(k) for k in self.ref_mer])
        self.first_ix = self.seq_index[0]
        self.last_ix = self.seq_index[-1]

    def __getitem__(self, item):
        try:
            return self.seq_index[item]
        except AttributeError:
            sys.stderr.write('Attribute `seq_index` is not set yet\n')
            return None

class AltSeq:
    """"""

    def __init__(self, alt_index, finder):
        """"""

        self.finder = finder

        self.seq_index = alt_index
        self.seq = self.finder.get_seq(self.seq_index, skip_prefix=False)
        self.first_ix = self.seq_index[0]
        self.last_ix = self.seq_index[-1]

        self.seq_len = len(self.seq_index)

        self.ref_index = self.finder.refpath.seq_index
        self.ref_name = self.finder.refpath.name

    def __getitem__(self, item):
        return self.seq_index[item]


import json
import os

OPERATOR_SERVICE_PORT = 8071

CLUSTER_NETWORK = "cello_net"

NETWORK_SIZE_FABRIC_PRE_V1 = [4, 6]
NETWORK_SIZE_FABRIC_V1 = [4]

# first port that can be assigned as cluster API
CLUSTER_PORT_START = int(os.getenv("CLUSTER_PORT_START", 30000))

# Fabric image related varible
# should be the same with scripts/worker_node/download_images.sh
HLF_VERSION = '1.0.5'
HLF_VERSION_1_1 = '1.1.0'

# vSphere requires this
ARCH = 'x86_64'
VERSION = '1.0.5'
BASEIMAGE_RELEASE = '0.3.2'
FABRIC_IMAGE_FULL = 'hyperledger/fabric-{}:{}-{}'
FABRIC_IMAGE_TAG = 'hyperledger/fabric-{}:{}'
FABRIC_IMAGE = 'hyperledger/fabric-{}'
FABRIC_IMAGES = ['peer', 'tools', 'orderer', 'ca', 'ccenv', 'kafka',
                 'zookeeper']
FABRIC_BASE_IMAGES = ['baseimage', 'baseos']

# explorer images
BLOCKCHAIN_EXPLORER_IMAGE = 'yeasy/blockchain-explorer'
BLOCKCHAIN_EXPLORER_TAG = '0.1.0-preview'

MYSQL_IMAGE = 'mysql'
MYSQL_TAG = '5.7'

# host status
HOST_STATUS = 'status'
HOST_STATUS_ACTIVE = 'active'
HOST_STATUS_PENDING = 'pending'

KAFKA_NODE_NUM = 4
ZOOKEEPER_NODE_NUM = 3

PROMETHEUS_EXPOSED_PORT = '29090'
PROMETHEUS_NAMESPACE = 'monitoring'
PROMETHEUS_NODE_EXPORTER_POD_PORT = '9100'

# number of port allocated to each cluster in case collision
CLUSTER_PORT_STEP = 1

PEER_SERVICE_PORTS = {
    'rest': 7050,  # this is the reference starter for cluster port step
    'grpc': 7051,
    'cli': 7052,
    'event': 7053,
}

CA_SERVICE_PORTS = {
    'ecap': 7054,
    'ecaa': 7055,
    'tcap': 7056,
    'tcaa': 7057,
    'tlscap': 7058,
    'tlscaa': 7059,
}

ORDERER_SERVICE_PORTS = {
    'orderer': 7050
}

EXPLORER_PORTS = {
    'explorer': 8080
}

SERVICE_PORTS = dict(list(PEER_SERVICE_PORTS.items()) +
                     list(CA_SERVICE_PORTS.items()))

NETWORK_TYPE_FABRIC_PRE_V1 = 'fabric-0.6'  # TODO: deprecate 0.6 support soon
NETWORK_TYPE_FABRIC_V1 = 'fabric-1.0'
NETWORK_TYPE_FABRIC_V1_1 = 'fabric-1.1'
NETWORK_TYPES = [NETWORK_TYPE_FABRIC_V1, NETWORK_TYPE_FABRIC_V1_1]
# only support fabric v1.x now

CONSENSUS_PLUGIN_NOOPS = 'noops'
CONSENSUS_PLUGIN_PBFT = 'pbft'
CONSENSUS_PLUGIN_SOLO = 'solo'
CONSENSUS_PLUGIN_KAFKA = 'kafka'

CONSENSUS_PLUGINS_FABRIC_V1 = [CONSENSUS_PLUGIN_SOLO, CONSENSUS_PLUGIN_KAFKA]
CONSENSUS_PLUGINS_FABRIC_PRE_V1 = [CONSENSUS_PLUGIN_NOOPS,
                                   CONSENSUS_PLUGIN_PBFT]
CONSENSUS_MODES_FABRIC_V1 = ['', '']

# CONSENSUS_MODES = ['classic', 'batch', 'sieve']  # pbft has various modes
CONSENSUS_MODE_BATCH = 'batch'
CONSENSUS_MODES = [CONSENSUS_MODE_BATCH]  # pbft has various modes

CONSENSUS_TYPES_FABRIC_PRE_V1 = [
    (CONSENSUS_PLUGIN_NOOPS, ''),
    (CONSENSUS_PLUGIN_PBFT, CONSENSUS_MODE_BATCH),
]

CONSENSUS_TYPES_FABRIC_V1 = [
    (CONSENSUS_PLUGIN_SOLO, ''),
    (CONSENSUS_PLUGIN_KAFKA, '')
]

WORKER_TYPE_DOCKER = 'docker'
WORKER_TYPE_SWARM = 'swarm'
WORKER_TYPE_K8S = 'kubernetes'
WORKER_TYPE_VSPHERE = 'vsphere'
# WORKER_TYPES = [WORKER_TYPE_DOCKER, WORKER_TYPE_SWARM, WORKER_TYPE_K8S, WORKER_TYPE_VSPHERE]
WORKER_TYPES = [WORKER_TYPE_DOCKER, WORKER_TYPE_K8S]
# TODO: might deprecate as can use agent to collect log seperately
CLUSTER_LOG_TYPES = ['local']  # TODO: we may remove this option
CLUSTER_LOG_LEVEL = ['DEBUG', 'INFO', 'NOTICE', 'WARNING', 'ERROR',
                     'CRITICAL']

NETWORK_STATUS_CREATING = 'creating'  # just in-creation
NETWORK_STATUS_RUNNING = 'running'  # running now, waiting for health check
NETWORK_STATUS_DELETING = 'deleting'  # network is in deleting
NETWORK_STATUS_STOPPED = 'stopped'  # network is stopped

K8S_CRED_TYPE = {
    'account': '0',
    'cert': '1',
    'config': '2'
}

# Vcenter and VirtualMachine Confs
VIRTUAL_MACHINE = 'vm'
VCENTER = 'vc'
VMUUID = 'vm_uuid'
VM_DEFAULT_HOSTNAME = "Gaea"
VMMEMORY = 'memory'
VMCPU = 'vcpus'
VMNAME = 'vmname'
VMIP = 'ip'
VMNETMASK = 'netmask'
VMDNS = 'dns'
VMGATEWAY = 'gateway'
TEMPLATE = 'template'
VC_DATACENTER = 'vc_datacenter'
VC_CLUSTER = 'vc_cluster'
VC_DATASTORE = 'vc_datastore'
NETWORK = 'network'
NIC_DEVICE_ADDRESS_TYPE = 'assigned'
VCIP = 'address'
VCUSERNAME = 'username'
VCPWD = 'password'
VCPORT = 'port'
VC_DEFAULT_PORT = 443
VCTHREAD_NAME = "setupvm"
WORKER_API_PORT = 2375
DEFAULT_TIMEOUT = 300

def json_decode(jsonstr):
    try:
        json_object = json.loads(jsonstr)
    except json.decoder.JSONDecodeError as e:
        print(e)
        return jsonstr
    return json_object

def request_debug(request, logger):
    logger.debug("path={}, method={}".format(request.path, request.method))
    logger.debug("request args:")
    for k in request.args:
        logger.debug("Arg: {0}:{1}".format(k, request.args[k]))
    logger.debug("request form:")
    for k in request.form:
        logger.debug("Form: {0}:{1}".format(k, request.form[k]))
    logger.debug("request raw body data:")
    logger.debug(request.data)
    logger.debug(request.get_json(force=True, silent=True))

def request_get(request, key, default_value=None):
    if key in request.args:
        return request.args.get(key)
    elif key in request.form:
        return request.form.get(key)
    try:
        json_body = request.get_json(force=True, silent=True)
        if key in json_body:
            return json_body[key]
        else:
            return default_value
    except Exception:
        return default_value

def request_json_body(request, default_value={}):
    try:
        json_body = request.get_json(force=True, silent=True)
        return json_body
    except Exception:
        return default_value


#!/usr/bin/env python
#
# This script will populate the mosques table with data gathered from
# the mosques website.
#
# The script needs to be run from a django shell
#  exec(open('Scripts/populate_mosque_table.py').read());

from mosques.models import Mosque
from mosques.serializers import MosqueSerializer
from django.contrib.gis.geos import Point
from geocoder import google
import pyproj;
import json

print("Deleting..");
for m in Mosque.objects.all():
    m.delete();

print("Adding..");
uid = 0;
f = open("../../data/MD_Site.JSON");
data = json.load(f);

for m in data:

    m["id"] = uid;

    #print(m["name"]);
    if "gender" in m.keys():
        g = str.lower(m["gender"]);
        if g.find("woman") != -1 or g.find("women") != -1 or g.find("female") != -1:
            m["gender"] = "both";
        elif g.find("men") != -1 or g.find("man") != -1 or g.find("male") != -1:
            m["gender"] = "men";
        else:
            m["gender"] = "unknown";
    else:
        m["gender"] = "unknown";

    try:
        if m["accuracy"] > "C":
            print("Ignored {}".format(m['name']));
            continue;
    except KeyError:
        print("");

    # gc = google("{}, {}, {}, United Kingdom".format(m['name'], m['address'], m['postcode']));
    # if gc.json['status'] == False:
    #     print(" ===> Failed");
    #     continue;
    # p = Point(gc.json['lat'], gc.json['lng'], srid=4326);
    #
    # geod = pyproj.Geod(ellps='WGS84')
    # d1, d2, p_dist = geod.inv(gc.json['lng'], gc.json['lat'], float(m['longitude']), float(m['latitude']), False);

    p = Point(float(m['latitude']), float(m['longitude']), srid=4326);
    m["location"] = p;
    del m['latitude'];
    del m['longitude'];
    try:
        del m['accuracy'];
    except KeyError:
        print("");

    serializer = MosqueSerializer(data=m);
    if serializer.is_valid():
        uid = uid + 1;
        serializer.save();
    else:
        print(" => Failed");
        print(" " + m["name"]);
        print(" " + str(serializer.errors));

f.close();

# exec(open('Scripts/populate_mosque_table.py').read())


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import logging as log

from BaseCM import cm_hddcdd
from BaseCM.cm_output import validate

logging = log.getLogger("cm-hdd_cdd")
logging.setLevel(log.DEBUG)

def hdd_cdd_stats(
    geo,
    refyear: int = 2050,
    rcp: str = "4.5",
    t_base_h: float = 18.0,
    t_base_c: float = 22.0,
):
    """The `hdd_cdd_stats` returns a set of graphs and KPI extracted by the HDD and CDD
    layers computed starting from the EURO CORDEX ensamble simulations.

    Graphs
    ======
    This funtion return the following graphs:
    * the total annual HDD & CDD for the baseline and the future year;
    * the total monthly HDD & CDD for the baseline and the future year;

    Key Performance Indicators (KPIs)
    =================================
    The main KPIs provide by the function are:
    * HDDs yearly statistics;
    * CDDs yearly statistics;
    """
    warnings = []
    msg = (
        f"    » ref. year: {refyear},"
        f" crp: {rcp}, Tbh: {t_base_h:.1f}, Tbc: {t_base_c:.1f}"
    )
    logging.info(msg)
    # Compute the centroid of the geometry selected by the user
    lon, lat = cm_hddcdd.compute_centroid(geo)
    logging.info(f"CENTROID: lon: {lon}, lat: {lat}")
    # Query the file-directory-netcdf structure for all the pixels involved
    hdd_path = cm_hddcdd.get_datadir(
        datarepository=cm_hddcdd.get_datarepodir(),
        sim_type=rcp,
        dd_type="hdd",
        Tb=t_base_h,
    )
    # check if path exists or raise an exception
    try:
        cm_hddcdd.check_valid_path(hdd_path, sim_type=rcp, dd_type="hdd", Tb=t_base_h)
    except Exception as exc:
        warnings.append((f"WARNING: {exc}", 0))

    # extract, cast to int from uint8 and transform * 10
    avg_hdds = cm_hddcdd.extract_by_dir(gdir=hdd_path, lon=lon, lat=lat)
    hdds = avg_hdds.astype(int) * 10

    cdd_path = cm_hddcdd.get_datadir(
        datarepository=cm_hddcdd.get_datarepodir(),
        sim_type=rcp,
        dd_type="cdd",
        Tb=t_base_c,
    )
    # check if path exists or raise an exception
    try:
        cm_hddcdd.check_valid_path(cdd_path, sim_type=rcp, dd_type="cdd", Tb=t_base_c)
    except Exception as exc:
        warnings.append((f"WARNING: {exc}", 0))

    # extract, cast to int from uint8 and transform * 10
    avg_cdds = cm_hddcdd.extract_by_dir(gdir=cdd_path, lon=lon, lat=lat)
    cdds = avg_cdds.astype(int) * 10

    # add yearly stats
    yhdds = hdds.groupby(hdds.index.str[:4]).sum()
    ycdds = cdds.groupby(cdds.index.str[:4]).sum()
    graphs = []
    values = []

    if len(yhdds):
        yr_hdd = {}
        yr_hdd["Yearly HDDs"] = {}
        yr_hdd["Yearly HDDs"]["type"] = "bar"
        yr_hdd["Yearly HDDs"]["values"] = list(yhdds.items())
        graphs.append(yr_hdd)
        values.extend(
            [
                (f"Yearly HDDs {stat}", value)
                for stat, value in yhdds.describe().astype(str).items()
            ]
        )
    else:
        values.append(("Yearly HDDs: Dataset not available", 0))

    if len(ycdds):
        yr_cdd = {}
        yr_cdd["Yearly CDDs"] = {}
        yr_cdd["Yearly CDDs"]["type"] = "bar"
        yr_cdd["Yearly CDDs"]["values"] = list(ycdds.items())
        graphs.append(yr_cdd)
        values.extend(
            [
                (f"Yearly CDDs {stat}", value)
                for stat, value in ycdds.describe().astype(str).items()
            ]
        )
    else:
        values.append(("Yearly CDDs: Dataset not available", 0))

    # prepare monthly and yearly graphs
    if len(hdds):
        mon_hdd = {}
        mon_hdd["Monthly HDDs"] = {}
        mon_hdd["Monthly HDDs"]["type"] = "line"
        mon_hdd["Monthly HDDs"]["values"] = list(hdds.items())
        graphs.append(mon_hdd)

    if len(cdds):
        mon_cdd = {}
        mon_cdd["Monthly CDDs"] = {}
        mon_cdd["Monthly CDDs"]["type"] = "line"
        mon_cdd["Monthly CDDs"]["values"] = list(cdds.items())
        graphs.append(mon_cdd)

    ret = dict()
    ret["graphs"] = graphs
    ret["geofiles"] = {}

    ret["values"] = {key: value for key, value in values}
    ret["values"].update({k: v for k, v in warnings})

    validate(ret)
    logging.info(f"Result is:\n{ret}")
    return ret


# -*- coding: utf-8 -*-

import os

from PIL import Image, ImageFont, ImageDraw, ImageFilter

CURRENT_DIRECTORY = os.path.dirname(os.path.realpath(__file__))
MM_LOGO_FILE_PATH = CURRENT_DIRECTORY + '/sources/mm-white-logo.png'
MAIN_FONT_FILE_PATH = CURRENT_DIRECTORY + '/sources/OpenSans-Regular.ttf'
DARKENING_LAYER_COLOR = '#1a2535'

# Originally by https://github.com/kuparez at https://github.com/kuparez/studsovet_scripts
def generate_image(heading, subheading, image, blackout, blur):
    width, height = image.size
    if width * 1.0 / height > 1920.0 / 1080:
        new_height = 1080
        new_width = int(new_height * width / height)
    elif width * 1.0 / height < 1920.0 / 1080:
        new_width = 1920
        new_height = int(new_width * height / width)
    else:
        new_width = 1920
        new_height = 1080
    image = image.resize((new_width, new_height), Image.ANTIALIAS).crop((0, 0, 1920, 1080))

    image = image.filter(ImageFilter.GaussianBlur(blur))
    blackout = int(255 * blackout)
    grey_img = Image.new(mode='RGBA', size=(1920, 1080), color=DARKENING_LAYER_COLOR)
    grey_img.putalpha(blackout)
    mask = Image.new('RGBA', (1920, 1080), (0, 0, 0, blackout))
    image.paste(grey_img, mask)
    logo = Image.open(MM_LOGO_FILE_PATH)
    image.paste(logo, (150, 323), logo)
    draw = ImageDraw.Draw(image)
    font = ImageFont.truetype(MAIN_FONT_FILE_PATH, 115)
    draw.multiline_text((120, 650), heading, (255, 255, 255), font=font)
    font = ImageFont.truetype(MAIN_FONT_FILE_PATH, 73)

    if '\n' not in heading:
        draw.multiline_text((120, 800), subheading, (255, 255, 255), font=font)
    else:
        draw.multiline_text((120, 900), subheading, (255, 255, 255), font=font)

    return image


import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import argparse

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

parser = argparse.ArgumentParser()
parser.add_argument('-t', '--task', type=str, default='3d', help='task to be trained')

args = parser.parse_args()

if args.task == '3d':
    input_size = 96
elif args.task == 'euler':
    input_size = 96
elif ars.task == 'quat':
    input_size = 128
#hidden_size = 512
hidden_size = 512
num_classes = 7
#num_epochs = 5
batch_size = 100
learning_rate = 0.001

# Fully connected layer with one hidden layer
class FCL(nn.Module):
    def __init__(self, input_size, hidden_size, num_classes):
        super(NeuralNet, self).__init__()
        self.fc1 = nn.Linear(input_size, hidden_size)
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(hidden_size, num_classes)

    def forward(self, x):
        out = self.fc1(x)
        out = self.relu(out)
        out = self.fc2(out)
        return out

model = FCL(input_size, hidden_size, num_classes).to(device)

criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr = learning_rate)

#train
total_step = len(train_loader)
for epoch in range(num_epochs):
    for i, (frame, labels) in enumerate(train_loader):
        #preparing the frame, ask Julian
        frames = frames.reshare(-1, 32 * 32).to(device)
        labels = labels.to(device)

        outputs = model(frames)
        loss = criterion(outputs, labels)

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if (i+1) % 100 == 0:
            print('Epoch [{}/{}], Step [{}/{}], Loss: {:,4f}'.format(epoch + 1, num_epochs, i+1, total_step, loss.item()))

#validation
with torch.no_grad():
    correct = 0
    total = 0
    for frames, labels in test_loader:
        frames = images.shape(-1).to(device)
        labels = labels.to(device)
        outputs = model(frames)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()
    print('Accuracy of the network on the S5 actor: {}%'.format(100 * correct / total))

torch.save(model.state_dict(), 'DNN-model.ckpt')


from django.contrib.auth.models import User
from django.urls import reverse
from rest_framework import status
from rest_framework.filters import OrderingFilter
from rest_framework.permissions import IsAuthenticated
from rest_framework.test import APITestCase
from rest_framework.viewsets import ModelViewSet

from ...models.JobTitle import JobTitle
from ...serializers.JobTitleSerializer import JobTitleSerializer
from ...views.JobTitleViewSet import JobTitleViewSet

class EmployeeViewSetTestCase(APITestCase):
    @classmethod
    def setUpTestData(cls):
        cls.tested_class = JobTitleViewSet
        cls.queryset = JobTitle.objects.all()
        cls.serializer = JobTitleSerializer
        cls.url = reverse('list_jobtitle')

        user = User.objects.create_user(**{
            'username': 'q' * 50,
            'email': 'q' * 50 + 'q@q.q',
            'password': 'q' * 50,
        })

        cls.job_title = JobTitle.objects.create(**{
            'title': 'q' * 50,
        })

        cls.data = {
            'title': 'q' * 50,
        }

        client = cls.client_class()
        client.force_authenticate(user=user)
        cls.logged_client = client

    def test_Should_InheritModelViewSet(self):
        expected_super_classes = (
            ModelViewSet,
        )
        real_super_classes = self.tested_class.__bases__

        self.assertEqual(expected_super_classes, real_super_classes)

    def test_Should_QuerySetAsAllEmployees(self):
        expected_queryset = str(self.queryset.query)
        real_queryset = str(self.tested_class.queryset.query)

        self.assertEqual(expected_queryset, real_queryset)

    def test_Should_PermissionClassesIsAuthenticated(self):
        expected_permission_classes = (
            IsAuthenticated,
        )
        real_permission_classes = self.tested_class.permission_classes

        self.assertEqual(expected_permission_classes, real_permission_classes)

    def test_Should_SerializerClassIsEmployeeWithBossSerializer(self):
        expected_serializer = self.serializer
        real_serializer = self.tested_class.serializer_class

        self.assertEqual(expected_serializer, real_serializer)

    def test_Should_FilterBackendsAsListOfDefinedFilters(self):
        expected_filter_backends = (
            OrderingFilter,
        )
        real_filter_backends = self.tested_class.filter_backends

        self.assertEqual(expected_filter_backends, real_filter_backends)

    def test_Should_DefaultOrderingAsId(self):
        expected_fields = (
            'id',
        )
        real_fields = self.tested_class.ordering

        self.assertEqual(expected_fields, real_fields)

    def test_Should_DontOverrideSuperMethods(self):
        expected_methods = [
            ModelViewSet.list,
            ModelViewSet.create,
            ModelViewSet.destroy,
            ModelViewSet.retrieve,
            ModelViewSet.update,
            ModelViewSet.partial_update,
        ]
        real_methods = [
            self.tested_class.list,
            self.tested_class.create,
            self.tested_class.destroy,
            self.tested_class.retrieve,
            self.tested_class.update,
            self.tested_class.partial_update,
        ]

        self.assertEqual(expected_methods, real_methods)

    def test_When_PostMethodForListEmployees_Should_ErrorWithStatus405(self):
        response = self.logged_client.post(self.url, {})

        expected_status = status.HTTP_405_METHOD_NOT_ALLOWED
        real_status = response.status_code

        self.assertEqual(expected_status, real_status)

    def test_When_PutMethodForListEmployees_Should_ErrorWithStatus405(self):
        response = self.logged_client.put(self.url)

        expected_status = status.HTTP_405_METHOD_NOT_ALLOWED
        real_status = response.status_code

        self.assertEqual(expected_status, real_status)

    def test_When_PatchMethodForListEmployees_Should_ErrorWithStatus405(self):
        response = self.logged_client.patch(self.url)

        expected_status = status.HTTP_405_METHOD_NOT_ALLOWED
        real_status = response.status_code

        self.assertEqual(expected_status, real_status)

    def test_When_DeleteMethodForListEmployees_Should_ErrorWithStatus405(
            self):
        response = self.logged_client.delete(self.url)

        expected_status = status.HTTP_405_METHOD_NOT_ALLOWED
        real_status = response.status_code

        self.assertEqual(expected_status, real_status)

    def test_When_GetMethodForListEmployees_Should_ReturnDataWithStatus200(
            self):
        response = self.logged_client.get(self.url)

        expected_status = status.HTTP_200_OK
        real_status = response.status_code

        expected_data = {
            'count': 1,
            'next': None,
            'previous': None,
            'results': self.serializer(**{
                'instance': self.queryset,
                'many': True,
            }).data,
        }
        real_data = dict(response.data)

        self.maxDiff = None

        self.assertEqual(expected_status, real_status)
        self.assertEqual(expected_data, real_data)


def solution(prices):
    counter = 0
    stk = []
    N = len(prices)
    ans = [N - 1 - i for i in range(N)]
    k = 0
    for i in range(N):
        while stk and stk[-1][0] > prices[i]:  # 비어있으면 제거를 하지 않음
            ans[stk[-1][1]] = i - stk[-1][1]
            stk.pop()
        stk.append([prices[i], i])

    return ans

프로그래머스/lv2/42584. 주식가격/주식가격.py


from datetime import date, timedelta

def is_leap_year(year):
    if(year % 100 == 0):
        if(year % 400 == 0):
            return True
        else:
            return False

    if(year % 4 == 0):
        return True
    else:
        return False

def get_delta(date):
    if (date.month in [4, 6, 9, 11]):
        delta = timedelta(days = 30)
    elif (date.month == 2):
        if(is_leap_year(date.year)):
            delta = timedelta(days = 29)
        else:
            delta = timedelta(days = 28)
    else:
        delta = timedelta(days = 31)
    return delta

def main():
    start = date(1901, 1, 1)
    end = date(2000, 12, 31)
    current = start
    count = 0

    while(current < end):
        delta = get_delta(current)
        print(current, delta, sep = '\t')
        if(current.weekday() == 6):
            count += 1
        current += delta
    print(count)

if __name__ == '__main__':
    main()


"""
Non-Overlap: Code to take in a set of raw detections and produce a set of non-overlapping detections from it.

Author: Jonathon Luiten
"""

import os
import sys
from multiprocessing.pool import Pool
from multiprocessing import freeze_support

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
from trackeval.baselines import baseline_utils as butils
from trackeval.utils import get_code_path

code_path = get_code_path()
config = {
    "INPUT_FOL": os.path.join(
        code_path, "data/detections/rob_mots/{split}/raw_supplied/data/"
    ),
    "OUTPUT_FOL": os.path.join(
        code_path, "data/detections/rob_mots/{split}/non_overlap_supplied/data/"
    ),
    "SPLIT": "train",
    "Benchmarks": None,
    "Num_Parallel_Cores": None,
    "THRESHOLD_NMS_MASK_IOU": 0.5,
}

def do_sequence(seq_file):

    data = butils.load_seq(seq_file)

    data = butils.combine_classes(data)

    output_data = []

    for timestep, t_data in enumerate(data):

        t_data = butils.mask_NMS(t_data, nms_threshold=config["THRESHOLD_NMS_MASK_IOU"])

        t_data = butils.non_overlap(t_data, already_sorted=True)

        for i in range(len(t_data["ids"])):
            row = [
                timestep,
                int(t_data["ids"][i]),
                t_data["cls"][i],
                t_data["scores"][i],
                t_data["im_hs"][i],
                t_data["im_ws"][i],
                t_data["mask_rles"][i],
            ]
            output_data.append(row)

    out_file = seq_file.replace(
        config["INPUT_FOL"].format(split=config["SPLIT"]),
        config["OUTPUT_FOL"].format(split=config["SPLIT"]),
    )
    butils.write_seq(output_data, out_file)

    print("DONE:", seq_file)

if __name__ == "__main__":

    freeze_support()

    if config["Benchmarks"]:
        benchmarks = config["Benchmarks"]
    else:
        benchmarks = [
            "davis_unsupervised",
            "kitti_mots",
            "youtube_vis",
            "ovis",
            "bdd_mots",
            "tao",
        ]
        if config["SPLIT"] != "train":
            benchmarks += ["waymo", "mots_challenge"]
    seqs_todo = []
    for bench in benchmarks:
        bench_fol = os.path.join(
            config["INPUT_FOL"].format(split=config["SPLIT"]), bench
        )
        seqs_todo += [os.path.join(bench_fol, seq) for seq in os.listdir(bench_fol)]

    if config["Num_Parallel_Cores"]:
        with Pool(config["Num_Parallel_Cores"]) as pool:
            results = pool.map(do_sequence, seqs_todo)

    else:
        for seq_todo in seqs_todo:
            do_sequence(seq_todo)


#!/usr/bin/env python3

from argparse import ArgumentParser

args = ArgumentParser('TravisHelper')

args.add_argument('command', type=str)

args.add_argument('items', nargs='*')

args = args.parse_args()

if args.command == 'get-closest-release':
    target = args.items.pop(0)

    assert(len(args.items) > 0)

    # First, check for exact match
    for e in args.items:
        if target == e:
            print(e)
            exit(0)

    # Second, check for approximate match
    for e in args.items:
        if target.startswith(e):
            print(e)
            exit(0)

    # In the worst case, return the latest release
    print(args.items.pop(0))
    exit(0)


import os
from selenium.webdriver import Chrome, ChromeOptions
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from pymongo import MongoClient
from datetime import datetime

chrome_options = ChromeOptions()
chrome_options.binary_location = os.environ.get('GOOGLE_CHROME_BIN')
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument('--no-sandbox')

driver = Chrome(executable_path=os.environ.get('CHROMEDRIVER_PATH'), chrome_options=chrome_options)
wait = WebDriverWait(driver, 15)
client = MongoClient(os.environ.get('MONGODB_URI'))
db = client['hoax-detection']
collection = db['train-datasets']
datetime_format = "%B %d, %Y"

def get_article(url):
    driver.execute_script(f'window.open("{url}")')
    driver.switch_to.window(driver.window_handles[1])

    article = wait.until(lambda drv: drv.find_element_by_css_selector('article.post'))
    article_title_element = article.find_element_by_css_selector('h1.entry-title')
    article_date_element = article.find_element_by_css_selector('span.entry-meta-date a')
    article_author_element = article.find_element_by_css_selector('span.entry-meta-author a')
    article_content_element = article.find_element_by_css_selector('div.entry-content')

    article_title = article_title_element.text
    article_date_text = article_date_element.text
    article_datetime = datetime.strptime(article_date_text, datetime_format)
    article_date = f'{article_datetime.year}-' \
        f'{"0" + str(article_datetime.month) if article_datetime.month < 10 else article_datetime.month}-' \
        f'{"0" + str(article_datetime.day) if article_datetime.day < 10 else article_datetime.day}'
    article_author = article_author_element.text
    article_content = article_content_element.text

    if not collection.find_one({'url': url}):
        collection.insert_one({
            'url': url,
            'title': article_title,
            'date': article_date,
            'author': article_author,
            'content': article_content,
            'class': 'Hoax'
        })

    driver.close()
    driver.switch_to.window(driver.window_handles[0])

def get_all_articles(page):
    driver.get(f'https://turnbackhoax.id/page/{page}')

    try:
        articles = wait.until(lambda drv: drv.find_elements_by_css_selector('article.mh-loop-item'))

        for article in articles:
            article_url_element = article.find_element_by_css_selector('h3.mh-loop-title a')
            article_url = article_url_element.get_attribute('href')
            get_article(article_url)

        get_all_articles(page + 1)
    except TimeoutException:
        get_all_articles(1)

get_all_articles(1)


import contextlib
from pathlib import Path
import re
import tempfile

import unittest

from launch import LaunchDescription
from launch.actions import ExecuteProcess

import launch_testing
import launch_testing.actions
import launch_testing.asserts
import launch_testing.markers
import launch_testing.tools

import pytest

PROFILE_PATH = Path(__file__).parent / 'resources'
TEST_NODE = 'ros2bag_record_qos_profile_test_node'
TEST_NAMESPACE = 'ros2bag_record_qos_profile'
ERROR_STRING = r'\[ERROR] \[ros2bag]:'

@pytest.mark.rostest
@launch_testing.markers.keep_alive
def generate_test_description():
    return LaunchDescription([launch_testing.actions.ReadyToTest()])

class TestRos2BagRecord(unittest.TestCase):

    @classmethod
    def setUpClass(cls, launch_service, proc_info, proc_output):
        @contextlib.contextmanager
        def launch_bag_command(self, arguments, **kwargs):
            pkg_command_action = ExecuteProcess(
                cmd=['ros2', 'bag', *arguments],
                additional_env={'PYTHONUNBUFFERED': '1'},
                name='ros2bag-cli',
                output='screen',
                **kwargs
            )
            with launch_testing.tools.launch_process(
                    launch_service, pkg_command_action, proc_info, proc_output
            ) as pkg_command:
                yield pkg_command
        cls.launch_bag_command = launch_bag_command

    def test_qos_simple(self):
        profile_path = PROFILE_PATH / 'qos_profile.yaml'
        with tempfile.TemporaryDirectory() as tmpdirname:
            output_path = Path(tmpdirname) / 'ros2bag_test_basic'
            arguments = ['record', '-a', '--qos-profile-overrides-path', profile_path.as_posix(),
                         '--output', output_path.as_posix()]
            with self.launch_bag_command(arguments=arguments) as bag_command:
                bag_command.wait_for_shutdown(timeout=5)
            expected_string_regex = re.compile(ERROR_STRING)
            matches = expected_string_regex.search(bag_command.output)
            assert not matches, print('ros2bag CLI did not produce the expected output')

    def test_incomplete_qos_profile(self):
        profile_path = PROFILE_PATH / 'incomplete_qos_profile.yaml'
        with tempfile.TemporaryDirectory() as tmpdirname:
            output_path = Path(tmpdirname) / 'ros2bag_test_incomplete'
            arguments = ['record', '-a', '--qos-profile-overrides-path', profile_path.as_posix(),
                         '--output', output_path.as_posix()]
            with self.launch_bag_command(arguments=arguments) as bag_command:
                bag_command.wait_for_shutdown(timeout=5)
            expected_string_regex = re.compile(ERROR_STRING)
            matches = expected_string_regex.search(bag_command.output)
            assert not matches, print('ros2bag CLI did not produce the expected output')

    def test_incomplete_qos_duration(self):
        profile_path = PROFILE_PATH / 'incomplete_qos_duration.yaml'
        with tempfile.TemporaryDirectory() as tmpdirname:
            output_path = Path(tmpdirname) / 'ros2bag_test_incomplete_duration'
            arguments = ['record', '-a', '--qos-profile-overrides-path', profile_path.as_posix(),
                         '--output', output_path.as_posix()]
            with self.launch_bag_command(arguments=arguments) as bag_command:
                bag_command.wait_for_shutdown(timeout=5)
            assert bag_command.exit_code != launch_testing.asserts.EXIT_OK
            expected_string_regex = re.compile(ERROR_STRING)
            matches = expected_string_regex.search(bag_command.output)
            assert matches, print('ros2bag CLI did not produce the expected output')

    def test_nonexistent_qos_profile(self):
        profile_path = PROFILE_PATH / 'foobar.yaml'
        with tempfile.TemporaryDirectory() as tmpdirname:
            output_path = Path(tmpdirname) / 'ros2bag_test_incomplete'
            arguments = ['record', '-a', '--qos-profile-overrides-path', profile_path.as_posix(),
                         '--output', output_path.as_posix()]
            with self.launch_bag_command(arguments=arguments) as bag_command:
                bag_command.wait_for_shutdown(timeout=5)
            assert bag_command.exit_code != launch_testing.asserts.EXIT_OK
            expected_string_regex = re.compile(
                r"ros2 bag record: error: argument --qos-profile-overrides-path: can't open")
            matches = expected_string_regex.search(bag_command.output)
            assert matches, print('ros2bag CLI did not produce the expected output')


#!/usr/bin/env python

import os
import matplotlib.pyplot as plt
import cv2
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import rospy
import tensorflow as tf
from cv_bridge import CvBridge, CvBridgeError
#load the trained model to classify sign
from keras.models import load_model
from PIL import Image
from sensor_msgs.msg import Image
from sklearn.model_selection import train_test_split
from tensorflow.keras.layers import Conv2D, Dense, Dropout, Flatten, MaxPool2D
from tensorflow.keras.models import Sequential
from tensorflow.keras.utils import to_categorical
from sklearn.metrics import accuracy_score
from std_msgs.msg import String

model = load_model(r"/home/michalis111/catkin_ws/src/puzzlebotcode/scripts/TSRv2.h5")

#dictionary to label all traffic signs class.
classes = { 0:'Speed limit (20km/h)',
            1:'Speed limit (30km/h)',
            2:'Speed limit (50km/h)',
            3:'Speed limit (60km/h)',
            4:'Speed limit (70km/h)',
            5:'Speed limit (80km/h)',
            6:'End of speed limit (80km/h)',
            7:'Speed limit (100km/h)',
            8:'Speed limit (120km/h)',
            9:'No passing',
            10:'No passing veh over 3.5 tons',
            11:'Right-of-way at intersection',
            12:'Priority road',
            13:'Yield',
            14:'Stop',
            15:'No vehicles',
            16:'Veh > 3.5 tons prohibited',
            17:'No entry',
            18:'General caution',
            19:'Dangerous curve left',
            20:'Dangerous curve right',
            21:'Double curve',
            22:'Bumpy road',
            23:'Slippery road',
            24:'Road narrows on the right',
            25:'Road work',
            26:'Traffic signals',
            27:'Pedestrians',
            28:'Children crossing',
            29:'Bicycles crossing',
            30:'Beware of ice/snow',
            31:'Wild animals crossing',
            32:'End speed + passing limits',
            33:'Turn right ahead',
            34:'Turn left ahead',
            35:'Ahead only',
            36:'Go straight or right',
            37:'Go straight or left',
            38:'Keep right',
            39:'Keep left',
            40:'Roundabout mandatory',
            41:'End of no passing',
            42:'End no passing veh > 3.5 tons' }

def grayscale(img):
  img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
  return img
def equalize(img):
  img =cv2.equalizeHist(img)
  return img
def preprocessing(img):
  img = grayscale(img)
  img = equalize(img)
  img = img/255
  return img

class camera_1:

  def __init__(self):
    self.image_sub = rospy.Subscriber("/camera/image_raw", Image, self.callback)

  def callback(self,data):
    bridge = CvBridge()

    try:
      image = bridge.imgmsg_to_cv2(data, desired_encoding="bgr8")
    except CvBridgeError as e:
      rospy.logerr(e)

    font = cv2.FONT_HERSHEY_SIMPLEX
    threshold = 0.95
    msg = String()

    sign_image = np.copy(image)
    #cropped_image = region_of_interest(sign_image)
    cropped_image = sign_image[260:410, 520:670] # Slicing to crop the image

    ncropped_image = np.asarray(cropped_image)
    ncropped_image = cv2.resize(ncropped_image, (32, 32))
    ncropped_image = preprocessing(ncropped_image)

    ncropped_image = ncropped_image.reshape(1, 32, 32, 1)
    cv2.putText(sign_image, "CLASS: " , (20, 35), font, 0.75, (0, 0, 255), 2, cv2.LINE_AA)
    cv2.putText(sign_image, "PROBABILITY: ", (20, 75), font, 0.75, (0, 0, 255), 2, cv2.LINE_AA)

    # PREDICT IMAGE
    predictions = model.predict(ncropped_image)
    classIndex = model.predict(ncropped_image)
    probabilityValue =np.amax(predictions)
    index = np.argmax(predictions)
    if probabilityValue > threshold:
      #print("Predicted traffic sign is: ", classes[index])
      #cv2.putText(sign_image,str(index)+" "+classes[index], (120, 35), font, 0.75, (0, 0, 255), 2, cv2.LINE_AA)
      #cv2.putText(sign_image, str(round(probabilityValue*100,2) )+"%", (180, 75), font, 0.75, (0, 0, 255), 2, cv2.LINE_AA)
      #cv2.imshow("Result", sign_image)
      #cv2.waitKey(3)
      msg = classes[index]
      print(msg)
      pub.publish(msg)
      return msg
    else:
      #print("Predicted traffic sign is: No Sign")
      #cv2.putText(sign_image,"No Sign", (120, 35), font, 0.75, (0, 0, 255), 2, cv2.LINE_AA)
      #cv2.putText(sign_image, "No Sign", (180, 75), font, 0.75, (0, 0, 255), 2, cv2.LINE_AA)
      #cv2.imshow("Result", sign_image)
      #cv2.waitKey(3)
      msg = "No Sign"
      print(msg)
      pub.publish(msg)
      return msg

if __name__ == '__main__':
    rospy.init_node('Sign Detection', anonymous=False)
    pub = rospy.Publisher('sign', String, queue_size=10)
    rate = rospy.Rate(10) # 10hz
    camera_1()

    try:
      rospy.spin()
    except KeyboardInterrupt:
      rospy.loginfo("Shutting down")

    cv2.destroyAllWindows()


import string

import aster
from ..Cata.Syntax import _F
from ..Commands import CALC_FERRAILLAGE, CREA_CHAMP, CREA_RESU, DETRUIRE, FORMULE
from ..Messages import UTMESS

def combinaison_ferraillage_ops(self, **args):
    """Command to combine results to estimate reinforcement of the structure."""

    resu         = args.get('reuse')
    combinaison  = args.get('COMBINAISON')
    affe         = args.get('AFFE')
    codification = args.get('CODIFICATION')

    #
    # Retriving MODELE from RESULTAT
    #
    modele = resu.getModel()

    #
    # Retriving CARA_ELEM from RESULTAT
    #
    # caraelem     = self [ 'CARA_ELEM' ] changed with dismoi
    caraelem = resu.getElementaryCharacteristics()

    if codification != 'EC2':
        UTMESS('F', 'COMBFERR_1')

    # Counting numbers of load combinations.
    #
    nmb_cas = countCase(combinaison)
    UTMESS('I', 'COMBFERR_10', vali=nmb_cas)

    # Build instant list (lst_inst_value of float) and instant index
    # and control about existing or duplicates NUM_CAS and NUME_ORDRE.
    #
    lst_inst_index, lst_inst_value, resu_nom_cas, resu_num_ord, lst_type_combo = \
        lstInst(nmb_cas,combinaison,resu)

    UTMESS('I', 'COMBFERR_11', valk=(
        '-'.join([str(i) for i in lst_inst_value]),
        '*'.join([str(i) for i in resu_nom_cas]),
        '*'.join([str(i) for i in resu_num_ord]),
    ))

    # Controlling overwriting results
    #
    if 'COMB_DIME_ORDRE' in resu_nom_cas:
        UTMESS('A', 'COMBFERR_9', valk='COMB_DIME_ORDRE')

    if 'COMB_DIME_ACIER' in resu_nom_cas:
        UTMESS('A', 'COMBFERR_9', valk='COMB_DIME_ACIER')

    UTMESS('I', 'COMBFERR_12', valk='\n    '.join(lst_type_combo))

    count_2D = 0
    lGroupSelec = []
    g = []
    TEST_TOUT = False
    for i_affe in affe :
        structure_type = i_affe.get('TYPE_STRUCTURE')

        # [structure_type] selects design algorithm.
        if structure_type == '2D' :
            if not i_affe.get('GROUP_MA') or i_affe.get('TOUT'):
                TEST_TOUT = True
            else:
                for Ma in i_affe.get('GROUP_MA'):
                    g.append(Ma)
                count_2D = count_2D + 1
        elif structure_type == 'POUTRE' :
            # Algorithm un available
            algo_POUTRE()
        elif structure_type == 'POTEAU' :
            # Algorithm un available
            algo_POTEAU()
        else:
            UTMESS('F', 'COMBFERR_14', valk=structure_type)

    lGroupSelec+=[{'GROUP_MA':g}]
    resu = algo_2D(resu, affe, lst_inst_index, codification, lst_type_combo)

    # - Build result type EVOL_ELAS from MULTI_ELAS and combo type list in order
    #   to select the right verify. This because CREA_CHAMP does'nt EXTR the
    #   MAXI from multi_elas
    __resfer = \
        evolElasFromMulti(nmb_cas,combinaison,lst_inst_value,resu,modele,caraelem)

    # Maximum reinforcement field (elementwise, component by component)
    __maxifer = CREA_CHAMP (
        RESULTAT = __resfer,
        # RESULTAT = resu,
        NOM_CHAM = 'FERRAILLAGE',
        TYPE_CHAM = 'ELEM_FER2_R',
        OPERATION = 'EXTR',
        TYPE_MAXI = 'MAXI',
        TYPE_RESU = 'VALE' ,
        TOUT_ORDRE = 'OUI',
    )

    # Instant for which maximum reinforcement field is retrieved (elementwise,
    # component by component) Later we want to see the NUME_ORDRE and not the
    # INSTant
    # NUME_ORDRE is not available now as an option of CREA_CHAMP-MAXI
    __instfer = CREA_CHAMP (
          RESULTAT = __resfer,
          # RESULTAT = resu,
          NOM_CHAM = 'FERRAILLAGE',
         TYPE_CHAM = 'ELEM_FER2_R',
         OPERATION = 'EXTR',
         TYPE_MAXI = 'MAXI',
         TYPE_RESU = 'INST',
        TOUT_ORDRE = 'OUI',
    )

    # Adding the field 'FERRAILLAGE' (steel reinforcement) to the MULTI_ELAS result,
    # for all load cases
    # MULTI_ELAS completed by the steel reinforcement field is the OUTPUT of the COMBINAISON_FERRAILLAGE
    # NOTA BENE : CREA_RESU cannot complete the existing NOM_CAS/NUME_ORDRE, it adds new NUME_ORDRE
    #                  see crtype.f90 call rsorac.f90
    #     Here we also test CALC_FERRAILLAGE (non-regression), can become analytical
    # By Luca

    # Build result type EVOL_ELAS from MULTI_ELAS and combo type list in order
    #
    # resu = multiFromEvolElas(nmb_cas, resu_nom_cas, lst_inst_index, lst_inst_value, __resfer, resu, modele, caraelem)
    # The reinforcement has 7 components
    #  DNSXI :
    #  DNSXS :
    #  DNSYI :
    #  DNSYS :
    #   DNST :
    # EPSIBE :
    # SIGMBE :

    if not TEST_TOUT:
        groupSelection = lGroupSelec[0]

    # Workaround to Bug: "ELEM_NEUT_R can use only X1"
    __CHP = [None] * 7
    for cmp_index, cmp_name in enumerate(['DNSXI','DNSXS','DNSYI','DNSYS','DNST','DNSVOL','CONSTRUC']):

        # Renaming component(s) in COMB_DIME_ORDRE to avoid overlapping with COMB_DIME_ACIER
        if TEST_TOUT :
            __CHORD2=CREA_CHAMP(OPERATION='ASSE',
                              MODELE=modele,
                              TYPE_CHAM='ELEM_NEUT_R',
                              ASSE=(
                                    # ~ _F(CHAM_GD=CHORD,TOUT='OUI',NOM_CMP=('DNSXI','DNSXS','DNSYI','DNSYS','DNST','SIGMBE','EPSIBE'),NOM_CMP_RESU=('X8','X9','X10','X11','X12','X13','X14')),
                                    _F(CHAM_GD=__instfer,TOUT='OUI',NOM_CMP=cmp_name,NOM_CMP_RESU='X1'),
                                  ),
                                  PROL_ZERO='OUI',
                                  )
        else:
            __CHORD2=CREA_CHAMP(OPERATION='ASSE',
                              MODELE=modele,
                              TYPE_CHAM='ELEM_NEUT_R',
                              ASSE=(_F(CHAM_GD=__instfer,NOM_CMP=cmp_name,NOM_CMP_RESU='X1',**groupSelection), ),
                              PROL_ZERO='OUI',)

        __FDNSXI=FORMULE(NOM_PARA=(cmp_name,'X1'),VALE="X1 if "+cmp_name+" > 0 else -1")

        if TEST_TOUT :
            __CHFMU=CREA_CHAMP(OPERATION='AFFE',
                             TYPE_CHAM='ELEM_NEUT_F',
                             # ~ TYPE_CHAM='CART_NEUT_F',
                             # ~ TYPE_CHAM='ELGA_NEUT_F',
                             MODELE=modele,
                             AFFE=(
                                    # ~ _F(TOUT = 'OUI',NOM_CMP = ('X1','X2','X3','X4','X5','X6','X7'),VALE_F = (FDNSXI,FDNSXS,FDNSYI,FDNSYS,FDNST,FSIGMBE,FEPSIBE)),
                                    _F(TOUT = 'OUI',NOM_CMP = 'X1',VALE_F = __FDNSXI,),
                                  ),
                                  PROL_ZERO='OUI',
                                  )
        else:
            __CHFMU=CREA_CHAMP(OPERATION='AFFE',
                             TYPE_CHAM='ELEM_NEUT_F',
                             MODELE=modele,
                             AFFE=(_F(NOM_CMP = 'X1',VALE_F = __FDNSXI,**groupSelection),),
                             PROL_ZERO='OUI',)

        # Bug 3 : cannot EVAL functions on CART_NEUT_F, ELGA_NEUT_F :
        __CHP[cmp_index]=CREA_CHAMP(OPERATION='EVAL',
                          TYPE_CHAM='ELEM_NEUT_R',
                          CHAM_F=__CHFMU,
                          CHAM_PARA=(__maxifer,__CHORD2),
                          )

        DETRUIRE(CONCEPT=(_F(NOM=(__CHORD2,__FDNSXI,__CHFMU)),),)

    # Bug il n y a pas de paramètre  INOUT  associe a la grandeur: FER2_R  dans l option: TOU_INI_ELEM
    # see https://www.code-aster.org/forum2/viewtopic.php?id=21005
    if TEST_TOUT :
        __CHORD4=CREA_CHAMP(OPERATION='ASSE',
                          # ~ TYPE_CHAM='ELEM_FER2_R',
                          TYPE_CHAM='CART_NEUT_R',
                          MODELE=modele,
                          # ~ PROL_ZERO='OUI',
                          ASSE=(
                                _F(TOUT='OUI',CHAM_GD=__CHP[0],NOM_CMP=('X1',), NOM_CMP_RESU=('X1',),),
                                _F(TOUT='OUI',CHAM_GD=__CHP[1],NOM_CMP=('X1',), NOM_CMP_RESU=('X2',),),
                                _F(TOUT='OUI',CHAM_GD=__CHP[2],NOM_CMP=('X1',), NOM_CMP_RESU=('X3',),),
                                _F(TOUT='OUI',CHAM_GD=__CHP[3],NOM_CMP=('X1',), NOM_CMP_RESU=('X4',),),
                                _F(TOUT='OUI',CHAM_GD=__CHP[4],NOM_CMP=('X1',), NOM_CMP_RESU=('X5',),),
                                _F(TOUT='OUI',CHAM_GD=__CHP[5],NOM_CMP=('X1',), NOM_CMP_RESU=('X6',),),
                                _F(TOUT='OUI',CHAM_GD=__CHP[6],NOM_CMP=('X1',), NOM_CMP_RESU=('X7',),),
                              )
                              )
    else:
        __CHORD4=CREA_CHAMP(OPERATION='ASSE',
                          # ~ TYPE_CHAM='ELEM_FER2_R',
                          TYPE_CHAM='CART_NEUT_R',
                          MODELE=modele,
                          # ~ PROL_ZERO='OUI',
                          ASSE=(
                                _F(**groupSelection,CHAM_GD=__CHP[0],NOM_CMP=('X1',), NOM_CMP_RESU=('X1',),),
                                _F(**groupSelection,CHAM_GD=__CHP[1],NOM_CMP=('X1',), NOM_CMP_RESU=('X2',),),
                                _F(**groupSelection,CHAM_GD=__CHP[2],NOM_CMP=('X1',), NOM_CMP_RESU=('X3',),),
                                _F(**groupSelection,CHAM_GD=__CHP[3],NOM_CMP=('X1',), NOM_CMP_RESU=('X4',),),
                                _F(**groupSelection,CHAM_GD=__CHP[4],NOM_CMP=('X1',), NOM_CMP_RESU=('X5',),),
                                _F(**groupSelection,CHAM_GD=__CHP[5],NOM_CMP=('X1',), NOM_CMP_RESU=('X6',),),
                                _F(**groupSelection,CHAM_GD=__CHP[6],NOM_CMP=('X1',), NOM_CMP_RESU=('X7',),),
                              )
                              )

    # Adding COMB_DIME_ACIER and COMB_DIME_ORDRE tu resu
    #
    resu = CREA_RESU(
                    reuse = resu,
                    RESULTAT = resu,
                    OPERATION = 'AFFE',
                    TYPE_RESU = 'MULT_ELAS' ,
                    NOM_CHAM = 'FERRAILLAGE',
                    AFFE = (
                            _F(
                             NOM_CAS = 'COMB_DIME_ACIER',
                             CHAM_GD = __maxifer,
                             MODELE = modele,
                             CARA_ELEM = caraelem,
                                ),
                        ),)

    # Adding COMB_DIME_ACIER and COMB_DIME_ORDRE tu resu
    #
    resu = CREA_RESU(
                    reuse = resu,
                    RESULTAT = resu,
                    OPERATION = 'AFFE',
                    TYPE_RESU = 'MULT_ELAS' ,
                    NOM_CHAM = 'UT01_ELEM',
                    AFFE = (
                            _F(
                             NOM_CAS = 'COMB_DIME_ORDRE',
                             # CHAM_GD = __instfer,
                             CHAM_GD = __CHORD4,
                             MODELE = modele,
                             CARA_ELEM = caraelem,
                                ),
                        ),)

    nc = resu.LIST_VARI_ACCES()['NOM_CAS']
    UTMESS('I', 'COMBFERR_13', valk='\n    '.join(nc))
    return resu

def algo_2D (_resfer, affe, lst_nume_ordre, code, type_combo):

    for idx, nume_ordre in enumerate(lst_nume_ordre):

        # seelction of mot-clè TYPE_COMB by [lst_type_combo]
        dic_type_comb = {}
        if type_combo [idx]  == 'ELS_CARACTERISTIQUE':
           dic_type_comb['TYPE_COMB'] = 'ELS'
        else:
           dic_type_comb['TYPE_COMB'] = 'ELU'

        lst_tmp_affe = []
        for i_affe in affe :

            structure_type = i_affe.get('TYPE_STRUCTURE')
            if structure_type == '2D' :
                dict_i_affe = i_affe.List_F()[0]

                # saving dict_affe
                i_affe_for_cf = dict_i_affe.copy();
                i_affe_for_cf.pop('TYPE_STRUCTURE')

                if type_combo [idx]  == 'ELU_FONDAMENTAL':
                    i_affe_for_cf.update({'GAMMA_S':i_affe_for_cf['GAMMA_S_FOND']})
                    i_affe_for_cf.update({'GAMMA_C':i_affe_for_cf['GAMMA_C_FOND']})

                elif type_combo [idx]  == 'ELU_ACCIDENTEL':
                    i_affe_for_cf.update({'GAMMA_S':i_affe_for_cf['GAMMA_S_ACCI']})
                    i_affe_for_cf.update({'GAMMA_C':i_affe_for_cf['GAMMA_C_ACCI']})

                # adjusting affe for calc_ferraillage
                i_affe_for_cf.pop('GAMMA_C_FOND')
                i_affe_for_cf.pop('GAMMA_S_FOND')
                i_affe_for_cf.pop('GAMMA_C_ACCI')
                i_affe_for_cf.pop('GAMMA_S_ACCI')

                lst_tmp_affe.append(_F(**i_affe_for_cf),)

        dic_type_comb['AFFE']=tuple(lst_tmp_affe)

        dic_type_comb['CODIFICATION'] = code

        _resfer = CALC_FERRAILLAGE (
            reuse = _resfer,
            RESULTAT = _resfer,
            NUME_ORDRE = nume_ordre,
            **dic_type_comb
        )

    return _resfer

def algo_POUTRE ():
    UTMESS('A', 'COMBFERR_2', valk='POUTRE')
    return None

def algo_POTEAU ():
    UTMESS('A', 'COMBFERR_2', valk='POTEAU')
    return None

def combdimferr(fer):
    if fer <= 0.:
        return 0.
    else:
        return 1.

# Counting numbers of load combinations.
#
def countCase(comb):
    nmb_cas = 0
    for idx_i_combo, i_combo in enumerate(comb) :
        # Case number from MULTI_ELAS
        lst_nomcas = i_combo.get('NOM_CAS')
        lst_numord = i_combo.get('NUME_ORDRE')
        if lst_nomcas is None:
            nmb_cas = nmb_cas + len(lst_numord)      # combinations number
        else:
            nmb_cas = nmb_cas + len(lst_nomcas)
    return nmb_cas

def lstInst(ncas, comb, resultat):

    lst_inst_value = [None] * ncas # list of float value as time for AFFE
    lst_inst_index = [None] * ncas # list of int value as index
    type_combo     = [None] * ncas # list of string as type of combo

    # Recupero i numeri d'ordine e nomi dei casi
    resu_nume_ordre = resultat.LIST_VARI_ACCES()['NUME_ORDRE']
    resu_nom_cas = resultat.LIST_VARI_ACCES()['NOM_CAS']

    # Deblanking di [resu_nom_cas]
    for idx, val in enumerate(resu_nom_cas):
        resu_nom_cas[idx]=val.strip()

    idx_shift = 0
    for idx_i_combo, i_combo in enumerate( comb ) :
        # Case number from MULTI_ELAS
        lst_nomcas = i_combo.get('NOM_CAS')
        lst_numord = i_combo.get('NUME_ORDRE')
        if lst_nomcas is None:
            lst_combo = lst_numord
            key_name_combo = 'NUME_ORDRE'
        else:
            lst_combo = lst_nomcas
            key_name_combo = 'NOM_CAS'

        for idx_combo, val_combo in enumerate( lst_combo ):

            # type combo list couple with instant
            type_combo [idx_shift] = i_combo.get('TYPE')

            if key_name_combo == 'NUME_ORDRE':
                inst = val_combo
                if not (inst in resu_nume_ordre):
                    UTMESS('F', 'COMBFERR_7')
                if inst in lst_inst_index:
                    UTMESS('F', 'COMBFERR_4')
            else:
                if not (val_combo in resu_nom_cas):
                    UTMESS('F', 'COMBFERR_6')
                # Index needs to be [inst_index + 1] because MUME_ORDRE is index + 1
                inst = resu_nom_cas.index(val_combo) + 1
                if inst in lst_inst_index:
                    UTMESS('F', 'COMBFERR_5')

            lst_inst_index [ idx_shift ] = inst
            lst_inst_value [ idx_shift ] = float(inst)
            idx_shift = idx_shift + 1

    return lst_inst_index, lst_inst_value, resu_nom_cas, resu_nume_ordre, type_combo

# Build result type EVOL_ELAS from MULTI_ELAS
#
def evolElasFromMulti(ncas, comb, lst_inst_value, resu, modele, caraelem):

    __EFGE         = [None] * ncas
    lst_AFFE_EFGE  = [None] * ncas
    # type_combo     = [None] * ncas # list of string as type of combo

    idx_shift = 0
    for idx_i_combo, i_combo in enumerate( comb ) :

        # Case number from MULTI_ELAS
        lst_nomcas = i_combo.get('NOM_CAS')
        lst_numord = i_combo.get('NUME_ORDRE')
        if lst_nomcas is None:
            lst_combo = lst_numord                   # list with combinations
            key_name_combo = 'NUME_ORDRE'
        else:
            lst_combo = lst_nomcas
            key_name_combo = 'NOM_CAS'

        for idx_combo, val_combo in enumerate( lst_combo ):

            # type combo list couple with instant
            # type_combo [idx_shift] = i_combo.get('TYPE')

            dic_idx_combo = { key_name_combo : val_combo }

            __EFGE[ idx_shift ] = CREA_CHAMP (

            OPERATION = 'EXTR',
            RESULTAT = resu,
            # TYPE_CHAM = 'ELNO_SIEF_R',
            # NOM_CHAM = 'EFGE_ELNO',
            TYPE_CHAM = 'ELEM_FER2_R',
            NOM_CHAM = 'FERRAILLAGE',
            **dic_idx_combo
            )

            lst_AFFE_EFGE [ idx_shift ] = _F (
                 INST = lst_inst_value [ idx_shift ],
              CHAM_GD = __EFGE [ idx_shift ],
               MODELE = modele,
            CARA_ELEM = caraelem,
            )

            idx_shift = idx_shift  + 1

    _resfer = CREA_RESU (
        OPERATION='AFFE',
        TYPE_RESU ='EVOL_ELAS',
        # NOM_CHAM ='EFGE_ELNO',
        NOM_CHAM ='FERRAILLAGE',
        AFFE = lst_AFFE_EFGE,
    )

    return _resfer# , type_combo