<commit_before>#!/usr/bin/env python
# encoding: utf-8

import sys
import os
import pprint
sys.path.insert(0, os.path.abspath('../'))
from ursgal.uparams import ursgal_params
from collections import defaultdict as ddict
import dash
import dash_core_components as dcc
import dash_html_components as html

def sort_params(uparams, sort_by=None):
    if sort_by is None:
        return uparams
    sorted_params = {}
    for ukey in uparams.keys():
        if type(uparams[ukey][sort_by]) in [list, dict]:
            for element in uparams[ukey][sort_by]:
                if element not in sorted_params.keys():
                    sorted_params[element] = {}
                sorted_params[element][ukey] = uparams[ukey]
        else:
            element = uparams[ukey][sort_by]
            if element not in sorted_params.keys():
                sorted_params[element] = {}
            sorted_params[element][ukey] = uparams[ukey]
    return sorted_params

app = dash.Dash()

colors = {
    'background_header': '#297FB8',
    'text_header': '#FCFFFF'
}

available_engines = []
unode_sorted_uparams = sort_params(ursgal_params, sort_by='available_in_unode')
for unode in sorted(unode_sorted_uparams.keys()):
    available_engines.append(unode)

available_tags = []
utag_sorted_uparams = sort_params(ursgal_params, sort_by='utag')
for utag in sorted(utag_sorted_uparams):
    available_tags.append(utag)

app.layout = html.Div([
    html.Div([
        dcc.Markdown(
            '''
.
''',
            containerProps={
                'style': {
                    'color': 'rgb(30, 120, 210)',
                }, })
    ], style={
        'backgroundColor': 'rgb(30, 120, 210)',
    },),

    html.Div([
        dcc.Markdown('''
# Ursgal Parameters
A searchable list of all parameters in Ursgal.
Use the dropdown options to select one or multiple engines or tags \
for which the corresponding parameters should be displayed

        ''',
                     containerProps={
                         'style': {
                             'color': 'rgb(35, 35, 35)',
                         }, })
    ], style={
        'marginLeft': 10,
        'marginRight': 10,
    }),

    html.Div([
        dcc.Markdown('**UParams**'),
        dcc.RadioItems(
            id='uparams_radio',
            options=[
                {'label': 'All uparams', 'value': 'all_uparams'},
                {'label': 'Select uparams', 'value': 'select_uparams'},
            ],
            value='all_uparams',
            labelStyle={'display': 'inline-block'}
        ),
        dcc.Dropdown(
            id='params',
            value='all_uparams',
            multi=True
        ),
    ], style={
        'width': '32%',
        'marginLeft': 10,
        'marginRight': 10,
        'display': 'inline-block',
        'backgroundColor': 'rgb(250, 250, 250)',
        'color': 'rgb(35, 35, 35)',
    }),

    html.Div([
        dcc.Markdown('**Engines**'),
        dcc.RadioItems(
            id='engines_radio',
            options=[
                {'label': 'All engines', 'value': 'all_engines'},
                {'label': 'Select engines', 'value': 'select_engines'},
            ],
            value='all_engines',
            labelStyle={'display': 'inline-block'}
        ),
        dcc.Dropdown(
            id='engine',
            value='all_engines',
            multi=True
        ),
    ], style={
        'width': '32%',
        'marginLeft': 10,
        'display': 'inline-block',
        'backgroundColor': 'rgb(250, 250, 250)',
        'color': 'rgb(35, 35, 35)',
    }),

    html.Div([
        dcc.Markdown('**Tags**'),
        dcc.RadioItems(
            id='tags_radio',
            options=[
                {'label': 'All tags', 'value': 'all_tags'},
                {'label': 'Select tags', 'value': 'select_tags'},
            ],
            value='all_tags',
            labelStyle={'display': 'inline-block'}
        ),
        dcc.Dropdown(
            id='tag',
            value='all_tags',
            multi=True
        ),
    ], style={
        'width': '32%',
        'display': 'inline-block',
        'backgroundColor': 'rgb(250, 250, 250)',
        'color': 'rgb(35, 35, 35)',
    }),

    html.Div([
        dcc.Checklist(
            id='text_options',
            options=[
                {'label': 'Show UNodes for each parameter',
                    'value': 'available_unodes'},
                {'label': 'Show Ursgal tags',
                    'value': 'show_utags'},
                {'label': 'Show Ursgal value translations',
                    'value': 'uvalue_translation'},
                {'label': 'Show Ursgal key translations',
                    'value': 'ukey_translation'},
            ],
            values=['available_unodes'],
            # labelStyle={'display': 'inline-block'}
        ),
    ], style={
        'marginLeft': 10,
        'marginRight': 10,
        'backgroundColor': 'rgb(250, 250, 250)',
        'color': 'rgb(35, 35, 35)',
    },),

    html.Div([
        dcc.Markdown(
            '''
.
''',
            containerProps={
                'style': {
                    'color': 'rgb(30, 120, 210)',
                }, })
    ], style={
        'backgroundColor': 'rgb(30, 120, 210)',
    },),

    html.Div([
        dcc.Markdown(
            id='selected_params',
            containerProps={
                'style': {
                    'color': 'rgb(37, 37, 37)',
                },
            },
        ),
    ], style={
        'marginLeft': 30,
        'marginRight': 10,
        'backgroundColor': 'rgb(250, 250, 250)',
    },)
], style={
    'backgroundColor': 'rgb(250, 250, 250)'
},)

@app.callback(
    dash.dependencies.Output('params', 'options'),
    [dash.dependencies.Input('uparams_radio', 'value'), ])
def set_uparams_dropdown(selected_uparams):
    if selected_uparams == 'all_uparams':
        return [{'disabled': True}]
    if selected_uparams == 'select_uparams':
        return [{'label': i, 'value': i} for i in sorted(ursgal_params) if i != '']

@app.callback(
    dash.dependencies.Output('params', 'disabled'),
    [dash.dependencies.Input('uparams_radio', 'value'), ])
def set_uparams_dropdown(selected_uparams):
    if selected_uparams == 'all_uparams':
        return True
    if selected_uparams == 'select_uparams':
        return False

@app.callback(
    dash.dependencies.Output('params', 'value'),
    [dash.dependencies.Input('uparams_radio', 'value'), ])
def set_engines_value(selected_uparams):
    if selected_uparams == 'all_uparams':
        return 'all_uparams'
    if selected_uparams == 'select_uparams':
        return []

@app.callback(
    dash.dependencies.Output('engine', 'options'),
    [dash.dependencies.Input('engines_radio', 'value'), ])
def set_engines_dropdown(selected_engines):
    if selected_engines == 'all_engines':
        return [{'disabled': True}]
    if selected_engines == 'select_engines':
        return [{'label': i, 'value': i} for i in sorted(available_engines) if i != '']

@app.callback(
    dash.dependencies.Output('engine', 'disabled'),
    [dash.dependencies.Input('engines_radio', 'value'), ])
def set_engines_dropdown(selected_engines):
    if selected_engines == 'all_engines':
        return True
    if selected_engines == 'select_engines':
        return False

@app.callback(
    dash.dependencies.Output('engine', 'value'),
    [dash.dependencies.Input('engines_radio', 'value'), ])
def set_engines_value(selected_engines):
    if selected_engines == 'all_engines':
        return 'all_engines'
    if selected_engines == 'select_engines':
        return []

@app.callback(
    dash.dependencies.Output('tag', 'options'),
    [dash.dependencies.Input('tags_radio', 'value'), ])
def set_engines_dropdown(selected_tags):
    if selected_tags == 'all_tags':
        return [{'disabled': True}]
    if selected_tags == 'select_tags':
        return [{'label': i, 'value': i} for i in sorted(available_tags) if i != '']

@app.callback(
    dash.dependencies.Output('tag', 'disabled'),
    [dash.dependencies.Input('tags_radio', 'value'), ])
def set_engines_dropdown(selected_tags):
    if selected_tags == 'all_tags':
        return True
    if selected_tags == 'select_tags':
        return False

@app.callback(
    dash.dependencies.Output('tag', 'value'),
    [dash.dependencies.Input('tags_radio', 'value'), ])
def set_engines_dropdown(selected_tags):
    if selected_tags == 'all_tags':
        return 'all_tags'
    if selected_tags == 'select_tags':
        return []

@app.callback(
    dash.dependencies.Output('selected_params', 'children'),
    [dash.dependencies.Input('engine', 'value'),
     dash.dependencies.Input('params', 'value'),
     dash.dependencies.Input('tag', 'value'),
     dash.dependencies.Input('text_options', 'values'), ])
def update_text(selected_engines, selected_uparams, selected_tags, selected_text_options):
    if selected_uparams == 'all_uparams':
        uparams = ursgal_params
    else:
        uparams = {}
        for ukey in selected_uparams:
            uparams[ukey] = ursgal_params[ukey]
    if selected_engines == 'all_engines':
        engine_params = uparams
    else:
        engine_params = {}
        for unode in selected_engines:
            for ukey in unode_sorted_uparams[unode]:
                if ukey not in uparams.keys():
                    continue
                if ukey not in engine_params.keys():
                    engine_params[ukey] = ursgal_params[ukey]
                else:
                    continue
    if selected_tags == 'all_tags':
        tag_engine_params = engine_params
    else:
        tag_engine_params = {}
        for utag in selected_tags:
            for ukey in utag_sorted_uparams[utag]:
                if ukey not in engine_params.keys():
                    continue
                if ukey not in tag_engine_params.keys():
                    tag_engine_params[ukey] = ursgal_params[ukey]
                else:
                    continue

    text = []
    for ursgal_param, udict in sorted(tag_engine_params.items()):
        if isinstance(udict['default_value'], dict):
            default_value = str(sorted(udict['default_value'])).strip()
        else:
            default_value = str(udict['default_value']).strip()
        text.append(
            '''
## {0}

{desc}

**Default value**: {default_value} \n
**type**: {type} \n
**triggers rerun**: {rerun} \n
'''.format(
                ursgal_param,
                desc=udict['description'].strip(),
                default_value=default_value,
                type=udict.get('uvalue_type', ''),
                rerun=udict.get('trigger_rerun', 'False')
            )
        )
        if 'available_unodes' in selected_text_options:
            text.append(
                '''
### Available in UNodes:
''')
            for unode in udict['available_in_unode']:
                text.append('* {0}'.format(unode))

        if 'show_utags' in selected_text_options:
            text.append(
                '''
### Ursgal tags:
''')
            for utag in udict['utag']:
                text.append('* {0}'.format(utag))

        if 'ukey_translation' in selected_text_options:
            text.append('''
### Ursgal key translations for {0}:
'''.format(ursgal_param)
            )
            for style, translation in sorted(udict['ukey_translation'].items()):
                text.append('* {0}: {1}'.format(
                    style,
                    translation)
                )

        if 'uvalue_translation' in selected_text_options:
            text.append('''
### Ursgal value translations for {0}:
'''.format(ursgal_param)
            )
            for style, translation in sorted(udict['uvalue_translation'].items()):
                if type(translation) is dict:
                    text.append(
                        '''* {0}: {1}'''.format(
                            style,
                            translation)
                    )
        text.append(
            '---------------')
    return '\n'.join(text)

if __name__ == '__main__':
    print('Collecting uparams ...')
    print(len(ursgal_params))
    app.run_server(debug=True)
<commit_msg>Start fixing uparams dash app<commit_after>#!/usr/bin/env python
# encoding: utf-8

import sys
import os
import pprint

sys.path.insert(0, os.path.abspath("../"))
from ursgal.uparams import ursgal_params
from collections import defaultdict as ddict
import dash
import dash_core_components as dcc
import dash_html_components as html

def sort_params(uparams, sort_by=None):
    if sort_by is None:
        return uparams
    sorted_params = {}
    for ukey in uparams.keys():
        if type(uparams[ukey][sort_by]) in [list, dict]:
            for element in uparams[ukey][sort_by]:
                if element not in sorted_params.keys():
                    sorted_params[element] = {}
                sorted_params[element][ukey] = uparams[ukey]
        else:
            element = uparams[ukey][sort_by]
            if element not in sorted_params.keys():
                sorted_params[element] = {}
            sorted_params[element][ukey] = uparams[ukey]
    return sorted_params

app = dash.Dash()

colors = {"background_header": "#297FB8", "text_header": "#FCFFFF"}

available_engines = []
unode_sorted_uparams = sort_params(ursgal_params, sort_by="available_in_unode")
for unode in sorted(unode_sorted_uparams.keys()):
    available_engines.append(unode)

available_tags = []
utag_sorted_uparams = sort_params(ursgal_params, sort_by="utag")
for utag in sorted(utag_sorted_uparams):
    available_tags.append(utag)

app.layout = html.Div(
    [
        html.Div(
            [
                dcc.Markdown(
                    """
.
""",
                    #containerProps={
                    #    "style": {
                    #        "color": "rgb(30, 120, 210)",
                    #    },
                    #},
                )
            ],
            style={
                "backgroundColor": "rgb(30, 120, 210)",
            },
        ),
        html.Div(
            [
                dcc.Markdown(
                    """
# Ursgal Parameters
A searchable list of all parameters in Ursgal.
Use the dropdown options to select one or multiple engines or tags \
for which the corresponding parameters should be displayed

        """,
                    #containerProps={
                    #    "style": {
                    #        "color": "rgb(35, 35, 35)",
                    #    },
                    #},
                )
            ],
            style={
                "marginLeft": 10,
                "marginRight": 10,
            },
        ),
        html.Div(
            [
                dcc.Markdown("**UParams**"),
                dcc.RadioItems(
                    id="uparams_radio",
                    options=[
                        {"label": "All uparams", "value": "all_uparams"},
                        {"label": "Select uparams", "value": "select_uparams"},
                    ],
                    value="all_uparams",
                    labelStyle={"display": "inline-block"},
                ),
                dcc.Dropdown(id="params", value="all_uparams", multi=True),
            ],
            style={
                "width": "32%",
                "marginLeft": 10,
                "marginRight": 10,
                "display": "inline-block",
                "backgroundColor": "rgb(250, 250, 250)",
                "color": "rgb(35, 35, 35)",
            },
        ),
        html.Div(
            [
                dcc.Markdown("**Engines**"),
                dcc.RadioItems(
                    id="engines_radio",
                    options=[
                        {"label": "All engines", "value": "all_engines"},
                        {"label": "Select engines", "value": "select_engines"},
                    ],
                    value="all_engines",
                    labelStyle={"display": "inline-block"},
                ),
                dcc.Dropdown(id="engine", value="all_engines", multi=True),
            ],
            style={
                "width": "32%",
                "marginLeft": 10,
                "display": "inline-block",
                "backgroundColor": "rgb(250, 250, 250)",
                "color": "rgb(35, 35, 35)",
            },
        ),
        html.Div(
            [
                dcc.Markdown("**Tags**"),
                dcc.RadioItems(
                    id="tags_radio",
                    options=[
                        {"label": "All tags", "value": "all_tags"},
                        {"label": "Select tags", "value": "select_tags"},
                    ],
                    value="all_tags",
                    labelStyle={"display": "inline-block"},
                ),
                dcc.Dropdown(id="tag", value="all_tags", multi=True),
            ],
            style={
                "width": "32%",
                "display": "inline-block",
                "backgroundColor": "rgb(250, 250, 250)",
                "color": "rgb(35, 35, 35)",
            },
        ),
        html.Div(
            [
                dcc.Checklist(
                    id="text_options",
                    options=[
                        {
                            "label": "Show UNodes for each parameter",
                            "value": "available_unodes",
                        },
                        {"label": "Show Ursgal tags", "value": "show_utags"},
                        {
                            "label": "Show Ursgal value translations",
                            "value": "uvalue_translation",
                        },
                        {
                            "label": "Show Ursgal key translations",
                            "value": "ukey_translation",
                        },
                    ],
                    value=["available_unodes"],
                    # labelStyle={'display': 'inline-block'}
                ),
            ],
            style={
                "marginLeft": 10,
                "marginRight": 10,
                "backgroundColor": "rgb(250, 250, 250)",
                "color": "rgb(35, 35, 35)",
            },
        ),
        html.Div(
            [
                dcc.Markdown(
                    """
.
""",
                    #containerProps={
                    #    "style": {
                    #        "color": "rgb(30, 120, 210)",
                    #    },
                    #},
                )
            ],
            style={
                "backgroundColor": "rgb(30, 120, 210)",
            },
        ),
        html.Div(
            [
                dcc.Markdown(
                    id="selected_params",
                    #containerProps={
                    #    "style": {
                    #        "color": "rgb(37, 37, 37)",
                    #    },
                    #},
                ),
            ],
            style={
                "marginLeft": 30,
                "marginRight": 10,
                "backgroundColor": "rgb(250, 250, 250)",
            },
        ),
    ],
    style={"backgroundColor": "rgb(250, 250, 250)"},
)

@app.callback(
    dash.dependencies.Output("params", "options"),
    [
        dash.dependencies.Input("uparams_radio", "value"),
    ],
)
def set_uparams_dropdown(selected_uparams):
    if selected_uparams == "all_uparams":
        #return [{"disabled": True}]
        return [{'label': '', 'value': ''}]
    if selected_uparams == "select_uparams":
        return [{"label": i, "value": i} for i in sorted(ursgal_params) if i != ""]

@app.callback(
    dash.dependencies.Output("params", "disabled"),
    [
        dash.dependencies.Input("uparams_radio", "value"),
    ],
)
def set_uparams_dropdown(selected_uparams):
    if selected_uparams == "all_uparams":
        return True
    if selected_uparams == "select_uparams":
        return False

@app.callback(
    dash.dependencies.Output("params", "value"),
    [
        dash.dependencies.Input("uparams_radio", "value"),
    ],
)
def set_engines_value(selected_uparams):
    if selected_uparams == "all_uparams":
        return "all_uparams"
    if selected_uparams == "select_uparams":
        return []

@app.callback(
    dash.dependencies.Output("engine", "options"),
    [
        dash.dependencies.Input("engines_radio", "value"),
    ],
)
def set_engines_dropdown(selected_engines):
    if selected_engines == "all_engines":
        #return [{"disabled": True}]
        return [{'label': '', 'value': ''}]
    if selected_engines == "select_engines":
        return [{"label": i, "value": i} for i in sorted(available_engines) if i != ""]

@app.callback(
    dash.dependencies.Output("engine", "disabled"),
    [
        dash.dependencies.Input("engines_radio", "value"),
    ],
)
def set_engines_dropdown(selected_engines):
    if selected_engines == "all_engines":
        return True
    if selected_engines == "select_engines":
        return False

@app.callback(
    dash.dependencies.Output("engine", "value"),
    [
        dash.dependencies.Input("engines_radio", "value"),
    ],
)
def set_engines_value(selected_engines):
    if selected_engines == "all_engines":
        return "all_engines"
    if selected_engines == "select_engines":
        return []

@app.callback(
    dash.dependencies.Output("tag", "options"),
    [
        dash.dependencies.Input("tags_radio", "value"),
    ],
)
def set_engines_dropdown(selected_tags):
    if selected_tags == "all_tags":
        #return [{"disabled": True}]
        return [{'label': '', 'value': ''}]
    if selected_tags == "select_tags":
        return [{"label": i, "value": i} for i in sorted(available_tags) if i != ""]

@app.callback(
    dash.dependencies.Output("tag", "disabled"),
    [
        dash.dependencies.Input("tags_radio", "value"),
    ],
)
def set_engines_dropdown(selected_tags):
    if selected_tags == "all_tags":
        return True
    if selected_tags == "select_tags":
        return False

@app.callback(
    dash.dependencies.Output("tag", "value"),
    [
        dash.dependencies.Input("tags_radio", "value"),
    ],
)
def set_engines_dropdown(selected_tags):
    if selected_tags == "all_tags":
        return "all_tags"
    if selected_tags == "select_tags":
        return []

@app.callback(
    dash.dependencies.Output("selected_params", "children"),
    [
        dash.dependencies.Input("engine", "value"),
        dash.dependencies.Input("params", "value"),
        dash.dependencies.Input("tag", "value"),
        dash.dependencies.Input("text_options", "value"),
    ],
)
def update_text(
    selected_engines, selected_uparams, selected_tags, selected_text_options
):
    if selected_uparams == "all_uparams":
        uparams = ursgal_params
    else:
        uparams = {}
        for ukey in selected_uparams:
            uparams[ukey] = ursgal_params[ukey]
    if selected_engines == "all_engines":
        engine_params = uparams
    else:
        engine_params = {}
        for unode in selected_engines:
            for ukey in unode_sorted_uparams[unode]:
                if ukey not in uparams.keys():
                    continue
                if ukey not in engine_params.keys():
                    engine_params[ukey] = ursgal_params[ukey]
                else:
                    continue
    if selected_tags == "all_tags":
        tag_engine_params = engine_params
    else:
        tag_engine_params = {}
        for utag in selected_tags:
            for ukey in utag_sorted_uparams[utag]:
                if ukey not in engine_params.keys():
                    continue
                if ukey not in tag_engine_params.keys():
                    tag_engine_params[ukey] = ursgal_params[ukey]
                else:
                    continue

    text = []
    for ursgal_param, udict in sorted(tag_engine_params.items()):
        if isinstance(udict["default_value"], dict):
            default_value = str(sorted(udict["default_value"])).strip()
        else:
            default_value = str(udict["default_value"]).strip()
        text.append(
            """
## {0}

{desc}

**Default value**: {default_value} \n
**type**: {type} \n
**triggers rerun**: {rerun} \n
""".format(
                ursgal_param,
                desc=udict["description"].strip(),
                default_value=default_value,
                type=udict.get("uvalue_type", ""),
                rerun=udict.get("trigger_rerun", "False"),
            )
        )
        if "available_unodes" in selected_text_options:
            text.append(
                """
### Available in UNodes:
"""
            )
            for unode in udict["available_in_unode"]:
                text.append("* {0}".format(unode))

        if "show_utags" in selected_text_options:
            text.append(
                """
### Ursgal tags:
"""
            )
            for utag in udict["utag"]:
                text.append("* {0}".format(utag))

        if "ukey_translation" in selected_text_options:
            text.append(
                """
### Ursgal key translations for {0}:
""".format(
                    ursgal_param
                )
            )
            for style, translation in sorted(udict["ukey_translation"].items()):
                text.append("* {0}: {1}".format(style, translation))

        if "uvalue_translation" in selected_text_options:
            text.append(
                """
### Ursgal value translations for {0}:
""".format(
                    ursgal_param
                )
            )
            for style, translation in sorted(udict["uvalue_translation"].items()):
                if type(translation) is dict:
                    text.append("""* {0}: {1}""".format(style, translation))
        text.append("---------------")
    return "\n".join(text)

if __name__ == "__main__":
    print("Collecting uparams ...")
    print(len(ursgal_params))
    app.run_server(debug=True)
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import datetime
import warnings

import pytest
import numpy
import pandas

from pandas.util.testing import assert_series_equal, assert_frame_equal

from pandasvalidation import (
    ValidationWarning,
    _datetime_to_string,
    _numeric_to_string,
    _get_return_object,
    mask_nonconvertible,
    to_datetime,
    to_numeric,
    to_string,
    validate_datetime,
    validate_numeric,
    validate_string)

class TestReturnTypes():

    strings = pandas.Series(['1', '1', 'ab\n', 'a b', 'Ab', 'AB', numpy.nan])
    masks = [
        pandas.Series([False, False, False, True, True, False, False]),
        pandas.Series([True, True, False, True, True, False, True])]

    def test_return_mask_series(self):
        assert_series_equal(
            _get_return_object(self.masks, self.strings, 'mask_series'),
            pandas.Series([True, True, False, True, True, False, True]))

    def test_return_mask_frame(self):
        assert_frame_equal(
            _get_return_object(self.masks, self.strings, 'mask_frame'),
            pandas.concat(self.masks, axis='columns'))

    def test_return_values(self):
        assert_series_equal(
            _get_return_object(self.masks, self.strings, 'values'),
            pandas.Series([
                numpy.nan, numpy.nan, 'ab\n', numpy.nan,
                numpy.nan, 'AB', numpy.nan]))

    def test_wrong_return_type(self):
        with pytest.raises(ValueError):
            _get_return_object(self.masks, self.strings, 'wrong return type')

class TestMaskNonconvertible():

    mixed = pandas.Series([
        1, 2.3, numpy.nan, 'abc', pandas.datetime(2014, 1, 7), '2014'])

    inconvertible_numeric = pandas.Series(
        [False, False, False, True, True, False])

    inconvertible_exact_dates = pandas.Series(
        [True, True, False, True, True, False])

    inconvertible_inexact_dates = pandas.Series(
        [True, True, False, True, False, False])

    def test_numeric(self):
        assert_series_equal(
            mask_nonconvertible(self.mixed, 'numeric'),
            self.inconvertible_numeric)

    def test_datetime_exact_date(self):
        assert_series_equal(
            mask_nonconvertible(
                self.mixed, 'datetime', datetime_format='%Y', exact_date=True),
            self.inconvertible_exact_dates)

        assert_series_equal(
            mask_nonconvertible(
                self.mixed, 'datetime', datetime_format='%Y',
                exact_date=False), self.inconvertible_inexact_dates)

class TestToDatetime():

    mixed = pandas.Series([
        1, 2.3, numpy.nan,
        'abc', pandas.datetime(2014, 1, 7), '2014'])

    def test_exact(self):
        assert (
            to_datetime(self.mixed, format='%Y', exact=True).tolist() == [
                pandas.NaT, pandas.NaT, pandas.NaT, pandas.NaT,
                pandas.NaT, pandas.Timestamp('2014-01-01 00:00:00')])
        assert (
            to_datetime(self.mixed, format='%Y', exact=False).tolist() == [
                pandas.NaT, pandas.NaT, pandas.NaT, pandas.NaT,
                pandas.Timestamp('2014-01-01 00:00:00'),
                pandas.Timestamp('2014-01-01 00:00:00')])

class TestToNumeric():

    mixed = pandas.Series([
        1, 2.3, numpy.nan, 'abc', pandas.datetime(2014, 1, 7), '2014'])

    def test_conversion(self):
        assert (
            to_numeric(self.mixed).sum() == 2017.3)

        pytest.warns(ValidationWarning, to_numeric, self.mixed)

class TestToString():

    mixed = pandas.Series(
        [1, 2.3, numpy.nan, 'abc', pandas.datetime(2014, 1, 7)])

    numeric_as_strings = pandas.Series(
        ['1', '2.3', numpy.nan, 'abc', pandas.datetime(2014, 1, 7)])

    datetimes_as_strings = pandas.Series(
        [1, 2.3, numpy.nan, 'abc', '2014-01-07'])

    all_values_as_strings = pandas.Series(
        ['1', '2.3', numpy.nan, 'abc', '2014-01-07'])

    def test_numeric_to_string(self):
        assert_series_equal(
            _numeric_to_string(self.mixed), self.numeric_as_strings)

    def test_datetime_to_string(self):
        assert_series_equal(
            _datetime_to_string(self.mixed, format='%Y-%m-%d'),
            self.datetimes_as_strings)

    def test_to_string(self):
        assert_series_equal(
            to_string(
                self.mixed, float_format='%g', datetime_format='%Y-%m-%d'),
            self.all_values_as_strings)

class TestValidateDatetime():

    dates_as_strings = pandas.Series([
        '2014-01-07', '2014-01-07', '2014-02-28', numpy.nan])

    dates = pandas.Series([
        datetime.datetime(2014, 1, 7), datetime.datetime(2014, 1, 7),
        datetime.datetime(2014, 2, 28), numpy.nan])

    def test_validation(self):

        assert_series_equal(
            validate_datetime(self.dates_as_strings, return_type='values'),
            validate_datetime(self.dates, return_type='values'))

        pytest.warns(
            ValidationWarning, validate_datetime, self.dates, nullable=False)

        pytest.warns(
            ValidationWarning, validate_datetime, self.dates, unique=True)

        pytest.warns(
            ValidationWarning, validate_datetime, self.dates,
            min_datetime='2014-01-08')

        pytest.warns(
            ValidationWarning, validate_datetime, self.dates,
            max_datetime='2014-01-08')

class TestValidateNumber():

    numeric_as_strings = pandas.Series(['-1', '-1', '2.3', numpy.nan])
    numeric = pandas.Series([-1, -1, 2.3, numpy.nan])

    def test_validation(self):

        assert_series_equal(
            validate_numeric(self.numeric_as_strings, return_type='values'),
            validate_numeric(self.numeric, return_type='values'))

        pytest.warns(
            ValidationWarning, validate_numeric, self.numeric, nullable=False)

        pytest.warns(
            ValidationWarning, validate_numeric, self.numeric, unique=True)

        pytest.warns(
            ValidationWarning, validate_numeric, self.numeric, integer=True)

        pytest.warns(
            ValidationWarning, validate_numeric, self.numeric, min_value=0)

        pytest.warns(
            ValidationWarning, validate_numeric, self.numeric, max_value=0)

class TestValidateString():

    mixed = pandas.Series([1, 1, 'ab\n', 'a b', 'Ab', 'AB', numpy.nan])
    strings = pandas.Series(['1', '1', 'ab\n', 'a b', 'Ab', 'AB', numpy.nan])

    def test_validation(self):

        assert_series_equal(
            validate_string(self.mixed, return_type='values'),
            validate_string(self.strings, return_type='values'))

        pytest.warns(
            ValidationWarning, validate_string, self.strings, nullable=False)

        pytest.warns(
            ValidationWarning, validate_string, self.strings, unique=True)

        pytest.warns(
            ValidationWarning, validate_string, self.strings, min_length=2)

        pytest.warns(
            ValidationWarning, validate_string, self.strings, max_length=2)

        pytest.warns(
            ValidationWarning, validate_string, self.strings[3:], case='lower')

        pytest.warns(
            ValidationWarning, validate_string, self.strings[3:], case='upper')

        pytest.warns(
            ValidationWarning, validate_string, self.strings[3:], case='title')

        pytest.warns(
            ValidationWarning, validate_string, self.strings, newlines=False)

        pytest.warns(
            ValidationWarning, validate_string, self.strings,
            trailing_whitespace=False)

        pytest.warns(
            ValidationWarning, validate_string, self.strings, whitespace=False)

        pytest.warns(
            ValidationWarning, validate_string, self.strings,
            matching_regex=r'\d')

        pytest.warns(
            ValidationWarning, validate_string, self.strings,
            non_matching_regex=r'[\d\s\w]')

        pytest.warns(
            ValidationWarning, validate_string, self.strings,
            whitelist=self.strings[:5])

        pytest.warns(
            ValidationWarning, validate_string, self.strings,
            blacklist=['a', 'Ab'])
<commit_msg>Adapt tests for numeric and string validation<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import datetime
import warnings

import pytest
import numpy
import pandas

from pandas.util.testing import assert_series_equal, assert_frame_equal

from pandasvalidation import (
    ValidationWarning,
    _datetime_to_string,
    _numeric_to_string,
    _get_return_object,
    mask_nonconvertible,
    to_datetime,
    to_numeric,
    to_string,
    validate_datetime,
    validate_numeric,
    validate_string)

class TestReturnTypes():

    strings = pandas.Series(['1', '1', 'ab\n', 'a b', 'Ab', 'AB', numpy.nan])
    masks = [
        pandas.Series([False, False, False, True, True, False, False]),
        pandas.Series([True, True, False, True, True, False, True])]

    def test_return_mask_series(self):
        assert_series_equal(
            _get_return_object(self.masks, self.strings, 'mask_series'),
            pandas.Series([True, True, False, True, True, False, True]))

    def test_return_mask_frame(self):
        assert_frame_equal(
            _get_return_object(self.masks, self.strings, 'mask_frame'),
            pandas.concat(self.masks, axis='columns'))

    def test_return_values(self):
        assert_series_equal(
            _get_return_object(self.masks, self.strings, 'values'),
            pandas.Series([
                numpy.nan, numpy.nan, 'ab\n', numpy.nan,
                numpy.nan, 'AB', numpy.nan]))

    def test_wrong_return_type(self):
        with pytest.raises(ValueError):
            _get_return_object(self.masks, self.strings, 'wrong return type')

class TestMaskNonconvertible():

    mixed = pandas.Series([
        1, 2.3, numpy.nan, 'abc', pandas.datetime(2014, 1, 7), '2014'])

    inconvertible_numeric = pandas.Series(
        [False, False, False, True, True, False])

    inconvertible_exact_dates = pandas.Series(
        [True, True, False, True, True, False])

    inconvertible_inexact_dates = pandas.Series(
        [True, True, False, True, False, False])

    def test_numeric(self):
        assert_series_equal(
            mask_nonconvertible(self.mixed, 'numeric'),
            self.inconvertible_numeric)

    def test_datetime_exact_date(self):
        assert_series_equal(
            mask_nonconvertible(
                self.mixed, 'datetime', datetime_format='%Y', exact_date=True),
            self.inconvertible_exact_dates)

        assert_series_equal(
            mask_nonconvertible(
                self.mixed, 'datetime', datetime_format='%Y',
                exact_date=False), self.inconvertible_inexact_dates)

class TestToDatetime():

    mixed = pandas.Series([
        1, 2.3, numpy.nan,
        'abc', pandas.datetime(2014, 1, 7), '2014'])

    def test_exact(self):
        assert (
            to_datetime(self.mixed, format='%Y', exact=True).tolist() == [
                pandas.NaT, pandas.NaT, pandas.NaT, pandas.NaT,
                pandas.NaT, pandas.Timestamp('2014-01-01 00:00:00')])
        assert (
            to_datetime(self.mixed, format='%Y', exact=False).tolist() == [
                pandas.NaT, pandas.NaT, pandas.NaT, pandas.NaT,
                pandas.Timestamp('2014-01-01 00:00:00'),
                pandas.Timestamp('2014-01-01 00:00:00')])

class TestToNumeric():

    mixed = pandas.Series([
        1, 2.3, numpy.nan, 'abc', pandas.datetime(2014, 1, 7), '2014'])

    def test_conversion(self):
        assert (
            to_numeric(self.mixed).sum() == 2017.3)

        pytest.warns(ValidationWarning, to_numeric, self.mixed)

class TestToString():

    mixed = pandas.Series(
        [1, 2.3, numpy.nan, 'abc', pandas.datetime(2014, 1, 7)])

    numeric_as_strings = pandas.Series(
        ['1', '2.3', numpy.nan, 'abc', pandas.datetime(2014, 1, 7)])

    datetimes_as_strings = pandas.Series(
        [1, 2.3, numpy.nan, 'abc', '2014-01-07'])

    all_values_as_strings = pandas.Series(
        ['1', '2.3', numpy.nan, 'abc', '2014-01-07'])

    def test_numeric_to_string(self):
        assert_series_equal(
            _numeric_to_string(self.mixed), self.numeric_as_strings)

    def test_datetime_to_string(self):
        assert_series_equal(
            _datetime_to_string(self.mixed, format='%Y-%m-%d'),
            self.datetimes_as_strings)

    def test_to_string(self):
        assert_series_equal(
            to_string(
                self.mixed, float_format='%g', datetime_format='%Y-%m-%d'),
            self.all_values_as_strings)

class TestValidateDatetime():

    dates_as_strings = pandas.Series([
        '2014-01-07', '2014-01-07', '2014-02-28', numpy.nan])

    dates = pandas.Series([
        datetime.datetime(2014, 1, 7), datetime.datetime(2014, 1, 7),
        datetime.datetime(2014, 2, 28), numpy.nan])

    def test_validation(self):

        assert_series_equal(
            validate_datetime(self.dates_as_strings, return_type='values'),
            validate_datetime(self.dates, return_type='values'))

        pytest.warns(
            ValidationWarning, validate_datetime, self.dates, nullable=False)

        pytest.warns(
            ValidationWarning, validate_datetime, self.dates, unique=True)

        pytest.warns(
            ValidationWarning, validate_datetime, self.dates,
            min_datetime='2014-01-08')

        pytest.warns(
            ValidationWarning, validate_datetime, self.dates,
            max_datetime='2014-01-08')

class TestValidateNumber():

    numeric_with_string = pandas.Series([-1, -1, 2.3, '1'])
    numeric = pandas.Series([-1, -1, 2.3, numpy.nan])

    def test_validation(self):

        assert_series_equal(
            validate_numeric(self.numeric_with_string, return_type='values'),
            self.numeric)

        pytest.warns(
            ValidationWarning, validate_numeric, self.numeric, nullable=False)

        pytest.warns(
            ValidationWarning, validate_numeric, self.numeric, unique=True)

        pytest.warns(
            ValidationWarning, validate_numeric, self.numeric, integer=True)

        pytest.warns(
            ValidationWarning, validate_numeric, self.numeric, min_value=0)

        pytest.warns(
            ValidationWarning, validate_numeric, self.numeric, max_value=0)

class TestValidateString():

    mixed = pandas.Series(['ab\n', 'a b', 'Ab', 'Ab', 'AB', 1, numpy.nan])
    strings = pandas.Series(
        ['ab\n', 'a b', 'Ab', 'Ab', 'AB', numpy.nan, numpy.nan])

    def test_validation(self):

        assert_series_equal(
            validate_string(self.mixed, return_type='values'),
            self.strings)

        pytest.warns(
            ValidationWarning, validate_string, self.strings, nullable=False)

        pytest.warns(
            ValidationWarning, validate_string, self.strings, unique=True)

        pytest.warns(
            ValidationWarning, validate_string, self.strings, min_length=3)

        pytest.warns(
            ValidationWarning, validate_string, self.strings, max_length=2)

        pytest.warns(
            ValidationWarning, validate_string, self.strings[3:], case='lower')

        pytest.warns(
            ValidationWarning, validate_string, self.strings[3:], case='upper')

        pytest.warns(
            ValidationWarning, validate_string, self.strings[3:], case='title')

        pytest.warns(
            ValidationWarning, validate_string, self.strings, newlines=False)

        pytest.warns(
            ValidationWarning, validate_string, self.strings,
            trailing_whitespace=False)

        pytest.warns(
            ValidationWarning, validate_string, self.strings, whitespace=False)

        pytest.warns(
            ValidationWarning, validate_string, self.strings,
            matching_regex=r'\d')

        pytest.warns(
            ValidationWarning, validate_string, self.strings,
            non_matching_regex=r'[\d\s\w]')

        pytest.warns(
            ValidationWarning, validate_string, self.strings,
            whitelist=self.strings[:4])

        pytest.warns(
            ValidationWarning, validate_string, self.strings,
            blacklist=['a', 'Ab'])
<|endoftext|>


<commit_before>#! /usr/bin/env python
from __future__ import print_function
from subprocess import Popen
import sys
import shlex

# Dict of {"func", "help", "alias"} indexed with a command name
cmds = {}

# - Dynamically generate a help text for all registered commands
# Syntax: help
def helpCmd(*_):
    print("RabbitHole SSH Portal\n\nCommands:")
    for name, cmd in cmds.iteritems():
        if cmd["alias"] != '':
            print("\t{} - Alias for {}".format(name, cmd["alias"].upper()))
            continue

        if cmd["help"] != '':
            print("\t{} - {}".format(name, cmd["help"]))

# - Start a fully interactive process
# cmd is a STRING with the full command and arguments
def startProcess(cmd):
    # Windows uses a string, *nix uses an array
    if not sys.platform == 'win32' and not sys.platform == 'cygwin':
        cmd = shlex.split(cmd)

    try:
        process = Popen(cmd, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)
        process.wait()
    except KeyboardInterrupt:
        print('', end='')
    finally:
        process.wait()

# - Register a command
# name (string) - Command name, what the user will type in
# func (function) - Function to handle command
# help (string) - Help text to display (optional)
def registerCmd(name, func, helpText=''):
    name = normalizeName(name)
    cmds[name] = {"func": func, "help": helpText, "alias": ''}

def registerAlias(alias, cmd):
    alias = normalizeName(alias)
    cmds[alias] = {"func": None, "help": '', "alias": cmd}

# - Register a help text for a command. Used if registerCmd has already been called
def registerHelp(name, text):
    name = normalizeName(name)
    cmd[name]["help"] = text

def normalizeName(name):
    return name.lower().replace(' ', '-')

# - Call command name with args
def callCmd(name, *args):
    name = normalizeName(name)
    try:
        return __callCmd(name, *args)
    except RuntimeError:
        print("Recursion loop detected for command '{}'".format(name))
        return True

def __callCmd(name, *args):
    if name in cmds:
        if cmds[name]["alias"] != '':
            return __callCmd(cmds[name]["alias"], args)

        cmds[name]["func"](*args)
        return True
    return False

# Register the help command
registerCmd('help', helpCmd, "Display this text")
<commit_msg>Fixed bug with calling command alias<commit_after>#! /usr/bin/env python
from __future__ import print_function
from subprocess import Popen
import sys
import shlex

# Dict of {"func", "help", "alias"} indexed with a command name
cmds = {}

# - Dynamically generate a help text for all registered commands
# Syntax: help
def helpCmd(*_):
    print("RabbitHole SSH Portal\n\nCommands:")
    for name, cmd in cmds.iteritems():
        if cmd["alias"] != '':
            print("\t{} - Alias for {}".format(name, cmd["alias"].upper()))
            continue

        if cmd["help"] != '':
            print("\t{} - {}".format(name, cmd["help"]))

# - Start a fully interactive process
# cmd is a STRING with the full command and arguments
def startProcess(cmd):
    # Windows uses a string, *nix uses an array
    if not sys.platform == 'win32' and not sys.platform == 'cygwin':
        cmd = shlex.split(cmd)

    try:
        process = Popen(cmd, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)
        process.wait()
    except KeyboardInterrupt:
        print('', end='')
    finally:
        process.wait()

# - Register a command
# name (string) - Command name, what the user will type in
# func (function) - Function to handle command
# help (string) - Help text to display (optional)
def registerCmd(name, func, helpText=''):
    name = normalizeName(name)
    cmds[name] = {"func": func, "help": helpText, "alias": ''}

def registerAlias(alias, cmd):
    alias = normalizeName(alias)
    cmds[alias] = {"func": None, "help": '', "alias": cmd}

# - Register a help text for a command. Used if registerCmd has already been called
def registerHelp(name, text):
    name = normalizeName(name)
    cmd[name]["help"] = text

def normalizeName(name):
    return name.lower().replace(' ', '-')

# - Call command name with args
def callCmd(name, *args):
    name = normalizeName(name)
    try:
        return __callCmd(name, *args)
    except RuntimeError:
        print("Recursion loop detected for command '{}'".format(name))
        return True

def __callCmd(name, *args):
    if name in cmds:
        if cmds[name]["alias"] != '':
            return __callCmd(cmds[name]["alias"], *args)

        cmds[name]["func"](*args)
        return True
    return False

# Register the help command
registerCmd('help', helpCmd, "Display this text")
<|endoftext|>


<commit_before># host and port for client and tracker
HOST = '127.0.0.1'
PORT = 9996

# redis key prefixes
TRANSACTION_QUEUE_KEY = 'transactions.queue'
BLOCK_KEY_PREFIX = 'chain.block.'
PREV_HASH_KEY = 'prev_hash'
BLOCK_USED_KEY_PREFIX = 'chain.block.used.'
SEND_TRANSACTIONS_QUEUE_KEY = 'send.transactions.queue'

# number of transactions in a block
TRANSACTIONS_IN_BLOCK = 1
<commit_msg>Config changes<commit_after># host and port for client and tracker
HOST = '192.168.43.92'
PORT = 9996

# redis key prefixes
TRANSACTION_QUEUE_KEY = 'transactions.queue'
BLOCK_KEY_PREFIX = 'chain.block.'
PREV_HASH_KEY = 'prev_hash'
BLOCK_USED_KEY_PREFIX = 'chain.block.used.'
SEND_TRANSACTIONS_QUEUE_KEY = 'send.transactions.queue'

# number of transactions in a block
TRANSACTIONS_IN_BLOCK = 1
<|endoftext|>


<commit_before>from dynamic_graph.sot.core.meta_task_6d import toFlags
from dynamic_graph import plug
from dynamic_graph.sot.core import *
from dynamic_graph.sot.core.meta_tasks import setGain
from dynamic_graph.sot.dyninv import *
from dynamic_graph.sot.core.matrix_util import matrixToTuple, vectorToTuple,rotate
from numpy import matrix, identity, zeros, eye

class MetaTaskPosture(object):
    postureRange = { \
        "rleg": range(6,12), \
        "rhip" : range(6,9), \
        "rknee": [9], \
        "rankle": range(10,12), \
        "lleg": range(12,18), \
        "lhip" : range(12,15), \
        "lknee": [15], \
        "lankle": range(16,18), \
        "chest": range(18,20), \
        "head": range(20,22), \
        "rarm": range(22,28), \
        "rshoulder": range(22,25), \
        "relbow": [25], \
        "rwrist": range(26,28), \
        "rhand": [28], \
        "larm": range(29,35), \
        "lshoulder": range(29,32), \
        "lelbow": [32], \
        "lwrist": range(33,35), \
        "lhand": [35], \
            }
    nbDof = None

    def __init__(self,dyn,name="posture"):
        self.dyn=dyn
        self.name=name
        self.feature    = FeatureGeneric('feature'+name)
        self.featureDes = FeatureGeneric('featureDes'+name)
        self.gain = GainAdaptive('gain'+name)
        plug(dyn.position,self.feature.errorIN)
        robotDim = len(dyn.position.value)
        self.feature.jacobianIN.value = matrixToTuple( identity(robotDim) )
        self.feature.setReference(self.featureDes.name)

    def plugTask(self):
        self.task.add(self.feature.name)
        plug(self.task.error,self.gain.error)
        plug(self.gain.gain,self.task.controlGain)

    @property
    def ref(self):
        return self.featureDes.errorIN.value

    @ref.setter
    def ref(self,v):
        self.featureDes.errorIN.value = v

    def gotoq(self,gain=None,qdes=None,**kwargs):
        act=list()
        if qdes!=None:
            if isinstance(qdes,tuple): qdes=matrix(qdes).T
        else:
            if MetaTaskPosture.nbDof==None:
                MetaTaskPosture.nbDof = len(self.feature.errorIN.value)
            qdes = zeros((MetaTaskPosture.nbDof,1))

        for limbName,jointValues in kwargs.items():
            limbRange = self.postureRange[limbName]
            act += limbRange
            if jointValues!=[]:
                if isinstance(jointValues,matrix):
                    qdes[limbRange,0] = vectorToTuple(jointValues)
                else: qdes[limbRange,0] = jointValues
        self.ref = vectorToTuple(qdes)
        self.feature.selec.value = toFlags(act)
        setGain(self.gain,gain)

class MetaTaskKinePosture(MetaTaskPosture):
    def __init__(self,dyn,name="posture"):
        MetaTaskPosture.__init__(self,dyn,name)
        self.task = Task('task'+name)
        self.plugTask()
<commit_msg>Minor feature added in meta task posture.<commit_after>from dynamic_graph.sot.core.meta_task_6d import toFlags
from dynamic_graph import plug
from dynamic_graph.sot.core import *
from dynamic_graph.sot.core.meta_tasks import setGain
from dynamic_graph.sot.dyninv import *
from dynamic_graph.sot.core.matrix_util import matrixToTuple, vectorToTuple,rotate
from numpy import matrix, identity, zeros, eye

class MetaTaskPosture(object):
    postureRange = { \
        "rleg": range(6,12), \
        "rhip" : range(6,9), \
        "rknee": [9], \
        "rankle": range(10,12), \
        "lleg": range(12,18), \
        "lhip" : range(12,15), \
        "lknee": [15], \
        "lankle": range(16,18), \
        "chest": range(18,20), \
        "head": range(20,22), \
        "rarm": range(22,28), \
        "rshoulder": range(22,25), \
        "relbow": [25], \
        "rwrist": range(26,28), \
        "rhand": [28], \
        "larm": range(29,35), \
        "lshoulder": range(29,32), \
        "lelbow": [32], \
        "lwrist": range(33,35), \
        "lhand": [35], \
            }
    nbDof = None

    def __init__(self,dyn,name="posture"):
        self.dyn=dyn
        self.name=name
        self.feature    = FeatureGeneric('feature'+name)
        self.featureDes = FeatureGeneric('featureDes'+name)
        self.gain = GainAdaptive('gain'+name)
        plug(dyn.position,self.feature.errorIN)
        robotDim = len(dyn.position.value)
        self.feature.jacobianIN.value = matrixToTuple( identity(robotDim) )
        self.feature.setReference(self.featureDes.name)

    def plugTask(self):
        self.task.add(self.feature.name)
        plug(self.task.error,self.gain.error)
        plug(self.gain.gain,self.task.controlGain)

    @property
    def ref(self):
        return self.featureDes.errorIN.value

    @ref.setter
    def ref(self,v):
        self.featureDes.errorIN.value = v

    def gotoq(self,gain=None,qdes=None,**kwargs):
        act=list()
        if qdes!=None:
            if isinstance(qdes,tuple): qdes=matrix(qdes).T
        else:
            if MetaTaskPosture.nbDof==None:
                MetaTaskPosture.nbDof = len(self.feature.errorIN.value)
            qdes = zeros((MetaTaskPosture.nbDof,1))

        for limbName,jointValues in kwargs.items():
            limbRange = self.postureRange[limbName]
            act += limbRange
            if jointValues!=[]:
                if isinstance(jointValues,matrix):
                    qdes[limbRange,0] = vectorToTuple(jointValues)
                else: qdes[limbRange,0] = jointValues
        self.ref = vectorToTuple(qdes)
        if(len(act)>0): self.feature.selec.value = toFlags(act)
        setGain(self.gain,gain)

class MetaTaskKinePosture(MetaTaskPosture):
    def __init__(self,dyn,name="posture"):
        MetaTaskPosture.__init__(self,dyn,name)
        self.task = Task('task'+name)
        self.plugTask()
<|endoftext|>


<commit_before># Django settings for testsite project.
import os
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', 'your_email@domain.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(PROJECT_ROOT, 'db.sqlite'),
    },
}

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = '/media/'
STATIC_URL = '/static/'

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'define in local settings file'

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.doc.XViewMiddleware',
)

ROOT_URLCONF = 'example.urls'

TEMPLATE_DIRS = (
    os.path.join(PROJECT_ROOT, 'templates'),
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.admin',
    'django.contrib.staticfiles',

    'sortedm2m',
    'sortedm2m_tests',
    'sortedm2m_tests.migrations_tests',
    'sortedm2m_tests.altersortedmanytomanyfield_tests',

    'example.testapp',
)

MIGRATION_MODULES = {
    'migrations_tests': 'sortedm2m_tests.migrations_tests.django17_migrations',
    'altersortedmanytomanyfield_tests': 'sortedm2m_tests.altersortedmanytomanyfield_tests.django17_migrations',
}

import django

if django.VERSION >= (1, 6):
    TEST_RUNNER = 'django.test.runner.DiscoverRunner'

# Only test south for django versions lower as 1.7
# 1.7 introduced it's own migrations framework
if django.VERSION < (1, 7):
    INSTALLED_APPS = INSTALLED_APPS + (
        'south',
        'test_south_support',
        'test_south_support.south_support_new_model',
        'test_south_support.south_support_new_field',
        'test_south_support.south_support_custom_sort_field_name',
    )

try:
    from local_settings import *
except ImportError:
    pass
<commit_msg>Fixing test_project for newer Djangos.<commit_after># Django settings for testsite project.
import os
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', 'your_email@domain.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(PROJECT_ROOT, 'db.sqlite'),
    },
}

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = '/media/'
STATIC_URL = '/static/'

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'define in local settings file'

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

ROOT_URLCONF = 'example.urls'

TEMPLATE_DIRS = (
    os.path.join(PROJECT_ROOT, 'templates'),
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.admin',
    'django.contrib.staticfiles',

    'sortedm2m',
    'sortedm2m_tests',
    'sortedm2m_tests.migrations_tests',
    'sortedm2m_tests.altersortedmanytomanyfield_tests',

    'example.testapp',
)

MIGRATION_MODULES = {
    'migrations_tests': 'sortedm2m_tests.migrations_tests.django17_migrations',
    'altersortedmanytomanyfield_tests': 'sortedm2m_tests.altersortedmanytomanyfield_tests.django17_migrations',
}

import django

if django.VERSION >= (1, 6):
    TEST_RUNNER = 'django.test.runner.DiscoverRunner'

# Only test south for django versions lower as 1.7
# 1.7 introduced it's own migrations framework
if django.VERSION < (1, 7):
    INSTALLED_APPS = INSTALLED_APPS + (
        'south',
        'test_south_support',
        'test_south_support.south_support_new_model',
        'test_south_support.south_support_new_field',
        'test_south_support.south_support_custom_sort_field_name',
    )

try:
    from local_settings import *
except ImportError:
    pass
<|endoftext|>


<commit_before>from rest_framework_httpsignature.authentication import SignatureAuthentication

from keybar.models.user import User

class KeybarApiSignatureAuthentication(SignatureAuthentication):
    API_KEY_HEADER = 'X-Api-Key'

    def fetch_user_data(self, api_key):
        try:
            user = User.objects.get(api_key=api_key)
            return (user, 'my secret string')
        except User.DoesNotExist:
            return None
<commit_msg>Fix return value in case user was not found<commit_after>from rest_framework_httpsignature.authentication import SignatureAuthentication

from keybar.models.user import User

class KeybarApiSignatureAuthentication(SignatureAuthentication):
    API_KEY_HEADER = 'X-Api-Key'

    def fetch_user_data(self, api_key):
        try:
            user = User.objects.get(api_key=api_key)
            return (user, 'my secret string')
        except User.DoesNotExist:
            return (None, None)
<|endoftext|>


<commit_before>import tornado
import tornado.ioloop
import tornado.web
import os, uuid

__UPLOADS__ = "uploads/"

import sys
sys.path.append('..')

from odt_parse import OdtData
from odt_diff import find_style_by_name

ref_name = '../libro_personalizados.odt'
par_prop = ['backgroundcolor', 'textalign', 'marginleft', 'marginright', 'margintop', 'marginbottom', 'breakbefore']
text_prop = ['fontsize', 'fontstyle', 'language']
ref = OdtData(ref_name, par_prop, text_prop)

sp_dict = {'Heading':'Título', 'Heading_1':'Título_1', 'breakbefore':'salto de página antes',
           'backgroundcolor':'color de fondo', 'textalign':'alineación',
           'Quotations':'Cita', 'fontsize':'tamaño de letra', 'fontstyle':'efecto tipográfico',
           'marginleft':'sangría izquierda', 'marginright':'sangría derecha',
           'margintop':'espacio superior', 'marginbottom':'espacio inferior',
           'justify':'justificada', 'end':'derecha', 'start':'izquierda'}

def sp_trans(s):
    try:
        t = sp_dict[s]
    except KeyError:
        t = s
    return t

errors = []
import io

def compare_style_attr(ref, doc, family, style_name, attr_list):
    stref = find_style_by_name(ref.style[family], style_name)
    stdoc = find_style_by_name(doc.style[family], style_name)
    f = io.StringIO()
    if stdoc:
        for attr in attr_list:
            try:
                val_ref = stref[attr]
                try:
                    val_doc = stdoc[attr]
                    if val_ref != val_doc:
                        f.write('Estilo %s tiene %s
  %s en lugar de %s.

' % (sp_trans(style_name), sp_trans(attr),
                                                                                sp_trans(val_doc), sp_trans(val_ref)))
                except KeyError:
                        f.write('Estilo %s no tiene %s definido.

' % (sp_trans(style_name), sp_trans(attr)))
                #except TypeError:
                #        f.write('Estilo %s no está definido.\n\n' % (sp_trans(style_name)))
            except KeyError:
                err = style_name + "_" + attr
                if not err in errors:
                    errors.append(err)
                    print('Estilo %s no tiene %s definido en el fichero de referencia.' % (sp_trans(style_name), sp_trans(attr)))
    else:
        f.write('Estilo %s no está definido.

' % (sp_trans(style_name)))
    return f.getvalue()

def compare_style_attrs(ref, doc):
    s = '
libro_personalizados

'
    errors = 0
    err = compare_style_attr(ref, doc, 'paragraph', 'Párrafo',
                       ['fontsize', 'textalign'])
    if err:
        s += err
        errors += 1
    err = compare_style_attr(ref, doc, 'paragraph', 'Heading_1',
                       ['margintop', 'breakbefore'])
    if err:
        s += err
        errors += 1
    err = compare_style_attr(ref, doc, 'paragraph', 'Nota',
                       ['fontsize', 'backgroundcolor', 'marginleft'])
    if err:
        s += err
        errors += 1
    err = compare_style_attr(ref, doc, 'paragraph', 'Quotations',
                       ['marginleft','marginright','textalign'])
    if err:
        s += err
        errors += 1
    err = compare_style_attr(ref, doc, 'paragraph', 'Cita_en_inglés',
                       ['language'])
    if err:
        s += err
        errors += 1
    err = compare_style_attr(ref, doc, 'paragraph', 'Autor_de_cita',
                       ['textalign'])
    if err:
        s += err
        errors += 1
    if not errors:
        s += "No s'han trobat errors."
    return s

class Userform(tornado.web.RequestHandler):
    def get(self):
        self.render("Personalizados.html")

class UploadAndCheck(tornado.web.RequestHandler):
    def post(self):
        try:
            fileinfo = self.request.files['filearg'][0]
            fname = fileinfo['filename']
            extn = os.path.splitext(fname)[1]
            cname = str(uuid.uuid4()) + extn
            fname = __UPLOADS__ + cname
            fh = open(fname, 'wb')
            fh.write(fileinfo['body'])
            #self.finish(cname + " is uploaded!! Check %s folder" %__UPLOADS__)
            doc = OdtData( fname, par_prop, text_prop )
            if doc.err:
                s = 'Error de lectura del fitxer\n'
            else:
                s = compare_style_attrs(ref, doc)
        except KeyError:
            s = "No s'ha triat cap fitxer."
        self.finish(s)

application = tornado.web.Application([
        (r"/", Userform),
        (r"/checkPersonalizados", UploadAndCheck),
        ], debug=True)

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
<commit_msg>added back button<commit_after>import tornado
import tornado.ioloop
import tornado.web
import os, uuid

__UPLOADS__ = "uploads/"

import sys
sys.path.append('..')

from odt_parse import OdtData
from odt_diff import find_style_by_name

ref_name = '../libro_personalizados.odt'
par_prop = ['backgroundcolor', 'textalign', 'marginleft', 'marginright', 'margintop', 'marginbottom', 'breakbefore']
text_prop = ['fontsize', 'fontstyle', 'language']
ref = OdtData(ref_name, par_prop, text_prop)

sp_dict = {'Heading':'Título', 'Heading_1':'Título_1', 'breakbefore':'salto de página antes',
           'backgroundcolor':'color de fondo', 'textalign':'alineación',
           'Quotations':'Cita', 'fontsize':'tamaño de letra', 'fontstyle':'efecto tipográfico',
           'marginleft':'sangría izquierda', 'marginright':'sangría derecha',
           'margintop':'espacio superior', 'marginbottom':'espacio inferior',
           'justify':'justificada', 'end':'derecha', 'start':'izquierda'}

def sp_trans(s):
    try:
        t = sp_dict[s]
    except KeyError:
        t = s
    return t

errors = []
import io

def compare_style_attr(ref, doc, family, style_name, attr_list):
    stref = find_style_by_name(ref.style[family], style_name)
    stdoc = find_style_by_name(doc.style[family], style_name)
    f = io.StringIO()
    if stdoc:
        for attr in attr_list:
            try:
                val_ref = stref[attr]
                try:
                    val_doc = stdoc[attr]
                    if val_ref != val_doc:
                        f.write('Estilo %s tiene %s
  %s en lugar de %s.

' % (sp_trans(style_name), sp_trans(attr),
                                                                                sp_trans(val_doc), sp_trans(val_ref)))
                except KeyError:
                        f.write('Estilo %s no tiene %s definido.

' % (sp_trans(style_name), sp_trans(attr)))
                #except TypeError:
                #        f.write('Estilo %s no está definido.\n\n' % (sp_trans(style_name)))
            except KeyError:
                err = style_name + "_" + attr
                if not err in errors:
                    errors.append(err)
                    print('Estilo %s no tiene %s definido en el fichero de referencia.' % (sp_trans(style_name), sp_trans(attr)))
    else:
        f.write('Estilo %s no está definido.

' % (sp_trans(style_name)))
    return f.getvalue()

def compare_style_attrs(ref, doc):
    s = '
libro_personalizados

'
    errors = 0
    err = compare_style_attr(ref, doc, 'paragraph', 'Párrafo',
                       ['fontsize', 'textalign'])
    if err:
        s += err
        errors += 1
    err = compare_style_attr(ref, doc, 'paragraph', 'Heading_1',
                       ['margintop', 'breakbefore'])
    if err:
        s += err
        errors += 1
    err = compare_style_attr(ref, doc, 'paragraph', 'Nota',
                       ['fontsize', 'backgroundcolor', 'marginleft'])
    if err:
        s += err
        errors += 1
    err = compare_style_attr(ref, doc, 'paragraph', 'Quotations',
                       ['marginleft','marginright','textalign'])
    if err:
        s += err
        errors += 1
    err = compare_style_attr(ref, doc, 'paragraph', 'Cita_en_inglés',
                       ['language'])
    if err:
        s += err
        errors += 1
    err = compare_style_attr(ref, doc, 'paragraph', 'Autor_de_cita',
                       ['textalign'])
    if err:
        s += err
        errors += 1
    if not errors:
        s += "No s'han trobat errors."
    return s

class Userform(tornado.web.RequestHandler):
    def get(self):
        self.render("Personalizados.html")

class UploadAndCheck(tornado.web.RequestHandler):
    def post(self):
        try:
            fileinfo = self.request.files['filearg'][0]
            fname = fileinfo['filename']
            extn = os.path.splitext(fname)[1]
            cname = str(uuid.uuid4()) + extn
            fname = __UPLOADS__ + cname
            fh = open(fname, 'wb')
            fh.write(fileinfo['body'])
            #self.finish(cname + " is uploaded!! Check %s folder" %__UPLOADS__)
            doc = OdtData( fname, par_prop, text_prop )
            if doc.err:
                s = 'Error de lectura del fitxer\n'
            else:
                s = compare_style_attrs(ref, doc)
        except KeyError:
            s = "No s'ha triat cap fitxer."
        s += '

<button type="button" onclick="javascript:history.back()">Back</button>'
        self.finish(s)

application = tornado.web.Application([
        (r"/", Userform),
        (r"/checkPersonalizados", UploadAndCheck),
        ], debug=True)

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
<|endoftext|>


<commit_before>VERSION_YEAR = 2017
VERSION_MONTH = 10
VERSION_DAY = 5
VERSION_REV = 1

whos_in = None
twitter = None
users = {}
twilio_client = None
ARGS = {}
smmry_api_key = None

# Variable hold trumps last tweet id
last_id = 0
trump_chance_roll_rdy = False

# Runtime stats
duels_conducted = 0
items_awarded = 0
trump_tweets_seen = 0

# Shot_duel acceptance and active
accepted = False
shot_duel_running = False
vict_name = ""

# News handles to pull from
news_handles = ['mashable', 'cnnbrk', 'whitehouse', 'cnn', 'nytimes',
                'foxnews', 'reuters', 'npr', 'usatoday', 'cbsnews',
                'abc', 'washingtonpost', 'msnbc', 'ap', 'aphealthscience',
                'lifehacker', 'cnnnewsroom', 'theonion']

# Delays for Newsfeed and Check_trump, These are in minutes
# remember that news_del is fuzzed + (0-10)
trump_del = 15
news_del = 55

# Location of db.json and tokens.config
data_dir = "/data"

# Create/Load Local Database
db_file = '{}/db.json'.format(data_dir)
db = {}

# Global toggle for news feed
NEWS_FEED_ON = False
NEWS_FEED_CREATED = False

async def trigger_social(ctx):
    """Triggers a social """
    for m in ctx.bot.get_all_members():
        if m.display_name != 'brochat-bot' and m.status == 'online':
            add_drink(m.display_name)
    glass = ":tumbler_glass:"
    await ctx.bot.say("Ah shit that's three in a row! ITS A SOCIAL! SHOTS! "
                      "SHOTS! SHOTS!\n{}{}{}".format(glass, glass, glass))

def add_drink(user):
    """
    Adds a drink for the user.
    :param user: users display name
    :return:
    """

    if user not in users:
        users[user] = {}

    if "drinks_owed" in users[user]:
        users[user]['drinks_owed'] += 1
    else:
        users[user]['drinks_owed'] = 1

    return users[user]['drinks_owed']
<commit_msg>Bump Version (v2017.10.16.0)<commit_after>VERSION_YEAR = 2017
VERSION_MONTH = 10
VERSION_DAY = 16
VERSION_REV = 0

whos_in = None
twitter = None
users = {}
twilio_client = None
ARGS = {}
smmry_api_key = None

# Variable hold trumps last tweet id
last_id = 0
trump_chance_roll_rdy = False

# Runtime stats
duels_conducted = 0
items_awarded = 0
trump_tweets_seen = 0

# Shot_duel acceptance and active
accepted = False
shot_duel_running = False
vict_name = ""

# News handles to pull from
news_handles = ['mashable', 'cnnbrk', 'whitehouse', 'cnn', 'nytimes',
                'foxnews', 'reuters', 'npr', 'usatoday', 'cbsnews',
                'abc', 'washingtonpost', 'msnbc', 'ap', 'aphealthscience',
                'lifehacker', 'cnnnewsroom', 'theonion']

# Delays for Newsfeed and Check_trump, These are in minutes
# remember that news_del is fuzzed + (0-10)
trump_del = 15
news_del = 55

# Location of db.json and tokens.config
data_dir = "/data"

# Create/Load Local Database
db_file = '{}/db.json'.format(data_dir)
db = {}

# Global toggle for news feed
NEWS_FEED_ON = False
NEWS_FEED_CREATED = False

async def trigger_social(ctx):
    """Triggers a social """
    for m in ctx.bot.get_all_members():
        if m.display_name != 'brochat-bot' and m.status == 'online':
            add_drink(m.display_name)
    glass = ":tumbler_glass:"
    await ctx.bot.say("Ah shit that's three in a row! ITS A SOCIAL! SHOTS! "
                      "SHOTS! SHOTS!\n{}{}{}".format(glass, glass, glass))

def add_drink(user):
    """
    Adds a drink for the user.
    :param user: users display name
    :return:
    """

    if user not in users:
        users[user] = {}

    if "drinks_owed" in users[user]:
        users[user]['drinks_owed'] += 1
    else:
        users[user]['drinks_owed'] = 1

    return users[user]['drinks_owed']
<|endoftext|>


<commit_before>from helpers import BaseBlockCommand

class SmartHeaderCommand(BaseBlockCommand):
    def run(self, edit):
        for region in self.view.sel():
            region, lines, indent = self.get_block_bounds()
            head_lines = len(lines)
            adornment_char = lines[-1][0]

            if (head_lines not in (2, 3) or
                    head_lines == 3 and lines[-3][0] != adornment_char):
                # invalid header
                return

            title = lines[-2]
            title_lenght = len(title)
            strike = adornment_char * title_lenght
            if head_lines == 2:
                result = title + '\n' + strike
            else:
                result = strike + '\n' + title + '\n' + strike
            self.view.replace(edit, region, result)
<commit_msg>over/undertitle lenght is the same than the title in bytes instead of characters. Chinese character are encoded in 2 bytes (utf-8)<commit_after>from helpers import BaseBlockCommand

class SmartHeaderCommand(BaseBlockCommand):
    def run(self, edit):
        for region in self.view.sel():
            region, lines, indent = self.get_block_bounds()
            head_lines = len(lines)
            adornment_char = lines[-1][0]

            if (head_lines not in (2, 3) or
                    head_lines == 3 and lines[-3][0] != adornment_char):
                # invalid header
                return

            title = lines[-2]
            title_lenght = len(title.encode("utf-8"))
            strike = adornment_char * title_lenght
            if head_lines == 2:
                result = title + '\n' + strike
            else:
                result = strike + '\n' + title + '\n' + strike
            self.view.replace(edit, region, result)
<|endoftext|>


<commit_before>from django.contrib.auth.models import User, Permission,Group
from django.shortcuts import render,render_to_response
from django.http import HttpResponse,HttpResponseRedirect
from django.contrib.auth.decorators import login_required,permission_required#,user_passes_test,permission_required
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.views import password_change
from models import UserProfile
from django.template import RequestContext
from django.contrib.contenttypes.models import ContentType

@login_required
def user_list(request):
	users = UserProfile.objects.all()
	groups = Group.objects.all()
	return render_to_response(
		'user_list.html',
		{'users':users,'groups':groups},
		context_instance=RequestContext(request)
		)

@login_required
@permission_required('account.change_userprofile',login_url='/403.html')
def user_modify(request,id):
	user_to_modify = UserProfile.objects.get(pk=id)
	if request.method == 'POST':
		truename = request.POST['truename']
		email = request.POST['email']
		qq = request.POST['qq']
		user_to_modify = UserProfile.objects.get(pk=id)
		user_to_modify.truename = truename
		user_to_modify.email = email
		user_to_modify.qq = qq
		user_to_modify.save()
		return HttpResponseRedirect('/account/manage/user_list.html')
	else:
		if request.user == user_to_modify:
			user = user_to_modify
			groups = Group.objects.all()
			return render_to_response('user_form.html',{'user':user,'groups':groups},context_instance=RequestContext(request))
		else:
			#@permission_required('account.change_other_userprofile')
			if request.user.has_perm('account.change_other_userprofile'):
				user = user_to_modify
				groups = Group.objects.all()
				return render_to_response('user_form.html',{'user':user,'groups':groups},context_instance=RequestContext(request))
			else:
				return HttpResponseRedirect('/404.html')

@login_required
@permission_required('account.add_userprofile',login_url='/403.html')
def user_add(request):
	errors= []
	if request.method == 'POST':
		username = request.POST['username']
		truename = request.POST['truename']
		email = request.POST['email']
		qq = request.POST['qq']
		password1 = request.POST['password1']
		password2 = request.POST['password2']
		print truename,email,qq,password1,password2
		if request.POST['is_active'] == 'true':
			is_active = True
		elif request.POST['is_active'] == 'false':
			is_active = False

		if username == '':
			errors.append('username failed')
		if password1 != password2:
			errors.append('different password!')
		if password1 == password2 and username != '':
			user=UserProfile.objects.create_user(username,email,password1)
			user.is_active=is_active
			user.qq = qq
			user.truename = truename
			user.save()
			return HttpResponseRedirect('/account/manage/user_list.html')

	disable = 'whatever what value it is, will not matters the template'
	return render_to_response(
		'user_add.html',
		{'disable':disable,'errors':errors},
		context_instance=RequestContext(request)
		)

@login_required
@permission_required('account.delete_userprofile',login_url='/403.html')
def user_remove(request,id):
	user_to_delete = UserProfile.objects.get(pk=id)
	user_to_delete.delete()
	return HttpResponseRedirect('/account/manage/user_list.html')

@login_required
def group_list(request):
	groups = Group.objects.all()
	#perms = groups[0].permission_set.all()
	return render_to_response('group_list.html',{'groups':groups},context_instance=RequestContext(request))#context_instance=RequestContext(request)

@login_required
def group_modify(request,id):#TODO
	return render_to_response('group_add.html',{'groups':groups},context_instance=RequestContext(request))

@login_required
@permission_required('account.add_group',login_url='/403.html')
def group_add(request):
	if request.method == 'POST':
		groupname = request.POST['groupname']
		perms = request.POST.getlist('perms',[])
		group = Group(name=groupname)
		group.save()
		for perm in perms:
			perm_to_link = Permission.objects.get(codename=perm)
			group.permissions.add(perm_to_link)
		return HttpResponseRedirect('/account/manage/group_list.html')
	else:
		permissions = Permission.objects.all()
		return render_to_response('group_add.html',{'permissions':permissions},context_instance=RequestContext(request))

@login_required
@permission_required('account.delete_group',login_url='/403.html')
def group_remove(request,id):
	group_to_remove = Group.objects.get(pk=id)
	if group_to_remove.name == '':
		return HttpResponse(group_to_remove.name + 'cannot be removed')
	else:
		group_to_remove.delete()
	return HttpResponseRedirect('/account/manage/group_list.html')

@login_required
def permission_list(request):
	all_perms = Permission.objects.all()
	return render_to_response('perm_list.html',{'all_perms':all_perms},context_instance=RequestContext(request))

@login_required
@permission_required('permission.add_permission',login_url='/403.html')
def permission_add(request):
	if request.method == "POST":
		name = request.POST['name']
		contenttype = request.POST['contenttype']
		codename = request.POST['codename']
		print name,contenttype,codename
		permission_to_save = Permission(
			name=name,
			content_type_id=contenttype,
			codename=codename,
			)
		permission_to_save.save()
		return HttpResponseRedirect('/account/manage/permission_list.html')
	else:
		content_types = ContentType.objects.all()
		return render_to_response('perm_add.html',{'content_types':content_types},context_instance=RequestContext(request))

@login_required
def permission_modify(request,id):
	perm_to_modify = Permission.objects.get(pk=id)
	if request.method == "POST":
		name = request.POST['name']
		contenttype = request.POST['contenttype']
		codename = request.POST['codename']
		print name,contenttype,codename
		perm_to_modify.name = name
		perm_to_modify.content_type_id = content_type_id
		perm_to_modify.codename = codename
		perm_to_modify.save()
		return HttpResponseRedirect('/account/manage/permission_list.html')
	else:
		content_types = ContentType.objects.all()
		return render_to_response('perm_form.html',{'content_types':content_types,'perm_to_modify':perm_to_modify},context_instance=RequestContext(request))<commit_msg>complete the function of modify group<commit_after>from django.contrib.auth.models import User, Permission,Group
from django.shortcuts import render,render_to_response
from django.http import HttpResponse,HttpResponseRedirect
from django.contrib.auth.decorators import login_required,permission_required#,user_passes_test,permission_required
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.views import password_change
from models import UserProfile
from django.template import RequestContext
from django.contrib.contenttypes.models import ContentType

@login_required
def user_list(request):
	users = UserProfile.objects.all()
	groups = Group.objects.all()
	return render_to_response(
		'user_list.html',
		{'users':users,'groups':groups},
		context_instance=RequestContext(request)
		)

@login_required
@permission_required('account.change_userprofile',login_url='/403.html')
def user_modify(request,id):
	user_to_modify = UserProfile.objects.get(pk=id)
	if request.method == 'POST':
		truename = request.POST['truename']
		email = request.POST['email']
		qq = request.POST['qq']
		user_to_modify = UserProfile.objects.get(pk=id)
		user_to_modify.truename = truename
		user_to_modify.email = email
		user_to_modify.qq = qq
		user_to_modify.save()
		return HttpResponseRedirect('/account/manage/user_list.html')
	else:
		if request.user == user_to_modify:
			user = user_to_modify
			groups = Group.objects.all()
			return render_to_response('user_form.html',{'user':user,'groups':groups},context_instance=RequestContext(request))
		else:
			#@permission_required('account.change_other_userprofile')
			if request.user.has_perm('account.change_other_userprofile'):
				user = user_to_modify
				groups = Group.objects.all()
				return render_to_response('user_form.html',{'user':user,'groups':groups},context_instance=RequestContext(request))
			else:
				return HttpResponseRedirect('/404.html')

@login_required
@permission_required('account.add_userprofile',login_url='/403.html')
def user_add(request):
	errors= []
	if request.method == 'POST':
		username = request.POST['username']
		truename = request.POST['truename']
		email = request.POST['email']
		qq = request.POST['qq']
		password1 = request.POST['password1']
		password2 = request.POST['password2']
		print truename,email,qq,password1,password2
		if request.POST['is_active'] == 'true':
			is_active = True
		elif request.POST['is_active'] == 'false':
			is_active = False

		if username == '':
			errors.append('username failed')
		if password1 != password2:
			errors.append('different password!')
		if password1 == password2 and username != '':
			user=UserProfile.objects.create_user(username,email,password1)
			user.is_active=is_active
			user.qq = qq
			user.truename = truename
			user.save()
			return HttpResponseRedirect('/account/manage/user_list.html')

	disable = 'whatever what value it is, will not matters the template'
	return render_to_response(
		'user_add.html',
		{'disable':disable,'errors':errors},
		context_instance=RequestContext(request)
		)

@login_required
@permission_required('account.delete_userprofile',login_url='/403.html')
def user_remove(request,id):
	user_to_delete = UserProfile.objects.get(pk=id)
	user_to_delete.delete()
	return HttpResponseRedirect('/account/manage/user_list.html')

@login_required
def group_list(request):
	groups = Group.objects.all()
	#perms = groups[0].permission_set.all()
	return render_to_response('group_list.html',{'groups':groups},context_instance=RequestContext(request))#context_instance=RequestContext(request)

@login_required
#@permission_required('auth.change_group',login_url='/403.html')
def group_modify(request,id):
	if request.method == 'POST':
		group_id = request.POST.get('group_id')
		chosen_perms =  request.POST.getlist('perms',[])
		group_name = request.POST.get('groupname')
		print chosen_perms,group_name,group_id

		group_to_modify = Group.objects.get(pk=group_id)
		group_to_modify.name = group_name
		group_to_modify.permissions.clear()
		for chosen_perm_id in chosen_perms:
			permission_to_add = Permission.objects.get(pk=chosen_perm_id)
			print permission_to_add
		group_to_modify.permissions.add(permission_to_add)
		group_to_modify.save()
		return HttpResponseRedirect('/account/manage/group_list.html')

	else:
		group_to_modify = Group.objects.get(id=id)
		permissions = Permission.objects.all()
		return render_to_response('group_form.html',{'permissions':permissions,'group_to_modify':group_to_modify},context_instance=RequestContext(request))

@login_required
@permission_required('account.add_group',login_url='/403.html')
def group_add(request):
	if request.method == 'POST':
		groupname = request.POST['groupname']
		perms = request.POST.getlist('perms',[])
		group = Group(name=groupname)
		group.save()
		for perm in perms:
			perm_to_link = Permission.objects.get(codename=perm)
			group.permissions.add(perm_to_link)
		return HttpResponseRedirect('/account/manage/group_list.html')
	else:
		permissions = Permission.objects.all()
		return render_to_response('group_add.html',{'permissions':permissions},context_instance=RequestContext(request))

@login_required
@permission_required('account.delete_group',login_url='/403.html')
def group_remove(request,id):
	group_to_remove = Group.objects.get(pk=id)
	if group_to_remove.name == '':
		return HttpResponse(group_to_remove.name + 'cannot be removed')
	else:
		group_to_remove.delete()
	return HttpResponseRedirect('/account/manage/group_list.html')

@login_required
def permission_list(request):
	all_perms = Permission.objects.all()
	return render_to_response('perm_list.html',{'all_perms':all_perms},context_instance=RequestContext(request))

@login_required
@permission_required('permission.add_permission',login_url='/403.html')
def permission_add(request):
	if request.method == "POST":
		name = request.POST['name']
		contenttype = request.POST['contenttype']
		codename = request.POST['codename']
		print name,contenttype,codename
		permission_to_save = Permission(
			name=name,
			content_type_id=contenttype,
			codename=codename,
			)
		permission_to_save.save()
		return HttpResponseRedirect('/account/manage/permission_list.html')
	else:
		content_types = ContentType.objects.all()
		return render_to_response('perm_add.html',{'content_types':content_types},context_instance=RequestContext(request))

@login_required
def permission_modify(request,id):
	perm_to_modify = Permission.objects.get(pk=id)
	if request.method == "POST":
		name = request.POST['name']
		contenttype = request.POST['contenttype']
		codename = request.POST['codename']
		print name,contenttype,codename
		perm_to_modify.name = name
		perm_to_modify.content_type_id = content_type_id
		perm_to_modify.codename = codename
		perm_to_modify.save()
		return HttpResponseRedirect('/account/manage/permission_list.html')
	else:
		content_types = ContentType.objects.all()
		return render_to_response('perm_form.html',{'content_types':content_types,'perm_to_modify':perm_to_modify},context_instance=RequestContext(request))<|endoftext|>